diff --git a/.gitignore b/.gitignore index 9f3784d3..eff03ec0 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,180 @@ -*.project + +# Created by https://www.gitignore.io/api/java,maven,eclipse + +### Java ### *.class -.* -**/dist/* -**/test-reports/**/*.html + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.ear + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + + +### Maven ### +target/ +pom.xml.tag +pom.xml.releaseBackup +pom.xml.versionsBackup +pom.xml.next +release.properties +dependency-reduced-pom.xml +buildNumber.properties +.mvn/timing.properties + + +### Eclipse ### +.toDelete + +#output/ +#input/ + +.vs/ +.metadata +bin/ +tmp/ +*.tmp +*.bak +*.swp +*~.nib +local.properties +.settings/ +.loadpath + +# Eclipse Core +.project + +# External tool builders +.externalToolBuilders/ + +# Locally stored "Eclipse launch configurations" +*.launch + +# PyDev specific (Python IDE for Eclipse) +*.pydevproject + +# CDT-specific (C/C++ Development Tooling) +.cproject + +# JDT-specific (Eclipse Java Development Tools) +.classpath + +# Java annotation processor (APT) +.factorypath + +# PDT-specific (PHP Development Tools) +.buildpath + +# sbteclipse plugin +.target + +# TeXlipse plugin +.texlipse + +# STS (Spring Tool Suite) +.springBeans + + +# Created by https://www.toptal.com/developers/gitignore/api/intellij+all +# Edit at https://www.toptal.com/developers/gitignore?templates=intellij+all + +### Intellij+all ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# AWS User-specific +.idea/**/aws.xml + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/artifacts +# .idea/compiler.xml +# .idea/jarRepositories.xml +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +### Intellij+all Patch ### +# Ignores the whole .idea folder and all .iml files +# See https://github.com/joeblau/gitignore.io/issues/186 and https://github.com/joeblau/gitignore.io/issues/360 + +.idea/ + +# Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-249601023 + +*.iml +modules.xml +.idea/misc.xml +*.ipr + +# Sonarlint plugin +.idea/sonarlint + +# End of https://www.toptal.com/developers/gitignore/api/intellij+all +/.vs/hapi-facade-example/v17 +/.vs/slnx.sqlite diff --git a/README.md b/README.md index e99b55b9..5056d244 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ The code for the i2b2 Server is maintained by the i2b2 team. Cells developed by the i2b2 Community can be found in the *i2b2/community-plugins/server* folder. - +[]() ## Reporting Issues If an issue is found with the i2b2 Server please submit an issue in the [i2b2 Bug Tracker](http://community.i2b2.org/jira/secure/Dashboard.jspa "i2b2 Bug Tracker") under the *i2b2 Core Software* project. diff --git a/edu.harvard.i2b2.crc/.classpath b/edu.harvard.i2b2.crc/.classpath index 96522149..b9f6029d 100755 --- a/edu.harvard.i2b2.crc/.classpath +++ b/edu.harvard.i2b2.crc/.classpath @@ -1,157 +1,46 @@ - - - - - + - + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/edu.harvard.i2b2.crc/.cvsignore b/edu.harvard.i2b2.crc/.cvsignore deleted file mode 100755 index 6fa9c997..00000000 --- a/edu.harvard.i2b2.crc/.cvsignore +++ /dev/null @@ -1,5 +0,0 @@ -dist -gensrc -classes -report -genlib diff --git a/edu.harvard.i2b2.crc/.gitignore b/edu.harvard.i2b2.crc/.gitignore deleted file mode 100644 index d2dce6a3..00000000 --- a/edu.harvard.i2b2.crc/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -/classes/ -/genlib/ diff --git a/edu.harvard.i2b2.crc/.project b/edu.harvard.i2b2.crc/.project index 463438e2..99012680 100755 --- a/edu.harvard.i2b2.crc/.project +++ b/edu.harvard.i2b2.crc/.project @@ -10,8 +10,14 @@ + + org.eclipse.m2e.core.maven2Builder + + + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature diff --git a/edu.harvard.i2b2.crc/LICENSE.txt b/edu.harvard.i2b2.crc/LICENSE.txt deleted file mode 100644 index 8d6b16a3..00000000 --- a/edu.harvard.i2b2.crc/LICENSE.txt +++ /dev/null @@ -1,406 +0,0 @@ -#------------------------------------------------------------------------------- -# Copyright (c) 2006-2018 Massachusetts General Hospital -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Mozilla Public License, -# v. 2.0. If a copy of the MPL was not distributed with this file, You can -# obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under -# the terms of the Healthcare Disclaimer. -#------------------------------------------------------------------------------- -Mozilla Public License, version 2.0 - -1. Definitions - -1.1. "Contributor" - - means each individual or legal entity that creates, contributes to the - creation of, or owns Covered Software. - -1.2. "Contributor Version" - - means the combination of the Contributions of others (if any) used by a - Contributor and that particular Contributor's Contribution. - -1.3. "Contribution" - - means Covered Software of a particular Contributor. - -1.4. "Covered Software" - - means Source Code Form to which the initial Contributor has attached the - notice in Exhibit A, the Executable Form of such Source Code Form, and - Modifications of such Source Code Form, in each case including portions - thereof. - -1.5. "Incompatible With Secondary Licenses" - means - - a. that the initial Contributor has attached the notice described in - Exhibit B to the Covered Software; or - - b. that the Covered Software was made available under the terms of - version 1.1 or earlier of the License, but not also under the terms of - a Secondary License. - -1.6. "Executable Form" - - means any form of the work other than Source Code Form. - -1.7. "Larger Work" - - means a work that combines Covered Software with other material, in a - separate file or files, that is not Covered Software. - -1.8. "License" - - means this document. - -1.9. "Licensable" - - means having the right to grant, to the maximum extent possible, whether - at the time of the initial grant or subsequently, any and all of the - rights conveyed by this License. - -1.10. "Modifications" - - means any of the following: - - a. any file in Source Code Form that results from an addition to, - deletion from, or modification of the contents of Covered Software; or - - b. any new file in Source Code Form that contains any Covered Software. - -1.11. "Patent Claims" of a Contributor - - means any patent claim(s), including without limitation, method, - process, and apparatus claims, in any patent Licensable by such - Contributor that would be infringed, but for the grant of the License, - by the making, using, selling, offering for sale, having made, import, - or transfer of either its Contributions or its Contributor Version. - -1.12. "Secondary License" - - means either the GNU General Public License, Version 2.0, the GNU Lesser - General Public License, Version 2.1, the GNU Affero General Public - License, Version 3.0, or any later versions of those licenses. - -1.13. "Source Code Form" - - means the form of the work preferred for making modifications. - -1.14. "You" (or "Your") - - means an individual or a legal entity exercising rights under this - License. For legal entities, "You" includes any entity that controls, is - controlled by, or is under common control with You. For purposes of this - definition, "control" means (a) the power, direct or indirect, to cause - the direction or management of such entity, whether by contract or - otherwise, or (b) ownership of more than fifty percent (50%) of the - outstanding shares or beneficial ownership of such entity. - - -2. License Grants and Conditions - -2.1. Grants - - Each Contributor hereby grants You a world-wide, royalty-free, - non-exclusive license: - - a. under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or - as part of a Larger Work; and - - b. under Patent Claims of such Contributor to make, use, sell, offer for - sale, have made, import, and otherwise transfer either its - Contributions or its Contributor Version. - -2.2. Effective Date - - The licenses granted in Section 2.1 with respect to any Contribution - become effective for each Contribution on the date the Contributor first - distributes such Contribution. - -2.3. Limitations on Grant Scope - - The licenses granted in this Section 2 are the only rights granted under - this License. No additional rights or licenses will be implied from the - distribution or licensing of Covered Software under this License. - Notwithstanding Section 2.1(b) above, no patent license is granted by a - Contributor: - - a. for any code that a Contributor has removed from Covered Software; or - - b. for infringements caused by: (i) Your and any other third party's - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - - c. under Patent Claims infringed by Covered Software in the absence of - its Contributions. - - This License does not grant any rights in the trademarks, service marks, - or logos of any Contributor (except as may be necessary to comply with - the notice requirements in Section 3.4). - -2.4. Subsequent Licenses - - No Contributor makes additional grants as a result of Your choice to - distribute the Covered Software under a subsequent version of this - License (see Section 10.2) or under the terms of a Secondary License (if - permitted under the terms of Section 3.3). - -2.5. Representation - - Each Contributor represents that the Contributor believes its - Contributions are its original creation(s) or it has sufficient rights to - grant the rights to its Contributions conveyed by this License. - -2.6. Fair Use - - This License is not intended to limit any rights You have under - applicable copyright doctrines of fair use, fair dealing, or other - equivalents. - -2.7. Conditions - - Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in - Section 2.1. - - -3. Responsibilities - -3.1. Distribution of Source Form - - All distribution of Covered Software in Source Code Form, including any - Modifications that You create or to which You contribute, must be under - the terms of this License. You must inform recipients that the Source - Code Form of the Covered Software is governed by the terms of this - License, and how they can obtain a copy of this License. You may not - attempt to alter or restrict the recipients' rights in the Source Code - Form. - -3.2. Distribution of Executable Form - - If You distribute Covered Software in Executable Form then: - - a. such Covered Software must also be made available in Source Code Form, - as described in Section 3.1, and You must inform recipients of the - Executable Form how they can obtain a copy of such Source Code Form by - reasonable means in a timely manner, at a charge no more than the cost - of distribution to the recipient; and - - b. You may distribute such Executable Form under the terms of this - License, or sublicense it under different terms, provided that the - license for the Executable Form does not attempt to limit or alter the - recipients' rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - - You may create and distribute a Larger Work under terms of Your choice, - provided that You also comply with the requirements of this License for - the Covered Software. If the Larger Work is a combination of Covered - Software with a work governed by one or more Secondary Licenses, and the - Covered Software is not Incompatible With Secondary Licenses, this - License permits You to additionally distribute such Covered Software - under the terms of such Secondary License(s), so that the recipient of - the Larger Work may, at their option, further distribute the Covered - Software under the terms of either this License or such Secondary - License(s). - -3.4. Notices - - You may not remove or alter the substance of any license notices - (including copyright notices, patent notices, disclaimers of warranty, or - limitations of liability) contained within the Source Code Form of the - Covered Software, except that You may alter any license notices to the - extent required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - - You may choose to offer, and to charge a fee for, warranty, support, - indemnity or liability obligations to one or more recipients of Covered - Software. However, You may do so only on Your own behalf, and not on - behalf of any Contributor. You must make it absolutely clear that any - such warranty, support, indemnity, or liability obligation is offered by - You alone, and You hereby agree to indemnify every Contributor for any - liability incurred by such Contributor as a result of warranty, support, - indemnity or liability terms You offer. You may include additional - disclaimers of warranty and limitations of liability specific to any - jurisdiction. - -4. Inability to Comply Due to Statute or Regulation - - If it is impossible for You to comply with any of the terms of this License - with respect to some or all of the Covered Software due to statute, - judicial order, or regulation then You must: (a) comply with the terms of - this License to the maximum extent possible; and (b) describe the - limitations and the code they affect. Such description must be placed in a - text file included with all distributions of the Covered Software under - this License. Except to the extent prohibited by statute or regulation, - such description must be sufficiently detailed for a recipient of ordinary - skill to be able to understand it. - -5. Termination - -5.1. The rights granted under this License will terminate automatically if You - fail to comply with any of its terms. However, if You become compliant, - then the rights granted under this License from a particular Contributor - are reinstated (a) provisionally, unless and until such Contributor - explicitly and finally terminates Your grants, and (b) on an ongoing - basis, if such Contributor fails to notify You of the non-compliance by - some reasonable means prior to 60 days after You have come back into - compliance. Moreover, Your grants from a particular Contributor are - reinstated on an ongoing basis if such Contributor notifies You of the - non-compliance by some reasonable means, this is the first time You have - received notice of non-compliance with this License from such - Contributor, and You become compliant prior to 30 days after Your receipt - of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent - infringement claim (excluding declaratory judgment actions, - counter-claims, and cross-claims) alleging that a Contributor Version - directly or indirectly infringes any patent, then the rights granted to - You by any and all Contributors for the Covered Software under Section - 2.1 of this License shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user - license agreements (excluding distributors and resellers) which have been - validly granted by You or Your distributors under this License prior to - termination shall survive termination. - -6. Disclaimer of Warranty - - Covered Software is provided under this License on an "as is" basis, - without warranty of any kind, either expressed, implied, or statutory, - including, without limitation, warranties that the Covered Software is free - of defects, merchantable, fit for a particular purpose or non-infringing. - The entire risk as to the quality and performance of the Covered Software - is with You. Should any Covered Software prove defective in any respect, - You (not any Contributor) assume the cost of any necessary servicing, - repair, or correction. This disclaimer of warranty constitutes an essential - part of this License. No use of any Covered Software is authorized under - this License except under this disclaimer. - -7. Limitation of Liability - - Under no circumstances and under no legal theory, whether tort (including - negligence), contract, or otherwise, shall any Contributor, or anyone who - distributes Covered Software as permitted above, be liable to You for any - direct, indirect, special, incidental, or consequential damages of any - character including, without limitation, damages for lost profits, loss of - goodwill, work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses, even if such party shall have been - informed of the possibility of such damages. This limitation of liability - shall not apply to liability for death or personal injury resulting from - such party's negligence to the extent applicable law prohibits such - limitation. Some jurisdictions do not allow the exclusion or limitation of - incidental or consequential damages, so this exclusion and limitation may - not apply to You. - -8. Litigation - - Any litigation relating to this License may be brought only in the courts - of a jurisdiction where the defendant maintains its principal place of - business and such litigation shall be governed by laws of that - jurisdiction, without reference to its conflict-of-law provisions. Nothing - in this Section shall prevent a party's ability to bring cross-claims or - counter-claims. - -9. Miscellaneous - - This License represents the complete agreement concerning the subject - matter hereof. If any provision of this License is held to be - unenforceable, such provision shall be reformed only to the extent - necessary to make it enforceable. Any law or regulation which provides that - the language of a contract shall be construed against the drafter shall not - be used to construe this License against a Contributor. - - -10. Versions of the License - -10.1. New Versions - - Mozilla Foundation is the license steward. Except as provided in Section - 10.3, no one other than the license steward has the right to modify or - publish new versions of this License. Each version will be given a - distinguishing version number. - -10.2. Effect of New Versions - - You may distribute the Covered Software under the terms of the version - of the License under which You originally received the Covered Software, - or under the terms of any subsequent version published by the license - steward. - -10.3. Modified Versions - - If you create software not governed by this License, and you want to - create a new license for such software, you may create and use a - modified version of this License if you rename the license and remove - any references to the name of the license steward (except to note that - such modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary - Licenses If You choose to distribute Source Code Form that is - Incompatible With Secondary Licenses under the terms of this version of - the License, the notice described in Exhibit B of this License must be - attached. - -Exhibit A - Source Code Form License Notice - - This Source Code Form is subject to the - terms of the Mozilla Public License, v. - 2.0. If a copy of the MPL was not - distributed with this file, You can - obtain one at - http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular file, -then You may include the notice in a location (such as a LICENSE file in a -relevant directory) where a recipient would be likely to look for such a -notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - "Incompatible With Secondary Licenses" Notice - - This Source Code Form is "Incompatible - With Secondary Licenses", as defined by - the Mozilla Public License, v. 2.0. - ---------------------- - -Healthcare Disclaimer - -In the United States, or any other jurisdictions where they may apply, the -following additional disclaimer of warranty and limitation of liability are -hereby incorporated into the terms and conditions of MPL 2.0: - -1. No warranties of any kind whatsoever are made as to the results that - You will obtain from relying upon the covered code (or any information - or content obtained by way of the covered code), including but not - limited to compliance with privacy laws or regulations or clinical - care industry standards and protocols. Use of the covered code is not - a substitute for a health care provider’s standard practice or - professional judgment. Any decision with regard to the appropriateness - of treatment, or the validity or reliability of information or content - made available by the covered code, is the sole responsibility of the - health care provider. Consequently, it is incumbent upon each health - care provider to verify all medical history and treatment plans with - each patient. - -2. Under no circumstances and under no legal theory, whether tort - (including negligence), contract, or otherwise, shall any Contributor, - or anyone who distributes Covered Software as permitted by the - license, be liable to You for any indirect, special, incidental, - consequential damages of any character including, without limitation, - damages for loss of goodwill, work stoppage, computer failure or - malfunction, or any and all other damages or losses, of any nature - whatsoever (direct or otherwise) on account of or associated with the - use or inability to use the covered content (including, without - limitation, the use of information or content made available by the - covered code, all documentation associated therewith, and the failure - of the covered code to comply with privacy laws and regulations or - clinical care industry standards and protocols), even if such party - shall have been informed of the possibility of such damages. diff --git a/edu.harvard.i2b2.crc/analysis_launch.xml b/edu.harvard.i2b2.crc/analysis_launch.xml deleted file mode 100755 index 5f157123..00000000 --- a/edu.harvard.i2b2.crc/analysis_launch.xml +++ /dev/null @@ -1,83 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/edu.harvard.i2b2.crc/build.properties b/edu.harvard.i2b2.crc/build.properties deleted file mode 100755 index 29ace291..00000000 --- a/edu.harvard.i2b2.crc/build.properties +++ /dev/null @@ -1,14 +0,0 @@ -#Ant build property file - -## TOMCAT HOME -jboss.home=/opt/wildfly-17.0.1.Final -axis2.war.name=i2b2.war - -#Test files home -report=test-reports -testfiledir=testfiles -#testhost=http://infra6.mgh.harvard.edu:9090/i2b2/rest -testhost=http://127.0.0.1:9090/i2b2/services - - - diff --git a/edu.harvard.i2b2.crc/build.xml b/edu.harvard.i2b2.crc/build.xml deleted file mode 100755 index 2add85ef..00000000 --- a/edu.harvard.i2b2.crc/build.xml +++ /dev/null @@ -1,318 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/edu.harvard.i2b2.crc/common-build.xml b/edu.harvard.i2b2.crc/common-build.xml deleted file mode 100755 index 3ecd0a07..00000000 --- a/edu.harvard.i2b2.crc/common-build.xml +++ /dev/null @@ -1,86 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/edu.harvard.i2b2.crc/data_build.xml b/edu.harvard.i2b2.crc/data_build.xml deleted file mode 100755 index 03f7ba04..00000000 --- a/edu.harvard.i2b2.crc/data_build.xml +++ /dev/null @@ -1,52 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - CREATE USER i2b2demodata IDENTIFIED BY i2b2demodata; - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/edu.harvard.i2b2.crc/db.oracle.properties b/edu.harvard.i2b2.crc/db.oracle.properties deleted file mode 100755 index 23f79a6a..00000000 --- a/edu.harvard.i2b2.crc/db.oracle.properties +++ /dev/null @@ -1,16 +0,0 @@ -#------------------------------------------------------------------------------- -# Copyright (c) 2006-2018 Massachusetts General Hospital -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Mozilla Public License, -# v. 2.0. If a copy of the MPL was not distributed with this file, You can -# obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under -# the terms of the Healthcare Disclaimer. -#------------------------------------------------------------------------------- -# Database setup parameters -db.type=oracle -db.username=i2b2demodata -db.password=i2b2demodata -db.server=localhost:1521:xe -db.driver=oracle.jdbc.driver.OracleDriver -db.url=jdbc:oracle:thin:@localhost:1521:xe -db.script.dir=/opt/data diff --git a/edu.harvard.i2b2.crc/master_build.xml b/edu.harvard.i2b2.crc/master_build.xml deleted file mode 100755 index c162fce1..00000000 --- a/edu.harvard.i2b2.crc/master_build.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/edu.harvard.i2b2.crc/pom.xml b/edu.harvard.i2b2.crc/pom.xml new file mode 100644 index 00000000..57491f09 --- /dev/null +++ b/edu.harvard.i2b2.crc/pom.xml @@ -0,0 +1,90 @@ + + 4.0.0 + + edu.harvard.i2b2.crc + jar + CRC Cell + + + edu.harvard.i2b2 + i2b2-parent + 2.0.0-SNAPSHOT + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 3.0.0 + + + generate-sources + + add-source + + + + gensrc + + + + + + + + + + + + + edu.harvard.i2b2 + edu.harvard.i2b2.server-common + + + + org.springframework + spring-core + + + + org.quartz-scheduler + quartz + 2.5.0 + + + + net.lingala.zip4j + zip4j + 2.11.5 + + + + jakarta.mail + jakarta.mail-api + 2.1.3 + + + + com.google.guava + guava + 33.4.8-jre + + + + org.apache.tomcat + tomcat-tribes + 11.0.9 + + + + + org.apache.commons + commons-exec + 1.5.0 + + + + + \ No newline at end of file diff --git a/edu.harvard.i2b2.crc/src/client/readme.txt b/edu.harvard.i2b2.crc/src/client/readme.txt deleted file mode 100755 index a4e2046b..00000000 --- a/edu.harvard.i2b2.crc/src/client/readme.txt +++ /dev/null @@ -1,9 +0,0 @@ -#------------------------------------------------------------------------------- -# Copyright (c) 2006-2018 Massachusetts General Hospital -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Mozilla Public License, -# v. 2.0. If a copy of the MPL was not distributed with this file, You can -# obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under -# the terms of the Healthcare Disclaimer. -#------------------------------------------------------------------------------- -Client source file goes here.. diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/axis2/DeleteDblookupDataMessage.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/axis2/DeleteDblookupDataMessage.java similarity index 93% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/axis2/DeleteDblookupDataMessage.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/axis2/DeleteDblookupDataMessage.java index 2ac9edc5..1dba452c 100644 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/axis2/DeleteDblookupDataMessage.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/axis2/DeleteDblookupDataMessage.java @@ -1,45 +1,43 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Wayne Chan - */ -package edu.harvard.i2b2.crc.axis2; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.pdo.query.DeleteDblookupType; -//import org.apache.commons.logging.Log; -//import org.apache.commons.logging.LogFactory; - -public class DeleteDblookupDataMessage extends RequestDataMessage { //swc20160523 - - //private static Log log = LogFactory.getLog(DeleteDblookupDataMessage.class); - - public DeleteDblookupDataMessage(String requestElementString) throws I2B2Exception { - super.setRequestMessageType(requestElementString); - } - - /** - * Function to get DeleteDblookupType object from i2b2 request message type - * @return - * @throws JAXBUtilException - */ - public DeleteDblookupType DeleteDblookupType() throws JAXBUtilException { - BodyType bodyType = reqMessageType.getMessageBody(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - DeleteDblookupType delDblookupType = (DeleteDblookupType) helper.getObjectByClass(bodyType.getAny(), DeleteDblookupType.class); - return delDblookupType; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Wayne Chan + */ +package edu.harvard.i2b2.crc.axis2; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.pdo.query.DeleteDblookupType; + +public class DeleteDblookupDataMessage extends RequestDataMessage { //swc20160523 + + //private static Log log = LogFactory.getLog(DeleteDblookupDataMessage.class); + + public DeleteDblookupDataMessage(String requestElementString) throws I2B2Exception { + super.setRequestMessageType(requestElementString); + } + + /** + * Function to get DeleteDblookupType object from i2b2 request message type + * @return + * @throws JAXBUtilException + */ + public DeleteDblookupType DeleteDblookupType() throws JAXBUtilException { + BodyType bodyType = reqMessageType.getMessageBody(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + DeleteDblookupType delDblookupType = (DeleteDblookupType) helper.getObjectByClass(bodyType.getAny(), DeleteDblookupType.class); + return delDblookupType; + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/axis2/ExecutorRunnable.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/axis2/ExecutorRunnable.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/axis2/ExecutorRunnable.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/axis2/ExecutorRunnable.java index 778a3de8..12b79f7e --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/axis2/ExecutorRunnable.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/axis2/ExecutorRunnable.java @@ -1,127 +1,127 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Raj Kuttan - * Lori Phillips - * Wayne Chan - */ -package edu.harvard.i2b2.crc.axis2; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import edu.harvard.i2b2.crc.delegate.DbLookupReqHandler; -import edu.harvard.i2b2.crc.delegate.JobReqHandler; -import edu.harvard.i2b2.crc.delegate.RPDOReqHandler; -import edu.harvard.i2b2.crc.delegate.RequestHandler; - -/** - * Implements thread runnable interface, to do CRC Dblookup - * processing using thread. - */ -public class ExecutorRunnable implements Runnable { - private static Log log = LogFactory.getLog(ExecutorRunnable.class); - private String inputString = null; - private String outputString = null; - private RequestHandler reqHandler = null; - private JobReqHandler jobHandler = null; - private DbLookupReqHandler dbluHdlr = null; - private RPDOReqHandler rpdoHandler = null; - private Exception ex = null; - private boolean jobCompleteFlag = false; - - public Exception getJobException() { - return ex; - } - - public boolean isJobCompleteFlag() { - return jobCompleteFlag; - } - - public void setJobCompleteFlag(boolean jobCompleteFlag) { - this.jobCompleteFlag = jobCompleteFlag; - } - - public void setJobException(Exception ex) { - this.ex = ex; - } - - public String getInputString() { - return inputString; - } - - public void setInputString(String inputString) { - this.inputString = inputString; - } - - public void setRequestHandler(RequestHandler handler) { - this.reqHandler = handler; - } - - public RequestHandler getRequestHandler() { - return this.reqHandler; - } - - public void setDbLookupReqHandler(DbLookupReqHandler handler) { - this.dbluHdlr = handler; - } - - public DbLookupReqHandler getDbLookupReqHandler() { - return this.dbluHdlr; - } - - public void setJobReqHandler(JobReqHandler handler) { - this.jobHandler = handler; - } - - public JobReqHandler getJobReqHandler() { - return this.jobHandler; - } - - public String getOutputString() { - return outputString; - } - - public void setOutputString(String outputString) { - this.outputString = outputString; - } - - @Override - public void run() { - try { - if (null != dbluHdlr) { - log.debug("about to run DbLookupReqHandler"); - outputString = dbluHdlr.execute().toString(); - } else if (null != reqHandler) { - log.debug("about to run RequestHandler"); - outputString = reqHandler.execute().toString(); - } else if (null != jobHandler) { - log.debug("about to run JobHandler"); - outputString = jobHandler.execute().toString(); - } else if (null != rpdoHandler) { - log.debug("about to run RPDOHandler"); - outputString = rpdoHandler.execute().toString(); - } - setJobCompleteFlag(true); - }catch (Exception e) { - setJobException(e); - } - } - - public RPDOReqHandler getRpdoHandler() { - return rpdoHandler; - } - - public void setRpdoHandler(RPDOReqHandler rpdoHandler) { - this.rpdoHandler = rpdoHandler; - } - - } +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Raj Kuttan + * Lori Phillips + * Wayne Chan + */ +package edu.harvard.i2b2.crc.axis2; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import edu.harvard.i2b2.crc.delegate.DbLookupReqHandler; +import edu.harvard.i2b2.crc.delegate.JobReqHandler; +import edu.harvard.i2b2.crc.delegate.RPDOReqHandler; +import edu.harvard.i2b2.crc.delegate.RequestHandler; + +/** + * Implements thread runnable interface, to do CRC Dblookup + * processing using thread. + */ +public class ExecutorRunnable implements Runnable { + private static Log log = LogFactory.getLog(ExecutorRunnable.class); + private String inputString = null; + private String outputString = null; + private RequestHandler reqHandler = null; + private JobReqHandler jobHandler = null; + private DbLookupReqHandler dbluHdlr = null; + private RPDOReqHandler rpdoHandler = null; + private Exception ex = null; + private boolean jobCompleteFlag = false; + + public Exception getJobException() { + return ex; + } + + public boolean isJobCompleteFlag() { + return jobCompleteFlag; + } + + public void setJobCompleteFlag(boolean jobCompleteFlag) { + this.jobCompleteFlag = jobCompleteFlag; + } + + public void setJobException(Exception ex) { + this.ex = ex; + } + + public String getInputString() { + return inputString; + } + + public void setInputString(String inputString) { + this.inputString = inputString; + } + + public void setRequestHandler(RequestHandler handler) { + this.reqHandler = handler; + } + + public RequestHandler getRequestHandler() { + return this.reqHandler; + } + + public void setDbLookupReqHandler(DbLookupReqHandler handler) { + this.dbluHdlr = handler; + } + + public DbLookupReqHandler getDbLookupReqHandler() { + return this.dbluHdlr; + } + + public void setJobReqHandler(JobReqHandler handler) { + this.jobHandler = handler; + } + + public JobReqHandler getJobReqHandler() { + return this.jobHandler; + } + + public String getOutputString() { + return outputString; + } + + public void setOutputString(String outputString) { + this.outputString = outputString; + } + + @Override + public void run() { + try { + if (null != dbluHdlr) { + log.debug("about to run DbLookupReqHandler"); + outputString = dbluHdlr.execute().toString(); + } else if (null != reqHandler) { + log.debug("about to run RequestHandler"); + outputString = reqHandler.execute().toString(); + } else if (null != jobHandler) { + log.debug("about to run JobHandler"); + outputString = jobHandler.execute().toString(); + } else if (null != rpdoHandler) { + log.debug("about to run RPDOHandler"); + outputString = rpdoHandler.execute().toString(); + } + setJobCompleteFlag(true); + }catch (Exception e) { + setJobException(e); + } + } + + public RPDOReqHandler getRpdoHandler() { + return rpdoHandler; + } + + public void setRpdoHandler(RPDOReqHandler rpdoHandler) { + this.rpdoHandler = rpdoHandler; + } + + } diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/axis2/GetAllDblookupsDataMessage.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/axis2/GetAllDblookupsDataMessage.java similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/axis2/GetAllDblookupsDataMessage.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/axis2/GetAllDblookupsDataMessage.java index 03c8f629..a34f0a5b 100644 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/axis2/GetAllDblookupsDataMessage.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/axis2/GetAllDblookupsDataMessage.java @@ -1,46 +1,46 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Wayne Chan - */ -package edu.harvard.i2b2.crc.axis2; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.pdo.query.DblookupsType; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -public class GetAllDblookupsDataMessage extends RequestDataMessage { //swc20160523 - - private static Log log = LogFactory.getLog(GetAllDblookupsDataMessage.class); - - public GetAllDblookupsDataMessage(String requestElementString) throws I2B2Exception { - super.setRequestMessageType(requestElementString); - } - - /** - * Function to get DblookupsType object from i2b2 request message type - * @return - * @throws JAXBUtilException - */ - public DblookupsType getDblookupsType() throws JAXBUtilException { - //log.info(" getDblookupsType()"); - BodyType bodyType = reqMessageType.getMessageBody(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - DblookupsType dblookupsType = (DblookupsType) helper.getObjectByClass(bodyType.getAny(), DblookupsType.class); - return dblookupsType; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Wayne Chan + */ +package edu.harvard.i2b2.crc.axis2; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.pdo.query.DblookupsType; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +public class GetAllDblookupsDataMessage extends RequestDataMessage { //swc20160523 + + private static Log log = LogFactory.getLog(GetAllDblookupsDataMessage.class); + + public GetAllDblookupsDataMessage(String requestElementString) throws I2B2Exception { + super.setRequestMessageType(requestElementString); + } + + /** + * Function to get DblookupsType object from i2b2 request message type + * @return + * @throws JAXBUtilException + */ + public DblookupsType getDblookupsType() throws JAXBUtilException { + //log.info(" getDblookupsType()"); + BodyType bodyType = reqMessageType.getMessageBody(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + DblookupsType dblookupsType = (DblookupsType) helper.getObjectByClass(bodyType.getAny(), DblookupsType.class); + return dblookupsType; + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/axis2/GetAllJobsDataMessage.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/axis2/GetAllJobsDataMessage.java similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/axis2/GetAllJobsDataMessage.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/axis2/GetAllJobsDataMessage.java index 870df7f3..45f6e40e 100644 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/axis2/GetAllJobsDataMessage.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/axis2/GetAllJobsDataMessage.java @@ -1,48 +1,48 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Wayne Chan - */ -package edu.harvard.i2b2.crc.axis2; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -//import edu.harvard.i2b2.crc.datavo.pdo.query.DblookupsType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.JobsType; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -public class GetAllJobsDataMessage extends RequestDataMessage { - - private static Log log = LogFactory.getLog(GetAllJobsDataMessage.class); - - public GetAllJobsDataMessage(String requestElementString) throws I2B2Exception { - super.setRequestMessageType(requestElementString); - } - - /** - * Function to get jbosType object from i2b2 request message type - * @return - * @throws JAXBUtilException - */ - public JobsType getJobsType() throws JAXBUtilException { - //log.info(" getDblookupsType()"); - BodyType bodyType = reqMessageType.getMessageBody(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - JobsType jobsType = (JobsType) helper.getObjectByClass(bodyType.getAny(), JobsType.class); - return jobsType; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Wayne Chan + */ +package edu.harvard.i2b2.crc.axis2; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +//import edu.harvard.i2b2.crc.datavo.pdo.query.DblookupsType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.JobsType; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +public class GetAllJobsDataMessage extends RequestDataMessage { + + private static Log log = LogFactory.getLog(GetAllJobsDataMessage.class); + + public GetAllJobsDataMessage(String requestElementString) throws I2B2Exception { + super.setRequestMessageType(requestElementString); + } + + /** + * Function to get jbosType object from i2b2 request message type + * @return + * @throws JAXBUtilException + */ + public JobsType getJobsType() throws JAXBUtilException { + //log.info(" getDblookupsType()"); + BodyType bodyType = reqMessageType.getMessageBody(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + JobsType jobsType = (JobsType) helper.getObjectByClass(bodyType.getAny(), JobsType.class); + return jobsType; + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/axis2/GetAllRPDOsDataMessage.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/axis2/GetAllRPDOsDataMessage.java similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/axis2/GetAllRPDOsDataMessage.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/axis2/GetAllRPDOsDataMessage.java index 80391f94..232c91ca 100644 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/axis2/GetAllRPDOsDataMessage.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/axis2/GetAllRPDOsDataMessage.java @@ -1,47 +1,47 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Mike Mendis - */ -package edu.harvard.i2b2.crc.axis2; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.pdo.query.RpdosType; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -public class GetAllRPDOsDataMessage extends RequestDataMessage { //swc20160523 - - private static Log log = LogFactory.getLog(GetAllRPDOsDataMessage.class); - String requestElementString = null; - public GetAllRPDOsDataMessage(String requestElementStr) throws I2B2Exception { - super.setRequestMessageType(requestElementStr); - requestElementString = requestElementStr; - } - - /** - * Function to get DblookupsType object from i2b2 request message type - * @return - * @throws JAXBUtilException - */ - public RpdosType getRPDOTablesType() throws JAXBUtilException { - //log.info(" getDblookupsType()"); - BodyType bodyType = reqMessageType.getMessageBody(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - RpdosType rpdotableType = (RpdosType) helper.getObjectByClass(bodyType.getAny(), RpdosType.class); - return rpdotableType; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Mike Mendis + */ +package edu.harvard.i2b2.crc.axis2; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.pdo.query.RpdosType; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +public class GetAllRPDOsDataMessage extends RequestDataMessage { //swc20160523 + + private static Log log = LogFactory.getLog(GetAllRPDOsDataMessage.class); + String requestElementString = null; + public GetAllRPDOsDataMessage(String requestElementStr) throws I2B2Exception { + super.setRequestMessageType(requestElementStr); + requestElementString = requestElementStr; + } + + /** + * Function to get DblookupsType object from i2b2 request message type + * @return + * @throws JAXBUtilException + */ + public RpdosType getRPDOTablesType() throws JAXBUtilException { + //log.info(" getDblookupsType()"); + BodyType bodyType = reqMessageType.getMessageBody(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + RpdosType rpdotableType = (RpdosType) helper.getObjectByClass(bodyType.getAny(), RpdosType.class); + return rpdotableType; + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/axis2/GetDblookupDataMessage.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/axis2/GetDblookupDataMessage.java similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/axis2/GetDblookupDataMessage.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/axis2/GetDblookupDataMessage.java index c9f95235..d003aa7a 100644 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/axis2/GetDblookupDataMessage.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/axis2/GetDblookupDataMessage.java @@ -1,45 +1,45 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Wayne Chan - */ -package edu.harvard.i2b2.crc.axis2; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.pdo.query.GetDblookupType; -//import org.apache.commons.logging.Log; -//import org.apache.commons.logging.LogFactory; - -public class GetDblookupDataMessage extends RequestDataMessage { //swc20160523 - - //private static Log log = LogFactory.getLog(GetDblookupDataMessage.class); - - public GetDblookupDataMessage(String requestElementString) throws I2B2Exception { - super.setRequestMessageType(requestElementString); - } - - /** - * Function to get GetDblookupType object from i2b2 request message type - * @return - * @throws JAXBUtilException - */ - public GetDblookupType getDblookupType() throws JAXBUtilException { - BodyType bodyType = reqMessageType.getMessageBody(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - GetDblookupType getdblookupType = (GetDblookupType) helper.getObjectByClass(bodyType.getAny(), GetDblookupType.class); - return getdblookupType; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Wayne Chan + */ +package edu.harvard.i2b2.crc.axis2; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.pdo.query.GetDblookupType; +//import org.apache.commons.logging.Log; +//import org.apache.commons.logging.LogFactory; + +public class GetDblookupDataMessage extends RequestDataMessage { //swc20160523 + + //private static Log log = LogFactory.getLog(GetDblookupDataMessage.class); + + public GetDblookupDataMessage(String requestElementString) throws I2B2Exception { + super.setRequestMessageType(requestElementString); + } + + /** + * Function to get GetDblookupType object from i2b2 request message type + * @return + * @throws JAXBUtilException + */ + public GetDblookupType getDblookupType() throws JAXBUtilException { + BodyType bodyType = reqMessageType.getMessageBody(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + GetDblookupType getdblookupType = (GetDblookupType) helper.getObjectByClass(bodyType.getAny(), GetDblookupType.class); + return getdblookupType; + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/axis2/GetRPDODataMessage.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/axis2/GetRPDODataMessage.java similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/axis2/GetRPDODataMessage.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/axis2/GetRPDODataMessage.java index 969dc07d..6b07eaf6 100644 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/axis2/GetRPDODataMessage.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/axis2/GetRPDODataMessage.java @@ -1,51 +1,51 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Mike Mendis - */ -package edu.harvard.i2b2.crc.axis2; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.pdo.query.RpdosType; -import edu.harvard.i2b2.crc.datavo.pdo.query.RpdoType; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -public class GetRPDODataMessage extends RequestDataMessage { //swc20160523 - - private static Log log = LogFactory.getLog(GetRPDODataMessage.class); - String requestElementString = null; - public GetRPDODataMessage(String requestElementStr) throws I2B2Exception { - super.setRequestMessageType(requestElementStr); - requestElementString = requestElementStr; - } - - /** - * Function to get DblookupsType object from i2b2 request message type - * @return - * @throws JAXBUtilException - */ - public RpdoType getRPDOTType() throws JAXBUtilException { - //log.info(" getDblookupsType()"); - BodyType bodyType = reqMessageType.getMessageBody(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - // RpdoType rpdotable = (RpdoType) helper.getObjectByClass(bodyType.getAny(), RpdoType.class); - RpdosType rpdotableType = (RpdosType) helper.getObjectByClass(bodyType.getAny(), RpdosType.class); - if (rpdotableType != null) - return rpdotableType.getRpdo().get(0); - return null; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Mike Mendis + */ +package edu.harvard.i2b2.crc.axis2; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.pdo.query.RpdosType; +import edu.harvard.i2b2.crc.datavo.pdo.query.RpdoType; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +public class GetRPDODataMessage extends RequestDataMessage { //swc20160523 + + private static Log log = LogFactory.getLog(GetRPDODataMessage.class); + String requestElementString = null; + public GetRPDODataMessage(String requestElementStr) throws I2B2Exception { + super.setRequestMessageType(requestElementStr); + requestElementString = requestElementStr; + } + + /** + * Function to get DblookupsType object from i2b2 request message type + * @return + * @throws JAXBUtilException + */ + public RpdoType getRPDOTType() throws JAXBUtilException { + //log.info(" getDblookupsType()"); + BodyType bodyType = reqMessageType.getMessageBody(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + // RpdoType rpdotable = (RpdoType) helper.getObjectByClass(bodyType.getAny(), RpdoType.class); + RpdosType rpdotableType = (RpdosType) helper.getObjectByClass(bodyType.getAny(), RpdosType.class); + if (rpdotableType != null) + return rpdotableType.getRpdo().get(0); + return null; + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/axis2/MessageFactory.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/axis2/MessageFactory.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/axis2/MessageFactory.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/axis2/MessageFactory.java index b1c23a56..9e6eff37 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/axis2/MessageFactory.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/axis2/MessageFactory.java @@ -1,501 +1,501 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Raj Kuttan - * Lori Phillips - * Wayne Chan - */ -package edu.harvard.i2b2.crc.axis2; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.DTOFactory; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.i2b2message.ApplicationType; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2message.FacilityType; -import edu.harvard.i2b2.crc.datavo.i2b2message.MessageControlIdType; -import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ProcessingIdType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResultStatusType; -import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; -import edu.harvard.i2b2.crc.datavo.pdo.query.PdoRequestTypeType; -import edu.harvard.i2b2.crc.datavo.pdo.query.RpdosType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.JobsType; -//import edu.harvard.i2b2.crc.datavo.wdo.AuditsType; -import edu.harvard.i2b2.crc.datavo.pdo.query.DblookupsType; -//import edu.harvard.i2b2.crc.datavo.wdo.IsKeySetType; -import edu.harvard.i2b2.crc.datavo.pdo.query.ObjectFactory; - -//import org.apache.axiom.om.OMAbstractFactory; -import org.apache.axiom.om.OMElement; -import org.apache.axiom.om.OMXMLBuilderFactory; -//import org.apache.axiom.om.OMFactory; -//import org.apache.axiom.om.OMNamespace; -//import org.apache.axis2.AxisFault; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.io.StringReader; -import java.io.StringWriter; - -import java.math.BigDecimal; - -import java.util.Date; - -//import javax.xml.stream.FactoryConfigurationError; -import javax.xml.stream.XMLInputFactory; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamReader; - - -/** - * Factory class to create request/response message objects. - * - */ -public class MessageFactory { - private static Log log = LogFactory.getLog(MessageFactory.class); - - /** - * Function creates Workplace response OMElement from xml string - * @param xmlString - * @return OMElement - * @throws XMLStreamException - */ - public static OMElement createResponseOMElementFromString(String xmlString) - throws I2B2Exception { - OMElement returnElement = null; - - try { - StringReader strReader = new StringReader(xmlString); - XMLInputFactory xif = XMLInputFactory.newInstance(); - XMLStreamReader reader = xif.createXMLStreamReader(strReader); - - //StAXOMBuilder builder = new StAXOMBuilder(reader); - returnElement = OMXMLBuilderFactory.createStAXOMBuilder(reader).getDocumentElement(); - - } catch (XMLStreamException e) { - log.error("xml stream response PDO to OMElement"); - throw new I2B2Exception("XML Stream error ", e); - } catch (Exception e) { - log.error("Error while converting CRC response PDO to OMElement"); - throw new I2B2Exception("Response OMElement creation error ", e); - } - return returnElement; - } - - - - /** - * Function to build workplaceData body type - * - * @param obsSet - * Observation fact set to be returned to requester - * @return BodyType object - */ - - public static BodyType createBodyType(PdoRequestTypeType workplaceData) { - -// edu.harvard.i2b2.im.datavo.pdo.query.ObjectFactory of = new edu.harvard.i2b2.im.datavo.pdo.query.ObjectFactory(); - BodyType bodyType = new BodyType(); - //MM bodyType.getAny().add(of..createFolders(workplaceData)); - - return bodyType; - } - - - -// private static BodyType createBodyType(AuditsType patientDataType) { -// -// edu.harvard.i2b2.im.datavo.wdo.ObjectFactory of = new edu.harvard.i2b2.im.datavo.wdo.ObjectFactory(); -// BodyType bodyType = new BodyType(); -// bodyType.getAny().add(of.createAudits(patientDataType)); -// -// return bodyType; -// } -// -// public static BodyType createBodyType(IsKeySetType workplaceData) { -// -// edu.harvard.i2b2.im.datavo.wdo.ObjectFactory of = new edu.harvard.i2b2.im.datavo.wdo.ObjectFactory(); -// BodyType bodyType = new BodyType(); -// bodyType.getAny().add(of.createKeySet(workplaceData)); -// -// return bodyType; -// } - -// public static BodyType createBodyType(String workplaceData) { -// -//// edu.harvard.i2b2.im.datavo.pdo.query.ObjectFactory of = new edu.harvard.i2b2.im.datavo.pdo.query.ObjectFactory(); -// BodyType bodyType = new BodyType(); -////MM bodyType.getAny().add(of.createRequestXML(workplaceData)); // createFolders(workplaceData)); -// -// return bodyType; -// } - - - /**swc20160520 - * Function to build concepts body type - * - * @param dblookups - * Concept set to be returned to requester - * @return BodyType object - */ - public static BodyType createBodyType(DblookupsType dblookups) { -// edu.harvard.i2b2.im.datavo.wdo.ObjectFactory of = new edu.harvard.i2b2.im.datavo.wdo.ObjectFactory(); - ObjectFactory of = new ObjectFactory(); - BodyType bodyType = new BodyType(); - bodyType.getAny().add(of.createDblookups(dblookups)); - - return bodyType; - } - - public static BodyType createBodyType(RpdosType dblookups) { -// edu.harvard.i2b2.im.datavo.wdo.ObjectFactory of = new edu.harvard.i2b2.im.datavo.wdo.ObjectFactory(); - ObjectFactory of = new ObjectFactory(); - BodyType bodyType = new BodyType(); - bodyType.getAny().add(of.createRpdos(dblookups)); - - return bodyType; - } - - public static BodyType createBodyType(JobsType dblookups) { -// edu.harvard.i2b2.im.datavo.wdo.ObjectFactory of = new edu.harvard.i2b2.im.datavo.wdo.ObjectFactory(); - edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); - BodyType bodyType = new BodyType(); - bodyType.getAny().add(of.createJobs(dblookups)); - - return bodyType; - } - - /** - * Function to create response message header based - * on request message header - * - * @return MessageHeader object - */ - public static MessageHeaderType createResponseMessageHeader(MessageHeaderType reqMsgHeader) { - MessageHeaderType messageHeader = new MessageHeaderType(); - - messageHeader.setI2B2VersionCompatible(new BigDecimal("1.1")); - messageHeader.setHl7VersionCompatible(new BigDecimal("2.4")); - - ApplicationType appType = new ApplicationType(); - appType.setApplicationName("CRC Cell"); - appType.setApplicationVersion("1.700"); - messageHeader.setSendingApplication(appType); - - FacilityType facility = new FacilityType(); - facility.setFacilityName("i2b2 Hive"); - messageHeader.setSendingFacility(facility); - - if (reqMsgHeader != null) { - ApplicationType recvApp = new ApplicationType(); - recvApp.setApplicationName(reqMsgHeader.getSendingApplication().getApplicationName()); - recvApp.setApplicationVersion(reqMsgHeader.getSendingApplication().getApplicationVersion()); - messageHeader.setReceivingApplication(recvApp); - - FacilityType recvFac = new FacilityType(); - recvFac.setFacilityName(reqMsgHeader.getSendingFacility().getFacilityName()); - messageHeader.setReceivingFacility(recvFac); - - messageHeader.setSecurity(reqMsgHeader.getSecurity()); - } - - Date currentDate = new Date(); - DTOFactory factory = new DTOFactory(); - messageHeader.setDatetimeOfMessage(factory.getXMLGregorianCalendar( - currentDate.getTime())); - - MessageControlIdType mcIdType = new MessageControlIdType(); - mcIdType.setInstanceNum(1); - - if (reqMsgHeader != null) { - if (reqMsgHeader.getMessageControlId() != null) { - mcIdType.setMessageNum(reqMsgHeader.getMessageControlId() - .getMessageNum()); - mcIdType.setSessionId(reqMsgHeader.getMessageControlId() - .getSessionId()); - } - } - - messageHeader.setMessageControlId(mcIdType); - - ProcessingIdType proc = new ProcessingIdType(); - proc.setProcessingId("P"); - proc.setProcessingMode("I"); - messageHeader.setProcessingId(proc); - - messageHeader.setAcceptAcknowledgementType("AL"); - messageHeader.setApplicationAcknowledgementType("AL"); - messageHeader.setCountryCode("US"); - if (reqMsgHeader != null) { - messageHeader.setProjectId(reqMsgHeader.getProjectId()); - } - return messageHeader; - } - - /** - * Function to create response message type - * @param messageHeader - * @param respHeader - * @param bodyType - * @return ResponseMessageType - */ - public static ResponseMessageType createResponseMessageType( - MessageHeaderType messageHeader, ResponseHeaderType respHeader, - BodyType bodyType) { - ResponseMessageType respMsgType = new ResponseMessageType(); - respMsgType.setMessageHeader(messageHeader); - respMsgType.setMessageBody(bodyType); - respMsgType.setResponseHeader(respHeader); - - return respMsgType; - } - - /** - * Function to convert ResponseMessageType to string - * @param respMessageType - * @return String - * @throws Exception - */ - public static String convertToXMLString(ResponseMessageType respMessageType) - throws I2B2Exception { - StringWriter strWriter = null; - - try { - strWriter = new StringWriter(); - - edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory objectFactory = new edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory(); - // CRCJAXBUtil.getJAXBUtil().marshaller(objectFactory.createResponse(respMessageType), - // strWriter); - - CRCJAXBUtil.getJAXBUtil().marshallerWithCDATA(objectFactory.createResponse(respMessageType), - strWriter, new String[]{"data"}, true); - } catch (JAXBUtilException e) { - log.error(e.getMessage()); - throw new I2B2Exception("Error converting response message type to string " + e.getMessage(), e); - } - - return strWriter.toString(); - } - - /** - * Function to build Response message type and return it as an XML string - * - * @param folders The set of Workplace folders that match request - * - * @return A String data type containing the ResponseMessage in XML format - * @throws Exception - */ - public static ResponseMessageType createBuildResponsePdo( - MessageHeaderType messageHeaderType, - PdoRequestTypeType folders) { - ResponseMessageType respMessageType = null; - BodyType bodyType = null; - - ResponseHeaderType respHeader = createResponseHeader("DONE", "CRC processing completed"); - if(folders != null) - bodyType = createBodyType(folders); - - // else - // log.error("creating response with null body type "); - - respMessageType = createResponseMessageType(messageHeaderType, respHeader, - bodyType); - - return respMessageType; - } - -// public static ResponseMessageType createBuildResponseKeySet( -// MessageHeaderType messageHeaderType, -// IsKeySetType folders) { -// ResponseMessageType respMessageType = null; -// BodyType bodyType = null; -// -// ResponseHeaderType respHeader = createResponseHeader("DONE", -// "CRC processing completed"); -// if(folders != null) -// bodyType = createBodyType(folders); -// -// // else -// // log.error("creating response with null body type "); -// -// respMessageType = createResponseMessageType(messageHeaderType, respHeader, -// bodyType); -// -// return respMessageType; -// } - - -// public static ResponseMessageType createBuildResponseRequestXML( -// MessageHeaderType messageHeaderType, -// String folders) { -// ResponseMessageType respMessageType = null; -// BodyType bodyType = null; -// -// ResponseHeaderType respHeader = createResponseHeader("DONE", -// "CRC processing completed"); -// if(folders != null) -// bodyType = createBodyType(folders); -// -// -// respMessageType = createResponseMessageType(messageHeaderType, respHeader, -// bodyType); -// -// return respMessageType; -// } - - - /**swc20160520 - * Function to build Response message type and return it as an XML string - * - * @param dblookups - * The set of i2b2hive.work_db_lookup entries, per request - * - * @return A String data type containing the ResponseMessage in XML format - * @throws Exception - */ - public static ResponseMessageType createBuildResponse(MessageHeaderType messageHeaderType, DblookupsType dblookups) { - ResponseMessageType respMessageType = null; - ResponseHeaderType respHeader = createResponseHeader("DONE", "CRC processing completed"); - BodyType bodyType = createBodyType(dblookups); - respMessageType = createResponseMessageType(messageHeaderType, respHeader, bodyType); - return respMessageType; - } - - public static ResponseMessageType createBuildResponse(MessageHeaderType messageHeaderType, RpdosType dblookups) { - ResponseMessageType respMessageType = null; - ResponseHeaderType respHeader = createResponseHeader("DONE", "CRC processing completed"); - BodyType bodyType = createBodyType(dblookups); - respMessageType = createResponseMessageType(messageHeaderType, respHeader, bodyType); - return respMessageType; - } - - public static ResponseMessageType createBuildResponse(MessageHeaderType messageHeaderType, JobsType dblus) { - ResponseMessageType respMessageType = null; - ResponseHeaderType respHeader = createResponseHeader("DONE", "CRC processing completed"); - BodyType bodyType = createBodyType(dblus); - respMessageType = createResponseMessageType(messageHeaderType, respHeader, bodyType); - return respMessageType; - } - - /**swc20160520 - * Function to build Response message type and return it as an XML string - * - * @return A String data type containing the ResponseMessage in XML format - * @throws Exception - */ - public static ResponseMessageType createBuildResponse(MessageHeaderType messageHeaderType) { - ResponseMessageType respMessageType = null; - ResponseHeaderType respHeader = createResponseHeader("DONE", "CRC processing completed"); - respMessageType = createResponseMessageType(messageHeaderType, respHeader, null); - return respMessageType; - } - - /**swc20160520 - * Function to build 'Non Standard' Response message and return it as an XML string - * - * @param messageHeaderType - * @param msg - * - * @return A String data type containing the ResponseMessage in XML format - * @throws Exception - */ - public static ResponseMessageType createNonStandardResponse(MessageHeaderType messageHeaderType, String msg) { - ResponseMessageType respMessageType = null; - ResponseHeaderType respHeader = createResponseHeader("DONE", msg + " - CRC processing completed"); - respMessageType = createResponseMessageType(messageHeaderType, respHeader, null); - return respMessageType; - } - - - /** - * Function to get i2b2 Request message header - * - * @return RequestHeader object - */ - public static RequestHeaderType getRequestHeader() { - RequestHeaderType reqHeader = new RequestHeaderType(); - reqHeader.setResultWaittimeMs(120000); - - return reqHeader; - } - - /** - * Function to create Response with given error message - * @param messageHeaderType - * @param errorMessage - * @return - * @throws Exception - */ - public static ResponseMessageType doBuildErrorResponse( - MessageHeaderType messageHeaderType, String errorMessage) { - ResponseMessageType respMessageType = null; - - MessageHeaderType messageHeader = createResponseMessageHeader(messageHeaderType); - ResponseHeaderType respHeader = createResponseHeader("ERROR", - errorMessage); - respMessageType = createResponseMessageType(messageHeader, respHeader, - null); - - return respMessageType; - } - - /** - * Creates ResponseHeader for the given type and value - * @param type - * @param value - * @return - */ - private static ResponseHeaderType createResponseHeader(String type, - String value) { - ResponseHeaderType respHeader = new ResponseHeaderType(); - StatusType status = new StatusType(); - status.setType(type); - status.setValue(value); - - ResultStatusType resStat = new ResultStatusType(); - resStat.setStatus(status); - respHeader.setResultStatus(resStat); - - return respHeader; - } - - - -// public static ResponseMessageType createBuildResponseAudits( -// MessageHeaderType messageHeader, AuditsType patientDataType) { -// -// ResponseMessageType respMessageType = null; -// BodyType bodyType = null; -// -// ResponseHeaderType respHeader = createResponseHeader("DONE", -// "CRC processing completed"); -// if(patientDataType != null) -// bodyType = createBodyType(patientDataType); -// -// // else -// // log.error("creating response with null body type "); -// -// respMessageType = createResponseMessageType(messageHeader, respHeader, -// bodyType); -// -// return respMessageType; -// -// } - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Raj Kuttan + * Lori Phillips + * Wayne Chan + */ +package edu.harvard.i2b2.crc.axis2; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.DTOFactory; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; +import edu.harvard.i2b2.crc.datavo.i2b2message.ApplicationType; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2message.FacilityType; +import edu.harvard.i2b2.crc.datavo.i2b2message.MessageControlIdType; +import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ProcessingIdType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResultStatusType; +import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; +import edu.harvard.i2b2.crc.datavo.pdo.query.PdoRequestTypeType; +import edu.harvard.i2b2.crc.datavo.pdo.query.RpdosType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.JobsType; +//import edu.harvard.i2b2.crc.datavo.wdo.AuditsType; +import edu.harvard.i2b2.crc.datavo.pdo.query.DblookupsType; +//import edu.harvard.i2b2.crc.datavo.wdo.IsKeySetType; +import edu.harvard.i2b2.crc.datavo.pdo.query.ObjectFactory; + +//import org.apache.axiom.om.OMAbstractFactory; +import org.apache.axiom.om.OMElement; +import org.apache.axiom.om.OMXMLBuilderFactory; +//import org.apache.axiom.om.OMFactory; +//import org.apache.axiom.om.OMNamespace; +//import org.apache.axis2.AxisFault; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.io.StringReader; +import java.io.StringWriter; + +import java.math.BigDecimal; + +import java.util.Date; + +//import javax.xml.stream.FactoryConfigurationError; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + + +/** + * Factory class to create request/response message objects. + * + */ +public class MessageFactory { + private static Log log = LogFactory.getLog(MessageFactory.class); + + /** + * Function creates Workplace response OMElement from xml string + * @param xmlString + * @return OMElement + * @throws XMLStreamException + */ + public static OMElement createResponseOMElementFromString(String xmlString) + throws I2B2Exception { + OMElement returnElement = null; + + try { + StringReader strReader = new StringReader(xmlString); + XMLInputFactory xif = XMLInputFactory.newInstance(); + XMLStreamReader reader = xif.createXMLStreamReader(strReader); + + //StAXOMBuilder builder = new StAXOMBuilder(reader); + returnElement = OMXMLBuilderFactory.createStAXOMBuilder(reader).getDocumentElement(); + + } catch (XMLStreamException e) { + log.error("xml stream response PDO to OMElement"); + throw new I2B2Exception("XML Stream error ", e); + } catch (Exception e) { + log.error("Error while converting CRC response PDO to OMElement"); + throw new I2B2Exception("Response OMElement creation error ", e); + } + return returnElement; + } + + + + /** + * Function to build workplaceData body type + * + * @param obsSet + * Observation fact set to be returned to requester + * @return BodyType object + */ + + public static BodyType createBodyType(PdoRequestTypeType workplaceData) { + +// edu.harvard.i2b2.im.datavo.pdo.query.ObjectFactory of = new edu.harvard.i2b2.im.datavo.pdo.query.ObjectFactory(); + BodyType bodyType = new BodyType(); + //MM bodyType.getAny().add(of..createFolders(workplaceData)); + + return bodyType; + } + + + +// private static BodyType createBodyType(AuditsType patientDataType) { +// +// edu.harvard.i2b2.im.datavo.wdo.ObjectFactory of = new edu.harvard.i2b2.im.datavo.wdo.ObjectFactory(); +// BodyType bodyType = new BodyType(); +// bodyType.getAny().add(of.createAudits(patientDataType)); +// +// return bodyType; +// } +// +// public static BodyType createBodyType(IsKeySetType workplaceData) { +// +// edu.harvard.i2b2.im.datavo.wdo.ObjectFactory of = new edu.harvard.i2b2.im.datavo.wdo.ObjectFactory(); +// BodyType bodyType = new BodyType(); +// bodyType.getAny().add(of.createKeySet(workplaceData)); +// +// return bodyType; +// } + +// public static BodyType createBodyType(String workplaceData) { +// +//// edu.harvard.i2b2.im.datavo.pdo.query.ObjectFactory of = new edu.harvard.i2b2.im.datavo.pdo.query.ObjectFactory(); +// BodyType bodyType = new BodyType(); +////MM bodyType.getAny().add(of.createRequestXML(workplaceData)); // createFolders(workplaceData)); +// +// return bodyType; +// } + + + /**swc20160520 + * Function to build concepts body type + * + * @param dblookups + * Concept set to be returned to requester + * @return BodyType object + */ + public static BodyType createBodyType(DblookupsType dblookups) { +// edu.harvard.i2b2.im.datavo.wdo.ObjectFactory of = new edu.harvard.i2b2.im.datavo.wdo.ObjectFactory(); + ObjectFactory of = new ObjectFactory(); + BodyType bodyType = new BodyType(); + bodyType.getAny().add(of.createDblookups(dblookups)); + + return bodyType; + } + + public static BodyType createBodyType(RpdosType dblookups) { +// edu.harvard.i2b2.im.datavo.wdo.ObjectFactory of = new edu.harvard.i2b2.im.datavo.wdo.ObjectFactory(); + ObjectFactory of = new ObjectFactory(); + BodyType bodyType = new BodyType(); + bodyType.getAny().add(of.createRpdos(dblookups)); + + return bodyType; + } + + public static BodyType createBodyType(JobsType dblookups) { +// edu.harvard.i2b2.im.datavo.wdo.ObjectFactory of = new edu.harvard.i2b2.im.datavo.wdo.ObjectFactory(); + edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); + BodyType bodyType = new BodyType(); + bodyType.getAny().add(of.createJobs(dblookups)); + + return bodyType; + } + + /** + * Function to create response message header based + * on request message header + * + * @return MessageHeader object + */ + public static MessageHeaderType createResponseMessageHeader(MessageHeaderType reqMsgHeader) { + MessageHeaderType messageHeader = new MessageHeaderType(); + + messageHeader.setI2B2VersionCompatible(new BigDecimal("1.1")); + messageHeader.setHl7VersionCompatible(new BigDecimal("2.4")); + + ApplicationType appType = new ApplicationType(); + appType.setApplicationName("CRC Cell"); + appType.setApplicationVersion("1.700"); + messageHeader.setSendingApplication(appType); + + FacilityType facility = new FacilityType(); + facility.setFacilityName("i2b2 Hive"); + messageHeader.setSendingFacility(facility); + + if (reqMsgHeader != null) { + ApplicationType recvApp = new ApplicationType(); + recvApp.setApplicationName(reqMsgHeader.getSendingApplication().getApplicationName()); + recvApp.setApplicationVersion(reqMsgHeader.getSendingApplication().getApplicationVersion()); + messageHeader.setReceivingApplication(recvApp); + + FacilityType recvFac = new FacilityType(); + recvFac.setFacilityName(reqMsgHeader.getSendingFacility().getFacilityName()); + messageHeader.setReceivingFacility(recvFac); + + messageHeader.setSecurity(reqMsgHeader.getSecurity()); + } + + Date currentDate = new Date(); + DTOFactory factory = new DTOFactory(); + messageHeader.setDatetimeOfMessage(factory.getXMLGregorianCalendar( + currentDate.getTime())); + + MessageControlIdType mcIdType = new MessageControlIdType(); + mcIdType.setInstanceNum(1); + + if (reqMsgHeader != null) { + if (reqMsgHeader.getMessageControlId() != null) { + mcIdType.setMessageNum(reqMsgHeader.getMessageControlId() + .getMessageNum()); + mcIdType.setSessionId(reqMsgHeader.getMessageControlId() + .getSessionId()); + } + } + + messageHeader.setMessageControlId(mcIdType); + + ProcessingIdType proc = new ProcessingIdType(); + proc.setProcessingId("P"); + proc.setProcessingMode("I"); + messageHeader.setProcessingId(proc); + + messageHeader.setAcceptAcknowledgementType("AL"); + messageHeader.setApplicationAcknowledgementType("AL"); + messageHeader.setCountryCode("US"); + if (reqMsgHeader != null) { + messageHeader.setProjectId(reqMsgHeader.getProjectId()); + } + return messageHeader; + } + + /** + * Function to create response message type + * @param messageHeader + * @param respHeader + * @param bodyType + * @return ResponseMessageType + */ + public static ResponseMessageType createResponseMessageType( + MessageHeaderType messageHeader, ResponseHeaderType respHeader, + BodyType bodyType) { + ResponseMessageType respMsgType = new ResponseMessageType(); + respMsgType.setMessageHeader(messageHeader); + respMsgType.setMessageBody(bodyType); + respMsgType.setResponseHeader(respHeader); + + return respMsgType; + } + + /** + * Function to convert ResponseMessageType to string + * @param respMessageType + * @return String + * @throws Exception + */ + public static String convertToXMLString(ResponseMessageType respMessageType) + throws I2B2Exception { + StringWriter strWriter = null; + + try { + strWriter = new StringWriter(); + + edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory objectFactory = new edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory(); + // CRCJAXBUtil.getJAXBUtil().marshaller(objectFactory.createResponse(respMessageType), + // strWriter); + + CRCJAXBUtil.getJAXBUtil().marshallerWithCDATA(objectFactory.createResponse(respMessageType), + strWriter, new String[]{"data"}, true); + } catch (JAXBUtilException e) { + log.error(e.getMessage()); + throw new I2B2Exception("Error converting response message type to string " + e.getMessage(), e); + } + + return strWriter.toString(); + } + + /** + * Function to build Response message type and return it as an XML string + * + * @param folders The set of Workplace folders that match request + * + * @return A String data type containing the ResponseMessage in XML format + * @throws Exception + */ + public static ResponseMessageType createBuildResponsePdo( + MessageHeaderType messageHeaderType, + PdoRequestTypeType folders) { + ResponseMessageType respMessageType = null; + BodyType bodyType = null; + + ResponseHeaderType respHeader = createResponseHeader("DONE", "CRC processing completed"); + if(folders != null) + bodyType = createBodyType(folders); + + // else + // log.error("creating response with null body type "); + + respMessageType = createResponseMessageType(messageHeaderType, respHeader, + bodyType); + + return respMessageType; + } + +// public static ResponseMessageType createBuildResponseKeySet( +// MessageHeaderType messageHeaderType, +// IsKeySetType folders) { +// ResponseMessageType respMessageType = null; +// BodyType bodyType = null; +// +// ResponseHeaderType respHeader = createResponseHeader("DONE", +// "CRC processing completed"); +// if(folders != null) +// bodyType = createBodyType(folders); +// +// // else +// // log.error("creating response with null body type "); +// +// respMessageType = createResponseMessageType(messageHeaderType, respHeader, +// bodyType); +// +// return respMessageType; +// } + + +// public static ResponseMessageType createBuildResponseRequestXML( +// MessageHeaderType messageHeaderType, +// String folders) { +// ResponseMessageType respMessageType = null; +// BodyType bodyType = null; +// +// ResponseHeaderType respHeader = createResponseHeader("DONE", +// "CRC processing completed"); +// if(folders != null) +// bodyType = createBodyType(folders); +// +// +// respMessageType = createResponseMessageType(messageHeaderType, respHeader, +// bodyType); +// +// return respMessageType; +// } + + + /**swc20160520 + * Function to build Response message type and return it as an XML string + * + * @param dblookups + * The set of i2b2hive.work_db_lookup entries, per request + * + * @return A String data type containing the ResponseMessage in XML format + * @throws Exception + */ + public static ResponseMessageType createBuildResponse(MessageHeaderType messageHeaderType, DblookupsType dblookups) { + ResponseMessageType respMessageType = null; + ResponseHeaderType respHeader = createResponseHeader("DONE", "CRC processing completed"); + BodyType bodyType = createBodyType(dblookups); + respMessageType = createResponseMessageType(messageHeaderType, respHeader, bodyType); + return respMessageType; + } + + public static ResponseMessageType createBuildResponse(MessageHeaderType messageHeaderType, RpdosType dblookups) { + ResponseMessageType respMessageType = null; + ResponseHeaderType respHeader = createResponseHeader("DONE", "CRC processing completed"); + BodyType bodyType = createBodyType(dblookups); + respMessageType = createResponseMessageType(messageHeaderType, respHeader, bodyType); + return respMessageType; + } + + public static ResponseMessageType createBuildResponse(MessageHeaderType messageHeaderType, JobsType dblus) { + ResponseMessageType respMessageType = null; + ResponseHeaderType respHeader = createResponseHeader("DONE", "CRC processing completed"); + BodyType bodyType = createBodyType(dblus); + respMessageType = createResponseMessageType(messageHeaderType, respHeader, bodyType); + return respMessageType; + } + + /**swc20160520 + * Function to build Response message type and return it as an XML string + * + * @return A String data type containing the ResponseMessage in XML format + * @throws Exception + */ + public static ResponseMessageType createBuildResponse(MessageHeaderType messageHeaderType) { + ResponseMessageType respMessageType = null; + ResponseHeaderType respHeader = createResponseHeader("DONE", "CRC processing completed"); + respMessageType = createResponseMessageType(messageHeaderType, respHeader, null); + return respMessageType; + } + + /**swc20160520 + * Function to build 'Non Standard' Response message and return it as an XML string + * + * @param messageHeaderType + * @param msg + * + * @return A String data type containing the ResponseMessage in XML format + * @throws Exception + */ + public static ResponseMessageType createNonStandardResponse(MessageHeaderType messageHeaderType, String msg) { + ResponseMessageType respMessageType = null; + ResponseHeaderType respHeader = createResponseHeader("DONE", msg + " - CRC processing completed"); + respMessageType = createResponseMessageType(messageHeaderType, respHeader, null); + return respMessageType; + } + + + /** + * Function to get i2b2 Request message header + * + * @return RequestHeader object + */ + public static RequestHeaderType getRequestHeader() { + RequestHeaderType reqHeader = new RequestHeaderType(); + reqHeader.setResultWaittimeMs(120000); + + return reqHeader; + } + + /** + * Function to create Response with given error message + * @param messageHeaderType + * @param errorMessage + * @return + * @throws Exception + */ + public static ResponseMessageType doBuildErrorResponse( + MessageHeaderType messageHeaderType, String errorMessage) { + ResponseMessageType respMessageType = null; + + MessageHeaderType messageHeader = createResponseMessageHeader(messageHeaderType); + ResponseHeaderType respHeader = createResponseHeader("ERROR", + errorMessage); + respMessageType = createResponseMessageType(messageHeader, respHeader, + null); + + return respMessageType; + } + + /** + * Creates ResponseHeader for the given type and value + * @param type + * @param value + * @return + */ + private static ResponseHeaderType createResponseHeader(String type, + String value) { + ResponseHeaderType respHeader = new ResponseHeaderType(); + StatusType status = new StatusType(); + status.setType(type); + status.setValue(value); + + ResultStatusType resStat = new ResultStatusType(); + resStat.setStatus(status); + respHeader.setResultStatus(resStat); + + return respHeader; + } + + + +// public static ResponseMessageType createBuildResponseAudits( +// MessageHeaderType messageHeader, AuditsType patientDataType) { +// +// ResponseMessageType respMessageType = null; +// BodyType bodyType = null; +// +// ResponseHeaderType respHeader = createResponseHeader("DONE", +// "CRC processing completed"); +// if(patientDataType != null) +// bodyType = createBodyType(patientDataType); +// +// // else +// // log.error("creating response with null body type "); +// +// respMessageType = createResponseMessageType(messageHeader, respHeader, +// bodyType); +// +// return respMessageType; +// +// } + + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/axis2/QueryService.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/axis2/QueryService.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/axis2/QueryService.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/axis2/QueryService.java index fc93bfd9..819e6268 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/axis2/QueryService.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/axis2/QueryService.java @@ -1,887 +1,887 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - * Wayne Chan - */ -package edu.harvard.i2b2.crc.axis2; - -import java.io.StringReader; - -import javax.xml.stream.XMLInputFactory; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamReader; - -import org.apache.axiom.om.OMElement; -import org.apache.axiom.om.OMXMLBuilderFactory; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.util.Assert; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate; -//import edu.harvard.i2b2.crc.delegate.loader.LoaderQueryRequestDelegate; -//import edu.harvard.i2b2.crc.delegate.loader.PublishDataRequestHandler; -import edu.harvard.i2b2.crc.delegate.getnameinfo.GetNameInfoRequestDelegate; -import edu.harvard.i2b2.crc.delegate.pdo.PdoQueryRequestDelegate; -import edu.harvard.i2b2.crc.delegate.setfinder.QueryRequestDelegate; -import edu.harvard.i2b2.crc.loader.delegate.BulkLoadRequestHandler; -import edu.harvard.i2b2.crc.loader.delegate.GetLoadStatusRequestHandler; -import edu.harvard.i2b2.crc.loader.delegate.LoaderQueryRequestDelegate; -import edu.harvard.i2b2.crc.loader.delegate.PublishDataRequestHandler; -//import edu.harvard.i2b2.crc.loader.ws.ProviderRestService; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.crc.delegate.DbLookupReqHandler; -//import edu.harvard.i2b2.ontology.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.crc.delegate.DeleteDblookupHandler; -import edu.harvard.i2b2.crc.delegate.GetAllDblookupsHandler; -import edu.harvard.i2b2.crc.delegate.GetDblookupHandler; -import edu.harvard.i2b2.crc.delegate.GetRPDODeleteHandler; -import edu.harvard.i2b2.crc.delegate.GetRPDOHandler; -import edu.harvard.i2b2.crc.delegate.GetRPDORenameHandler; -import edu.harvard.i2b2.crc.delegate.GetRPDOSetHandler; -import edu.harvard.i2b2.crc.delegate.GetAllRPDOsHandler; -import edu.harvard.i2b2.crc.delegate.JobReqHandler; -import edu.harvard.i2b2.crc.delegate.QTBreakdownRequestDelegate; -import edu.harvard.i2b2.crc.delegate.RPDOReqHandler; -import edu.harvard.i2b2.crc.delegate.RequestHandler; -import edu.harvard.i2b2.crc.delegate.SetDblookupHandler; -import edu.harvard.i2b2.crc.delegate.quartz.GetAllJobsHandler; -import edu.harvard.i2b2.crc.delegate.quartz.SetJobHandler; -import edu.harvard.i2b2.crc.delegate.quartz.SetJobHandlerMaybe; -import edu.harvard.i2b2.crc.axis2.DeleteDblookupDataMessage; -import edu.harvard.i2b2.crc.axis2.GetAllDblookupsDataMessage; -import edu.harvard.i2b2.crc.axis2.GetDblookupDataMessage; -import edu.harvard.i2b2.crc.axis2.MessageFactory; -import edu.harvard.i2b2.crc.axis2.SetDblookupDataMessage; -import edu.harvard.i2b2.crc.dao.redcap.RedcapPuller; -import edu.harvard.i2b2.crc.dao.redcap.APISurveyResponse; -import edu.harvard.i2b2.crc.dao.redcap.SurveyRecord; - -/** - * Axis2's service class - * - *

- * This class implements methods related to webservice operation. - *

  • For example http://localhost:8080/axis2/services/crc/serfinderrequest - * http://localhost:8080/axis2/services/crc/pdorequest - * - * $Id: QueryService.java,v 1.14 2009/09/10 19:32:06 rk903 Exp $ - * - * @author rkuttan - * @see QueryRequestDelegate - * @see PdoQueryRequestDelegate - */ -public class QueryService { - /** log **/ - protected final Log log = LogFactory.getLog(getClass()); - //protected final Log logesapi = LogFactory.getLog(getClass()); - - /** set pdo request constant used only inside this class **/ - private final String PDO_REQUEST = "PDO_REQUEST"; - - /** set finder request constant used only inside this class **/ - private final String SETFINDER_REQUEST = "SETFINDER_REQUEST"; - - /** get name info request constant used only inside this class **/ - private final String GETNAMEINFO_REQUEST = "GETNAMEINFO_REQUEST"; - - /** get name info request constant used only inside this class **/ - private final String REDCAP_REQUEST = "REDCAP_REQUEST"; - - /** get name info request constant used only inside this class **/ - private final String QTBREAKDOWN_REQUEST = "QTBREAKDOWN_REQUEST"; - - private static final String EAV_RECORD_TYPE = "eav"; - /** - * Webservice function to handle setfinder request - * - * @param omElement - * request message wrapped in OMElement - * @return response message in wrapped inside OMElement - */ - public OMElement request(OMElement omElement) { - Assert.notNull(omElement, - "Setfinder request OMElement must not be null"); - log.debug("Inside setfinder request " + omElement); - return handleRequest(SETFINDER_REQUEST, omElement); - } - - /** - * Webservice function to handle setfinder request - * - * @param omElement - * request message wrapped in OMElement - * @return response message in wrapped inside OMElement - */ - public OMElement breakdownrequest(OMElement omElement) { - Assert.notNull(omElement, - "Setfinder request OMElement must not be null"); - log.debug("Inside setfinder request " + omElement); - return handleRequest(QTBREAKDOWN_REQUEST, omElement); - } - /** - * Webservice function to handle pdo request - * - * @param omElement - * request message wrapped in OMElement - * @return response message in wrapped inside OMElement - */ - public OMElement pdorequest(OMElement omElement) { - Assert.notNull(omElement, "PDO request OMElement must not be null"); - log.debug("Inside pdo request " + omElement); - return handleRequest(PDO_REQUEST, omElement); - } - - /* - * Webservice function to handle find request - * - * @param omElement - * request message wrapped in OMElement - * @return response message in wrapped inside OMElement - * */ - - public void redcapPush( - String record, - String recordType, - //@RequestParam(value = "token", required = true) String projectToken, - String project_id, - String redcap_url, - String instrument) { - - RedcapPuller redcapService = new RedcapPuller(); - log.debug("Inside getNameInfo request " ); - - if (recordType == null || recordType.isEmpty()) - recordType = EAV_RECORD_TYPE; - try { - redcapService.pullRecordRequest(redcap_url, recordType, record, instrument, project_id); - } catch (Exception e) { - log.error("i2b2 exception", e); - } catch (Throwable e) { - log.error("Throwable", e); - } - } - - - /** - * Webservice function to handle find request - * - * @param omElement - * request message wrapped in OMElement - * @return response message in wrapped inside OMElement - */ - public OMElement getNameInfo(OMElement omElement) { - Assert.notNull(omElement, "getNameInfo OMElement must not be null"); - log.debug("Inside getNameInfo request " + omElement); - return handleRequest(GETNAMEINFO_REQUEST, omElement); - } - - public OMElement publishDataRequest(OMElement request) { - Assert.notNull(request, - "publish data request OMElement must not be null"); - log.debug("Inside publish data request " + request); - //TODO removed loader - // Added back - LoaderQueryRequestDelegate queryDelegate = new LoaderQueryRequestDelegate(); - OMElement responseElement = null; - try { - String requestXml = request.toString(); - PublishDataRequestHandler handler = new PublishDataRequestHandler( - requestXml); - String response = queryDelegate.handleRequest(requestXml, handler); - responseElement = buildOMElementFromString(response); - - } catch (Exception e) { - log.error("i2b2 exception", e); - } catch (Throwable e) { - log.error("Throwable", e); - } - return responseElement; - - } - - public OMElement bulkLoadRequest(OMElement request) { - Assert.notNull(request, - "bulk load request OMElement must not be null"); - log.debug("Inside bulk load request " + request); - - //LoaderQueryReqDel handles permissions... - LoaderQueryRequestDelegate queryDelegate = new LoaderQueryRequestDelegate(); - OMElement responseElement = null; - try { - String requestXml = request.toString(); - BulkLoadRequestHandler handler = new BulkLoadRequestHandler( - requestXml); - String response = queryDelegate.handleRequest(requestXml, handler); - responseElement = buildOMElementFromString(response); - - } catch (Exception e) { - log.error("i2b2 exception", e); - } catch (Throwable e) { - log.error("Throwable", e); - } - return responseElement; - - } - - /** - * This function get the RPDO All Tables - * - * It accepts incoming request, and returns a response, both in i2b2 message format. - * - * @param OMElement - * getAllJobsElement - * @return OMElement in i2b2message format - * @throws Exception - */ - public OMElement getAllTablesList(OMElement getAllJobsElement) throws I2B2Exception { - String crcDataResponse = null; - String unknownErrMsg = null; - if (null == getAllJobsElement) { - log.error("Incoming CRC request is null"); - unknownErrMsg = "Error message delivered from the remote server.\nYou may wish to retry your last action"; - ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, unknownErrMsg); - crcDataResponse = MessageFactory.convertToXMLString(responseMsgType); - return MessageFactory.createResponseOMElementFromString(crcDataResponse); - } - String requestElementString = getAllJobsElement.toString(); - GetAllRPDOsDataMessage jobsDataMsg = new GetAllRPDOsDataMessage(requestElementString); - long waitTime = 0; - if (null != jobsDataMsg.getRequestMessageType()) { - if (null != jobsDataMsg.getRequestMessageType().getRequestHeader()) { - waitTime = jobsDataMsg.getRequestMessageType().getRequestHeader().getResultWaittimeMs(); - } - } - - return execute(new GetAllRPDOsHandler(jobsDataMsg), waitTime); - } - - /** - * This function get the RPDO All Tables - * - * It accepts incoming request, and returns a response, both in i2b2 message format. - * - * @param OMElement - * getAllJobsElement - * @return OMElement in i2b2message format - * @throws Exception - */ - public OMElement getTable(OMElement getAllJobsElement) throws I2B2Exception { - String crcDataResponse = null; - String unknownErrMsg = null; - if (null == getAllJobsElement) { - log.error("Incoming CRC request is null"); - unknownErrMsg = "Error message delivered from the remote server.\nYou may wish to retry your last action"; - ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, unknownErrMsg); - crcDataResponse = MessageFactory.convertToXMLString(responseMsgType); - return MessageFactory.createResponseOMElementFromString(crcDataResponse); - } - String requestElementString = getAllJobsElement.toString(); - GetRPDODataMessage jobsDataMsg = new GetRPDODataMessage(requestElementString); - long waitTime = 0; - if (null != jobsDataMsg.getRequestMessageType()) { - if (null != jobsDataMsg.getRequestMessageType().getRequestHeader()) { - waitTime = jobsDataMsg.getRequestMessageType().getRequestHeader().getResultWaittimeMs(); - } - } - - return execute(new GetRPDOHandler(jobsDataMsg), waitTime); - } - - - /** - * This function rename the RPDO Tables - * - * It accepts incoming request, and returns a response, both in i2b2 message format. - * - * @param OMElement - * getAllJobsElement - * @return OMElement in i2b2message format - * @throws Exception - */ - public OMElement deleteTable(OMElement getAllJobsElement) throws I2B2Exception { - String crcDataResponse = null; - String unknownErrMsg = null; - if (null == getAllJobsElement) { - log.error("Incoming CRC request is null"); - unknownErrMsg = "Error message delivered from the remote server.\nYou may wish to retry your last action"; - ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, unknownErrMsg); - crcDataResponse = MessageFactory.convertToXMLString(responseMsgType); - return MessageFactory.createResponseOMElementFromString(crcDataResponse); - } - String requestElementString = getAllJobsElement.toString(); - GetRPDODataMessage jobsDataMsg = new GetRPDODataMessage(requestElementString); - long waitTime = 0; - if (null != jobsDataMsg.getRequestMessageType()) { - if (null != jobsDataMsg.getRequestMessageType().getRequestHeader()) { - waitTime = jobsDataMsg.getRequestMessageType().getRequestHeader().getResultWaittimeMs(); - } - } - - return execute(new GetRPDODeleteHandler(jobsDataMsg), waitTime); - } - - /** - * This function rename the RPDO Tables - * - * It accepts incoming request, and returns a response, both in i2b2 message format. - * - * @param OMElement - * getAllJobsElement - * @return OMElement in i2b2message format - * @throws Exception - */ - public OMElement renameTable(OMElement getAllJobsElement) throws I2B2Exception { - String crcDataResponse = null; - String unknownErrMsg = null; - if (null == getAllJobsElement) { - log.error("Incoming CRC request is null"); - unknownErrMsg = "Error message delivered from the remote server.\nYou may wish to retry your last action"; - ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, unknownErrMsg); - crcDataResponse = MessageFactory.convertToXMLString(responseMsgType); - return MessageFactory.createResponseOMElementFromString(crcDataResponse); - } - String requestElementString = getAllJobsElement.toString(); - GetRPDODataMessage jobsDataMsg = new GetRPDODataMessage(requestElementString); - long waitTime = 0; - if (null != jobsDataMsg.getRequestMessageType()) { - if (null != jobsDataMsg.getRequestMessageType().getRequestHeader()) { - waitTime = jobsDataMsg.getRequestMessageType().getRequestHeader().getResultWaittimeMs(); - } - } - - return execute(new GetRPDORenameHandler(jobsDataMsg), waitTime); - } - - - /** - * This function save the RPDO Tables - * - * It accepts incoming request, and returns a response, both in i2b2 message format. - * - * @param OMElement - * getAllJobsElement - * @return OMElement in i2b2message format - * @throws Exception - */ - public OMElement setTable(OMElement getAllJobsElement) throws I2B2Exception { - String crcDataResponse = null; - String unknownErrMsg = null; - if (null == getAllJobsElement) { - log.error("Incoming CRC request is null"); - unknownErrMsg = "Error message delivered from the remote server.\nYou may wish to retry your last action"; - ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, unknownErrMsg); - crcDataResponse = MessageFactory.convertToXMLString(responseMsgType); - return MessageFactory.createResponseOMElementFromString(crcDataResponse); - } - String requestElementString = getAllJobsElement.toString(); - GetRPDODataMessage jobsDataMsg = new GetRPDODataMessage(requestElementString); - long waitTime = 0; - if (null != jobsDataMsg.getRequestMessageType()) { - if (null != jobsDataMsg.getRequestMessageType().getRequestHeader()) { - waitTime = jobsDataMsg.getRequestMessageType().getRequestHeader().getResultWaittimeMs(); - } - } - return execute(new GetRPDOSetHandler(jobsDataMsg), waitTime); - - } - - /** - * This function save the RPDO Tables - * - * It accepts incoming request, and returns a response, both in i2b2 message format. - * - * @param OMElement - * getAllJobsElement - * @return OMElement in i2b2message format - * @throws Exception - */ - public OMElement makeRequest(OMElement getAllJobsElement) throws I2B2Exception { - String crcDataResponse = null; - String unknownErrMsg = null; - if (null == getAllJobsElement) { - log.error("Incoming CRC request is null"); - unknownErrMsg = "Error message delivered from the remote server.\nYou may wish to retry your last action"; - ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, unknownErrMsg); - crcDataResponse = MessageFactory.convertToXMLString(responseMsgType); - return MessageFactory.createResponseOMElementFromString(crcDataResponse); - } - String requestElementString = getAllJobsElement.toString(); - GetAllJobsDataMessage jobsDataMsg = new GetAllJobsDataMessage(requestElementString); - long waitTime = 0; - if (null != jobsDataMsg.getRequestMessageType()) { - if (null != jobsDataMsg.getRequestMessageType().getRequestHeader()) { - waitTime = jobsDataMsg.getRequestMessageType().getRequestHeader().getResultWaittimeMs(); - } - } - - return executeJobs(new GetAllJobsHandler(requestElementString), waitTime); - } - - /** - * This function is main webservice interface to get the I2B2HIVE.CRC_DB_LOOKUP data. - * It uses AXIOM elements(OMElement) to conveniently parse xml messages. - * - * It accepts incoming request, and returns a response, both in i2b2 message format. - * - * @param OMElement - * getAllJobsElement - * @return OMElement in i2b2message format - * @throws Exception - */ - public OMElement getAllJobs(OMElement getAllJobsElement) throws I2B2Exception { - String crcDataResponse = null; - String unknownErrMsg = null; - if (null == getAllJobsElement) { - log.error("Incoming CRC request is null"); - unknownErrMsg = "Error message delivered from the remote server.\nYou may wish to retry your last action"; - ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, unknownErrMsg); - crcDataResponse = MessageFactory.convertToXMLString(responseMsgType); - return MessageFactory.createResponseOMElementFromString(crcDataResponse); - } - String requestElementString = getAllJobsElement.toString(); - GetAllJobsDataMessage jobsDataMsg = new GetAllJobsDataMessage(requestElementString); - long waitTime = 0; - if (null != jobsDataMsg.getRequestMessageType()) { - if (null != jobsDataMsg.getRequestMessageType().getRequestHeader()) { - waitTime = jobsDataMsg.getRequestMessageType().getRequestHeader().getResultWaittimeMs(); - } - } - - return executeJobs(new GetAllJobsHandler(requestElementString), waitTime); - } - - public OMElement setJob(OMElement setJobElement) throws I2B2Exception { - String crcDataResponse = null; - String unknownErrMsg = null; - if (null == setJobElement) { - log.error("Incoming CRC request is null"); - unknownErrMsg = "Error message delivered from the remote server.\nYou may wish to retry your last action"; - ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, unknownErrMsg); - crcDataResponse = MessageFactory.convertToXMLString(responseMsgType); - return MessageFactory.createResponseOMElementFromString(crcDataResponse); - } - String requestElementString = setJobElement.toString(); - SetJobDataMessage jobsDataMsg = new SetJobDataMessage(requestElementString); - long waitTime = 0; - if (null != jobsDataMsg.getRequestMessageType()) { - if (null != jobsDataMsg.getRequestMessageType().getRequestHeader()) { - waitTime = jobsDataMsg.getRequestMessageType().getRequestHeader().getResultWaittimeMs(); - } - } - - return executeJobs(new SetJobHandler(requestElementString), waitTime); - } - - public OMElement getLoadDataStatusRequest(OMElement request) { - Assert.notNull(request, - "get load Data status request OMElement must not be null"); - log.debug("Inside load status request " + request); - - //LoaderQueryReqDel handles permissions... - LoaderQueryRequestDelegate queryDelegate = new LoaderQueryRequestDelegate(); - OMElement responseElement = null; - try { - String requestXml = request.toString(); - GetLoadStatusRequestHandler handler = new GetLoadStatusRequestHandler( - requestXml); - String response = queryDelegate.handleRequest(requestXml, handler); - responseElement = buildOMElementFromString(response); - - } catch (Exception e) { - log.error("i2b2 exception", e); - } catch (Throwable e) { - log.error("Throwable", e); - } - return responseElement; - - } - - - private OMElement executeJobs(JobReqHandler getAllJobsHandler, long waitTime) throws I2B2Exception { - //do processing inside thread, so that service could send back message with timeout error. - OMElement returnElement = null; - String unknownErrorMessage = "Error message delivered from the remote server \nYou may wish to retry your last action"; - ExecutorRunnable er = new ExecutorRunnable(); - er.setJobReqHandler(getAllJobsHandler); - Thread t = new Thread(er); - String dataResponse = null; - log.info("waiting " + waitTime + "ms for response from remote server processing " + getAllJobsHandler.getClass().getName()); - synchronized (t) { - t.start(); - try { - long startTime = System.currentTimeMillis(); - long deltaTime = -1; - while((er.isJobCompleteFlag() == false) && (deltaTime < waitTime)) { - if (waitTime > 0) { - t.wait(waitTime - deltaTime); - deltaTime = System.currentTimeMillis() - startTime; - } else { - t.wait(); - } - } - dataResponse = er.getOutputString(); - if (dataResponse == null) { - ResponseMessageType responseMsgType = null; - if (!er.isJobCompleteFlag()) { - String timeOuterror = "Remote server timed out after waittime of " + waitTime + "ms."; - log.error(timeOuterror); - responseMsgType = MessageFactory.doBuildErrorResponse(null, timeOuterror); - } else { - if (null != er.getJobException()) { - log.error("jobException: " + er.getJobException().getMessage()); - dataResponse = MessageFactory.convertToXMLString(responseMsgType); - } else { - log.error("CRC data response is null!"); - log.info("CRC waited " + deltaTime + "ms for " + getAllJobsHandler.getClass().getName()); - } - log.info("waitTime is " + waitTime); - responseMsgType = MessageFactory.doBuildErrorResponse(null, unknownErrorMessage); - dataResponse = MessageFactory.convertToXMLString(responseMsgType); - } - dataResponse = MessageFactory.convertToXMLString(responseMsgType); - } - } catch (InterruptedException e) { - log.error(e.getMessage()); - throw new I2B2Exception("Thread error while running CRC job!"); - } finally { - t.interrupt(); - er = null; - t = null; - } - } - returnElement = MessageFactory.createResponseOMElementFromString(dataResponse); - return returnElement; - } - - - private OMElement execute(RPDOReqHandler handler, long waitTime) throws I2B2Exception { - //do processing inside thread, so that service could send back message with timeout error. - OMElement returnElement = null; - String unknownErrorMessage = "Error message delivered from the remote server \nYou may wish to retry your last action"; - ExecutorRunnable er = new ExecutorRunnable(); - er.setRpdoHandler(handler); - Thread t = new Thread(er); - String dataResponse = null; - log.info("waiting " + waitTime + "ms for response from remote server processing " + handler.getClass().getName()); - synchronized (t) { - t.start(); - try { - long startTime = System.currentTimeMillis(); - long deltaTime = -1; - while((er.isJobCompleteFlag() == false) && (deltaTime < waitTime)) { - if (waitTime > 0) { - t.wait(waitTime - deltaTime); - deltaTime = System.currentTimeMillis() - startTime; - } else { - t.wait(); - } - } - dataResponse = er.getOutputString(); - if (dataResponse == null) { - ResponseMessageType responseMsgType = null; - if (!er.isJobCompleteFlag()) { - String timeOuterror = "Remote server timed out after waittime of " + waitTime + "ms."; - log.error(timeOuterror); - responseMsgType = MessageFactory.doBuildErrorResponse(null, timeOuterror); - } else { - if (null != er.getJobException()) { - log.error("jobException: " + er.getJobException().getMessage()); - dataResponse = MessageFactory.convertToXMLString(responseMsgType); - } else { - log.error("CRC data response is null!"); - log.info("CRC waited " + deltaTime + "ms for " + handler.getClass().getName()); - } - log.info("waitTime is " + waitTime); - responseMsgType = MessageFactory.doBuildErrorResponse(null, unknownErrorMessage); - dataResponse = MessageFactory.convertToXMLString(responseMsgType); - } - dataResponse = MessageFactory.convertToXMLString(responseMsgType); - } - } catch (InterruptedException e) { - log.error(e.getMessage()); - throw new I2B2Exception("Thread error while running CRC job!"); - } finally { - t.interrupt(); - er = null; - t = null; - } - } - returnElement = MessageFactory.createResponseOMElementFromString(dataResponse); - return returnElement; - } - - - //swc20160523 copied from edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/ws/IMService.java - private OMElement execute(DbLookupReqHandler handler, long waitTime) throws I2B2Exception { - //do processing inside thread, so that service could send back message with timeout error. - OMElement returnElement = null; - String unknownErrorMessage = "Error message delivered from the remote server \nYou may wish to retry your last action"; - ExecutorRunnable er = new ExecutorRunnable(); - er.setDbLookupReqHandler(handler); - Thread t = new Thread(er); - String dataResponse = null; - log.info("waiting " + waitTime + "ms for response from remote server processing " + handler.getClass().getName()); - synchronized (t) { - t.start(); - try { - long startTime = System.currentTimeMillis(); - long deltaTime = -1; - while((er.isJobCompleteFlag() == false) && (deltaTime < waitTime)) { - if (waitTime > 0) { - t.wait(waitTime - deltaTime); - deltaTime = System.currentTimeMillis() - startTime; - } else { - t.wait(); - } - } - dataResponse = er.getOutputString(); - if (dataResponse == null) { - ResponseMessageType responseMsgType = null; - if (!er.isJobCompleteFlag()) { - String timeOuterror = "Remote server timed out after waittime of " + waitTime + "ms."; - log.error(timeOuterror); - responseMsgType = MessageFactory.doBuildErrorResponse(null, timeOuterror); - } else { - if (null != er.getJobException()) { - log.error("jobException: " + er.getJobException().getMessage()); - dataResponse = MessageFactory.convertToXMLString(responseMsgType); - } else { - log.error("CRC data response is null!"); - log.info("CRC waited " + deltaTime + "ms for " + handler.getClass().getName()); - } - log.info("waitTime is " + waitTime); - responseMsgType = MessageFactory.doBuildErrorResponse(null, unknownErrorMessage); - dataResponse = MessageFactory.convertToXMLString(responseMsgType); - } - dataResponse = MessageFactory.convertToXMLString(responseMsgType); - } - } catch (InterruptedException e) { - log.error(e.getMessage()); - throw new I2B2Exception("Thread error while running CRC job!"); - } finally { - t.interrupt(); - er = null; - t = null; - } - } - returnElement = MessageFactory.createResponseOMElementFromString(dataResponse); - return returnElement; - } - - - /** swc20160523 - * This function is main webservice interface to get the I2B2HIVE.CRC_DB_LOOKUP data. - * It uses AXIOM elements(OMElement) to conveniently parse xml messages. - * - * It accepts incoming request, and returns a response, both in i2b2 message format. - * - * @param OMElement - * getAllDblookupsElement - * @return OMElement in i2b2message format - * @throws Exception - */ - public OMElement getAllDblookups(OMElement getAllDblookupsElement) throws I2B2Exception { - String crcDataResponse = null; - String unknownErrMsg = null; - if (null == getAllDblookupsElement) { - log.error("Incoming CRC request is null"); - unknownErrMsg = "Error message delivered from the remote server.\nYou may wish to retry your last action"; - ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, unknownErrMsg); - crcDataResponse = MessageFactory.convertToXMLString(responseMsgType); - return MessageFactory.createResponseOMElementFromString(crcDataResponse); - } - String requestElementString = getAllDblookupsElement.toString(); - GetAllDblookupsDataMessage dblookupsDataMsg = new GetAllDblookupsDataMessage(requestElementString); - long waitTime = 0; - if (null != dblookupsDataMsg.getRequestMessageType()) { - if (null != dblookupsDataMsg.getRequestMessageType().getRequestHeader()) { - waitTime = dblookupsDataMsg.getRequestMessageType().getRequestHeader().getResultWaittimeMs(); - } - } - // do processing inside thread, so that service could send back message with timeout error. - return execute(new GetAllDblookupsHandler(dblookupsDataMsg), waitTime); - } - - /** swc20160523 - * This function is main webservice interface to get specific I2B2HIVE.CRC_DB_LOOKUP data. - * It uses AXIOM elements(OMElement) to conveniently parse xml messages. - * - * It accepts incoming request, and returns a response, both in i2b2 message format. - * - * @param OMElement - * getDblookupElement - * @return OMElement in i2b2message format - * @throws Exception - */ - public OMElement getDblookup(OMElement getDblookupElement) throws I2B2Exception { - String crcDataResponse = null; - String unknownErrMsg = null; - if (null == getDblookupElement) { - log.error("Incoming CRC request is null"); - unknownErrMsg = "Error message delivered from the remote server.\nYou may wish to retry your last action"; - ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, unknownErrMsg); - crcDataResponse = MessageFactory.convertToXMLString(responseMsgType); - return MessageFactory.createResponseOMElementFromString(crcDataResponse); - } - String requestElementString = getDblookupElement.toString(); - GetDblookupDataMessage dblookupDataMsg = new GetDblookupDataMessage(requestElementString); - long waitTime = 0; - if (null != dblookupDataMsg.getRequestMessageType()) { - if (null != dblookupDataMsg.getRequestMessageType().getRequestHeader()) { - waitTime = dblookupDataMsg.getRequestMessageType().getRequestHeader().getResultWaittimeMs(); - } - } - // do processing inside thread, so that service could send back message with timeout error. - return execute(new GetDblookupHandler(dblookupDataMsg), waitTime); - } - - /** swc20160523 - * This function is main webservice interface to add a new entry to the I2B2HIVE.CRC_DB_LOOKUP data. - * It uses AXIOM elements(OMElement) to conveniently parse xml messages. - * - * It accepts incoming request, and returns a response, both in i2b2 message format. - * - * @param OMElement - * getAllDblookupsElement - * @return OMElement in i2b2message format - * @throws Exception - */ - public OMElement setDblookup(OMElement setDblookupElement) throws I2B2Exception { - String crcDataResponse = null; - String unknownErrMsg = null; - if (null == setDblookupElement) { - log.error("Incoming CRC request is null"); - unknownErrMsg = "Error message delivered from the remote server.\nYou may wish to retry your last action"; - ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, unknownErrMsg); - crcDataResponse = MessageFactory.convertToXMLString(responseMsgType); - return MessageFactory.createResponseOMElementFromString(crcDataResponse); - } - String requestElementString = setDblookupElement.toString(); - SetDblookupDataMessage dblookupDataMsg = new SetDblookupDataMessage(requestElementString); - long waitTime = 0; - if (null != dblookupDataMsg.getRequestMessageType()) { - if (null != dblookupDataMsg.getRequestMessageType().getRequestHeader()) { - waitTime = dblookupDataMsg.getRequestMessageType().getRequestHeader().getResultWaittimeMs(); - } - } - // do processing inside thread, so that service could send back message with timeout error. - return execute(new SetDblookupHandler(dblookupDataMsg), waitTime); - } - - /** swc20160523 - * This function is main webservice interface to delete specific I2B2HIVE.CRC_DB_LOOKUP data. - * It uses AXIOM elements(OMElement) to conveniently parse xml messages. - * - * It accepts incoming request, and returns a response, both in i2b2 message format. - * - * @param OMElement - * deleteDblookupElement - * @return OMElement in i2b2message format - * @throws Exception - */ - public OMElement deleteDblookup(OMElement deleteDblookupElement) throws I2B2Exception { - String crcDataResponse = null; - String unknownErrMsg = null; - if (null == deleteDblookupElement) { - log.error("Incoming CRC request is null"); - unknownErrMsg = "Error message delivered from the remote server.\nYou may wish to retry your last action"; - ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, unknownErrMsg); - crcDataResponse = MessageFactory.convertToXMLString(responseMsgType); - return MessageFactory.createResponseOMElementFromString(crcDataResponse); - } - String requestElementString = deleteDblookupElement.toString(); - DeleteDblookupDataMessage dblookupDataMsg = new DeleteDblookupDataMessage(requestElementString); - long waitTime = 0; - if (null != dblookupDataMsg.getRequestMessageType()) { - if (null != dblookupDataMsg.getRequestMessageType().getRequestHeader()) { - waitTime = dblookupDataMsg.getRequestMessageType().getRequestHeader().getResultWaittimeMs(); - } - } - // do processing inside thread, so that service could send back message with timeout error. - return execute(new DeleteDblookupHandler(dblookupDataMsg), waitTime); - } - - - - //TODO removed loader - // added back above (lcp5) - /* - public OMElement getLoadDataStatusRequest(OMElement request) { - Assert.notNull(request, - "Data load status request OMElement must not be null"); - log.debug("Inside data load status request " + request); - ProviderRestService rs = new ProviderRestService(); - return rs.getLoadDataStatusRequest(request); - } - - public OMElement getMissingTermRequest(OMElement request) { - Assert.notNull(request, - "Missing term request OMElement must not be null"); - log.debug("Inside missing term request " + request); - ProviderRestService rs = new ProviderRestService(); - return rs.getMissingTermRequest(request); - } - */ - // -------------------------------------------- - // Creates delegate based on the request type - // -------------------------------------------- - private OMElement handleRequest(String requestType, OMElement request) { - RequestHandlerDelegate requestHandlerDelegate = null; - - if (requestType.equals(PDO_REQUEST)) { - requestHandlerDelegate = new PdoQueryRequestDelegate(); - } else if (requestType.equals(SETFINDER_REQUEST)) { - requestHandlerDelegate = new QueryRequestDelegate(); - } else if (requestType.equals(GETNAMEINFO_REQUEST)) { - requestHandlerDelegate = new GetNameInfoRequestDelegate(); - } else if (requestType.equals(QTBREAKDOWN_REQUEST)) { - requestHandlerDelegate = new QTBreakdownRequestDelegate(); - // } else if (requestType.equals(REDCAP_REQUEST)) { - // requestHandlerDelegate = new RedCapRequestDelegate(); - } - OMElement returnElement = null; - try { - // call delegate's handleRequest function - String xmlString= request.toStringWithConsume(); - String response = requestHandlerDelegate.handleRequest(request - .toString()); - log.debug("Response in service" + response); - returnElement = buildOMElementFromString(response); - } catch (XMLStreamException e) { - log.error("xml stream exception", e); - } catch (I2B2Exception e) { - log.error("i2b2 exception", e); - } catch (Throwable e) { - log.error("Throwable", e); - } - return returnElement; - } - - /** - * Function constructs OMElement for the given String - * - * @param xmlString - * @return OMElement - * @throws XMLStreamException - */ - private OMElement buildOMElementFromString(String xmlString) - throws XMLStreamException { - XMLInputFactory xif = XMLInputFactory.newInstance(); - StringReader strReader = new StringReader(xmlString); - XMLStreamReader reader = xif.createXMLStreamReader(strReader); - OMElement element = OMXMLBuilderFactory.createStAXOMBuilder(reader).getDocumentElement(); - - return element; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + * Wayne Chan + */ +package edu.harvard.i2b2.crc.axis2; + +import java.io.StringReader; + +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import org.apache.axiom.om.OMElement; +import org.apache.axiom.om.OMXMLBuilderFactory; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.util.Assert; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate; +//import edu.harvard.i2b2.crc.delegate.loader.LoaderQueryRequestDelegate; +//import edu.harvard.i2b2.crc.delegate.loader.PublishDataRequestHandler; +import edu.harvard.i2b2.crc.delegate.getnameinfo.GetNameInfoRequestDelegate; +import edu.harvard.i2b2.crc.delegate.pdo.PdoQueryRequestDelegate; +import edu.harvard.i2b2.crc.delegate.setfinder.QueryRequestDelegate; +import edu.harvard.i2b2.crc.loader.delegate.BulkLoadRequestHandler; +import edu.harvard.i2b2.crc.loader.delegate.GetLoadStatusRequestHandler; +import edu.harvard.i2b2.crc.loader.delegate.LoaderQueryRequestDelegate; +import edu.harvard.i2b2.crc.loader.delegate.PublishDataRequestHandler; +//import edu.harvard.i2b2.crc.loader.ws.ProviderRestService; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.crc.delegate.DbLookupReqHandler; +//import edu.harvard.i2b2.ontology.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.crc.delegate.DeleteDblookupHandler; +import edu.harvard.i2b2.crc.delegate.GetAllDblookupsHandler; +import edu.harvard.i2b2.crc.delegate.GetDblookupHandler; +import edu.harvard.i2b2.crc.delegate.GetRPDODeleteHandler; +import edu.harvard.i2b2.crc.delegate.GetRPDOHandler; +import edu.harvard.i2b2.crc.delegate.GetRPDORenameHandler; +import edu.harvard.i2b2.crc.delegate.GetRPDOSetHandler; +import edu.harvard.i2b2.crc.delegate.GetAllRPDOsHandler; +import edu.harvard.i2b2.crc.delegate.JobReqHandler; +import edu.harvard.i2b2.crc.delegate.QTBreakdownRequestDelegate; +import edu.harvard.i2b2.crc.delegate.RPDOReqHandler; +import edu.harvard.i2b2.crc.delegate.RequestHandler; +import edu.harvard.i2b2.crc.delegate.SetDblookupHandler; +import edu.harvard.i2b2.crc.delegate.quartz.GetAllJobsHandler; +import edu.harvard.i2b2.crc.delegate.quartz.SetJobHandler; +import edu.harvard.i2b2.crc.delegate.quartz.SetJobHandlerMaybe; +import edu.harvard.i2b2.crc.axis2.DeleteDblookupDataMessage; +import edu.harvard.i2b2.crc.axis2.GetAllDblookupsDataMessage; +import edu.harvard.i2b2.crc.axis2.GetDblookupDataMessage; +import edu.harvard.i2b2.crc.axis2.MessageFactory; +import edu.harvard.i2b2.crc.axis2.SetDblookupDataMessage; +import edu.harvard.i2b2.crc.dao.redcap.RedcapPuller; +import edu.harvard.i2b2.crc.dao.redcap.APISurveyResponse; +import edu.harvard.i2b2.crc.dao.redcap.SurveyRecord; + +/** + * Axis2's service class + * + *

    + * This class implements methods related to webservice operation. + *

  • For example http://localhost:8080/axis2/services/crc/serfinderrequest + * http://localhost:8080/axis2/services/crc/pdorequest + * + * $Id: QueryService.java,v 1.14 2009/09/10 19:32:06 rk903 Exp $ + * + * @author rkuttan + * @see QueryRequestDelegate + * @see PdoQueryRequestDelegate + */ +public class QueryService { + /** log **/ + protected final Log log = LogFactory.getLog(getClass()); + //protected final Log logesapi = LogFactory.getLog(getClass()); + + /** set pdo request constant used only inside this class **/ + private final String PDO_REQUEST = "PDO_REQUEST"; + + /** set finder request constant used only inside this class **/ + private final String SETFINDER_REQUEST = "SETFINDER_REQUEST"; + + /** get name info request constant used only inside this class **/ + private final String GETNAMEINFO_REQUEST = "GETNAMEINFO_REQUEST"; + + /** get name info request constant used only inside this class **/ + private final String REDCAP_REQUEST = "REDCAP_REQUEST"; + + /** get name info request constant used only inside this class **/ + private final String QTBREAKDOWN_REQUEST = "QTBREAKDOWN_REQUEST"; + + private static final String EAV_RECORD_TYPE = "eav"; + /** + * Webservice function to handle setfinder request + * + * @param omElement + * request message wrapped in OMElement + * @return response message in wrapped inside OMElement + */ + public OMElement request(OMElement omElement) { + Assert.notNull(omElement, + "Setfinder request OMElement must not be null"); + log.debug("Inside setfinder request " + omElement); + return handleRequest(SETFINDER_REQUEST, omElement); + } + + /** + * Webservice function to handle setfinder request + * + * @param omElement + * request message wrapped in OMElement + * @return response message in wrapped inside OMElement + */ + public OMElement breakdownrequest(OMElement omElement) { + Assert.notNull(omElement, + "Setfinder request OMElement must not be null"); + log.debug("Inside setfinder request " + omElement); + return handleRequest(QTBREAKDOWN_REQUEST, omElement); + } + /** + * Webservice function to handle pdo request + * + * @param omElement + * request message wrapped in OMElement + * @return response message in wrapped inside OMElement + */ + public OMElement pdorequest(OMElement omElement) { + Assert.notNull(omElement, "PDO request OMElement must not be null"); + log.debug("Inside pdo request " + omElement); + return handleRequest(PDO_REQUEST, omElement); + } + + /* + * Webservice function to handle find request + * + * @param omElement + * request message wrapped in OMElement + * @return response message in wrapped inside OMElement + * */ + + public void redcapPush( + String record, + String recordType, + //@RequestParam(value = "token", required = true) String projectToken, + String project_id, + String redcap_url, + String instrument) { + + RedcapPuller redcapService = new RedcapPuller(); + log.debug("Inside getNameInfo request " ); + + if (recordType == null || recordType.isEmpty()) + recordType = EAV_RECORD_TYPE; + try { + redcapService.pullRecordRequest(redcap_url, recordType, record, instrument, project_id); + } catch (Exception e) { + log.error("i2b2 exception", e); + } catch (Throwable e) { + log.error("Throwable", e); + } + } + + + /** + * Webservice function to handle find request + * + * @param omElement + * request message wrapped in OMElement + * @return response message in wrapped inside OMElement + */ + public OMElement getNameInfo(OMElement omElement) { + Assert.notNull(omElement, "getNameInfo OMElement must not be null"); + log.debug("Inside getNameInfo request " + omElement); + return handleRequest(GETNAMEINFO_REQUEST, omElement); + } + + public OMElement publishDataRequest(OMElement request) { + Assert.notNull(request, + "publish data request OMElement must not be null"); + log.debug("Inside publish data request " + request); + //TODO removed loader + // Added back + LoaderQueryRequestDelegate queryDelegate = new LoaderQueryRequestDelegate(); + OMElement responseElement = null; + try { + String requestXml = request.toString(); + PublishDataRequestHandler handler = new PublishDataRequestHandler( + requestXml); + String response = queryDelegate.handleRequest(requestXml, handler); + responseElement = buildOMElementFromString(response); + + } catch (Exception e) { + log.error("i2b2 exception", e); + } catch (Throwable e) { + log.error("Throwable", e); + } + return responseElement; + + } + + public OMElement bulkLoadRequest(OMElement request) { + Assert.notNull(request, + "bulk load request OMElement must not be null"); + log.debug("Inside bulk load request " + request); + + //LoaderQueryReqDel handles permissions... + LoaderQueryRequestDelegate queryDelegate = new LoaderQueryRequestDelegate(); + OMElement responseElement = null; + try { + String requestXml = request.toString(); + BulkLoadRequestHandler handler = new BulkLoadRequestHandler( + requestXml); + String response = queryDelegate.handleRequest(requestXml, handler); + responseElement = buildOMElementFromString(response); + + } catch (Exception e) { + log.error("i2b2 exception", e); + } catch (Throwable e) { + log.error("Throwable", e); + } + return responseElement; + + } + + /** + * This function get the RPDO All Tables + * + * It accepts incoming request, and returns a response, both in i2b2 message format. + * + * @param OMElement + * getAllJobsElement + * @return OMElement in i2b2message format + * @throws Exception + */ + public OMElement getAllTablesList(OMElement getAllJobsElement) throws I2B2Exception { + String crcDataResponse = null; + String unknownErrMsg = null; + if (null == getAllJobsElement) { + log.error("Incoming CRC request is null"); + unknownErrMsg = "Error message delivered from the remote server.\nYou may wish to retry your last action"; + ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, unknownErrMsg); + crcDataResponse = MessageFactory.convertToXMLString(responseMsgType); + return MessageFactory.createResponseOMElementFromString(crcDataResponse); + } + String requestElementString = getAllJobsElement.toString(); + GetAllRPDOsDataMessage jobsDataMsg = new GetAllRPDOsDataMessage(requestElementString); + long waitTime = 0; + if (null != jobsDataMsg.getRequestMessageType()) { + if (null != jobsDataMsg.getRequestMessageType().getRequestHeader()) { + waitTime = jobsDataMsg.getRequestMessageType().getRequestHeader().getResultWaittimeMs(); + } + } + + return execute(new GetAllRPDOsHandler(jobsDataMsg), waitTime); + } + + /** + * This function get the RPDO All Tables + * + * It accepts incoming request, and returns a response, both in i2b2 message format. + * + * @param OMElement + * getAllJobsElement + * @return OMElement in i2b2message format + * @throws Exception + */ + public OMElement getTable(OMElement getAllJobsElement) throws I2B2Exception { + String crcDataResponse = null; + String unknownErrMsg = null; + if (null == getAllJobsElement) { + log.error("Incoming CRC request is null"); + unknownErrMsg = "Error message delivered from the remote server.\nYou may wish to retry your last action"; + ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, unknownErrMsg); + crcDataResponse = MessageFactory.convertToXMLString(responseMsgType); + return MessageFactory.createResponseOMElementFromString(crcDataResponse); + } + String requestElementString = getAllJobsElement.toString(); + GetRPDODataMessage jobsDataMsg = new GetRPDODataMessage(requestElementString); + long waitTime = 0; + if (null != jobsDataMsg.getRequestMessageType()) { + if (null != jobsDataMsg.getRequestMessageType().getRequestHeader()) { + waitTime = jobsDataMsg.getRequestMessageType().getRequestHeader().getResultWaittimeMs(); + } + } + + return execute(new GetRPDOHandler(jobsDataMsg), waitTime); + } + + + /** + * This function rename the RPDO Tables + * + * It accepts incoming request, and returns a response, both in i2b2 message format. + * + * @param OMElement + * getAllJobsElement + * @return OMElement in i2b2message format + * @throws Exception + */ + public OMElement deleteTable(OMElement getAllJobsElement) throws I2B2Exception { + String crcDataResponse = null; + String unknownErrMsg = null; + if (null == getAllJobsElement) { + log.error("Incoming CRC request is null"); + unknownErrMsg = "Error message delivered from the remote server.\nYou may wish to retry your last action"; + ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, unknownErrMsg); + crcDataResponse = MessageFactory.convertToXMLString(responseMsgType); + return MessageFactory.createResponseOMElementFromString(crcDataResponse); + } + String requestElementString = getAllJobsElement.toString(); + GetRPDODataMessage jobsDataMsg = new GetRPDODataMessage(requestElementString); + long waitTime = 0; + if (null != jobsDataMsg.getRequestMessageType()) { + if (null != jobsDataMsg.getRequestMessageType().getRequestHeader()) { + waitTime = jobsDataMsg.getRequestMessageType().getRequestHeader().getResultWaittimeMs(); + } + } + + return execute(new GetRPDODeleteHandler(jobsDataMsg), waitTime); + } + + /** + * This function rename the RPDO Tables + * + * It accepts incoming request, and returns a response, both in i2b2 message format. + * + * @param OMElement + * getAllJobsElement + * @return OMElement in i2b2message format + * @throws Exception + */ + public OMElement renameTable(OMElement getAllJobsElement) throws I2B2Exception { + String crcDataResponse = null; + String unknownErrMsg = null; + if (null == getAllJobsElement) { + log.error("Incoming CRC request is null"); + unknownErrMsg = "Error message delivered from the remote server.\nYou may wish to retry your last action"; + ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, unknownErrMsg); + crcDataResponse = MessageFactory.convertToXMLString(responseMsgType); + return MessageFactory.createResponseOMElementFromString(crcDataResponse); + } + String requestElementString = getAllJobsElement.toString(); + GetRPDODataMessage jobsDataMsg = new GetRPDODataMessage(requestElementString); + long waitTime = 0; + if (null != jobsDataMsg.getRequestMessageType()) { + if (null != jobsDataMsg.getRequestMessageType().getRequestHeader()) { + waitTime = jobsDataMsg.getRequestMessageType().getRequestHeader().getResultWaittimeMs(); + } + } + + return execute(new GetRPDORenameHandler(jobsDataMsg), waitTime); + } + + + /** + * This function save the RPDO Tables + * + * It accepts incoming request, and returns a response, both in i2b2 message format. + * + * @param OMElement + * getAllJobsElement + * @return OMElement in i2b2message format + * @throws Exception + */ + public OMElement setTable(OMElement getAllJobsElement) throws I2B2Exception { + String crcDataResponse = null; + String unknownErrMsg = null; + if (null == getAllJobsElement) { + log.error("Incoming CRC request is null"); + unknownErrMsg = "Error message delivered from the remote server.\nYou may wish to retry your last action"; + ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, unknownErrMsg); + crcDataResponse = MessageFactory.convertToXMLString(responseMsgType); + return MessageFactory.createResponseOMElementFromString(crcDataResponse); + } + String requestElementString = getAllJobsElement.toString(); + GetRPDODataMessage jobsDataMsg = new GetRPDODataMessage(requestElementString); + long waitTime = 0; + if (null != jobsDataMsg.getRequestMessageType()) { + if (null != jobsDataMsg.getRequestMessageType().getRequestHeader()) { + waitTime = jobsDataMsg.getRequestMessageType().getRequestHeader().getResultWaittimeMs(); + } + } + return execute(new GetRPDOSetHandler(jobsDataMsg), waitTime); + + } + + /** + * This function save the RPDO Tables + * + * It accepts incoming request, and returns a response, both in i2b2 message format. + * + * @param OMElement + * getAllJobsElement + * @return OMElement in i2b2message format + * @throws Exception + */ + public OMElement makeRequest(OMElement getAllJobsElement) throws I2B2Exception { + String crcDataResponse = null; + String unknownErrMsg = null; + if (null == getAllJobsElement) { + log.error("Incoming CRC request is null"); + unknownErrMsg = "Error message delivered from the remote server.\nYou may wish to retry your last action"; + ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, unknownErrMsg); + crcDataResponse = MessageFactory.convertToXMLString(responseMsgType); + return MessageFactory.createResponseOMElementFromString(crcDataResponse); + } + String requestElementString = getAllJobsElement.toString(); + GetAllJobsDataMessage jobsDataMsg = new GetAllJobsDataMessage(requestElementString); + long waitTime = 0; + if (null != jobsDataMsg.getRequestMessageType()) { + if (null != jobsDataMsg.getRequestMessageType().getRequestHeader()) { + waitTime = jobsDataMsg.getRequestMessageType().getRequestHeader().getResultWaittimeMs(); + } + } + + return executeJobs(new GetAllJobsHandler(requestElementString), waitTime); + } + + /** + * This function is main webservice interface to get the I2B2HIVE.CRC_DB_LOOKUP data. + * It uses AXIOM elements(OMElement) to conveniently parse xml messages. + * + * It accepts incoming request, and returns a response, both in i2b2 message format. + * + * @param OMElement + * getAllJobsElement + * @return OMElement in i2b2message format + * @throws Exception + */ + public OMElement getAllJobs(OMElement getAllJobsElement) throws I2B2Exception { + String crcDataResponse = null; + String unknownErrMsg = null; + if (null == getAllJobsElement) { + log.error("Incoming CRC request is null"); + unknownErrMsg = "Error message delivered from the remote server.\nYou may wish to retry your last action"; + ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, unknownErrMsg); + crcDataResponse = MessageFactory.convertToXMLString(responseMsgType); + return MessageFactory.createResponseOMElementFromString(crcDataResponse); + } + String requestElementString = getAllJobsElement.toString(); + GetAllJobsDataMessage jobsDataMsg = new GetAllJobsDataMessage(requestElementString); + long waitTime = 0; + if (null != jobsDataMsg.getRequestMessageType()) { + if (null != jobsDataMsg.getRequestMessageType().getRequestHeader()) { + waitTime = jobsDataMsg.getRequestMessageType().getRequestHeader().getResultWaittimeMs(); + } + } + + return executeJobs(new GetAllJobsHandler(requestElementString), waitTime); + } + + public OMElement setJob(OMElement setJobElement) throws I2B2Exception { + String crcDataResponse = null; + String unknownErrMsg = null; + if (null == setJobElement) { + log.error("Incoming CRC request is null"); + unknownErrMsg = "Error message delivered from the remote server.\nYou may wish to retry your last action"; + ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, unknownErrMsg); + crcDataResponse = MessageFactory.convertToXMLString(responseMsgType); + return MessageFactory.createResponseOMElementFromString(crcDataResponse); + } + String requestElementString = setJobElement.toString(); + SetJobDataMessage jobsDataMsg = new SetJobDataMessage(requestElementString); + long waitTime = 0; + if (null != jobsDataMsg.getRequestMessageType()) { + if (null != jobsDataMsg.getRequestMessageType().getRequestHeader()) { + waitTime = jobsDataMsg.getRequestMessageType().getRequestHeader().getResultWaittimeMs(); + } + } + + return executeJobs(new SetJobHandler(requestElementString), waitTime); + } + + public OMElement getLoadDataStatusRequest(OMElement request) { + Assert.notNull(request, + "get load Data status request OMElement must not be null"); + log.debug("Inside load status request " + request); + + //LoaderQueryReqDel handles permissions... + LoaderQueryRequestDelegate queryDelegate = new LoaderQueryRequestDelegate(); + OMElement responseElement = null; + try { + String requestXml = request.toString(); + GetLoadStatusRequestHandler handler = new GetLoadStatusRequestHandler( + requestXml); + String response = queryDelegate.handleRequest(requestXml, handler); + responseElement = buildOMElementFromString(response); + + } catch (Exception e) { + log.error("i2b2 exception", e); + } catch (Throwable e) { + log.error("Throwable", e); + } + return responseElement; + + } + + + private OMElement executeJobs(JobReqHandler getAllJobsHandler, long waitTime) throws I2B2Exception { + //do processing inside thread, so that service could send back message with timeout error. + OMElement returnElement = null; + String unknownErrorMessage = "Error message delivered from the remote server \nYou may wish to retry your last action"; + ExecutorRunnable er = new ExecutorRunnable(); + er.setJobReqHandler(getAllJobsHandler); + Thread t = new Thread(er); + String dataResponse = null; + log.info("waiting " + waitTime + "ms for response from remote server processing " + getAllJobsHandler.getClass().getName()); + synchronized (t) { + t.start(); + try { + long startTime = System.currentTimeMillis(); + long deltaTime = -1; + while((er.isJobCompleteFlag() == false) && (deltaTime < waitTime)) { + if (waitTime > 0) { + t.wait(waitTime - deltaTime); + deltaTime = System.currentTimeMillis() - startTime; + } else { + t.wait(); + } + } + dataResponse = er.getOutputString(); + if (dataResponse == null) { + ResponseMessageType responseMsgType = null; + if (!er.isJobCompleteFlag()) { + String timeOuterror = "Remote server timed out after waittime of " + waitTime + "ms."; + log.error(timeOuterror); + responseMsgType = MessageFactory.doBuildErrorResponse(null, timeOuterror); + } else { + if (null != er.getJobException()) { + log.error("jobException: " + er.getJobException().getMessage()); + dataResponse = MessageFactory.convertToXMLString(responseMsgType); + } else { + log.error("CRC data response is null!"); + log.info("CRC waited " + deltaTime + "ms for " + getAllJobsHandler.getClass().getName()); + } + log.info("waitTime is " + waitTime); + responseMsgType = MessageFactory.doBuildErrorResponse(null, unknownErrorMessage); + dataResponse = MessageFactory.convertToXMLString(responseMsgType); + } + dataResponse = MessageFactory.convertToXMLString(responseMsgType); + } + } catch (InterruptedException e) { + log.error(e.getMessage()); + throw new I2B2Exception("Thread error while running CRC job!"); + } finally { + t.interrupt(); + er = null; + t = null; + } + } + returnElement = MessageFactory.createResponseOMElementFromString(dataResponse); + return returnElement; + } + + + private OMElement execute(RPDOReqHandler handler, long waitTime) throws I2B2Exception { + //do processing inside thread, so that service could send back message with timeout error. + OMElement returnElement = null; + String unknownErrorMessage = "Error message delivered from the remote server \nYou may wish to retry your last action"; + ExecutorRunnable er = new ExecutorRunnable(); + er.setRpdoHandler(handler); + Thread t = new Thread(er); + String dataResponse = null; + log.info("waiting " + waitTime + "ms for response from remote server processing " + handler.getClass().getName()); + synchronized (t) { + t.start(); + try { + long startTime = System.currentTimeMillis(); + long deltaTime = -1; + while((er.isJobCompleteFlag() == false) && (deltaTime < waitTime)) { + if (waitTime > 0) { + t.wait(waitTime - deltaTime); + deltaTime = System.currentTimeMillis() - startTime; + } else { + t.wait(); + } + } + dataResponse = er.getOutputString(); + if (dataResponse == null) { + ResponseMessageType responseMsgType = null; + if (!er.isJobCompleteFlag()) { + String timeOuterror = "Remote server timed out after waittime of " + waitTime + "ms."; + log.error(timeOuterror); + responseMsgType = MessageFactory.doBuildErrorResponse(null, timeOuterror); + } else { + if (null != er.getJobException()) { + log.error("jobException: " + er.getJobException().getMessage()); + dataResponse = MessageFactory.convertToXMLString(responseMsgType); + } else { + log.error("CRC data response is null!"); + log.info("CRC waited " + deltaTime + "ms for " + handler.getClass().getName()); + } + log.info("waitTime is " + waitTime); + responseMsgType = MessageFactory.doBuildErrorResponse(null, unknownErrorMessage); + dataResponse = MessageFactory.convertToXMLString(responseMsgType); + } + dataResponse = MessageFactory.convertToXMLString(responseMsgType); + } + } catch (InterruptedException e) { + log.error(e.getMessage()); + throw new I2B2Exception("Thread error while running CRC job!"); + } finally { + t.interrupt(); + er = null; + t = null; + } + } + returnElement = MessageFactory.createResponseOMElementFromString(dataResponse); + return returnElement; + } + + + //swc20160523 copied from edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/ws/IMService.java + private OMElement execute(DbLookupReqHandler handler, long waitTime) throws I2B2Exception { + //do processing inside thread, so that service could send back message with timeout error. + OMElement returnElement = null; + String unknownErrorMessage = "Error message delivered from the remote server \nYou may wish to retry your last action"; + ExecutorRunnable er = new ExecutorRunnable(); + er.setDbLookupReqHandler(handler); + Thread t = new Thread(er); + String dataResponse = null; + log.info("waiting " + waitTime + "ms for response from remote server processing " + handler.getClass().getName()); + synchronized (t) { + t.start(); + try { + long startTime = System.currentTimeMillis(); + long deltaTime = -1; + while((er.isJobCompleteFlag() == false) && (deltaTime < waitTime)) { + if (waitTime > 0) { + t.wait(waitTime - deltaTime); + deltaTime = System.currentTimeMillis() - startTime; + } else { + t.wait(); + } + } + dataResponse = er.getOutputString(); + if (dataResponse == null) { + ResponseMessageType responseMsgType = null; + if (!er.isJobCompleteFlag()) { + String timeOuterror = "Remote server timed out after waittime of " + waitTime + "ms."; + log.error(timeOuterror); + responseMsgType = MessageFactory.doBuildErrorResponse(null, timeOuterror); + } else { + if (null != er.getJobException()) { + log.error("jobException: " + er.getJobException().getMessage()); + dataResponse = MessageFactory.convertToXMLString(responseMsgType); + } else { + log.error("CRC data response is null!"); + log.info("CRC waited " + deltaTime + "ms for " + handler.getClass().getName()); + } + log.info("waitTime is " + waitTime); + responseMsgType = MessageFactory.doBuildErrorResponse(null, unknownErrorMessage); + dataResponse = MessageFactory.convertToXMLString(responseMsgType); + } + dataResponse = MessageFactory.convertToXMLString(responseMsgType); + } + } catch (InterruptedException e) { + log.error(e.getMessage()); + throw new I2B2Exception("Thread error while running CRC job!"); + } finally { + t.interrupt(); + er = null; + t = null; + } + } + returnElement = MessageFactory.createResponseOMElementFromString(dataResponse); + return returnElement; + } + + + /** swc20160523 + * This function is main webservice interface to get the I2B2HIVE.CRC_DB_LOOKUP data. + * It uses AXIOM elements(OMElement) to conveniently parse xml messages. + * + * It accepts incoming request, and returns a response, both in i2b2 message format. + * + * @param OMElement + * getAllDblookupsElement + * @return OMElement in i2b2message format + * @throws Exception + */ + public OMElement getAllDblookups(OMElement getAllDblookupsElement) throws I2B2Exception { + String crcDataResponse = null; + String unknownErrMsg = null; + if (null == getAllDblookupsElement) { + log.error("Incoming CRC request is null"); + unknownErrMsg = "Error message delivered from the remote server.\nYou may wish to retry your last action"; + ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, unknownErrMsg); + crcDataResponse = MessageFactory.convertToXMLString(responseMsgType); + return MessageFactory.createResponseOMElementFromString(crcDataResponse); + } + String requestElementString = getAllDblookupsElement.toString(); + GetAllDblookupsDataMessage dblookupsDataMsg = new GetAllDblookupsDataMessage(requestElementString); + long waitTime = 0; + if (null != dblookupsDataMsg.getRequestMessageType()) { + if (null != dblookupsDataMsg.getRequestMessageType().getRequestHeader()) { + waitTime = dblookupsDataMsg.getRequestMessageType().getRequestHeader().getResultWaittimeMs(); + } + } + // do processing inside thread, so that service could send back message with timeout error. + return execute(new GetAllDblookupsHandler(dblookupsDataMsg), waitTime); + } + + /** swc20160523 + * This function is main webservice interface to get specific I2B2HIVE.CRC_DB_LOOKUP data. + * It uses AXIOM elements(OMElement) to conveniently parse xml messages. + * + * It accepts incoming request, and returns a response, both in i2b2 message format. + * + * @param OMElement + * getDblookupElement + * @return OMElement in i2b2message format + * @throws Exception + */ + public OMElement getDblookup(OMElement getDblookupElement) throws I2B2Exception { + String crcDataResponse = null; + String unknownErrMsg = null; + if (null == getDblookupElement) { + log.error("Incoming CRC request is null"); + unknownErrMsg = "Error message delivered from the remote server.\nYou may wish to retry your last action"; + ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, unknownErrMsg); + crcDataResponse = MessageFactory.convertToXMLString(responseMsgType); + return MessageFactory.createResponseOMElementFromString(crcDataResponse); + } + String requestElementString = getDblookupElement.toString(); + GetDblookupDataMessage dblookupDataMsg = new GetDblookupDataMessage(requestElementString); + long waitTime = 0; + if (null != dblookupDataMsg.getRequestMessageType()) { + if (null != dblookupDataMsg.getRequestMessageType().getRequestHeader()) { + waitTime = dblookupDataMsg.getRequestMessageType().getRequestHeader().getResultWaittimeMs(); + } + } + // do processing inside thread, so that service could send back message with timeout error. + return execute(new GetDblookupHandler(dblookupDataMsg), waitTime); + } + + /** swc20160523 + * This function is main webservice interface to add a new entry to the I2B2HIVE.CRC_DB_LOOKUP data. + * It uses AXIOM elements(OMElement) to conveniently parse xml messages. + * + * It accepts incoming request, and returns a response, both in i2b2 message format. + * + * @param OMElement + * getAllDblookupsElement + * @return OMElement in i2b2message format + * @throws Exception + */ + public OMElement setDblookup(OMElement setDblookupElement) throws I2B2Exception { + String crcDataResponse = null; + String unknownErrMsg = null; + if (null == setDblookupElement) { + log.error("Incoming CRC request is null"); + unknownErrMsg = "Error message delivered from the remote server.\nYou may wish to retry your last action"; + ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, unknownErrMsg); + crcDataResponse = MessageFactory.convertToXMLString(responseMsgType); + return MessageFactory.createResponseOMElementFromString(crcDataResponse); + } + String requestElementString = setDblookupElement.toString(); + SetDblookupDataMessage dblookupDataMsg = new SetDblookupDataMessage(requestElementString); + long waitTime = 0; + if (null != dblookupDataMsg.getRequestMessageType()) { + if (null != dblookupDataMsg.getRequestMessageType().getRequestHeader()) { + waitTime = dblookupDataMsg.getRequestMessageType().getRequestHeader().getResultWaittimeMs(); + } + } + // do processing inside thread, so that service could send back message with timeout error. + return execute(new SetDblookupHandler(dblookupDataMsg), waitTime); + } + + /** swc20160523 + * This function is main webservice interface to delete specific I2B2HIVE.CRC_DB_LOOKUP data. + * It uses AXIOM elements(OMElement) to conveniently parse xml messages. + * + * It accepts incoming request, and returns a response, both in i2b2 message format. + * + * @param OMElement + * deleteDblookupElement + * @return OMElement in i2b2message format + * @throws Exception + */ + public OMElement deleteDblookup(OMElement deleteDblookupElement) throws I2B2Exception { + String crcDataResponse = null; + String unknownErrMsg = null; + if (null == deleteDblookupElement) { + log.error("Incoming CRC request is null"); + unknownErrMsg = "Error message delivered from the remote server.\nYou may wish to retry your last action"; + ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, unknownErrMsg); + crcDataResponse = MessageFactory.convertToXMLString(responseMsgType); + return MessageFactory.createResponseOMElementFromString(crcDataResponse); + } + String requestElementString = deleteDblookupElement.toString(); + DeleteDblookupDataMessage dblookupDataMsg = new DeleteDblookupDataMessage(requestElementString); + long waitTime = 0; + if (null != dblookupDataMsg.getRequestMessageType()) { + if (null != dblookupDataMsg.getRequestMessageType().getRequestHeader()) { + waitTime = dblookupDataMsg.getRequestMessageType().getRequestHeader().getResultWaittimeMs(); + } + } + // do processing inside thread, so that service could send back message with timeout error. + return execute(new DeleteDblookupHandler(dblookupDataMsg), waitTime); + } + + + + //TODO removed loader + // added back above (lcp5) + /* + public OMElement getLoadDataStatusRequest(OMElement request) { + Assert.notNull(request, + "Data load status request OMElement must not be null"); + log.debug("Inside data load status request " + request); + ProviderRestService rs = new ProviderRestService(); + return rs.getLoadDataStatusRequest(request); + } + + public OMElement getMissingTermRequest(OMElement request) { + Assert.notNull(request, + "Missing term request OMElement must not be null"); + log.debug("Inside missing term request " + request); + ProviderRestService rs = new ProviderRestService(); + return rs.getMissingTermRequest(request); + } + */ + // -------------------------------------------- + // Creates delegate based on the request type + // -------------------------------------------- + private OMElement handleRequest(String requestType, OMElement request) { + RequestHandlerDelegate requestHandlerDelegate = null; + + if (requestType.equals(PDO_REQUEST)) { + requestHandlerDelegate = new PdoQueryRequestDelegate(); + } else if (requestType.equals(SETFINDER_REQUEST)) { + requestHandlerDelegate = new QueryRequestDelegate(); + } else if (requestType.equals(GETNAMEINFO_REQUEST)) { + requestHandlerDelegate = new GetNameInfoRequestDelegate(); + } else if (requestType.equals(QTBREAKDOWN_REQUEST)) { + requestHandlerDelegate = new QTBreakdownRequestDelegate(); + // } else if (requestType.equals(REDCAP_REQUEST)) { + // requestHandlerDelegate = new RedCapRequestDelegate(); + } + OMElement returnElement = null; + try { + // call delegate's handleRequest function + String xmlString= request.toStringWithConsume(); + String response = requestHandlerDelegate.handleRequest(request + .toString()); + log.debug("Response in service" + response); + returnElement = buildOMElementFromString(response); + } catch (XMLStreamException e) { + log.error("xml stream exception", e); + } catch (I2B2Exception e) { + log.error("i2b2 exception", e); + } catch (Throwable e) { + log.error("Throwable", e); + } + return returnElement; + } + + /** + * Function constructs OMElement for the given String + * + * @param xmlString + * @return OMElement + * @throws XMLStreamException + */ + private OMElement buildOMElementFromString(String xmlString) + throws XMLStreamException { + XMLInputFactory xif = XMLInputFactory.newInstance(); + StringReader strReader = new StringReader(xmlString); + XMLStreamReader reader = xif.createXMLStreamReader(strReader); + OMElement element = OMXMLBuilderFactory.createStAXOMBuilder(reader).getDocumentElement(); + + return element; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/axis2/RequestDataMessage.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/axis2/RequestDataMessage.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/axis2/RequestDataMessage.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/axis2/RequestDataMessage.java index d137c0e3..cbf63eba --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/axis2/RequestDataMessage.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/axis2/RequestDataMessage.java @@ -1,178 +1,178 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Raj Kuttan - * Lori Phillips - */ -package edu.harvard.i2b2.crc.axis2; - -import java.io.StringWriter; -import java.math.BigDecimal; -import java.util.Date; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.DTOFactory; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -//import edu.harvard.i2b2.crc.util.QueryProcessorUtil; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.i2b2message.ApplicationType; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2message.FacilityType; -import edu.harvard.i2b2.crc.datavo.i2b2message.MessageControlIdType; -import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ProcessingIdType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import jakarta.xml.bind.JAXBElement; - - -/** - * The RequestDataMessage class is a helper class to build Workplace messages in the - * i2b2 format - */ -public abstract class RequestDataMessage{ - protected final Log log = LogFactory.getLog(getClass()); - - public RequestMessageType reqMessageType = null; - - public void setRequestMessageType(String requestWdo) throws I2B2Exception { - try { - JAXBElement jaxbElement = CRCJAXBUtil.getJAXBUtil().unMashallFromString(requestWdo); - this.reqMessageType = (RequestMessageType) jaxbElement.getValue(); - - } catch (JAXBUtilException e) { - throw new I2B2Exception("Umarshaller error: " + e.getMessage() + - requestWdo, e); - } - } - - - /** - * Function to build i2b2 message header - * - * @return MessageHeader object - */ - public MessageHeaderType getMessageHeader() { - MessageHeaderType messageHeader = new MessageHeaderType(); - - messageHeader.setI2B2VersionCompatible(new BigDecimal("1.1")); - messageHeader.setHl7VersionCompatible(new BigDecimal("2.4")); - - ApplicationType appType = new ApplicationType(); - appType.setApplicationName("CRC Cell"); - appType.setApplicationVersion("1.700"); - messageHeader.setSendingApplication(appType); - - FacilityType facility = new FacilityType(); - facility.setFacilityName("i2b2 Hive"); - messageHeader.setSendingFacility(facility); - - ApplicationType appType2 = new ApplicationType(); - appType2.setApplicationVersion("1.700"); - appType2.setApplicationName("i2b2_QueryTool"); - messageHeader.setReceivingApplication(appType2); - - FacilityType facility2 = new FacilityType(); - facility2.setFacilityName("i2b2 Hive"); - messageHeader.setReceivingFacility(facility2); - - Date currentDate = new Date(); - DTOFactory factory = new DTOFactory(); - messageHeader.setDatetimeOfMessage(factory.getXMLGregorianCalendar(currentDate.getTime())); - - MessageControlIdType mcIdType = new MessageControlIdType(); - mcIdType.setInstanceNum(0); - mcIdType.setMessageNum(generateMessageId()); - messageHeader.setMessageControlId(mcIdType); - - ProcessingIdType proc = new ProcessingIdType(); - proc.setProcessingId("P"); - proc.setProcessingMode("I"); - messageHeader.setProcessingId(proc); - - messageHeader.setAcceptAcknowledgementType("AL"); - messageHeader.setApplicationAcknowledgementType("AL"); - messageHeader.setCountryCode("US"); - - return messageHeader; - } - - /** - * Function to generate i2b2 message header message number - * - * @return String - */ - protected String generateMessageId() { - StringWriter strWriter = new StringWriter(); - for(int i=0; i<20; i++) { - int num = getValidAcsiiValue(); - strWriter.append((char)num); - } - return strWriter.toString(); - } - /** - * Function to build i2b2 Request message header - * - * @return RequestHeader object - */ - public RequestHeaderType getRequestHeader() { - RequestHeaderType reqHeader = new RequestHeaderType(); - reqHeader.setResultWaittimeMs(120000); - return reqHeader; - } - - - /** - * Function to build Request message type - * - * @param messageHeader MessageHeader object - * @param reqHeader RequestHeader object - * @param bodyType BodyType object - * @return RequestMessageType object - */ - public RequestMessageType getRequestMessageType(MessageHeaderType messageHeader, - RequestHeaderType reqHeader, BodyType bodyType) { - RequestMessageType reqMsgType = new RequestMessageType(); - reqMsgType.setMessageHeader(messageHeader); - reqMsgType.setMessageBody(bodyType); - reqMsgType.setRequestHeader(reqHeader); - return reqMsgType; - } - - /** - * Function to generate random number used in message number - * - * @return int - */ - private int getValidAcsiiValue() { - int number = 48; - while(true) { - number = 48+(int) Math.round(Math.random() * 74); - if((number > 47 && number < 58) || (number > 64 && number < 91) - || (number > 96 && number < 123)) { - break; - } - } - return number; - } - public RequestMessageType getRequestMessageType() { - return reqMessageType; - } - - public MessageHeaderType getMessageHeaderType() { - return reqMessageType.getMessageHeader(); - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Raj Kuttan + * Lori Phillips + */ +package edu.harvard.i2b2.crc.axis2; + +import java.io.StringWriter; +import java.math.BigDecimal; +import java.util.Date; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.DTOFactory; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +//import edu.harvard.i2b2.crc.util.QueryProcessorUtil; +import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; +import edu.harvard.i2b2.crc.datavo.i2b2message.ApplicationType; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2message.FacilityType; +import edu.harvard.i2b2.crc.datavo.i2b2message.MessageControlIdType; +import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ProcessingIdType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import jakarta.xml.bind.JAXBElement; + + +/** + * The RequestDataMessage class is a helper class to build Workplace messages in the + * i2b2 format + */ +public abstract class RequestDataMessage{ + protected final Log log = LogFactory.getLog(getClass()); + + public RequestMessageType reqMessageType = null; + + public void setRequestMessageType(String requestWdo) throws I2B2Exception { + try { + JAXBElement jaxbElement = CRCJAXBUtil.getJAXBUtil().unMashallFromString(requestWdo); + this.reqMessageType = (RequestMessageType) jaxbElement.getValue(); + + } catch (JAXBUtilException e) { + throw new I2B2Exception("Umarshaller error: " + e.getMessage() + + requestWdo, e); + } + } + + + /** + * Function to build i2b2 message header + * + * @return MessageHeader object + */ + public MessageHeaderType getMessageHeader() { + MessageHeaderType messageHeader = new MessageHeaderType(); + + messageHeader.setI2B2VersionCompatible(new BigDecimal("1.1")); + messageHeader.setHl7VersionCompatible(new BigDecimal("2.4")); + + ApplicationType appType = new ApplicationType(); + appType.setApplicationName("CRC Cell"); + appType.setApplicationVersion("1.700"); + messageHeader.setSendingApplication(appType); + + FacilityType facility = new FacilityType(); + facility.setFacilityName("i2b2 Hive"); + messageHeader.setSendingFacility(facility); + + ApplicationType appType2 = new ApplicationType(); + appType2.setApplicationVersion("1.700"); + appType2.setApplicationName("i2b2_QueryTool"); + messageHeader.setReceivingApplication(appType2); + + FacilityType facility2 = new FacilityType(); + facility2.setFacilityName("i2b2 Hive"); + messageHeader.setReceivingFacility(facility2); + + Date currentDate = new Date(); + DTOFactory factory = new DTOFactory(); + messageHeader.setDatetimeOfMessage(factory.getXMLGregorianCalendar(currentDate.getTime())); + + MessageControlIdType mcIdType = new MessageControlIdType(); + mcIdType.setInstanceNum(0); + mcIdType.setMessageNum(generateMessageId()); + messageHeader.setMessageControlId(mcIdType); + + ProcessingIdType proc = new ProcessingIdType(); + proc.setProcessingId("P"); + proc.setProcessingMode("I"); + messageHeader.setProcessingId(proc); + + messageHeader.setAcceptAcknowledgementType("AL"); + messageHeader.setApplicationAcknowledgementType("AL"); + messageHeader.setCountryCode("US"); + + return messageHeader; + } + + /** + * Function to generate i2b2 message header message number + * + * @return String + */ + protected String generateMessageId() { + StringWriter strWriter = new StringWriter(); + for(int i=0; i<20; i++) { + int num = getValidAcsiiValue(); + strWriter.append((char)num); + } + return strWriter.toString(); + } + /** + * Function to build i2b2 Request message header + * + * @return RequestHeader object + */ + public RequestHeaderType getRequestHeader() { + RequestHeaderType reqHeader = new RequestHeaderType(); + reqHeader.setResultWaittimeMs(120000); + return reqHeader; + } + + + /** + * Function to build Request message type + * + * @param messageHeader MessageHeader object + * @param reqHeader RequestHeader object + * @param bodyType BodyType object + * @return RequestMessageType object + */ + public RequestMessageType getRequestMessageType(MessageHeaderType messageHeader, + RequestHeaderType reqHeader, BodyType bodyType) { + RequestMessageType reqMsgType = new RequestMessageType(); + reqMsgType.setMessageHeader(messageHeader); + reqMsgType.setMessageBody(bodyType); + reqMsgType.setRequestHeader(reqHeader); + return reqMsgType; + } + + /** + * Function to generate random number used in message number + * + * @return int + */ + private int getValidAcsiiValue() { + int number = 48; + while(true) { + number = 48+(int) Math.round(Math.random() * 74); + if((number > 47 && number < 58) || (number > 64 && number < 91) + || (number > 96 && number < 123)) { + break; + } + } + return number; + } + public RequestMessageType getRequestMessageType() { + return reqMessageType; + } + + public MessageHeaderType getMessageHeaderType() { + return reqMessageType.getMessageHeader(); + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/axis2/ResponseDataMessage.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/axis2/ResponseDataMessage.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/axis2/ResponseDataMessage.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/axis2/ResponseDataMessage.java index a466c810..93bc1ed6 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/axis2/ResponseDataMessage.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/axis2/ResponseDataMessage.java @@ -1,186 +1,186 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Raj Kuttan - * Lori Phillips - */ -package edu.harvard.i2b2.crc.axis2; - -import java.io.StringWriter; -import java.math.BigDecimal; -import java.util.Date; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.DTOFactory; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.i2b2message.ApplicationType; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2message.FacilityType; -import edu.harvard.i2b2.crc.datavo.i2b2message.MessageControlIdType; -import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ProcessingIdType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResultStatusType; -import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import jakarta.xml.bind.JAXBElement; - - -/** - * The ResponseDataMessage class is a helper class to build Workplace messages in the - * i2b2 format - */ -public abstract class ResponseDataMessage{ - protected final Log log = LogFactory.getLog(getClass()); - - public ResponseMessageType reqMessageType = null; - - public void setResponseMessageType(String responseWdo) throws I2B2Exception { - try { - JAXBElement jaxbElement = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseWdo); - this.reqMessageType = (ResponseMessageType) jaxbElement.getValue(); - - } catch (JAXBUtilException e) { - throw new I2B2Exception("Umarshaller error: " + e.getMessage() + - responseWdo, e); - } - } - - - /** - * Function to build i2b2 message header - * - * @return MessageHeader object - */ - public MessageHeaderType getMessageHeader() { - MessageHeaderType messageHeader = new MessageHeaderType(); - - messageHeader.setI2B2VersionCompatible(new BigDecimal("1.1")); - messageHeader.setHl7VersionCompatible(new BigDecimal("2.4")); - - ApplicationType appType = new ApplicationType(); - appType.setApplicationName("CRC Cell"); - appType.setApplicationVersion("1.700"); - messageHeader.setSendingApplication(appType); - - FacilityType facility = new FacilityType(); - facility.setFacilityName("i2b2 Hive"); - messageHeader.setSendingFacility(facility); - - ApplicationType appType2 = new ApplicationType(); - appType2.setApplicationVersion("1.700"); - appType2.setApplicationName("i2b2_QueryTool"); - messageHeader.setReceivingApplication(appType2); - - FacilityType facility2 = new FacilityType(); - facility2.setFacilityName("i2b2 Hive"); - messageHeader.setReceivingFacility(facility2); - - Date currentDate = new Date(); - DTOFactory factory = new DTOFactory(); - messageHeader.setDatetimeOfMessage(factory.getXMLGregorianCalendar(currentDate.getTime())); - - MessageControlIdType mcIdType = new MessageControlIdType(); - mcIdType.setInstanceNum(0); - mcIdType.setMessageNum(generateMessageId()); - messageHeader.setMessageControlId(mcIdType); - - ProcessingIdType proc = new ProcessingIdType(); - proc.setProcessingId("P"); - proc.setProcessingMode("I"); - messageHeader.setProcessingId(proc); - - messageHeader.setAcceptAcknowledgementType("AL"); - messageHeader.setApplicationAcknowledgementType("AL"); - messageHeader.setCountryCode("US"); - - return messageHeader; - } - - /** - * Function to generate i2b2 message header message number - * - * @return String - */ - protected String generateMessageId() { - StringWriter strWriter = new StringWriter(); - for(int i=0; i<20; i++) { - int num = getValidAcsiiValue(); - strWriter.append((char)num); - } - return strWriter.toString(); - } - /** - * Function to build i2b2 Response message header - * - * @return ResponseHeader object - */ - public ResponseHeaderType getResponseHeader() { - ResponseHeaderType reqHeader = new ResponseHeaderType(); - - StatusType status = new StatusType(); - status.setType("DONE"); - status.setValue("DONE"); - - ResultStatusType resStat = new ResultStatusType(); - resStat.setStatus(status); - reqHeader.setResultStatus(resStat); - return reqHeader; - } - - - /** - * Function to build Response message type - * - * @param messageHeader MessageHeader object - * @param reqHeader ResponseHeader object - * @param bodyType BodyType object - * @return ResponseMessageType object - */ - public ResponseMessageType getResponseMessageType(MessageHeaderType messageHeader, - ResponseHeaderType reqHeader, BodyType bodyType) { - ResponseMessageType reqMsgType = new ResponseMessageType(); - reqMsgType.setMessageHeader(messageHeader); - reqMsgType.setMessageBody(bodyType); - reqMsgType.setResponseHeader(reqHeader); - return reqMsgType; - } - - /** - * Function to generate random number used in message number - * - * @return int - */ - private int getValidAcsiiValue() { - int number = 48; - while(true) { - number = 48+(int) Math.round(Math.random() * 74); - if((number > 47 && number < 58) || (number > 64 && number < 91) - || (number > 96 && number < 123)) { - break; - } - } - return number; - } - public ResponseMessageType getResponseMessageType() { - return reqMessageType; - } - - public MessageHeaderType getMessageHeaderType() { - return reqMessageType.getMessageHeader(); - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Raj Kuttan + * Lori Phillips + */ +package edu.harvard.i2b2.crc.axis2; + +import java.io.StringWriter; +import java.math.BigDecimal; +import java.util.Date; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.DTOFactory; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; +import edu.harvard.i2b2.crc.datavo.i2b2message.ApplicationType; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2message.FacilityType; +import edu.harvard.i2b2.crc.datavo.i2b2message.MessageControlIdType; +import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ProcessingIdType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResultStatusType; +import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import jakarta.xml.bind.JAXBElement; + + +/** + * The ResponseDataMessage class is a helper class to build Workplace messages in the + * i2b2 format + */ +public abstract class ResponseDataMessage{ + protected final Log log = LogFactory.getLog(getClass()); + + public ResponseMessageType reqMessageType = null; + + public void setResponseMessageType(String responseWdo) throws I2B2Exception { + try { + JAXBElement jaxbElement = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseWdo); + this.reqMessageType = (ResponseMessageType) jaxbElement.getValue(); + + } catch (JAXBUtilException e) { + throw new I2B2Exception("Umarshaller error: " + e.getMessage() + + responseWdo, e); + } + } + + + /** + * Function to build i2b2 message header + * + * @return MessageHeader object + */ + public MessageHeaderType getMessageHeader() { + MessageHeaderType messageHeader = new MessageHeaderType(); + + messageHeader.setI2B2VersionCompatible(new BigDecimal("1.1")); + messageHeader.setHl7VersionCompatible(new BigDecimal("2.4")); + + ApplicationType appType = new ApplicationType(); + appType.setApplicationName("CRC Cell"); + appType.setApplicationVersion("1.700"); + messageHeader.setSendingApplication(appType); + + FacilityType facility = new FacilityType(); + facility.setFacilityName("i2b2 Hive"); + messageHeader.setSendingFacility(facility); + + ApplicationType appType2 = new ApplicationType(); + appType2.setApplicationVersion("1.700"); + appType2.setApplicationName("i2b2_QueryTool"); + messageHeader.setReceivingApplication(appType2); + + FacilityType facility2 = new FacilityType(); + facility2.setFacilityName("i2b2 Hive"); + messageHeader.setReceivingFacility(facility2); + + Date currentDate = new Date(); + DTOFactory factory = new DTOFactory(); + messageHeader.setDatetimeOfMessage(factory.getXMLGregorianCalendar(currentDate.getTime())); + + MessageControlIdType mcIdType = new MessageControlIdType(); + mcIdType.setInstanceNum(0); + mcIdType.setMessageNum(generateMessageId()); + messageHeader.setMessageControlId(mcIdType); + + ProcessingIdType proc = new ProcessingIdType(); + proc.setProcessingId("P"); + proc.setProcessingMode("I"); + messageHeader.setProcessingId(proc); + + messageHeader.setAcceptAcknowledgementType("AL"); + messageHeader.setApplicationAcknowledgementType("AL"); + messageHeader.setCountryCode("US"); + + return messageHeader; + } + + /** + * Function to generate i2b2 message header message number + * + * @return String + */ + protected String generateMessageId() { + StringWriter strWriter = new StringWriter(); + for(int i=0; i<20; i++) { + int num = getValidAcsiiValue(); + strWriter.append((char)num); + } + return strWriter.toString(); + } + /** + * Function to build i2b2 Response message header + * + * @return ResponseHeader object + */ + public ResponseHeaderType getResponseHeader() { + ResponseHeaderType reqHeader = new ResponseHeaderType(); + + StatusType status = new StatusType(); + status.setType("DONE"); + status.setValue("DONE"); + + ResultStatusType resStat = new ResultStatusType(); + resStat.setStatus(status); + reqHeader.setResultStatus(resStat); + return reqHeader; + } + + + /** + * Function to build Response message type + * + * @param messageHeader MessageHeader object + * @param reqHeader ResponseHeader object + * @param bodyType BodyType object + * @return ResponseMessageType object + */ + public ResponseMessageType getResponseMessageType(MessageHeaderType messageHeader, + ResponseHeaderType reqHeader, BodyType bodyType) { + ResponseMessageType reqMsgType = new ResponseMessageType(); + reqMsgType.setMessageHeader(messageHeader); + reqMsgType.setMessageBody(bodyType); + reqMsgType.setResponseHeader(reqHeader); + return reqMsgType; + } + + /** + * Function to generate random number used in message number + * + * @return int + */ + private int getValidAcsiiValue() { + int number = 48; + while(true) { + number = 48+(int) Math.round(Math.random() * 74); + if((number > 47 && number < 58) || (number > 64 && number < 91) + || (number > 96 && number < 123)) { + break; + } + } + return number; + } + public ResponseMessageType getResponseMessageType() { + return reqMessageType; + } + + public MessageHeaderType getMessageHeaderType() { + return reqMessageType.getMessageHeader(); + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/axis2/SetDblookupDataMessage.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/axis2/SetDblookupDataMessage.java similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/axis2/SetDblookupDataMessage.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/axis2/SetDblookupDataMessage.java index 199f8037..eb4fb47f 100644 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/axis2/SetDblookupDataMessage.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/axis2/SetDblookupDataMessage.java @@ -1,46 +1,46 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Wayne Chan - */ -package edu.harvard.i2b2.crc.axis2; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.pdo.query.SetDblookupType; -//import edu.harvard.i2b2.crc.util.I2B2RequestMessageHelper; -//import org.apache.commons.logging.Log; -//import org.apache.commons.logging.LogFactory; - -public class SetDblookupDataMessage extends RequestDataMessage { //swc20160523 - - //private static Log log = LogFactory.getLog(SetDblookupDataMessage.class); - - public SetDblookupDataMessage(String requestElementString) throws I2B2Exception { - super.setRequestMessageType(requestElementString); - } - - /** - * Function to get SetDblookupType object from i2b2 request message type - * @return - * @throws JAXBUtilException - */ - public SetDblookupType setDblookupType() throws JAXBUtilException { - BodyType bodyType = reqMessageType.getMessageBody(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - SetDblookupType setDblookupType = (SetDblookupType) helper.getObjectByClass(bodyType.getAny(), SetDblookupType.class); - return setDblookupType; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Wayne Chan + */ +package edu.harvard.i2b2.crc.axis2; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.pdo.query.SetDblookupType; +//import edu.harvard.i2b2.crc.util.I2B2RequestMessageHelper; +//import org.apache.commons.logging.Log; +//import org.apache.commons.logging.LogFactory; + +public class SetDblookupDataMessage extends RequestDataMessage { //swc20160523 + + //private static Log log = LogFactory.getLog(SetDblookupDataMessage.class); + + public SetDblookupDataMessage(String requestElementString) throws I2B2Exception { + super.setRequestMessageType(requestElementString); + } + + /** + * Function to get SetDblookupType object from i2b2 request message type + * @return + * @throws JAXBUtilException + */ + public SetDblookupType setDblookupType() throws JAXBUtilException { + BodyType bodyType = reqMessageType.getMessageBody(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + SetDblookupType setDblookupType = (SetDblookupType) helper.getObjectByClass(bodyType.getAny(), SetDblookupType.class); + return setDblookupType; + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/axis2/SetJobDataMessage.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/axis2/SetJobDataMessage.java similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/axis2/SetJobDataMessage.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/axis2/SetJobDataMessage.java index fedeff10..448e0f30 100644 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/axis2/SetJobDataMessage.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/axis2/SetJobDataMessage.java @@ -1,48 +1,48 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Wayne Chan - */ -package edu.harvard.i2b2.crc.axis2; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -//import edu.harvard.i2b2.crc.datavo.pdo.query.DblookupsType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.JobsType; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -public class SetJobDataMessage extends RequestDataMessage { - - private static Log log = LogFactory.getLog(SetJobDataMessage.class); - - public SetJobDataMessage(String requestElementString) throws I2B2Exception { - super.setRequestMessageType(requestElementString); - } - - /** - * Function to get jbosType object from i2b2 request message type - * @return - * @throws JAXBUtilException - */ - public JobsType setJobType() throws JAXBUtilException { - //log.info(" getDblookupsType()"); - BodyType bodyType = reqMessageType.getMessageBody(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - JobsType jobsType = (JobsType) helper.getObjectByClass(bodyType.getAny(), JobsType.class); - return jobsType; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Wayne Chan + */ +package edu.harvard.i2b2.crc.axis2; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +//import edu.harvard.i2b2.crc.datavo.pdo.query.DblookupsType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.JobsType; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +public class SetJobDataMessage extends RequestDataMessage { + + private static Log log = LogFactory.getLog(SetJobDataMessage.class); + + public SetJobDataMessage(String requestElementString) throws I2B2Exception { + super.setRequestMessageType(requestElementString); + } + + /** + * Function to get jbosType object from i2b2 request message type + * @return + * @throws JAXBUtilException + */ + public JobsType setJobType() throws JAXBUtilException { + //log.info(" getDblookupsType()"); + BodyType bodyType = reqMessageType.getMessageBody(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + JobsType jobsType = (JobsType) helper.getObjectByClass(bodyType.getAny(), JobsType.class); + return jobsType; + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/CRCDAO.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/CRCDAO.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/CRCDAO.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/CRCDAO.java index ed8222cd..1664a6cf --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/CRCDAO.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/CRCDAO.java @@ -1,125 +1,125 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.ServiceLocator; -import edu.harvard.i2b2.crc.datavo.pdo.query.OutputOptionType; -//import edu.harvard.i2b2.crc.util.HibernateUtil; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - - -import java.sql.Connection; -import java.sql.SQLException; - -import javax.sql.DataSource; - -/** - * DAO abstract class to provide common dao functions $Id: CRCDAO.java,v 1.8 - * 2008/03/27 23:38:50 rk903 Exp $ - * - * @author rkuttan - * @see Connection - * @see Session - */ -public abstract class CRCDAO { - /** log * */ - protected final Log log = LogFactory.getLog(CRCDAO.class); - - protected DataSource dataSource = null; - - protected String dbSchemaName = null; - - /** - * Returns connection from appserver datasource - * - * @return Appserver database Connection - * @throws SQLException - * @throws I2B2DAOException - * @throws SQLException - */ - - protected DataSource getApplicationDataSource(String dataSourceName) - throws I2B2DAOException { - try { - // dataSource = (DataSource) - // crcUtil.getSpringDataSource(dataSourceName); - DataSource dataSource = ServiceLocator.getInstance() - .getAppServerDataSource(dataSourceName); - return dataSource; - } catch (I2B2Exception i2b2Ex) { - log.error(i2b2Ex); - throw new I2B2DAOException( - "Error getting appliation/spring datasource " - + dataSourceName + " : " + i2b2Ex.getMessage(), - i2b2Ex); - } - } - - /** - * Helper function to construct {@link OutputOptionType} from given boolean - * flags - * - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return OutputOptionType - */ - protected OutputOptionType buildOutputOptionType(boolean detailFlag, - boolean blobFlag, boolean statusFlag) { - OutputOptionType outputOptionType = new OutputOptionType(); - outputOptionType.setOnlykeys((detailFlag) ? false : true); - outputOptionType.setBlob(blobFlag); - outputOptionType.setTechdata(statusFlag); - - return outputOptionType; - } - - /** - * Get hibernate session - * - * @return Session - */ -// protected Session getSession() { -// return HibernateUtil.getSession(); -// } - - public DataSource getDataSource() { - return dataSource; - } - - public void setDataSource(DataSource dataSource) { - this.dataSource = dataSource; - } - - public String getDbSchemaName() { - return this.dbSchemaName; - } - - public void setDbSchemaName(String dbSchemaName) { - if (dbSchemaName != null && dbSchemaName.endsWith(".")) { - this.dbSchemaName = dbSchemaName.trim(); - } - else if (dbSchemaName != null) { - this.dbSchemaName = dbSchemaName.trim() + "."; - } - - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.ServiceLocator; +import edu.harvard.i2b2.crc.datavo.pdo.query.OutputOptionType; +//import edu.harvard.i2b2.crc.util.HibernateUtil; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + + +import java.sql.Connection; +import java.sql.SQLException; + +import javax.sql.DataSource; + +/** + * DAO abstract class to provide common dao functions $Id: CRCDAO.java,v 1.8 + * 2008/03/27 23:38:50 rk903 Exp $ + * + * @author rkuttan + * @see Connection + * @see Session + */ +public abstract class CRCDAO { + /** log * */ + protected final Log log = LogFactory.getLog(CRCDAO.class); + + protected DataSource dataSource = null; + + protected String dbSchemaName = null; + + /** + * Returns connection from appserver datasource + * + * @return Appserver database Connection + * @throws SQLException + * @throws I2B2DAOException + * @throws SQLException + */ + + protected DataSource getApplicationDataSource(String dataSourceName) + throws I2B2DAOException { + try { + // dataSource = (DataSource) + // crcUtil.getSpringDataSource(dataSourceName); + DataSource dataSource = ServiceLocator.getInstance() + .getAppServerDataSource(dataSourceName); + return dataSource; + } catch (I2B2Exception i2b2Ex) { + log.error(i2b2Ex); + throw new I2B2DAOException( + "Error getting appliation/spring datasource " + + dataSourceName + " : " + i2b2Ex.getMessage(), + i2b2Ex); + } + } + + /** + * Helper function to construct {@link OutputOptionType} from given boolean + * flags + * + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return OutputOptionType + */ + protected OutputOptionType buildOutputOptionType(boolean detailFlag, + boolean blobFlag, boolean statusFlag) { + OutputOptionType outputOptionType = new OutputOptionType(); + outputOptionType.setOnlykeys((detailFlag) ? false : true); + outputOptionType.setBlob(blobFlag); + outputOptionType.setTechdata(statusFlag); + + return outputOptionType; + } + + /** + * Get hibernate session + * + * @return Session + */ +// protected Session getSession() { +// return HibernateUtil.getSession(); +// } + + public DataSource getDataSource() { + return dataSource; + } + + public void setDataSource(DataSource dataSource) { + this.dataSource = dataSource; + } + + public String getDbSchemaName() { + return this.dbSchemaName; + } + + public void setDbSchemaName(String dbSchemaName) { + if (dbSchemaName != null && dbSchemaName.endsWith(".")) { + this.dbSchemaName = dbSchemaName.trim(); + } + else if (dbSchemaName != null) { + this.dbSchemaName = dbSchemaName.trim() + "."; + } + + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/CRCQueueDAO.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/CRCQueueDAO.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/CRCQueueDAO.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/CRCQueueDAO.java index d15f138a..43476426 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/CRCQueueDAO.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/CRCQueueDAO.java @@ -1,112 +1,112 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao; - -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.List; - -import javax.sql.DataSource; - -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.RowMapper; - -import edu.harvard.i2b2.crc.datavo.db.AnalysisJob; -import edu.harvard.i2b2.crc.datavo.db.StatusEnum; - -public class CRCQueueDAO extends CRCDAO implements ICRCQueueDAO { - JdbcTemplate jdbcTemplate = null; - AnalysisJobRowMapper analysisJobMapper = new AnalysisJobRowMapper(); - - public CRCQueueDAO(DataSource dataSource, String schemaName) { - setDataSource(dataSource); - setDbSchemaName(schemaName); - jdbcTemplate = new JdbcTemplate(dataSource); - } - - @Override - public void addJob(AnalysisJob analysisJob) { - String sql = "insert into " - + getDbSchemaName() - + "CRC_ANALYSIS_JOB(job_id, queue_name, status_type_id,domain_id, project_id, user_id, request_xml, create_date) " - + " values(?,?,?,?,?,?,?,?)"; - Object[] params = new Object[] { analysisJob.getJobId(), - analysisJob.getQueueName(), analysisJob.getStatusTypeId(), - analysisJob.getDomainId(), analysisJob.getProjectId(), - analysisJob.getUserId(), analysisJob.getRequestXml(), - analysisJob.getCreateDate() }; - jdbcTemplate.update(sql, params); - } - - @Override - public List getJob(String jobId, String projectId) { - String sql = "select * from " + getDbSchemaName() - + "CRC_ANALYSIS_JOB where job_id = ? and project_id = ? "; - List analysisJobList = jdbcTemplate.query(sql, - new Object[] { jobId, projectId }, analysisJobMapper); - return analysisJobList; - } - - @Override - public void moveJob(String jobId, String projectId, String queueName, - String statusType) { - String sql = "update " - + getDbSchemaName() - + "CRC_ANALYSIS_JOB set status_type_id = ?, queue_name = ? where job_id = ? and project_id = ?"; - StatusEnum statusEnum = StatusEnum.valueOf(statusType); - - jdbcTemplate.update(sql, new Object[] { statusEnum.ordinal(), - queueName, jobId }); - } - - @Override - public void updateStatus(String jobId, String projectId, String statusType) { - String sql = "update " - + getDbSchemaName() - + "CRC_ANALYSIS_JOB set status_type_id = ? where job_id = ? and project_id =? "; - StatusEnum statusEnum = StatusEnum.valueOf(statusType); - jdbcTemplate.update(sql, new Object[] { statusEnum.ordinal(), jobId, - projectId }); - } - - @Override - public List getJobListByQueuedStatus(String queueName, - int maxReturnSize) { - int QUEUED_STATUS_TYPE_ID = StatusEnum.QUEUED.ordinal(); - JdbcTemplate localJdbcTemplate = new JdbcTemplate(getDataSource()); - String sql = " select * from " - + getDbSchemaName() - + "CRC_ANALYSIS_JOB where queue_name = ? and status_type_id = ? order by create_date"; - localJdbcTemplate.setMaxRows(maxReturnSize); - List analysisJobList = localJdbcTemplate.query(sql, - new Object[] { queueName, QUEUED_STATUS_TYPE_ID }, - analysisJobMapper); - return analysisJobList; - - } - - private class AnalysisJobRowMapper implements RowMapper { - - @Override - public Object mapRow(ResultSet rs, int rowNum) throws SQLException { - AnalysisJob analysisJob = new AnalysisJob(); - analysisJob.setJobId(rs.getString("JOB_ID")); - analysisJob.setQueueName(rs.getString("QUEUE_NAME")); - analysisJob.setStatusTypeId(rs.getInt("STATUS_TYPE_ID")); - analysisJob.setDomainId(rs.getString("DOMAIN_ID")); - analysisJob.setProjectId(rs.getString("PROJECT_ID")); - analysisJob.setUserId(rs.getString("USER_ID")); - analysisJob.setRequestXml(rs.getString("REQUEST_XML")); - analysisJob.setCreateDate(rs.getTimestamp("CREATE_DATE")); - analysisJob.setUpdateDate(rs.getTime("UPDATE_DATE")); - return analysisJob; - } - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.List; + +import javax.sql.DataSource; + +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.RowMapper; + +import edu.harvard.i2b2.crc.datavo.db.AnalysisJob; +import edu.harvard.i2b2.crc.datavo.db.StatusEnum; + +public class CRCQueueDAO extends CRCDAO implements ICRCQueueDAO { + JdbcTemplate jdbcTemplate = null; + AnalysisJobRowMapper analysisJobMapper = new AnalysisJobRowMapper(); + + public CRCQueueDAO(DataSource dataSource, String schemaName) { + setDataSource(dataSource); + setDbSchemaName(schemaName); + jdbcTemplate = new JdbcTemplate(dataSource); + } + + @Override + public void addJob(AnalysisJob analysisJob) { + String sql = "insert into " + + getDbSchemaName() + + "CRC_ANALYSIS_JOB(job_id, queue_name, status_type_id,domain_id, project_id, user_id, request_xml, create_date) " + + " values(?,?,?,?,?,?,?,?)"; + Object[] params = new Object[] { analysisJob.getJobId(), + analysisJob.getQueueName(), analysisJob.getStatusTypeId(), + analysisJob.getDomainId(), analysisJob.getProjectId(), + analysisJob.getUserId(), analysisJob.getRequestXml(), + analysisJob.getCreateDate() }; + jdbcTemplate.update(sql, params); + } + + @Override + public List getJob(String jobId, String projectId) { + String sql = "select * from " + getDbSchemaName() + + "CRC_ANALYSIS_JOB where job_id = ? and project_id = ? "; + List analysisJobList = jdbcTemplate.query(sql, + new Object[] { jobId, projectId }, analysisJobMapper); + return analysisJobList; + } + + @Override + public void moveJob(String jobId, String projectId, String queueName, + String statusType) { + String sql = "update " + + getDbSchemaName() + + "CRC_ANALYSIS_JOB set status_type_id = ?, queue_name = ? where job_id = ? and project_id = ?"; + StatusEnum statusEnum = StatusEnum.valueOf(statusType); + + jdbcTemplate.update(sql, new Object[] { statusEnum.ordinal(), + queueName, jobId }); + } + + @Override + public void updateStatus(String jobId, String projectId, String statusType) { + String sql = "update " + + getDbSchemaName() + + "CRC_ANALYSIS_JOB set status_type_id = ? where job_id = ? and project_id =? "; + StatusEnum statusEnum = StatusEnum.valueOf(statusType); + jdbcTemplate.update(sql, new Object[] { statusEnum.ordinal(), jobId, + projectId }); + } + + @Override + public List getJobListByQueuedStatus(String queueName, + int maxReturnSize) { + int QUEUED_STATUS_TYPE_ID = StatusEnum.QUEUED.ordinal(); + JdbcTemplate localJdbcTemplate = new JdbcTemplate(getDataSource()); + String sql = " select * from " + + getDbSchemaName() + + "CRC_ANALYSIS_JOB where queue_name = ? and status_type_id = ? order by create_date"; + localJdbcTemplate.setMaxRows(maxReturnSize); + List analysisJobList = localJdbcTemplate.query(sql, + new Object[] { queueName, QUEUED_STATUS_TYPE_ID }, + analysisJobMapper); + return analysisJobList; + + } + + private class AnalysisJobRowMapper implements RowMapper { + + @Override + public Object mapRow(ResultSet rs, int rowNum) throws SQLException { + AnalysisJob analysisJob = new AnalysisJob(); + analysisJob.setJobId(rs.getString("JOB_ID")); + analysisJob.setQueueName(rs.getString("QUEUE_NAME")); + analysisJob.setStatusTypeId(rs.getInt("STATUS_TYPE_ID")); + analysisJob.setDomainId(rs.getString("DOMAIN_ID")); + analysisJob.setProjectId(rs.getString("PROJECT_ID")); + analysisJob.setUserId(rs.getString("USER_ID")); + analysisJob.setRequestXml(rs.getString("REQUEST_XML")); + analysisJob.setCreateDate(rs.getTimestamp("CREATE_DATE")); + analysisJob.setUpdateDate(rs.getTime("UPDATE_DATE")); + return analysisJob; + } + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/DAOFactoryHelper.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/DAOFactoryHelper.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/DAOFactoryHelper.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/DAOFactoryHelper.java index 517842b2..82542633 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/DAOFactoryHelper.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/DAOFactoryHelper.java @@ -1,90 +1,90 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao; - -import javax.sql.DataSource; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; - -public class DAOFactoryHelper { - - public static final String ORACLE = "ORACLE"; - public static final String SQLSERVER = "SQLSERVER"; - public static final String POSTGRESQL = "POSTGRESQL"; - DataSourceLookup dataSourceLookup = null; - DataSource dataSource = null; - DataSourceLookup originalDataSourceLookup = null; - - public DAOFactoryHelper(String hiveId, String projectId, String ownerId) - throws I2B2DAOException { - originalDataSourceLookup = new DataSourceLookup(); - originalDataSourceLookup.setProjectPath(projectId); - originalDataSourceLookup.setOwnerId(ownerId); - originalDataSourceLookup.setDomainId(hiveId); - try { - DataSourceLookupHelper dsHelper = new DataSourceLookupHelper(); - dataSourceLookup = dsHelper.matchDataSource(hiveId, projectId, - ownerId); - } catch (I2B2Exception i2b2Ex) { - throw new I2B2DAOException("DataSource lookup error" - + i2b2Ex.getMessage(), i2b2Ex); - } - } - - public DAOFactoryHelper(DataSourceLookup dataSourceLookup) - throws I2B2DAOException { - this(dataSourceLookup.getDomainId(), dataSourceLookup.getProjectPath(), - dataSourceLookup.getOwnerId()); - } - - public DAOFactoryHelper(DataSourceLookup dataSourceLookup, - DataSource dataSource) { - this.dataSourceLookup = dataSourceLookup; - this.dataSource = dataSource; - } - - public DataSourceLookup getDataSourceLookup() { - return dataSourceLookup; - } - - public DataSourceLookup getOriginalDataSource() { - return originalDataSourceLookup; - } - - public IDAOFactory getDAOFactory() throws I2B2DAOException { - String dataSourceName = dataSourceLookup.getServerType(); - if (dataSourceName.equalsIgnoreCase(ORACLE)) { - if (dataSource != null) { - return new OracleDAOFactory(dataSourceLookup, dataSource); - } else { - return new OracleDAOFactory(dataSourceLookup, - originalDataSourceLookup); - } - } else if (dataSourceName.equalsIgnoreCase(SQLSERVER)) { - if (dataSource != null) { - return new OracleDAOFactory(dataSourceLookup, dataSource); - } else { - return new OracleDAOFactory(dataSourceLookup, - originalDataSourceLookup); - } - } else if (dataSourceName.equalsIgnoreCase(POSTGRESQL)) { - if (dataSource != null) { - return new OracleDAOFactory(dataSourceLookup, dataSource); - } else { - return new OracleDAOFactory(dataSourceLookup, - originalDataSourceLookup); - } - } else { - return null; - } - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao; + +import javax.sql.DataSource; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; + +public class DAOFactoryHelper { + + public static final String ORACLE = "ORACLE"; + public static final String SQLSERVER = "SQLSERVER"; + public static final String POSTGRESQL = "POSTGRESQL"; + DataSourceLookup dataSourceLookup = null; + DataSource dataSource = null; + DataSourceLookup originalDataSourceLookup = null; + + public DAOFactoryHelper(String hiveId, String projectId, String ownerId) + throws I2B2DAOException { + originalDataSourceLookup = new DataSourceLookup(); + originalDataSourceLookup.setProjectPath(projectId); + originalDataSourceLookup.setOwnerId(ownerId); + originalDataSourceLookup.setDomainId(hiveId); + try { + DataSourceLookupHelper dsHelper = new DataSourceLookupHelper(); + dataSourceLookup = dsHelper.matchDataSource(hiveId, projectId, + ownerId); + } catch (I2B2Exception i2b2Ex) { + throw new I2B2DAOException("DataSource lookup error" + + i2b2Ex.getMessage(), i2b2Ex); + } + } + + public DAOFactoryHelper(DataSourceLookup dataSourceLookup) + throws I2B2DAOException { + this(dataSourceLookup.getDomainId(), dataSourceLookup.getProjectPath(), + dataSourceLookup.getOwnerId()); + } + + public DAOFactoryHelper(DataSourceLookup dataSourceLookup, + DataSource dataSource) { + this.dataSourceLookup = dataSourceLookup; + this.dataSource = dataSource; + } + + public DataSourceLookup getDataSourceLookup() { + return dataSourceLookup; + } + + public DataSourceLookup getOriginalDataSource() { + return originalDataSourceLookup; + } + + public IDAOFactory getDAOFactory() throws I2B2DAOException { + String dataSourceName = dataSourceLookup.getServerType(); + if (dataSourceName.equalsIgnoreCase(ORACLE)) { + if (dataSource != null) { + return new OracleDAOFactory(dataSourceLookup, dataSource); + } else { + return new OracleDAOFactory(dataSourceLookup, + originalDataSourceLookup); + } + } else if (dataSourceName.equalsIgnoreCase(SQLSERVER)) { + if (dataSource != null) { + return new OracleDAOFactory(dataSourceLookup, dataSource); + } else { + return new OracleDAOFactory(dataSourceLookup, + originalDataSourceLookup); + } + } else if (dataSourceName.equalsIgnoreCase(POSTGRESQL)) { + if (dataSource != null) { + return new OracleDAOFactory(dataSourceLookup, dataSource); + } else { + return new OracleDAOFactory(dataSourceLookup, + originalDataSourceLookup); + } + } else { + return null; + } + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/DataSourceLookupDAO.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/DataSourceLookupDAO.java old mode 100755 new mode 100644 similarity index 98% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/DataSourceLookupDAO.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/DataSourceLookupDAO.java index 47b1ee6c..6e340fe0 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/DataSourceLookupDAO.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/DataSourceLookupDAO.java @@ -1,23 +1,23 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao; - -import java.util.List; - -import org.springframework.jdbc.core.JdbcTemplate; - -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; - -public abstract class DataSourceLookupDAO extends JdbcTemplate { - public abstract List getDbLookupByHiveOwner(String hiveId,String ownerId); - //public abstract DataSourceLookup getDataSourceByHiveProjectOwner(String hive,String projectId, String owner); - public abstract List getDbLookupByHiveProjectOwner(String hiveId, String projectId, - String ownerId); - public abstract List getDbLookupByHive(String hiveId); -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao; + +import java.util.List; + +import org.springframework.jdbc.core.JdbcTemplate; + +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; + +public abstract class DataSourceLookupDAO extends JdbcTemplate { + public abstract List getDbLookupByHiveOwner(String hiveId,String ownerId); + //public abstract DataSourceLookup getDataSourceByHiveProjectOwner(String hive,String projectId, String owner); + public abstract List getDbLookupByHiveProjectOwner(String hiveId, String projectId, + String ownerId); + public abstract List getDbLookupByHive(String hiveId); +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/DataSourceLookupDAOFactory.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/DataSourceLookupDAOFactory.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/DataSourceLookupDAOFactory.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/DataSourceLookupDAOFactory.java index 2e9bf346..b945185b --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/DataSourceLookupDAOFactory.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/DataSourceLookupDAOFactory.java @@ -1,98 +1,98 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao; - -import java.sql.Connection; -import java.sql.SQLException; - -import javax.sql.DataSource; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - -public class DataSourceLookupDAOFactory { - - /** log **/ - protected final static Log log = LogFactory - .getLog(DataSourceLookupDAOFactory.class); - - public static final String ORACLE = "ORACLE"; - public static final String SQLSERVER = "MICROSOFT SQL SERVER"; - public static final String POSTGRESQL = "POSTGRESQL"; - -// private static String dataSourceName = null; - private static String serverType = null; - private static String schemaName = null; - private static DataSource lookupDataSource = null; - - // private static ServiceLocator serviceLocator = - // ServiceLocator.getInstance(); - // private static QueryProcessorUtil crcUtil = QueryProcessorUtil - // .getInstance(); - - public static DataSourceLookupDAO getDataSourceLookupDAO() - throws I2B2DAOException { - if (serverType == null) { - getLookupDataSourceFromPropertyFile(); - } - if (serverType.equalsIgnoreCase(ORACLE)) { - return new OracleDataSourceLookupDAO(lookupDataSource, schemaName); - } else if (serverType.equalsIgnoreCase(SQLSERVER)) { - return new OracleDataSourceLookupDAO(lookupDataSource, schemaName); - } else if (serverType.equalsIgnoreCase(POSTGRESQL)) { - return new OracleDataSourceLookupDAO(lookupDataSource, schemaName); - } else { - throw new I2B2DAOException( - "DataSourceLookupDAOFactory.getDataSourceLookupDAO: serverType=" - + serverType + " not valid"); - } - } - - public static CRCQueueDAO getCRCQueueDAO() throws I2B2DAOException { - if (serverType == null) { - getLookupDataSourceFromPropertyFile(); - } - CRCQueueDAO queueDAO = new CRCQueueDAO(lookupDataSource, schemaName); - return queueDAO; - } - - private static void getLookupDataSourceFromPropertyFile() - throws I2B2DAOException { - QueryProcessorUtil crcUtil = QueryProcessorUtil.getInstance(); - try { - // dataSourceName = crcUtil.getCRCDBLookupDataSource(); - // serverType = crcUtil.getCRCDBLookupServerType(); - // schemaName = crcUtil.getCRCDBLookupSchemaName(); - lookupDataSource = crcUtil - .getDataSource("java:/CRCBootStrapDS"); - - Connection conn = lookupDataSource.getConnection(); - - serverType = conn.getMetaData().getDatabaseProductName().toUpperCase(); - schemaName = conn.getSchema(); - conn.close(); - } catch (I2B2Exception i2b2Ex) { - log.error( - "DataSourceLookupDAOFactory.getLookupDataSourceFromPropertyFile" - + i2b2Ex.getMessage(), i2b2Ex); - throw new I2B2DAOException( - "DataSourceLookupDAOFactory.getLookupDataSourceFromPropertyFile" - + i2b2Ex.getMessage(), i2b2Ex); - } catch (SQLException e) { - // TODO Auto-generated catch block - throw new I2B2DAOException( - "DataSourceLookupDAOFactory.getLookupDataSourceFromPropertyFile SQL Error" - + e.getMessage(), e); - } - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao; + +import java.sql.Connection; +import java.sql.SQLException; + +import javax.sql.DataSource; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + +public class DataSourceLookupDAOFactory { + + /** log **/ + protected final static Log log = LogFactory + .getLog(DataSourceLookupDAOFactory.class); + + public static final String ORACLE = "ORACLE"; + public static final String SQLSERVER = "MICROSOFT SQL SERVER"; + public static final String POSTGRESQL = "POSTGRESQL"; + +// private static String dataSourceName = null; + private static String serverType = null; + private static String schemaName = null; + private static DataSource lookupDataSource = null; + + // private static ServiceLocator serviceLocator = + // ServiceLocator.getInstance(); + // private static QueryProcessorUtil crcUtil = QueryProcessorUtil + // .getInstance(); + + public static DataSourceLookupDAO getDataSourceLookupDAO() + throws I2B2DAOException { + if (serverType == null) { + getLookupDataSourceFromPropertyFile(); + } + if (serverType.equalsIgnoreCase(ORACLE)) { + return new OracleDataSourceLookupDAO(lookupDataSource, schemaName); + } else if (serverType.equalsIgnoreCase(SQLSERVER)) { + return new OracleDataSourceLookupDAO(lookupDataSource, schemaName); + } else if (serverType.equalsIgnoreCase(POSTGRESQL)) { + return new OracleDataSourceLookupDAO(lookupDataSource, schemaName); + } else { + throw new I2B2DAOException( + "DataSourceLookupDAOFactory.getDataSourceLookupDAO: serverType=" + + serverType + " not valid"); + } + } + + public static CRCQueueDAO getCRCQueueDAO() throws I2B2DAOException { + if (serverType == null) { + getLookupDataSourceFromPropertyFile(); + } + CRCQueueDAO queueDAO = new CRCQueueDAO(lookupDataSource, schemaName); + return queueDAO; + } + + private static void getLookupDataSourceFromPropertyFile() + throws I2B2DAOException { + QueryProcessorUtil crcUtil = QueryProcessorUtil.getInstance(); + try { + // dataSourceName = crcUtil.getCRCDBLookupDataSource(); + // serverType = crcUtil.getCRCDBLookupServerType(); + // schemaName = crcUtil.getCRCDBLookupSchemaName(); + lookupDataSource = crcUtil + .getDataSource("java:/CRCBootStrapDS"); + + Connection conn = lookupDataSource.getConnection(); + + serverType = conn.getMetaData().getDatabaseProductName().toUpperCase(); + schemaName = conn.getSchema(); + conn.close(); + } catch (I2B2Exception i2b2Ex) { + log.error( + "DataSourceLookupDAOFactory.getLookupDataSourceFromPropertyFile" + + i2b2Ex.getMessage(), i2b2Ex); + throw new I2B2DAOException( + "DataSourceLookupDAOFactory.getLookupDataSourceFromPropertyFile" + + i2b2Ex.getMessage(), i2b2Ex); + } catch (SQLException e) { + // TODO Auto-generated catch block + throw new I2B2DAOException( + "DataSourceLookupDAOFactory.getLookupDataSourceFromPropertyFile SQL Error" + + e.getMessage(), e); + } + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/DataSourceLookupHelper.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/DataSourceLookupHelper.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/DataSourceLookupHelper.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/DataSourceLookupHelper.java index 1c7dd636..b88d151e --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/DataSourceLookupHelper.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/DataSourceLookupHelper.java @@ -1,180 +1,180 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao; - -import java.util.List; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; - -public class DataSourceLookupHelper { - - /** log **/ - protected final static Log log = LogFactory - .getLog(DataSourceLookupHelper.class); - - - protected final Log logesapi = LogFactory.getLog(getClass()); - - private DataSourceLookupDAO dsLookupDao = null; - - public DataSourceLookupHelper() throws I2B2Exception { - - dsLookupDao = DataSourceLookupDAOFactory.getDataSourceLookupDAO(); - } - - public DataSourceLookupDAO getLookupDAO() { - return dsLookupDao; - } - - public DataSourceLookup matchDataSource(String hiveId, String projectId, - String ownerId) throws I2B2Exception { - DataSourceLookup matchedDataSourceLookup = null; - List dataSourceLookupList = null; - if (projectId == null) { - throw new I2B2Exception( - " Project id is null, could not perform datasource lookup for given domain[" - + hiveId + "] and owner[" + ownerId + "]"); - } - - if (projectId.equals("@")) { - matchedDataSourceLookup = matchHiveOwner(hiveId, ownerId); - return matchedDataSourceLookup; - } - - // check if project id contains subprojects, if so then query by first - // level subproject - if (projectId.endsWith("/") == false) { - projectId += "/"; - } - if (projectId.startsWith("/") == false) { - projectId = "/" + projectId; - } - String[] projectSplit = projectId.split("/"); - String filterProjectId = ""; - if (projectSplit.length > 2) { - filterProjectId = "/" + projectSplit[1] + "/" + projectSplit[2] - + "/"; - } else { - filterProjectId = "/" + projectSplit[1] + "/"; - } - dataSourceLookupList = dsLookupDao.getDbLookupByHiveProjectOwner( - hiveId, filterProjectId, ownerId); - // if the project path with two level fails then try with one level - if (dataSourceLookupList.size() < 1) { - filterProjectId = "/" + projectSplit[1] + "/"; - dataSourceLookupList = dsLookupDao.getDbLookupByHiveProjectOwner( - hiveId, filterProjectId, ownerId); - } - if (dataSourceLookupList.size() > 0) { - DataSourceLookup matchedDataSource = null; - int projectLevel = projectId.length(); - boolean matchedFlag = false; - String parentProjectId = null; - while ((projectLevel = projectId.lastIndexOf('/', projectLevel)) > 0) { - parentProjectId = projectId.substring(0, projectLevel + 1); - logesapi.debug("Trying with project id :" + parentProjectId); - matchedDataSource = match(parentProjectId, ownerId, - dataSourceLookupList); - if (matchedDataSource != null) { - matchedFlag = true; - break; - } - - projectLevel = projectId.lastIndexOf('/', projectLevel - 1); - } - if (matchedFlag) { - if (ownerId.equalsIgnoreCase(matchedDataSource.getOwnerId())) { - logesapi.info("Located DataSource for hiveId=[" + hiveId - + "] projectId=[" + parentProjectId - + "] and ownerId =[" + ownerId + "]"); - } else { - logesapi.info("Located DataSource for hiveId=[" + hiveId - + "] projectId=[" + parentProjectId + "]"); - - } - return matchedDataSource; - - } else { - logesapi.info("Could not match Project id=[" + projectId - + "] Trying with hive =" + hiveId); - matchedDataSourceLookup = matchHiveOwner(hiveId, ownerId); - return matchedDataSourceLookup; - } - - } else { - logesapi.info("Could not match Project id=[" + projectId - + "] Trying with hive =" + hiveId); - matchedDataSourceLookup = matchHiveOwner(hiveId, ownerId); - return matchedDataSourceLookup; - } - - } - - private DataSourceLookup matchHiveOwner(String hiveId, String ownerId) - throws I2B2Exception { - DataSourceLookup matchedDataSourceLookup = null; - // check for hive and owner (userid or @) - List dataSourceLookupList = dsLookupDao - .getDbLookupByHiveOwner(hiveId, ownerId); - if (dataSourceLookupList.size() == 0) { - throw new I2B2Exception("Could not locate hive= " + hiveId); - } else if (dataSourceLookupList.size() > 0) { - boolean matchedFlag = false; - - for (DataSourceLookup dsLookup : dataSourceLookupList) { - if (dsLookup.getOwnerId() != null - && dsLookup.getOwnerId().equalsIgnoreCase(ownerId)) { - matchedDataSourceLookup = dsLookup; - matchedFlag = true; - break; - } else if (dsLookup.getOwnerId() != null - && dsLookup.getOwnerId().equals("@")) { - matchedDataSourceLookup = dsLookup; - } - } - if (matchedFlag) { - logesapi.info("Located Datasource matching hive=[" + hiveId - + "] and owner=[" + ownerId + "]"); - } else if (matchedDataSourceLookup != null) { - logesapi.info("Located Datasource matching hive=[" + hiveId - + " and owner =[@]"); - } else { - throw new I2B2Exception( - "Could not locate Datasource matching hive=[" + hiveId - + "] and owner=[" + ownerId + " or @]"); - } - } - return matchedDataSourceLookup; - } - - private DataSourceLookup match(String searchProjectId, String owner, - List dataSourceLookupList) { - DataSourceLookup matchedDataSource = null; - - for (DataSourceLookup dataSourceLookup : dataSourceLookupList) { - String lookupProjectId = dataSourceLookup.getProjectPath(); - String lookupOwnerId = dataSourceLookup.getOwnerId(); - if (searchProjectId.equalsIgnoreCase(lookupProjectId)) { - matchedDataSource = dataSourceLookup; - if (owner.equalsIgnoreCase(lookupOwnerId)) { - break; - } - - } - } - return matchedDataSource; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao; + +import java.util.List; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; + +public class DataSourceLookupHelper { + + /** log **/ + protected final static Log log = LogFactory + .getLog(DataSourceLookupHelper.class); + + + protected final Log logesapi = LogFactory.getLog(getClass()); + + private DataSourceLookupDAO dsLookupDao = null; + + public DataSourceLookupHelper() throws I2B2Exception { + + dsLookupDao = DataSourceLookupDAOFactory.getDataSourceLookupDAO(); + } + + public DataSourceLookupDAO getLookupDAO() { + return dsLookupDao; + } + + public DataSourceLookup matchDataSource(String hiveId, String projectId, + String ownerId) throws I2B2Exception { + DataSourceLookup matchedDataSourceLookup = null; + List dataSourceLookupList = null; + if (projectId == null) { + throw new I2B2Exception( + " Project id is null, could not perform datasource lookup for given domain[" + + hiveId + "] and owner[" + ownerId + "]"); + } + + if (projectId.equals("@")) { + matchedDataSourceLookup = matchHiveOwner(hiveId, ownerId); + return matchedDataSourceLookup; + } + + // check if project id contains subprojects, if so then query by first + // level subproject + if (projectId.endsWith("/") == false) { + projectId += "/"; + } + if (projectId.startsWith("/") == false) { + projectId = "/" + projectId; + } + String[] projectSplit = projectId.split("/"); + String filterProjectId = ""; + if (projectSplit.length > 2) { + filterProjectId = "/" + projectSplit[1] + "/" + projectSplit[2] + + "/"; + } else { + filterProjectId = "/" + projectSplit[1] + "/"; + } + dataSourceLookupList = dsLookupDao.getDbLookupByHiveProjectOwner( + hiveId, filterProjectId, ownerId); + // if the project path with two level fails then try with one level + if (dataSourceLookupList.size() < 1) { + filterProjectId = "/" + projectSplit[1] + "/"; + dataSourceLookupList = dsLookupDao.getDbLookupByHiveProjectOwner( + hiveId, filterProjectId, ownerId); + } + if (dataSourceLookupList.size() > 0) { + DataSourceLookup matchedDataSource = null; + int projectLevel = projectId.length(); + boolean matchedFlag = false; + String parentProjectId = null; + while ((projectLevel = projectId.lastIndexOf('/', projectLevel)) > 0) { + parentProjectId = projectId.substring(0, projectLevel + 1); + logesapi.debug("Trying with project id :" + parentProjectId); + matchedDataSource = match(parentProjectId, ownerId, + dataSourceLookupList); + if (matchedDataSource != null) { + matchedFlag = true; + break; + } + + projectLevel = projectId.lastIndexOf('/', projectLevel - 1); + } + if (matchedFlag) { + if (ownerId.equalsIgnoreCase(matchedDataSource.getOwnerId())) { + logesapi.info("Located DataSource for hiveId=[" + hiveId + + "] projectId=[" + parentProjectId + + "] and ownerId =[" + ownerId + "]"); + } else { + logesapi.info("Located DataSource for hiveId=[" + hiveId + + "] projectId=[" + parentProjectId + "]"); + + } + return matchedDataSource; + + } else { + logesapi.info("Could not match Project id=[" + projectId + + "] Trying with hive =" + hiveId); + matchedDataSourceLookup = matchHiveOwner(hiveId, ownerId); + return matchedDataSourceLookup; + } + + } else { + logesapi.info("Could not match Project id=[" + projectId + + "] Trying with hive =" + hiveId); + matchedDataSourceLookup = matchHiveOwner(hiveId, ownerId); + return matchedDataSourceLookup; + } + + } + + private DataSourceLookup matchHiveOwner(String hiveId, String ownerId) + throws I2B2Exception { + DataSourceLookup matchedDataSourceLookup = null; + // check for hive and owner (userid or @) + List dataSourceLookupList = dsLookupDao + .getDbLookupByHiveOwner(hiveId, ownerId); + if (dataSourceLookupList.size() == 0) { + throw new I2B2Exception("Could not locate hive= " + hiveId); + } else if (dataSourceLookupList.size() > 0) { + boolean matchedFlag = false; + + for (DataSourceLookup dsLookup : dataSourceLookupList) { + if (dsLookup.getOwnerId() != null + && dsLookup.getOwnerId().equalsIgnoreCase(ownerId)) { + matchedDataSourceLookup = dsLookup; + matchedFlag = true; + break; + } else if (dsLookup.getOwnerId() != null + && dsLookup.getOwnerId().equals("@")) { + matchedDataSourceLookup = dsLookup; + } + } + if (matchedFlag) { + logesapi.info("Located Datasource matching hive=[" + hiveId + + "] and owner=[" + ownerId + "]"); + } else if (matchedDataSourceLookup != null) { + logesapi.info("Located Datasource matching hive=[" + hiveId + + " and owner =[@]"); + } else { + throw new I2B2Exception( + "Could not locate Datasource matching hive=[" + hiveId + + "] and owner=[" + ownerId + " or @]"); + } + } + return matchedDataSourceLookup; + } + + private DataSourceLookup match(String searchProjectId, String owner, + List dataSourceLookupList) { + DataSourceLookup matchedDataSource = null; + + for (DataSourceLookup dataSourceLookup : dataSourceLookupList) { + String lookupProjectId = dataSourceLookup.getProjectPath(); + String lookupOwnerId = dataSourceLookup.getOwnerId(); + if (searchProjectId.equalsIgnoreCase(lookupProjectId)) { + matchedDataSource = dataSourceLookup; + if (owner.equalsIgnoreCase(lookupOwnerId)) { + break; + } + + } + } + return matchedDataSource; + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/DblookupDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/DblookupDao.java similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/DblookupDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/DblookupDao.java index 5be7439f..1895cddc 100644 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/DblookupDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/DblookupDao.java @@ -1,247 +1,247 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Wayne Chan - */ -package edu.harvard.i2b2.crc.dao; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; -import edu.harvard.i2b2.crc.datavo.pdo.query.DblookupType; -import edu.harvard.i2b2.crc.datavo.pdo.query.DeleteDblookupType; -import edu.harvard.i2b2.crc.datavo.pdo.query.SetDblookupType; -import edu.harvard.i2b2.crc.loader.ejb.DataMartLoaderAsyncBean; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.Calendar; -import java.util.List; -import javax.sql.DataSource; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.dao.DataAccessException; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.RowMapper; -import org.springframework.jdbc.core.support.JdbcDaoSupport; - -public class DblookupDao extends JdbcDaoSupport { - protected static Log logesapi = LogFactory.getLog(DblookupDao.class); - - private static Log log = LogFactory.getLog(DblookupDao.class); - private static DataSource ds = null; - private static JdbcTemplate jt; - private static String dbluTable; - private static String key = " LOWER(c_domain_id)=LOWER(?) AND (LOWER(c_owner_id)=LOWER(?) OR c_owner_id='@') "; - private static String keyOrder = " LOWER(c_domain_id)=LOWER(?) AND (LOWER(c_owner_id)=LOWER(?) OR c_owner_id='@') ORDER BY c_project_path "; - private String domainId = null; - private String userId = null; - - public DblookupDao() { - initDblookupDao(); - } - - public DblookupDao(MessageHeaderType reqMsgHdr) throws I2B2Exception, JAXBUtilException { - domainId = reqMsgHdr.getSecurity().getDomain(); - userId = reqMsgHdr.getSecurity().getUsername(); - initDblookupDao(); - } - - private void initDblookupDao() { - try { - ds = QueryProcessorUtil.getInstance().getDataSource("java:/CRCBootStrapDS"); - } catch (I2B2Exception e2) { - log.error(e2.getMessage());; - } - jt = new JdbcTemplate(ds); - String dataSchema = ""; - try { - - Connection conn = ds.getConnection(); - - dataSchema = conn.getSchema(); - conn.close(); - } catch (SQLException e1) { - log.error(e1.getMessage()); - } - if (dataSchema.endsWith(".")) { - dbluTable = dataSchema + "crc_db_lookup "; - } else { - dbluTable = dataSchema + ".crc_db_lookup "; - } - log.info("CRC_DB_LOOKUP = " + dbluTable); - } - - public String slashSandwich(String s) { - StringBuffer sb = new StringBuffer(); - if (!s.startsWith("/")) { - sb.append('/'); - } - sb.append(s); - if (!s.endsWith("/")) { - sb.append('/'); - } - log.info(sb.toString()); - return sb.toString(); - } - - - public List findDblookups() throws DataAccessException, I2B2DAOException{ - String sql = "SELECT * FROM " + dbluTable + " WHERE" + keyOrder; - List queryResult = null; - try { - queryResult = jt.query(sql, new getMapper(), domainId, userId); - } catch (DataAccessException e) { - log.error(e.getMessage()); - throw e; - } - log.info("result size = " + queryResult.size()); - return queryResult; - } - - public List getDblookup(final SetDblookupType dblookupType) throws DataAccessException, I2B2Exception { - String sql = "SELECT * FROM " + dbluTable + " WHERE c_project_path=? AND " + keyOrder; - List queryResult = null; - try { - queryResult = jt.query(sql, new getMapper(), slashSandwich(dblookupType.getProjectPath()), dblookupType.getDomainId(), dblookupType.getOwnerId()); - } catch (DataAccessException e) { - log.error(e.getMessage()); - e.printStackTrace(); - throw new I2B2DAOException("Database error"); - } - return queryResult; - } - - public List getDblookup(String column, String value) throws DataAccessException, I2B2Exception { - String sql = "SELECT * FROM " + dbluTable + " WHERE "; - String v = value, s = column.toLowerCase(); - List queryResult = null; - try { - if (s.equalsIgnoreCase("domain_id")) { - sql += keyOrder; - queryResult = jt.query(sql, new getMapper(), value, userId); - } else if (s.equalsIgnoreCase("owner_id")) { - sql += keyOrder; - queryResult = jt.query(sql, new getMapper(), domainId, value); - } else { - sql += "c_" + column + "=? AND " + keyOrder; - if (s.equalsIgnoreCase("project_path")) { - v = slashSandwich(value); - } else { - } - queryResult = jt.query(sql, new getMapper(), v, domainId, userId); - } - logesapi.info(sql + "(c_" + column + "=" + v + ", domainId=" + domainId + ", userId=" + userId + ") -- # of entries found: " + queryResult.size()); - } catch (DataAccessException e) { - log.error(e.getMessage()); - e.printStackTrace(); - throw new I2B2DAOException("Database error"); - } - return queryResult; - } - - public int setDblookup(final SetDblookupType dblookupType) throws DataAccessException, I2B2Exception { - List queryResult = getDblookup(dblookupType); - if (null == queryResult || (0 == queryResult.size())) { - return insertDblookup(dblookupType); - } else { - return updateDblookup(dblookupType); - } - } - - public int insertDblookup(final SetDblookupType dblookupType) throws DataAccessException, I2B2Exception { - int numRowsAdded = 0; - String sql = "INSERT INTO " + dbluTable + - "(c_domain_id, c_project_path, c_owner_id, c_db_fullschema, c_db_datasource, c_db_servertype, c_db_nicename, c_db_tooltip, c_comment, c_entry_date, c_change_date, c_status_cd) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)"; - numRowsAdded = jt.update(sql, - dblookupType.getDomainId(), - slashSandwich(dblookupType.getProjectPath()), - dblookupType.getOwnerId(), - dblookupType.getDbFullschema(), - dblookupType.getDbDatasource(), - dblookupType.getDbServertype(), - dblookupType.getDbNicename(), - dblookupType.getDbTooltip(), - dblookupType.getComment(), - Calendar.getInstance().getTime(), - Calendar.getInstance().getTime(), - dblookupType.getStatusCd() - ); - log.info("insertDblookup - Number of rows added: " + numRowsAdded); - return numRowsAdded; - } - - public int updateDblookup(final SetDblookupType dblookupType) throws DataAccessException, I2B2Exception { - int numRowsSet = 0; - String sql = "UPDATE " + dbluTable + - "SET c_db_fullschema=?, c_db_datasource=?, c_db_servertype=?, c_db_nicename=?, c_db_tooltip=?, c_comment=?, c_change_date=?, c_status_cd=? WHERE c_project_path=? AND " + - key; - numRowsSet = jt.update(sql, - dblookupType.getDbFullschema(), - dblookupType.getDbDatasource(), - dblookupType.getDbServertype(), - dblookupType.getDbNicename(), - dblookupType.getDbTooltip(), - dblookupType.getComment(), - Calendar.getInstance().getTime(), - dblookupType.getStatusCd(), - slashSandwich(dblookupType.getProjectPath()), - dblookupType.getDomainId(), - dblookupType.getOwnerId() - ); - log.info("updateDblookup - Number of rows updated: " + numRowsSet); - return numRowsSet; - } - - public int deleteDblookup(final DeleteDblookupType dblookupType) throws DataAccessException, I2B2Exception { - int numRowsDeleted = 0; - String sql = "DELETE FROM " + dbluTable + " WHERE c_project_path=? AND " + key; - try { - numRowsDeleted = jt.update(sql, slashSandwich(dblookupType.getProjectPath()), dblookupType.getDomainId(), dblookupType.getOwnerId()); - } catch (DataAccessException e) { - log.error(e.getMessage()); - e.printStackTrace(); - throw new I2B2DAOException("Database error"); - } - return numRowsDeleted; - } - -} - - - -class getMapper implements RowMapper { - @Override - public DblookupType mapRow(ResultSet rs, int rowNum) throws SQLException { - DblookupType dblu = new DblookupType(); - dblu.setDomainId(rs.getString("c_domain_id")); - dblu.setProjectPath(rs.getString("c_project_path")); - dblu.setOwnerId(rs.getString("c_owner_id")); - dblu.setDbFullschema(rs.getString("c_db_fullschema")); - dblu.setDbDatasource(rs.getString("c_db_datasource")); - dblu.setDbServertype(rs.getString("c_db_servertype")); - dblu.setDbNicename(rs.getString("c_db_nicename")); - dblu.setDbTooltip(rs.getString("c_db_tooltip")); - dblu.setComment(rs.getString("c_comment")); - dblu.setEntryDate(rs.getString("c_entry_date")); - dblu.setChangeDate(rs.getString("c_change_date")); - dblu.setStatusCd(rs.getString("c_status_cd")); - return dblu; - } - } - - +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Wayne Chan + */ +package edu.harvard.i2b2.crc.dao; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; +import edu.harvard.i2b2.crc.datavo.pdo.query.DblookupType; +import edu.harvard.i2b2.crc.datavo.pdo.query.DeleteDblookupType; +import edu.harvard.i2b2.crc.datavo.pdo.query.SetDblookupType; +import edu.harvard.i2b2.crc.loader.ejb.DataMartLoaderAsyncBean; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Calendar; +import java.util.List; +import javax.sql.DataSource; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.dao.DataAccessException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.RowMapper; +import org.springframework.jdbc.core.support.JdbcDaoSupport; + +public class DblookupDao extends JdbcDaoSupport { + protected static Log logesapi = LogFactory.getLog(DblookupDao.class); + + private static Log log = LogFactory.getLog(DblookupDao.class); + private static DataSource ds = null; + private static JdbcTemplate jt; + private static String dbluTable; + private static String key = " LOWER(c_domain_id)=LOWER(?) AND (LOWER(c_owner_id)=LOWER(?) OR c_owner_id='@') "; + private static String keyOrder = " LOWER(c_domain_id)=LOWER(?) AND (LOWER(c_owner_id)=LOWER(?) OR c_owner_id='@') ORDER BY c_project_path "; + private String domainId = null; + private String userId = null; + + public DblookupDao() { + initDblookupDao(); + } + + public DblookupDao(MessageHeaderType reqMsgHdr) throws I2B2Exception, JAXBUtilException { + domainId = reqMsgHdr.getSecurity().getDomain(); + userId = reqMsgHdr.getSecurity().getUsername(); + initDblookupDao(); + } + + private void initDblookupDao() { + try { + ds = QueryProcessorUtil.getInstance().getDataSource("java:/CRCBootStrapDS"); + } catch (I2B2Exception e2) { + log.error(e2.getMessage());; + } + jt = new JdbcTemplate(ds); + String dataSchema = ""; + try { + + Connection conn = ds.getConnection(); + + dataSchema = conn.getSchema(); + conn.close(); + } catch (SQLException e1) { + log.error(e1.getMessage()); + } + if (dataSchema.endsWith(".")) { + dbluTable = dataSchema + "crc_db_lookup "; + } else { + dbluTable = dataSchema + ".crc_db_lookup "; + } + log.info("CRC_DB_LOOKUP = " + dbluTable); + } + + public String slashSandwich(String s) { + StringBuffer sb = new StringBuffer(); + if (!s.startsWith("/")) { + sb.append('/'); + } + sb.append(s); + if (!s.endsWith("/")) { + sb.append('/'); + } + log.info(sb.toString()); + return sb.toString(); + } + + + public List findDblookups() throws DataAccessException, I2B2DAOException{ + String sql = "SELECT * FROM " + dbluTable + " WHERE" + keyOrder; + List queryResult = null; + try { + queryResult = jt.query(sql, new getMapper(), domainId, userId); + } catch (DataAccessException e) { + log.error(e.getMessage()); + throw e; + } + log.info("result size = " + queryResult.size()); + return queryResult; + } + + public List getDblookup(final SetDblookupType dblookupType) throws DataAccessException, I2B2Exception { + String sql = "SELECT * FROM " + dbluTable + " WHERE c_project_path=? AND " + keyOrder; + List queryResult = null; + try { + queryResult = jt.query(sql, new getMapper(), slashSandwich(dblookupType.getProjectPath()), dblookupType.getDomainId(), dblookupType.getOwnerId()); + } catch (DataAccessException e) { + log.error(e.getMessage()); + e.printStackTrace(); + throw new I2B2DAOException("Database error"); + } + return queryResult; + } + + public List getDblookup(String column, String value) throws DataAccessException, I2B2Exception { + String sql = "SELECT * FROM " + dbluTable + " WHERE "; + String v = value, s = column.toLowerCase(); + List queryResult = null; + try { + if (s.equalsIgnoreCase("domain_id")) { + sql += keyOrder; + queryResult = jt.query(sql, new getMapper(), value, userId); + } else if (s.equalsIgnoreCase("owner_id")) { + sql += keyOrder; + queryResult = jt.query(sql, new getMapper(), domainId, value); + } else { + sql += "c_" + column + "=? AND " + keyOrder; + if (s.equalsIgnoreCase("project_path")) { + v = slashSandwich(value); + } else { + } + queryResult = jt.query(sql, new getMapper(), v, domainId, userId); + } + logesapi.info(sql + "(c_" + column + "=" + v + ", domainId=" + domainId + ", userId=" + userId + ") -- # of entries found: " + queryResult.size()); + } catch (DataAccessException e) { + log.error(e.getMessage()); + e.printStackTrace(); + throw new I2B2DAOException("Database error"); + } + return queryResult; + } + + public int setDblookup(final SetDblookupType dblookupType) throws DataAccessException, I2B2Exception { + List queryResult = getDblookup(dblookupType); + if (null == queryResult || (0 == queryResult.size())) { + return insertDblookup(dblookupType); + } else { + return updateDblookup(dblookupType); + } + } + + public int insertDblookup(final SetDblookupType dblookupType) throws DataAccessException, I2B2Exception { + int numRowsAdded = 0; + String sql = "INSERT INTO " + dbluTable + + "(c_domain_id, c_project_path, c_owner_id, c_db_fullschema, c_db_datasource, c_db_servertype, c_db_nicename, c_db_tooltip, c_comment, c_entry_date, c_change_date, c_status_cd) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)"; + numRowsAdded = jt.update(sql, + dblookupType.getDomainId(), + slashSandwich(dblookupType.getProjectPath()), + dblookupType.getOwnerId(), + dblookupType.getDbFullschema(), + dblookupType.getDbDatasource(), + dblookupType.getDbServertype(), + dblookupType.getDbNicename(), + dblookupType.getDbTooltip(), + dblookupType.getComment(), + Calendar.getInstance().getTime(), + Calendar.getInstance().getTime(), + dblookupType.getStatusCd() + ); + log.info("insertDblookup - Number of rows added: " + numRowsAdded); + return numRowsAdded; + } + + public int updateDblookup(final SetDblookupType dblookupType) throws DataAccessException, I2B2Exception { + int numRowsSet = 0; + String sql = "UPDATE " + dbluTable + + "SET c_db_fullschema=?, c_db_datasource=?, c_db_servertype=?, c_db_nicename=?, c_db_tooltip=?, c_comment=?, c_change_date=?, c_status_cd=? WHERE c_project_path=? AND " + + key; + numRowsSet = jt.update(sql, + dblookupType.getDbFullschema(), + dblookupType.getDbDatasource(), + dblookupType.getDbServertype(), + dblookupType.getDbNicename(), + dblookupType.getDbTooltip(), + dblookupType.getComment(), + Calendar.getInstance().getTime(), + dblookupType.getStatusCd(), + slashSandwich(dblookupType.getProjectPath()), + dblookupType.getDomainId(), + dblookupType.getOwnerId() + ); + log.info("updateDblookup - Number of rows updated: " + numRowsSet); + return numRowsSet; + } + + public int deleteDblookup(final DeleteDblookupType dblookupType) throws DataAccessException, I2B2Exception { + int numRowsDeleted = 0; + String sql = "DELETE FROM " + dbluTable + " WHERE c_project_path=? AND " + key; + try { + numRowsDeleted = jt.update(sql, slashSandwich(dblookupType.getProjectPath()), dblookupType.getDomainId(), dblookupType.getOwnerId()); + } catch (DataAccessException e) { + log.error(e.getMessage()); + e.printStackTrace(); + throw new I2B2DAOException("Database error"); + } + return numRowsDeleted; + } + +} + + + +class getMapper implements RowMapper { + @Override + public DblookupType mapRow(ResultSet rs, int rowNum) throws SQLException { + DblookupType dblu = new DblookupType(); + dblu.setDomainId(rs.getString("c_domain_id")); + dblu.setProjectPath(rs.getString("c_project_path")); + dblu.setOwnerId(rs.getString("c_owner_id")); + dblu.setDbFullschema(rs.getString("c_db_fullschema")); + dblu.setDbDatasource(rs.getString("c_db_datasource")); + dblu.setDbServertype(rs.getString("c_db_servertype")); + dblu.setDbNicename(rs.getString("c_db_nicename")); + dblu.setDbTooltip(rs.getString("c_db_tooltip")); + dblu.setComment(rs.getString("c_comment")); + dblu.setEntryDate(rs.getString("c_entry_date")); + dblu.setChangeDate(rs.getString("c_change_date")); + dblu.setStatusCd(rs.getString("c_status_cd")); + return dblu; + } + } + + diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/EmailUtil.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/EmailUtil.java similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/EmailUtil.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/EmailUtil.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/ICRCQueueDAO.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/ICRCQueueDAO.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/ICRCQueueDAO.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/ICRCQueueDAO.java index 8ca21755..6379d481 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/ICRCQueueDAO.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/ICRCQueueDAO.java @@ -1,29 +1,29 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao; - -import java.util.List; - -import edu.harvard.i2b2.crc.datavo.db.AnalysisJob; - -public interface ICRCQueueDAO { - - public void addJob(AnalysisJob analysisJob); - - public List getJob(String jobId, String projectId); - - public void moveJob(String jobId, String projectId, String queueName, - String statusTypeId); - - public void updateStatus(String jobId, String projectId, String statusType); - - public List getJobListByQueuedStatus(String queueName, - int maxReturnSize); - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao; + +import java.util.List; + +import edu.harvard.i2b2.crc.datavo.db.AnalysisJob; + +public interface ICRCQueueDAO { + + public void addJob(AnalysisJob analysisJob); + + public List getJob(String jobId, String projectId); + + public void moveJob(String jobId, String projectId, String queueName, + String statusTypeId); + + public void updateStatus(String jobId, String projectId, String statusType); + + public List getJobListByQueuedStatus(String queueName, + int maxReturnSize); + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/IDAOFactory.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/IDAOFactory.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/IDAOFactory.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/IDAOFactory.java index ed13ca80..5839b16a --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/IDAOFactory.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/IDAOFactory.java @@ -1,19 +1,19 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao; - - -public interface IDAOFactory { - - // List of DAO types supported by the factory - public PatientDataDAOFactory getPatientDataDAOFactory(); - - public SetFinderDAOFactory getSetFinderDAOFactory(); - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao; + + +public interface IDAOFactory { + + // List of DAO types supported by the factory + public PatientDataDAOFactory getPatientDataDAOFactory(); + + public SetFinderDAOFactory getSetFinderDAOFactory(); + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/OracleDAOFactory.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/OracleDAOFactory.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/OracleDAOFactory.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/OracleDAOFactory.java index 31ec5d66..dfbca2c8 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/OracleDAOFactory.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/OracleDAOFactory.java @@ -1,349 +1,349 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao; - -import javax.sql.DataSource; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.ServiceLocator; -import edu.harvard.i2b2.crc.dao.pdo.IMetadataDao; -import edu.harvard.i2b2.crc.dao.pdo.IPageDao; -import edu.harvard.i2b2.crc.dao.pdo.IPdoQueryEidDao; -import edu.harvard.i2b2.crc.dao.pdo.IPdoQueryPidDao; -import edu.harvard.i2b2.crc.dao.pdo.MetadataDao; -import edu.harvard.i2b2.crc.dao.pdo.ObservationFactDao; -import edu.harvard.i2b2.crc.dao.pdo.PageTotalDao; -import edu.harvard.i2b2.crc.dao.pdo.PdoQueryConceptDao; -import edu.harvard.i2b2.crc.dao.pdo.PdoQueryEidDao; -import edu.harvard.i2b2.crc.dao.pdo.PdoQueryModifierDao; -import edu.harvard.i2b2.crc.dao.pdo.PdoQueryPatientDao; -import edu.harvard.i2b2.crc.dao.pdo.PdoQueryPidDao; -import edu.harvard.i2b2.crc.dao.pdo.PdoQueryProviderDao; -import edu.harvard.i2b2.crc.dao.pdo.PdoQueryVisitDao; -import edu.harvard.i2b2.crc.dao.pdo.TablePdoQueryConceptDao; -import edu.harvard.i2b2.crc.dao.pdo.TablePdoQueryModifierDao; -import edu.harvard.i2b2.crc.dao.pdo.TablePdoQueryPatientDao; -import edu.harvard.i2b2.crc.dao.pdo.TablePdoQueryProviderDao; -import edu.harvard.i2b2.crc.dao.pdo.TablePdoQueryVisitDao; -import edu.harvard.i2b2.crc.dao.role.IPriviledgeDao; -import edu.harvard.i2b2.crc.dao.role.PriviledgeSpringDao; -import edu.harvard.i2b2.crc.dao.setfinder.AnalysisPluginSpringDao; -import edu.harvard.i2b2.crc.dao.setfinder.EncounterSetCollectionSpringDao; -import edu.harvard.i2b2.crc.dao.setfinder.IAnalysisPluginDao; -import edu.harvard.i2b2.crc.dao.setfinder.IEncounterSetCollectionDao; -import edu.harvard.i2b2.crc.dao.setfinder.IPatientSetCollectionDao; -import edu.harvard.i2b2.crc.dao.setfinder.IQueryBreakdownTypeDao; -import edu.harvard.i2b2.crc.dao.setfinder.IQueryInstanceDao; -import edu.harvard.i2b2.crc.dao.setfinder.IQueryMasterDao; -import edu.harvard.i2b2.crc.dao.setfinder.IQueryPdoMasterDao; -import edu.harvard.i2b2.crc.dao.setfinder.IQueryRequestDao; -import edu.harvard.i2b2.crc.dao.setfinder.IQueryResultInstanceDao; -import edu.harvard.i2b2.crc.dao.setfinder.IQueryResultTypeDao; -import edu.harvard.i2b2.crc.dao.setfinder.IQueryStatusTypeDao; -import edu.harvard.i2b2.crc.dao.setfinder.IXmlResultDao; -import edu.harvard.i2b2.crc.dao.setfinder.PatientSetCollectionSpringDao; -import edu.harvard.i2b2.crc.dao.setfinder.QueryBreakdownTypeSpringDao; -import edu.harvard.i2b2.crc.dao.setfinder.QueryInstanceSpringDao; -import edu.harvard.i2b2.crc.dao.setfinder.QueryMasterSpringDao; -import edu.harvard.i2b2.crc.dao.setfinder.QueryPdoMasterSpringDao; -import edu.harvard.i2b2.crc.dao.setfinder.QueryRequestSpringDao; -import edu.harvard.i2b2.crc.dao.setfinder.QueryResultInstanceSpringDao; -import edu.harvard.i2b2.crc.dao.setfinder.QueryResultTypeSpringDao; -import edu.harvard.i2b2.crc.dao.setfinder.QueryStatusTypeSpringDao; -import edu.harvard.i2b2.crc.dao.setfinder.XmlResultSpringDao; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - -public class OracleDAOFactory implements IDAOFactory { - - private DataSourceLookup dataSourceLookup = null, - orignalDataSourceLookup = null; - private DataSource dataSource = null; - private QueryProcessorUtil crcUtil = null; - /** log **/ - protected final static Log log = LogFactory.getLog(OracleDAOFactory.class); - - public OracleDAOFactory(DataSourceLookup dataSourceLookup, - DataSourceLookup originalDataSourceLookup) throws I2B2DAOException { - this.dataSourceLookup = dataSourceLookup; - this.orignalDataSourceLookup = originalDataSourceLookup; - crcUtil = QueryProcessorUtil.getInstance(); - String dataSourceName = dataSourceLookup.getDataSource(); - log.info("Using datasource " + dataSourceName); - try { - // dataSource = (DataSource) - // crcUtil.getSpringDataSource(dataSourceName); - dataSource = ServiceLocator.getInstance().getAppServerDataSource( - dataSourceName); - } catch (I2B2Exception i2b2Ex) { - log.error(i2b2Ex); - throw new I2B2DAOException( - "Error getting application/spring datasource " - + dataSourceName + " : " + i2b2Ex.getMessage(), - i2b2Ex); - } - } - - public OracleDAOFactory(DataSourceLookup dataSourceLookup, - DataSource dataSource) throws I2B2DAOException { - this.dataSourceLookup = dataSourceLookup; - this.dataSource = dataSource; - this.orignalDataSourceLookup = dataSourceLookup; - crcUtil = QueryProcessorUtil.getInstance(); - } - - @Override - public SetFinderDAOFactory getSetFinderDAOFactory() { - return new OracleSetFinderDAOFactory(dataSource, dataSourceLookup, - orignalDataSourceLookup); - } - - @Override - public PatientDataDAOFactory getPatientDataDAOFactory() { - return new OraclePatientDataDAOFactory(dataSource, dataSourceLookup, - orignalDataSourceLookup); - } - - // - public class OraclePatientDataDAOFactory implements PatientDataDAOFactory { - private DataSourceLookup dataSourceLookup = null, - orignalDataSourceLookup = null; - private DataSource dataSource = null; - - public OraclePatientDataDAOFactory(DataSource dataSource, - DataSourceLookup dataSourceLookup, - DataSourceLookup orignalDataSourceLookup) { - this.dataSourceLookup = dataSourceLookup; - this.dataSource = dataSource; - this.orignalDataSourceLookup = orignalDataSourceLookup; - - } - - @Override - public ObservationFactDao getObservationFactDAO() { - // TODO Auto-generated method stub - // - return new ObservationFactDao(dataSourceLookup, dataSource); - // return null; - - } - - @Override - public PdoQueryConceptDao getPdoQueryConceptDAO() { - // TODO Auto-generated method stub - return new PdoQueryConceptDao(dataSourceLookup, dataSource); - // return null; - } - - @Override - public PdoQueryModifierDao getPdoQueryModifierDAO() { - // TODO Auto-generated method stub - return new PdoQueryModifierDao(dataSourceLookup, dataSource); - // return null; - } - - @Override - public PdoQueryPatientDao getPdoQueryPatientDAO() { - // TODO Auto-generated method stub - return new PdoQueryPatientDao(dataSourceLookup, dataSource); - // return null; - } - - @Override - public PdoQueryProviderDao getPdoQueryProviderDAO() { - // TODO Auto-generated method stub - return new PdoQueryProviderDao(dataSourceLookup, dataSource); - } - - @Override - public PdoQueryVisitDao getPdoQueryVisitDAO() { - // TODO Auto-generated method stub - return new PdoQueryVisitDao(dataSourceLookup, dataSource); - } - - @Override - public TablePdoQueryConceptDao getTablePdoQueryConceptDAO() { - // TODO Auto-generated method stub - return new TablePdoQueryConceptDao(dataSourceLookup, dataSource); - } - - @Override - public TablePdoQueryModifierDao getTablePdoQueryModifierDAO() { - // TODO Auto-generated method stub - return new TablePdoQueryModifierDao(dataSourceLookup, dataSource); - } - - @Override - public TablePdoQueryPatientDao getTablePdoQueryPatientDAO() { - // TODO Auto-generated method stub - return new TablePdoQueryPatientDao(dataSourceLookup, dataSource); - } - - @Override - public TablePdoQueryProviderDao getTablePdoQueryProviderDAO() { - // TODO Auto-generated method stub - return new TablePdoQueryProviderDao(dataSourceLookup, dataSource); - } - - @Override - public TablePdoQueryVisitDao getTablePdoQueryVisitDAO() { - // TODO Auto-generated method stub - return new TablePdoQueryVisitDao(dataSourceLookup, dataSource); - } - - @Override - public IPageDao getPageDAO() { - return new PageTotalDao(dataSourceLookup, dataSource); - } - - @Override - public IPdoQueryPidDao getPdoQueryPidDAO() { - return new PdoQueryPidDao(dataSourceLookup, dataSource); - } - - @Override - public IPdoQueryEidDao getPdoQueryEidDAO() { - return new PdoQueryEidDao(dataSourceLookup, dataSource); - } - - @Override - public IMetadataDao getMetadataDAO() { - return new MetadataDao(dataSourceLookup, dataSource); - } - - @Override - public DataSourceLookup getDataSourceLookup() { - return dataSourceLookup; - } - - @Override - public DataSourceLookup getOriginalDataSourceLookup() { - return orignalDataSourceLookup; - } - - @Override - public DataSource getDataSource() { - return this.dataSource; - } - } - - public class OracleSetFinderDAOFactory implements SetFinderDAOFactory { - - private DataSourceLookup dataSourceLookup = null, - orignalDataSourceLookup = null; - private DataSource dataSource = null; - - public OracleSetFinderDAOFactory(DataSource dataSource, - DataSourceLookup dataSourceLookup, - DataSourceLookup orignalDataSourceLookup) { - this.dataSourceLookup = dataSourceLookup; - this.dataSource = dataSource; - this.orignalDataSourceLookup = orignalDataSourceLookup; - - } - - @Override - public IXmlResultDao getXmlResultDao() { - // TODO Auto-generated method stub - return new XmlResultSpringDao(dataSource, dataSourceLookup); - } - - @Override - public IPatientSetCollectionDao getPatientSetCollectionDAO() { - // TODO Auto-generated method stub - return new PatientSetCollectionSpringDao(dataSource, - dataSourceLookup); - } - - @Override - public IEncounterSetCollectionDao getEncounterSetCollectionDAO() { - // TODO Auto-generated method stub - return new EncounterSetCollectionSpringDao(dataSource, - dataSourceLookup); - } - - @Override - public IQueryResultInstanceDao getPatientSetResultDAO() { - // TODO Auto-generated method stub - return new QueryResultInstanceSpringDao(dataSource, - dataSourceLookup); - } - - @Override - public IQueryInstanceDao getQueryInstanceDAO() { - // TODO Auto-generated method stub - return new QueryInstanceSpringDao(dataSource, dataSourceLookup); - } - - @Override - public IQueryMasterDao getQueryMasterDAO() { - // TODO Auto-generated method stub - return new QueryMasterSpringDao(dataSource, dataSourceLookup); - } - - @Override - public IQueryPdoMasterDao getQueryPdoMasterDAO() { - // TODO Auto-generated method stub - return new QueryPdoMasterSpringDao(dataSource, dataSourceLookup); - } - - @Override - public IQueryRequestDao getQueryRequestDAO() { - // TODO Auto-generated method stub - return new QueryRequestSpringDao(dataSource, dataSourceLookup); - } - - @Override - public DataSourceLookup getDataSourceLookup() { - return dataSourceLookup; - } - - @Override - public DataSourceLookup getOriginalDataSourceLookup() { - return orignalDataSourceLookup; - } - - @Override - public DataSource getDataSource() { - return dataSource; - } - - @Override - public IQueryResultTypeDao getQueryResultTypeDao() { - // TODO Auto-generated method stub - return new QueryResultTypeSpringDao(dataSource, dataSourceLookup); - } - - @Override - public IQueryStatusTypeDao getQueryStatusTypeDao() { - // TODO Auto-generated method stub - return new QueryStatusTypeSpringDao(dataSource, dataSourceLookup); - } - - @Override - public IAnalysisPluginDao getAnalysisPluginDao() { - return new AnalysisPluginSpringDao(dataSource, dataSourceLookup); - } - - @Override - public IPriviledgeDao getPriviledgeDao() { - return new PriviledgeSpringDao(dataSource, dataSourceLookup); - } - - @Override - public IQueryBreakdownTypeDao getQueryBreakdownTypeDao() { - return new QueryBreakdownTypeSpringDao(dataSource, dataSourceLookup); - } - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao; + +import javax.sql.DataSource; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.ServiceLocator; +import edu.harvard.i2b2.crc.dao.pdo.IMetadataDao; +import edu.harvard.i2b2.crc.dao.pdo.IPageDao; +import edu.harvard.i2b2.crc.dao.pdo.IPdoQueryEidDao; +import edu.harvard.i2b2.crc.dao.pdo.IPdoQueryPidDao; +import edu.harvard.i2b2.crc.dao.pdo.MetadataDao; +import edu.harvard.i2b2.crc.dao.pdo.ObservationFactDao; +import edu.harvard.i2b2.crc.dao.pdo.PageTotalDao; +import edu.harvard.i2b2.crc.dao.pdo.PdoQueryConceptDao; +import edu.harvard.i2b2.crc.dao.pdo.PdoQueryEidDao; +import edu.harvard.i2b2.crc.dao.pdo.PdoQueryModifierDao; +import edu.harvard.i2b2.crc.dao.pdo.PdoQueryPatientDao; +import edu.harvard.i2b2.crc.dao.pdo.PdoQueryPidDao; +import edu.harvard.i2b2.crc.dao.pdo.PdoQueryProviderDao; +import edu.harvard.i2b2.crc.dao.pdo.PdoQueryVisitDao; +import edu.harvard.i2b2.crc.dao.pdo.TablePdoQueryConceptDao; +import edu.harvard.i2b2.crc.dao.pdo.TablePdoQueryModifierDao; +import edu.harvard.i2b2.crc.dao.pdo.TablePdoQueryPatientDao; +import edu.harvard.i2b2.crc.dao.pdo.TablePdoQueryProviderDao; +import edu.harvard.i2b2.crc.dao.pdo.TablePdoQueryVisitDao; +import edu.harvard.i2b2.crc.dao.role.IPriviledgeDao; +import edu.harvard.i2b2.crc.dao.role.PriviledgeSpringDao; +import edu.harvard.i2b2.crc.dao.setfinder.AnalysisPluginSpringDao; +import edu.harvard.i2b2.crc.dao.setfinder.EncounterSetCollectionSpringDao; +import edu.harvard.i2b2.crc.dao.setfinder.IAnalysisPluginDao; +import edu.harvard.i2b2.crc.dao.setfinder.IEncounterSetCollectionDao; +import edu.harvard.i2b2.crc.dao.setfinder.IPatientSetCollectionDao; +import edu.harvard.i2b2.crc.dao.setfinder.IQueryBreakdownTypeDao; +import edu.harvard.i2b2.crc.dao.setfinder.IQueryInstanceDao; +import edu.harvard.i2b2.crc.dao.setfinder.IQueryMasterDao; +import edu.harvard.i2b2.crc.dao.setfinder.IQueryPdoMasterDao; +import edu.harvard.i2b2.crc.dao.setfinder.IQueryRequestDao; +import edu.harvard.i2b2.crc.dao.setfinder.IQueryResultInstanceDao; +import edu.harvard.i2b2.crc.dao.setfinder.IQueryResultTypeDao; +import edu.harvard.i2b2.crc.dao.setfinder.IQueryStatusTypeDao; +import edu.harvard.i2b2.crc.dao.setfinder.IXmlResultDao; +import edu.harvard.i2b2.crc.dao.setfinder.PatientSetCollectionSpringDao; +import edu.harvard.i2b2.crc.dao.setfinder.QueryBreakdownTypeSpringDao; +import edu.harvard.i2b2.crc.dao.setfinder.QueryInstanceSpringDao; +import edu.harvard.i2b2.crc.dao.setfinder.QueryMasterSpringDao; +import edu.harvard.i2b2.crc.dao.setfinder.QueryPdoMasterSpringDao; +import edu.harvard.i2b2.crc.dao.setfinder.QueryRequestSpringDao; +import edu.harvard.i2b2.crc.dao.setfinder.QueryResultInstanceSpringDao; +import edu.harvard.i2b2.crc.dao.setfinder.QueryResultTypeSpringDao; +import edu.harvard.i2b2.crc.dao.setfinder.QueryStatusTypeSpringDao; +import edu.harvard.i2b2.crc.dao.setfinder.XmlResultSpringDao; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + +public class OracleDAOFactory implements IDAOFactory { + + private DataSourceLookup dataSourceLookup = null, + orignalDataSourceLookup = null; + private DataSource dataSource = null; + private QueryProcessorUtil crcUtil = null; + /** log **/ + protected final static Log log = LogFactory.getLog(OracleDAOFactory.class); + + public OracleDAOFactory(DataSourceLookup dataSourceLookup, + DataSourceLookup originalDataSourceLookup) throws I2B2DAOException { + this.dataSourceLookup = dataSourceLookup; + this.orignalDataSourceLookup = originalDataSourceLookup; + crcUtil = QueryProcessorUtil.getInstance(); + String dataSourceName = dataSourceLookup.getDataSource(); + log.info("Using datasource " + dataSourceName); + try { + // dataSource = (DataSource) + // crcUtil.getSpringDataSource(dataSourceName); + dataSource = ServiceLocator.getInstance().getAppServerDataSource( + dataSourceName); + } catch (I2B2Exception i2b2Ex) { + log.error(i2b2Ex); + throw new I2B2DAOException( + "Error getting application/spring datasource " + + dataSourceName + " : " + i2b2Ex.getMessage(), + i2b2Ex); + } + } + + public OracleDAOFactory(DataSourceLookup dataSourceLookup, + DataSource dataSource) throws I2B2DAOException { + this.dataSourceLookup = dataSourceLookup; + this.dataSource = dataSource; + this.orignalDataSourceLookup = dataSourceLookup; + crcUtil = QueryProcessorUtil.getInstance(); + } + + @Override + public SetFinderDAOFactory getSetFinderDAOFactory() { + return new OracleSetFinderDAOFactory(dataSource, dataSourceLookup, + orignalDataSourceLookup); + } + + @Override + public PatientDataDAOFactory getPatientDataDAOFactory() { + return new OraclePatientDataDAOFactory(dataSource, dataSourceLookup, + orignalDataSourceLookup); + } + + // + public class OraclePatientDataDAOFactory implements PatientDataDAOFactory { + private DataSourceLookup dataSourceLookup = null, + orignalDataSourceLookup = null; + private DataSource dataSource = null; + + public OraclePatientDataDAOFactory(DataSource dataSource, + DataSourceLookup dataSourceLookup, + DataSourceLookup orignalDataSourceLookup) { + this.dataSourceLookup = dataSourceLookup; + this.dataSource = dataSource; + this.orignalDataSourceLookup = orignalDataSourceLookup; + + } + + @Override + public ObservationFactDao getObservationFactDAO() { + // TODO Auto-generated method stub + // + return new ObservationFactDao(dataSourceLookup, dataSource); + // return null; + + } + + @Override + public PdoQueryConceptDao getPdoQueryConceptDAO() { + // TODO Auto-generated method stub + return new PdoQueryConceptDao(dataSourceLookup, dataSource); + // return null; + } + + @Override + public PdoQueryModifierDao getPdoQueryModifierDAO() { + // TODO Auto-generated method stub + return new PdoQueryModifierDao(dataSourceLookup, dataSource); + // return null; + } + + @Override + public PdoQueryPatientDao getPdoQueryPatientDAO() { + // TODO Auto-generated method stub + return new PdoQueryPatientDao(dataSourceLookup, dataSource); + // return null; + } + + @Override + public PdoQueryProviderDao getPdoQueryProviderDAO() { + // TODO Auto-generated method stub + return new PdoQueryProviderDao(dataSourceLookup, dataSource); + } + + @Override + public PdoQueryVisitDao getPdoQueryVisitDAO() { + // TODO Auto-generated method stub + return new PdoQueryVisitDao(dataSourceLookup, dataSource); + } + + @Override + public TablePdoQueryConceptDao getTablePdoQueryConceptDAO() { + // TODO Auto-generated method stub + return new TablePdoQueryConceptDao(dataSourceLookup, dataSource); + } + + @Override + public TablePdoQueryModifierDao getTablePdoQueryModifierDAO() { + // TODO Auto-generated method stub + return new TablePdoQueryModifierDao(dataSourceLookup, dataSource); + } + + @Override + public TablePdoQueryPatientDao getTablePdoQueryPatientDAO() { + // TODO Auto-generated method stub + return new TablePdoQueryPatientDao(dataSourceLookup, dataSource); + } + + @Override + public TablePdoQueryProviderDao getTablePdoQueryProviderDAO() { + // TODO Auto-generated method stub + return new TablePdoQueryProviderDao(dataSourceLookup, dataSource); + } + + @Override + public TablePdoQueryVisitDao getTablePdoQueryVisitDAO() { + // TODO Auto-generated method stub + return new TablePdoQueryVisitDao(dataSourceLookup, dataSource); + } + + @Override + public IPageDao getPageDAO() { + return new PageTotalDao(dataSourceLookup, dataSource); + } + + @Override + public IPdoQueryPidDao getPdoQueryPidDAO() { + return new PdoQueryPidDao(dataSourceLookup, dataSource); + } + + @Override + public IPdoQueryEidDao getPdoQueryEidDAO() { + return new PdoQueryEidDao(dataSourceLookup, dataSource); + } + + @Override + public IMetadataDao getMetadataDAO() { + return new MetadataDao(dataSourceLookup, dataSource); + } + + @Override + public DataSourceLookup getDataSourceLookup() { + return dataSourceLookup; + } + + @Override + public DataSourceLookup getOriginalDataSourceLookup() { + return orignalDataSourceLookup; + } + + @Override + public DataSource getDataSource() { + return this.dataSource; + } + } + + public class OracleSetFinderDAOFactory implements SetFinderDAOFactory { + + private DataSourceLookup dataSourceLookup = null, + orignalDataSourceLookup = null; + private DataSource dataSource = null; + + public OracleSetFinderDAOFactory(DataSource dataSource, + DataSourceLookup dataSourceLookup, + DataSourceLookup orignalDataSourceLookup) { + this.dataSourceLookup = dataSourceLookup; + this.dataSource = dataSource; + this.orignalDataSourceLookup = orignalDataSourceLookup; + + } + + @Override + public IXmlResultDao getXmlResultDao() { + // TODO Auto-generated method stub + return new XmlResultSpringDao(dataSource, dataSourceLookup); + } + + @Override + public IPatientSetCollectionDao getPatientSetCollectionDAO() { + // TODO Auto-generated method stub + return new PatientSetCollectionSpringDao(dataSource, + dataSourceLookup); + } + + @Override + public IEncounterSetCollectionDao getEncounterSetCollectionDAO() { + // TODO Auto-generated method stub + return new EncounterSetCollectionSpringDao(dataSource, + dataSourceLookup); + } + + @Override + public IQueryResultInstanceDao getPatientSetResultDAO() { + // TODO Auto-generated method stub + return new QueryResultInstanceSpringDao(dataSource, + dataSourceLookup); + } + + @Override + public IQueryInstanceDao getQueryInstanceDAO() { + // TODO Auto-generated method stub + return new QueryInstanceSpringDao(dataSource, dataSourceLookup); + } + + @Override + public IQueryMasterDao getQueryMasterDAO() { + // TODO Auto-generated method stub + return new QueryMasterSpringDao(dataSource, dataSourceLookup); + } + + @Override + public IQueryPdoMasterDao getQueryPdoMasterDAO() { + // TODO Auto-generated method stub + return new QueryPdoMasterSpringDao(dataSource, dataSourceLookup); + } + + @Override + public IQueryRequestDao getQueryRequestDAO() { + // TODO Auto-generated method stub + return new QueryRequestSpringDao(dataSource, dataSourceLookup); + } + + @Override + public DataSourceLookup getDataSourceLookup() { + return dataSourceLookup; + } + + @Override + public DataSourceLookup getOriginalDataSourceLookup() { + return orignalDataSourceLookup; + } + + @Override + public DataSource getDataSource() { + return dataSource; + } + + @Override + public IQueryResultTypeDao getQueryResultTypeDao() { + // TODO Auto-generated method stub + return new QueryResultTypeSpringDao(dataSource, dataSourceLookup); + } + + @Override + public IQueryStatusTypeDao getQueryStatusTypeDao() { + // TODO Auto-generated method stub + return new QueryStatusTypeSpringDao(dataSource, dataSourceLookup); + } + + @Override + public IAnalysisPluginDao getAnalysisPluginDao() { + return new AnalysisPluginSpringDao(dataSource, dataSourceLookup); + } + + @Override + public IPriviledgeDao getPriviledgeDao() { + return new PriviledgeSpringDao(dataSource, dataSourceLookup); + } + + @Override + public IQueryBreakdownTypeDao getQueryBreakdownTypeDao() { + return new QueryBreakdownTypeSpringDao(dataSource, dataSourceLookup); + } + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/OracleDataSourceLookupDAO.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/OracleDataSourceLookupDAO.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/OracleDataSourceLookupDAO.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/OracleDataSourceLookupDAO.java index cf7a9282..8b8ced1d --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/OracleDataSourceLookupDAO.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/OracleDataSourceLookupDAO.java @@ -1,106 +1,106 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao; - -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Types; -import java.util.List; - -import javax.sql.DataSource; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.jdbc.core.RowMapper; - -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; - -public class OracleDataSourceLookupDAO extends DataSourceLookupDAO { - - /** log **/ - protected final Log log = LogFactory - .getLog(OracleDataSourceLookupDAO.class); - - private String schemaName = null; - - public OracleDataSourceLookupDAO(DataSource dataSource, String schemaName) { - setDataSource(dataSource); - if (schemaName != null && schemaName.endsWith(".")) { - this.schemaName = schemaName; - } else { - this.schemaName = schemaName + "."; - } - } - - @Override - public List getDbLookupByHive(String domainId) { - String sql = "select * from " - + schemaName - + "crc_db_lookup where LOWER(c_domain_id) like ? "; - log.debug("Executing SQL [" + sql + "]"); - List dataSourceLookupList = this.query(sql, - new Object[] { domainId.toLowerCase() }, new mapper()); - return dataSourceLookupList; - } - - - @Override - public List getDbLookupByHiveOwner(String domainId, - String ownerId) { - String sql = "select * from " - + schemaName - + "crc_db_lookup where LOWER(c_domain_id) = ? and c_project_path = ? and (LOWER(c_owner_id) = ? or c_owner_id ='@') order by c_project_path"; - String projectId = "@"; - log.debug("Executing SQL [" + sql + "]"); - List dataSourceLookupList = this.query(sql, - new Object[] { domainId.toLowerCase(), projectId, ownerId.toLowerCase() }, new mapper()); - return dataSourceLookupList; - } - - @Override - @SuppressWarnings("unchecked") - public List getDbLookupByHiveProjectOwner( - String domainId, String projectId, String ownerId) { - String sql = "select * from " - + schemaName - + "crc_db_lookup where LOWER(c_domain_id) = ? and c_project_path like ? and (LOWER(c_owner_id) =? or c_owner_id = '@') order by c_project_path"; - List dataSourceLookupList = this.query(sql, - new Object[] { domainId.toLowerCase(), projectId + "%", ownerId.toLowerCase() }, new int[] { - Types.VARCHAR, Types.VARCHAR, Types.VARCHAR }, - new mapper()); - return dataSourceLookupList; - } - - public static void main(String args[]) { - OracleDataSourceLookupDAO dao = new OracleDataSourceLookupDAO(null, - null); - - } - - public class mapper implements RowMapper { - - @Override - public Object mapRow(ResultSet rs, int rowNum) throws SQLException { - DataSourceLookup dataSourceLookup = new DataSourceLookup(); - dataSourceLookup.setDomainId(rs.getString("c_domain_id")); - dataSourceLookup.setProjectPath(rs.getString("c_project_path")); - dataSourceLookup.setOwnerId(rs.getString("c_owner_id")); - dataSourceLookup.setFullSchema(rs.getString("c_db_fullschema")); - dataSourceLookup.setDataSource(rs.getString("c_db_datasource")); - dataSourceLookup.setServerType(rs.getString("c_db_servertype")); - dataSourceLookup.setNiceName(rs.getString("c_db_nicename")); - dataSourceLookup.setToolTip(rs.getString("c_db_tooltip")); - dataSourceLookup.setComment(rs.getString("c_comment")); - dataSourceLookup.setEntryDate(rs.getDate("c_entry_date")); - dataSourceLookup.setChangeDate(rs.getDate("c_change_date")); - dataSourceLookup.setStatusCd(rs.getString("c_status_cd")); - return dataSourceLookup; - } - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Types; +import java.util.List; + +import javax.sql.DataSource; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.jdbc.core.RowMapper; + +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; + +public class OracleDataSourceLookupDAO extends DataSourceLookupDAO { + + /** log **/ + protected final Log log = LogFactory + .getLog(OracleDataSourceLookupDAO.class); + + private String schemaName = null; + + public OracleDataSourceLookupDAO(DataSource dataSource, String schemaName) { + setDataSource(dataSource); + if (schemaName != null && schemaName.endsWith(".")) { + this.schemaName = schemaName; + } else { + this.schemaName = schemaName + "."; + } + } + + @Override + public List getDbLookupByHive(String domainId) { + String sql = "select * from " + + schemaName + + "crc_db_lookup where LOWER(c_domain_id) like ? "; + log.debug("Executing SQL [" + sql + "]"); + List dataSourceLookupList = this.query(sql, + new Object[] { domainId.toLowerCase() }, new mapper()); + return dataSourceLookupList; + } + + + @Override + public List getDbLookupByHiveOwner(String domainId, + String ownerId) { + String sql = "select * from " + + schemaName + + "crc_db_lookup where LOWER(c_domain_id) = ? and c_project_path = ? and (LOWER(c_owner_id) = ? or c_owner_id ='@') order by c_project_path"; + String projectId = "@"; + log.debug("Executing SQL [" + sql + "]"); + List dataSourceLookupList = this.query(sql, + new Object[] { domainId.toLowerCase(), projectId, ownerId.toLowerCase() }, new mapper()); + return dataSourceLookupList; + } + + @Override + @SuppressWarnings("unchecked") + public List getDbLookupByHiveProjectOwner( + String domainId, String projectId, String ownerId) { + String sql = "select * from " + + schemaName + + "crc_db_lookup where LOWER(c_domain_id) = ? and c_project_path like ? and (LOWER(c_owner_id) =? or c_owner_id = '@') order by c_project_path"; + List dataSourceLookupList = this.query(sql, + new Object[] { domainId.toLowerCase(), projectId + "%", ownerId.toLowerCase() }, new int[] { + Types.VARCHAR, Types.VARCHAR, Types.VARCHAR }, + new mapper()); + return dataSourceLookupList; + } + + public static void main(String args[]) { + OracleDataSourceLookupDAO dao = new OracleDataSourceLookupDAO(null, + null); + + } + + public class mapper implements RowMapper { + + @Override + public Object mapRow(ResultSet rs, int rowNum) throws SQLException { + DataSourceLookup dataSourceLookup = new DataSourceLookup(); + dataSourceLookup.setDomainId(rs.getString("c_domain_id")); + dataSourceLookup.setProjectPath(rs.getString("c_project_path")); + dataSourceLookup.setOwnerId(rs.getString("c_owner_id")); + dataSourceLookup.setFullSchema(rs.getString("c_db_fullschema")); + dataSourceLookup.setDataSource(rs.getString("c_db_datasource")); + dataSourceLookup.setServerType(rs.getString("c_db_servertype")); + dataSourceLookup.setNiceName(rs.getString("c_db_nicename")); + dataSourceLookup.setToolTip(rs.getString("c_db_tooltip")); + dataSourceLookup.setComment(rs.getString("c_comment")); + dataSourceLookup.setEntryDate(rs.getDate("c_entry_date")); + dataSourceLookup.setChangeDate(rs.getDate("c_change_date")); + dataSourceLookup.setStatusCd(rs.getString("c_status_cd")); + return dataSourceLookup; + } + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/PatientDataDAOFactory.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/PatientDataDAOFactory.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/PatientDataDAOFactory.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/PatientDataDAOFactory.java index 83da323e..aba284b0 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/PatientDataDAOFactory.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/PatientDataDAOFactory.java @@ -1,66 +1,66 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao; - -import javax.sql.DataSource; - -import edu.harvard.i2b2.crc.dao.pdo.IMetadataDao; -import edu.harvard.i2b2.crc.dao.pdo.IObservationFactDao; -import edu.harvard.i2b2.crc.dao.pdo.IPageDao; -import edu.harvard.i2b2.crc.dao.pdo.IPdoQueryConceptDao; -import edu.harvard.i2b2.crc.dao.pdo.IPdoQueryEidDao; -import edu.harvard.i2b2.crc.dao.pdo.IPdoQueryModifierDao; -import edu.harvard.i2b2.crc.dao.pdo.IPdoQueryPatientDao; -import edu.harvard.i2b2.crc.dao.pdo.IPdoQueryPidDao; -import edu.harvard.i2b2.crc.dao.pdo.IPdoQueryProviderDao; -import edu.harvard.i2b2.crc.dao.pdo.IPdoQueryVisitDao; -import edu.harvard.i2b2.crc.dao.pdo.ITablePdoQueryConceptDao; -import edu.harvard.i2b2.crc.dao.pdo.ITablePdoQueryModifierDao; -import edu.harvard.i2b2.crc.dao.pdo.ITablePdoQueryPatientDao; -import edu.harvard.i2b2.crc.dao.pdo.ITablePdoQueryProviderDao; -import edu.harvard.i2b2.crc.dao.pdo.ITablePdoQueryVisitDao; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; - -public interface PatientDataDAOFactory { - public IObservationFactDao getObservationFactDAO(); - - public IPdoQueryConceptDao getPdoQueryConceptDAO(); - - public IPdoQueryModifierDao getPdoQueryModifierDAO(); - - public IPdoQueryPatientDao getPdoQueryPatientDAO(); - - public IPdoQueryProviderDao getPdoQueryProviderDAO(); - - public IPdoQueryVisitDao getPdoQueryVisitDAO(); - - public ITablePdoQueryConceptDao getTablePdoQueryConceptDAO(); - - public ITablePdoQueryModifierDao getTablePdoQueryModifierDAO(); - - public ITablePdoQueryPatientDao getTablePdoQueryPatientDAO(); - - public ITablePdoQueryProviderDao getTablePdoQueryProviderDAO(); - - public ITablePdoQueryVisitDao getTablePdoQueryVisitDAO(); - - public IPageDao getPageDAO(); - - public IPdoQueryPidDao getPdoQueryPidDAO(); - - public IPdoQueryEidDao getPdoQueryEidDAO(); - - public IMetadataDao getMetadataDAO(); - - public DataSourceLookup getDataSourceLookup(); - - public DataSourceLookup getOriginalDataSourceLookup(); - - public DataSource getDataSource(); -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao; + +import javax.sql.DataSource; + +import edu.harvard.i2b2.crc.dao.pdo.IMetadataDao; +import edu.harvard.i2b2.crc.dao.pdo.IObservationFactDao; +import edu.harvard.i2b2.crc.dao.pdo.IPageDao; +import edu.harvard.i2b2.crc.dao.pdo.IPdoQueryConceptDao; +import edu.harvard.i2b2.crc.dao.pdo.IPdoQueryEidDao; +import edu.harvard.i2b2.crc.dao.pdo.IPdoQueryModifierDao; +import edu.harvard.i2b2.crc.dao.pdo.IPdoQueryPatientDao; +import edu.harvard.i2b2.crc.dao.pdo.IPdoQueryPidDao; +import edu.harvard.i2b2.crc.dao.pdo.IPdoQueryProviderDao; +import edu.harvard.i2b2.crc.dao.pdo.IPdoQueryVisitDao; +import edu.harvard.i2b2.crc.dao.pdo.ITablePdoQueryConceptDao; +import edu.harvard.i2b2.crc.dao.pdo.ITablePdoQueryModifierDao; +import edu.harvard.i2b2.crc.dao.pdo.ITablePdoQueryPatientDao; +import edu.harvard.i2b2.crc.dao.pdo.ITablePdoQueryProviderDao; +import edu.harvard.i2b2.crc.dao.pdo.ITablePdoQueryVisitDao; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; + +public interface PatientDataDAOFactory { + public IObservationFactDao getObservationFactDAO(); + + public IPdoQueryConceptDao getPdoQueryConceptDAO(); + + public IPdoQueryModifierDao getPdoQueryModifierDAO(); + + public IPdoQueryPatientDao getPdoQueryPatientDAO(); + + public IPdoQueryProviderDao getPdoQueryProviderDAO(); + + public IPdoQueryVisitDao getPdoQueryVisitDAO(); + + public ITablePdoQueryConceptDao getTablePdoQueryConceptDAO(); + + public ITablePdoQueryModifierDao getTablePdoQueryModifierDAO(); + + public ITablePdoQueryPatientDao getTablePdoQueryPatientDAO(); + + public ITablePdoQueryProviderDao getTablePdoQueryProviderDAO(); + + public ITablePdoQueryVisitDao getTablePdoQueryVisitDAO(); + + public IPageDao getPageDAO(); + + public IPdoQueryPidDao getPdoQueryPidDAO(); + + public IPdoQueryEidDao getPdoQueryEidDAO(); + + public IMetadataDao getMetadataDAO(); + + public DataSourceLookup getDataSourceLookup(); + + public DataSourceLookup getOriginalDataSourceLookup(); + + public DataSource getDataSource(); +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/RPDODao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/RPDODao.java similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/RPDODao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/RPDODao.java index 9f031ff0..4f53c4ea 100644 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/RPDODao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/RPDODao.java @@ -1,503 +1,503 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Wayne Chan - */ -package edu.harvard.i2b2.crc.dao; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.ServiceLocator; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; -import edu.harvard.i2b2.crc.datavo.pdo.query.ConceptTableType; -import edu.harvard.i2b2.crc.datavo.pdo.query.DblookupType; -import edu.harvard.i2b2.crc.datavo.pdo.query.DeleteDblookupType; -import edu.harvard.i2b2.crc.datavo.pdo.query.RpdoType; -import edu.harvard.i2b2.crc.datavo.pdo.query.RpdosType; -import edu.harvard.i2b2.crc.datavo.pdo.query.SetDblookupType; -import edu.harvard.i2b2.crc.loader.ejb.DataMartLoaderAsyncBean; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; -import edu.harvard.i2b2.crc.dao.pdo.RpdoTable; -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.List; -import javax.sql.DataSource; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.dao.DataAccessException; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.RowMapper; -import org.springframework.jdbc.core.support.JdbcDaoSupport; - -import com.google.gson.Gson; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; - -public class RPDODao extends JdbcDaoSupport { - protected static Log logesapi = LogFactory.getLog(RPDODao.class); - - private static Log log = LogFactory.getLog(RPDODao.class); - private static DataSource ds = null; - private static JdbcTemplate jt; - private static String dbluTable; - private static String breakdownTable; - private static String resultTypeTable; - private static String getTable = " (LOWER(group_id)=LOWER(?) OR group_id='@') AND (LOWER(user_id)=LOWER(?) OR user_id='@') AND table_instance_id=? order by set_index "; - private static String keyOrder = " LOWER(group_id)=LOWER(?) AND (LOWER(user_id)=LOWER(?) OR user_id='@') "; //ORDER BY TABLE_INSTANCE_NAME "; - private String domainId = null; - private String userId = null; - private String projectPath = null; - - public RPDODao() { - initDblookupDao(); - } - - public RPDODao(MessageHeaderType reqMsgHdr) throws I2B2Exception, JAXBUtilException { - domainId = reqMsgHdr.getSecurity().getDomain(); - userId = reqMsgHdr.getSecurity().getUsername(); - projectPath = reqMsgHdr.getProjectId(); - initDblookupDao(); - } - - private void initDblookupDao() { - String dataSchema = ""; - - try { - - - DAOFactoryHelper daoFactoryHelper = new DAOFactoryHelper( - domainId, projectPath, userId); - - IDAOFactory daoFactory = daoFactoryHelper.getDAOFactory(); - ds = daoFactory.getSetFinderDAOFactory().getDataSource(); - - dataSchema = daoFactory.getSetFinderDAOFactory().getDataSourceLookup().getFullSchema(); - //ds = QueryProcessorUtil.getInstance().getDataSource("java:/CRCBootStrapDS"); - //ServiceLocator.getInstance() - //.getAppServerDataSource(dataSourceName); - } catch (I2B2Exception e2) { - log.error(e2.getMessage());; - } - jt = new JdbcTemplate(ds); - if (dataSchema.equals("")) - try { - - Connection conn = ds.getConnection(); - - dataSchema = conn.getSchema(); - conn.close(); - } catch (SQLException e1) { - log.error(e1.getMessage()); - } - if (dataSchema.endsWith(".")) { - dbluTable = dataSchema + "RPDO_TABLE_REQUEST "; - breakdownTable = dataSchema + "QT_BREAKDOWN_PATH "; - resultTypeTable = dataSchema + "QT_QUERY_RESULT_TYPE "; - - } else { - dbluTable = dataSchema + ".RPDO_TABLE_REQUEST "; - breakdownTable = dataSchema + ".QT_BREAKDOWN_PATH "; - resultTypeTable = dataSchema + ".QT_QUERY_RESULT_TYPE "; - } - log.info("RPDO_TABLE_REQUEST = " + dbluTable); - } - - public String slashSandwich(String s) { - StringBuffer sb = new StringBuffer(); - if (!s.startsWith("/")) { - sb.append('/'); - } - sb.append(s); - if (!s.endsWith("/")) { - sb.append('/'); - } - log.info(sb.toString()); - return sb.toString(); - } - - - public List findRPDOs() throws DataAccessException, I2B2DAOException{ - //String sql = "SELECT * FROM " + dbluTable + " WHERE" + keyOrder; - String sql = "select distinct table_instance_id, table_instance_name, max(set_index) as set_index, user_id, create_date " - + " FROM " + dbluTable - + " WHERE delete_flag = 'N' and " + keyOrder - + " group by table_instance_id, table_instance_name, user_id, create_date"; - List queryResult = null; - try { - queryResult = jt.query(sql, new getMapperRPDOs(), projectPath, userId); - } catch (DataAccessException e) { - log.error(e.getMessage()); - throw e; - } - log.info("result size = " + queryResult.size()); - return queryResult; - } - - public List getRPDO( int tableID) throws DataAccessException, I2B2Exception { - String sql = "SELECT table_instance_id, table_instance_name, column_name, user_id, set_index, json_data, required, create_date, update_date FROM " + dbluTable + " WHERE " + getTable; - List queryResult = null; - try { - queryResult = jt.query(sql, new getMapperRPDO(), projectPath, userId,tableID); - } catch (DataAccessException e) { - log.error(e.getMessage()); - e.printStackTrace(); - throw new I2B2DAOException("Database error"); - } - return queryResult; - } - - public List getDblookup(String column, String value) throws DataAccessException, I2B2Exception { - String sql = "SELECT * FROM " + dbluTable + " WHERE "; - String v = value, s = column.toLowerCase(); - List queryResult = null; - try { - if (s.equalsIgnoreCase("domain_id")) { - sql += keyOrder; - queryResult = jt.query(sql, new getMapperRPDO(), value, userId); - } else if (s.equalsIgnoreCase("user_id")) { - sql += keyOrder; - queryResult = jt.query(sql, new getMapperRPDO(), domainId, value); - } else { - sql += "c_" + column + "=? AND " + keyOrder; - if (s.equalsIgnoreCase("group_id")) { - v = slashSandwich(value); - } else { - } - queryResult = jt.query(sql, new getMapperRPDO(), v, domainId, userId); - } - } catch (DataAccessException e) { - log.error(e.getMessage()); - e.printStackTrace(); - throw new I2B2DAOException("Database error"); - } - return queryResult; - } - - public int setRPDO(final RpdoType rpdoType) throws DataAccessException, I2B2Exception { - int naxtTableInstanceID = 0; - int numRowsAdded = 0; - String sql = "SELECT MAX(TABLE_INSTANCE_ID) from " + dbluTable; - naxtTableInstanceID = jt.queryForObject(sql, Integer.class) + 1; - - java.sql.Timestamp now = new java.sql.Timestamp(System.currentTimeMillis()); - for(int i=0; i < rpdoType.getConcept().size(); i++) - { - // - // }RpdoType rpdoType: rpdosType.getRPDO()) { - //RpdoType rpdoType = rpdosType.getRpdo().get(i); - String json = rpdoType.getConcept().get(i).getData(); - - //Gson gson = new Gson(); - //json = gson.toJson(json); - - if (json != null && !json.trim().equals("")) { - String c_fullpath = " "; - String c_columnname = " "; - String c_tablename = " "; - String c_operator = " "; - String c_dimcode = " "; - String aggType = " "; - - try { - json = json.trim(); - JsonElement jelement = JsonParser.parseString(json); - //JsonElement jelement = new JsonParser().parse(json); - - JsonArray jarray = jelement.getAsJsonArray(); - JsonObject jobject = jarray.get(0).getAsJsonObject(); - - - - aggType = jobject.get("dataOption").getAsString(); - - JsonObject jObj= jobject.get("sdxData").getAsJsonObject(); - JsonElement jObj2 = jObj.get("origData"); - jobject =jObj2.getAsJsonObject(); - c_fullpath = jobject.get("key").getAsString(); - c_columnname = jobject.get("column_name").getAsString(); - c_tablename = jobject.get("table_name").getAsString(); - c_operator = jobject.get("operator").getAsString(); - c_dimcode = jobject.get("dim_code").getAsString(); - } catch (Exception e) {} - - if (rpdoType.isVisible() == null) - rpdoType.setVisible(false); - if (rpdoType.isShared() == null) - rpdoType.setShared(false); - - - sql = "INSERT INTO " + dbluTable + - "(TABLE_INSTANCE_ID, TABLE_INSTANCE_NAME, COLUMN_NAME, C_FACTTABLECOLUMN, C_FULLPATH, AGG_TYPE,C_COLUMNNAME,C_TABLENAME,C_OPERATOR,C_DIMCODE,USER_ID ,GROUP_ID ,SET_INDEX,JSON_DATA,CREATE_DATE,UPDATE_DATE,DELETE_FLAG,USE_AS_COHORT,REQUIRED) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,'N',?)"; - numRowsAdded = jt.update(sql, - naxtTableInstanceID, - rpdoType.getTitle(), - rpdoType.getConcept().get(i).getName(), - "concept_cd", - c_fullpath, - aggType, - c_columnname, - c_tablename, - c_operator, - c_dimcode, - (rpdoType.isShared() == true?"@":userId), - projectPath, - i, - json, - now, - now, - (rpdoType.isVisible() == true?"Y":"N"), - (rpdoType.getConcept().get(i).isRequired()== true?"Y":"N") - ); - - log.info("setRPDO - Number of rows added: " + numRowsAdded); - } - } - - // Always save regardless of isVisible is set - //if (rpdoType.isVisible()) - //{ - //Remove existing - try { - sql = "DELETE FROM " + breakdownTable + - " WHERE NAME = ? and USER_ID = ? "; - - jt.update(sql, - naxtTableInstanceID, - (rpdoType.isShared() == true?"@":userId)); - - //Remove existing - sql = "DELETE FROM " + resultTypeTable + - " WHERE NAME = ? and CLASSNAME = 'edu.harvard.i2b2.crc.dao.setfinder.QueryResultUserCreated' "; - - jt.update(sql, - naxtTableInstanceID); - } catch (Exception e) - { - e.printStackTrace(); - } - //Insert - sql = "INSERT INTO " + breakdownTable + - "(NAME, VALUE, CREATE_DATE, UPDATE_DATE, USER_ID) VALUES (?,?,?,?,?) "; - jt.update(sql, - naxtTableInstanceID, - "RPDO()", - now, - now, - (rpdoType.isShared() == true?"@":userId)); - - - sql = "SELECT MAX(RESULT_TYPE_ID) from " + resultTypeTable; - int resultTypeId = jt.queryForObject(sql, Integer.class) + 1; - - - //Insert - sql = "INSERT INTO " + resultTypeTable + - "(RESULT_TYPE_ID, NAME, DESCRIPTION, DISPLAY_TYPE_ID, VISUAL_ATTRIBUTE_TYPE_ID, USER_ROLE_CD, CLASSNAME) VALUES (?,?,?,?,?,?,?) "; - jt.update(sql, - resultTypeId, - naxtTableInstanceID, - rpdoType.getTitle(), - "CATNUM", - "LU", - null, - "edu.harvard.i2b2.crc.dao.setfinder.QueryResultUserCreated"); - - //} - return numRowsAdded; - } - - - //rpdoType.getcFacttablecolumn(),rpdoType.getcTablename(),rpdoType.getColumnName(),rpdoType.getcFullpath(), rpdoType.getcColumnname(),rpdoType.getcColumndatatype(), rpdoType.getcOperator(), rpdoType.getcDimcode(), rpdoType.getAggType(), rpdoType.getConstrainByDateTo(), rpdoType.getConstrainByDateFrom(), rpdoType.getConstrainByValueOperator(), - // rpdoType.getConstrainByValueConstraint(), rpdoType.getConstrainByValueUnitOfMeasure(), rpdoType.getConstrainByValueType(), - - //rpdoType.getCreateDate(), rpdoType.getUpdateDate() - //, rpdoType.getDeleteFlag() - //, rpdoType.getConstrainByIndexdateColumnname(), rpdoType.getConstrainByIndexdateFromDays(), rpdoType.getConstrainByIndexdateToDays(), rpdoType.getUseAsCohort() - - public int getRPDORename(Integer id, String title) { - int numRowsAdded = 0; - - String sql = "UPDATE " + dbluTable + - " SET TABLE_INSTANCE_NAME = ? WHERE TABLE_INSTANCE_ID = ? and USER_ID = ?"; - numRowsAdded = jt.update(sql, - title, - id, - userId - ); - return numRowsAdded; - } - - public int getRPDODelete(Integer id) { - int numRowsAdded = 0; - - String sql = "UPDATE " + dbluTable + - " SET DELETE_FLAG = 'Y' WHERE TABLE_INSTANCE_ID = ? and USER_ID = ?"; - numRowsAdded = jt.update(sql, - id, - userId - ); - return numRowsAdded; - } - - /* - public int setRPDO(final SetRpdoType dblookupType) throws DataAccessException, I2B2Exception { - List queryResult = getDblookup(dblookupType); - if (null == queryResult || (0 == queryResult.size())) { - return insertRPDO(dblookupType); - } else { - return updateDblookup(dblookupType); - } - } - - public int insertRPDO(final SetRpdoType rpdoType) throws DataAccessException, I2B2Exception { - int numRowsAdded = 0; - String sql = "INSERT INTO " + dbluTable + - "(TABLE_INSTANCE_ID ,TABLE_INSTANCE_NAME ,USER_ID ,GROUP_ID ,SET_INDEX ,C_FACTTABLECOLUMN ,C_TABLENAME ,COLUMN_NAME ,C_FULLPATH ,C_COLUMNNAME ,C_COLUMNDATATYPE ,C_OPERATOR ,C_DIMCODE ,AGG_TYPE ,CONSTRAIN_BY_DATE_TO ,CONSTRAIN_BY_DATE_FROM ,CONSTRAIN_BY_VALUE_OPERATOR ,CONSTRAIN_BY_VALUE_CONSTRAINT ,CONSTRAIN_BY_VALUE_UNIT_OF_MEASURE ,CONSTRAIN_BY_VALUE_TYPE ,CREATE_DATE ,DELETE_DATE ,DELETE_FLAG ,GENERATED_SQL ,CONSTRAIN_BY_INDEXDATE_COLUMNNAME ,CONSTRAIN_BY_INDEXDATE_FROM_DAYS ,CONSTRAIN_BY_INDEXDATE_TO_DAYS ,USE_AS_COHORT) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; - numRowsAdded = jt.update(sql, - dblookupType.getDomainId(), - slashSandwich(dblookupType.getProjectPath()), - dblookupType.getOwnerId(), - dblookupType.getDbFullschema(), - dblookupType.getDbDatasource(), - dblookupType.getDbServertype(), - dblookupType.getDbNicename(), - dblookupType.getDbTooltip(), - dblookupType.getComment(), - Calendar.getInstance().getTime(), - Calendar.getInstance().getTime(), - dblookupType.getStatusCd() - ); - log.info("insertDblookup - Number of rows added: " + numRowsAdded); - return numRowsAdded; - } - - public int updateDblookup(final SetDblookupType dblookupType) throws DataAccessException, I2B2Exception { - int numRowsSet = 0; - String sql = "UPDATE " + dbluTable + - "SET c_db_fullschema=?, c_db_datasource=?, c_db_servertype=?, c_db_nicename=?, c_db_tooltip=?, c_comment=?, c_change_date=?, c_status_cd=? WHERE c_project_path=? AND " + - key; - numRowsSet = jt.update(sql, - dblookupType.getDbFullschema(), - dblookupType.getDbDatasource(), - dblookupType.getDbServertype(), - dblookupType.getDbNicename(), - dblookupType.getDbTooltip(), - dblookupType.getComment(), - Calendar.getInstance().getTime(), - dblookupType.getStatusCd(), - slashSandwich(dblookupType.getProjectPath()), - dblookupType.getDomainId(), - dblookupType.getOwnerId() - ); - log.info("updateDblookup - Number of rows updated: " + numRowsSet); - return numRowsSet; - } - - public int deleteDblookup(final DeleteDblookupType dblookupType) throws DataAccessException, I2B2Exception { - int numRowsDeleted = 0; - String sql = "DELETE FROM " + dbluTable + " WHERE c_project_path=? AND " + key; - try { - numRowsDeleted = jt.update(sql, slashSandwich(dblookupType.getProjectPath()), dblookupType.getDomainId(), dblookupType.getOwnerId()); - } catch (DataAccessException e) { - log.error(e.getMessage()); - e.printStackTrace(); - throw new I2B2DAOException("Database error"); - } - return numRowsDeleted; - } - */ -} - - - -class getMapperRPDOs implements RowMapper { - @Override - public RpdoType mapRow(ResultSet rs, int rowNum) throws SQLException { - RpdoType dblu = new RpdoType(); - //dblu.setDomainId(rs.getString("c_domain_id")); - //String sql = "select distinct table_instance_id, table_instance_name, max(set_index) as set_index, user_id, create_date " - - dblu.setId(rs.getInt("table_instance_id")); - dblu.setTitle(rs.getString("table_instance_name")); - dblu.setCreatorId(rs.getString("user_id")); - dblu.setColumnCount((rs.getInt("set_index")+1) + ""); - dblu.setCreateDate(rs.getTimestamp("create_date")); - if (rs.getString("user_id").equals("@")) - dblu.setShared(true); - else - dblu.setShared(false); - - return dblu; - } -} - -class getMapperRPDO implements RowMapper { - @Override - public RpdoTable mapRow(ResultSet rs, int rowNum) throws SQLException { - RpdoTable dblu = new RpdoTable(); - //dblu.setDomainId(rs.getString("c_domain_id")); - dblu.setId(rs.getInt("table_instance_id")); - dblu.setTitle(rs.getString("table_instance_name")); - dblu.setColumnName(rs.getString("column_name")); - dblu.setCreatorId(rs.getString("user_id")); - // dblu.setGroupId(rs.getString("group_id")); - dblu.setColumnCount(rs.getString("set_index")); - dblu.setConcept(rs.getString("json_data")); - if (dblu.getId() == -1 || (rs.getString("required") != null && rs.getString("required").equals("Y"))) - dblu.setRequired(true); - else - dblu.setRequired(false); - - // dblu.setJsonData(rs.getString("json_data")); - /* - dblu.setcFacttablecolumn(rs.getString("c_facttablecolumn")); - dblu.setcTablename(rs.getString("c_tablename")); - dblu.setColumnName(rs.getString("column_name")); - dblu.setcFullpath(rs.getString("c_fullpath")); - dblu.setcColumnname(rs.getString("c_columnname")); - dblu.setcColumndatatype(rs.getString("c_columndatatype")); - dblu.setcOperator(rs.getString("c_operator")); - dblu.setcDimcode(rs.getString("c_dimcode")); - dblu.setAggType(rs.getString("agg_type")); - dblu.setConstrainByDateTo(rs.getTimestamp("constrain_by_date_to")); - dblu.setConstrainByDateFrom(rs.getTimestamp("constrain_by_date_from")); - dblu.setConstrainByValueOperator(rs.getString("constrain_by_value_operator")); - dblu.setConstrainByValueConstraint(rs.getString("constrain_by_value_constraint")); - dblu.setConstrainByValueUnitOfMeasure(rs.getString("constrain_by_value_unit_of_measure")); - dblu.setConstrainByValueType(rs.getString("constrain_by_value_type")); - */ - if (rs.getString("user_id").equals("@")) - dblu.setShared(true); - else - dblu.setShared(false); - //dblu.setShared(true); - dblu.setCreateDate(rs.getTimestamp("create_date")); - dblu.setUpdateDate(rs.getTimestamp("update_date")); - // dblu.setDeleteFlag(rs.getString("delete_flag")); - // dblu.setGeneratedSql(rs.getString("generated_sql")); - // dblu.setConstrainByIndexdateColumnname(rs.getString("constrain_by_indexdate_columnname")); - // dblu.setConstrainByIndexdateFromDays(rs.getInt("constrain_by_indexdate_from_days")); - // dblu.setConstrainByIndexdateToDays(rs.getInt("constrain_by_indexdate_to_days")); - // dblu.setUseAsCohort(rs.getString("use_as_cohort")); - return dblu; - } -} - - +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Wayne Chan + */ +package edu.harvard.i2b2.crc.dao; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.ServiceLocator; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; +import edu.harvard.i2b2.crc.datavo.pdo.query.ConceptTableType; +import edu.harvard.i2b2.crc.datavo.pdo.query.DblookupType; +import edu.harvard.i2b2.crc.datavo.pdo.query.DeleteDblookupType; +import edu.harvard.i2b2.crc.datavo.pdo.query.RpdoType; +import edu.harvard.i2b2.crc.datavo.pdo.query.RpdosType; +import edu.harvard.i2b2.crc.datavo.pdo.query.SetDblookupType; +import edu.harvard.i2b2.crc.loader.ejb.DataMartLoaderAsyncBean; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; +import edu.harvard.i2b2.crc.dao.pdo.RpdoTable; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.List; +import javax.sql.DataSource; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.dao.DataAccessException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.RowMapper; +import org.springframework.jdbc.core.support.JdbcDaoSupport; + +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; + +public class RPDODao extends JdbcDaoSupport { + protected static Log logesapi = LogFactory.getLog(RPDODao.class); + + private static Log log = LogFactory.getLog(RPDODao.class); + private static DataSource ds = null; + private static JdbcTemplate jt; + private static String dbluTable; + private static String breakdownTable; + private static String resultTypeTable; + private static String getTable = " (LOWER(group_id)=LOWER(?) OR group_id='@') AND (LOWER(user_id)=LOWER(?) OR user_id='@') AND table_instance_id=? order by set_index "; + private static String keyOrder = " LOWER(group_id)=LOWER(?) AND (LOWER(user_id)=LOWER(?) OR user_id='@') "; //ORDER BY TABLE_INSTANCE_NAME "; + private String domainId = null; + private String userId = null; + private String projectPath = null; + + public RPDODao() { + initDblookupDao(); + } + + public RPDODao(MessageHeaderType reqMsgHdr) throws I2B2Exception, JAXBUtilException { + domainId = reqMsgHdr.getSecurity().getDomain(); + userId = reqMsgHdr.getSecurity().getUsername(); + projectPath = reqMsgHdr.getProjectId(); + initDblookupDao(); + } + + private void initDblookupDao() { + String dataSchema = ""; + + try { + + + DAOFactoryHelper daoFactoryHelper = new DAOFactoryHelper( + domainId, projectPath, userId); + + IDAOFactory daoFactory = daoFactoryHelper.getDAOFactory(); + ds = daoFactory.getSetFinderDAOFactory().getDataSource(); + + dataSchema = daoFactory.getSetFinderDAOFactory().getDataSourceLookup().getFullSchema(); + //ds = QueryProcessorUtil.getInstance().getDataSource("java:/CRCBootStrapDS"); + //ServiceLocator.getInstance() + //.getAppServerDataSource(dataSourceName); + } catch (I2B2Exception e2) { + log.error(e2.getMessage());; + } + jt = new JdbcTemplate(ds); + if (dataSchema.equals("")) + try { + + Connection conn = ds.getConnection(); + + dataSchema = conn.getSchema(); + conn.close(); + } catch (SQLException e1) { + log.error(e1.getMessage()); + } + if (dataSchema.endsWith(".")) { + dbluTable = dataSchema + "RPDO_TABLE_REQUEST "; + breakdownTable = dataSchema + "QT_BREAKDOWN_PATH "; + resultTypeTable = dataSchema + "QT_QUERY_RESULT_TYPE "; + + } else { + dbluTable = dataSchema + ".RPDO_TABLE_REQUEST "; + breakdownTable = dataSchema + ".QT_BREAKDOWN_PATH "; + resultTypeTable = dataSchema + ".QT_QUERY_RESULT_TYPE "; + } + log.info("RPDO_TABLE_REQUEST = " + dbluTable); + } + + public String slashSandwich(String s) { + StringBuffer sb = new StringBuffer(); + if (!s.startsWith("/")) { + sb.append('/'); + } + sb.append(s); + if (!s.endsWith("/")) { + sb.append('/'); + } + log.info(sb.toString()); + return sb.toString(); + } + + + public List findRPDOs() throws DataAccessException, I2B2DAOException{ + //String sql = "SELECT * FROM " + dbluTable + " WHERE" + keyOrder; + String sql = "select distinct table_instance_id, table_instance_name, max(set_index) as set_index, user_id, create_date " + + " FROM " + dbluTable + + " WHERE delete_flag = 'N' and " + keyOrder + + " group by table_instance_id, table_instance_name, user_id, create_date"; + List queryResult = null; + try { + queryResult = jt.query(sql, new getMapperRPDOs(), projectPath, userId); + } catch (DataAccessException e) { + log.error(e.getMessage()); + throw e; + } + log.info("result size = " + queryResult.size()); + return queryResult; + } + + public List getRPDO( int tableID) throws DataAccessException, I2B2Exception { + String sql = "SELECT table_instance_id, table_instance_name, column_name, user_id, set_index, json_data, required, create_date, update_date FROM " + dbluTable + " WHERE " + getTable; + List queryResult = null; + try { + queryResult = jt.query(sql, new getMapperRPDO(), projectPath, userId,tableID); + } catch (DataAccessException e) { + log.error(e.getMessage()); + e.printStackTrace(); + throw new I2B2DAOException("Database error"); + } + return queryResult; + } + + public List getDblookup(String column, String value) throws DataAccessException, I2B2Exception { + String sql = "SELECT * FROM " + dbluTable + " WHERE "; + String v = value, s = column.toLowerCase(); + List queryResult = null; + try { + if (s.equalsIgnoreCase("domain_id")) { + sql += keyOrder; + queryResult = jt.query(sql, new getMapperRPDO(), value, userId); + } else if (s.equalsIgnoreCase("user_id")) { + sql += keyOrder; + queryResult = jt.query(sql, new getMapperRPDO(), domainId, value); + } else { + sql += "c_" + column + "=? AND " + keyOrder; + if (s.equalsIgnoreCase("group_id")) { + v = slashSandwich(value); + } else { + } + queryResult = jt.query(sql, new getMapperRPDO(), v, domainId, userId); + } + } catch (DataAccessException e) { + log.error(e.getMessage()); + e.printStackTrace(); + throw new I2B2DAOException("Database error"); + } + return queryResult; + } + + public int setRPDO(final RpdoType rpdoType) throws DataAccessException, I2B2Exception { + int naxtTableInstanceID = 0; + int numRowsAdded = 0; + String sql = "SELECT MAX(TABLE_INSTANCE_ID) from " + dbluTable; + naxtTableInstanceID = jt.queryForObject(sql, Integer.class) + 1; + + java.sql.Timestamp now = new java.sql.Timestamp(System.currentTimeMillis()); + for(int i=0; i < rpdoType.getConcept().size(); i++) + { + // + // }RpdoType rpdoType: rpdosType.getRPDO()) { + //RpdoType rpdoType = rpdosType.getRpdo().get(i); + String json = rpdoType.getConcept().get(i).getData(); + + //Gson gson = new Gson(); + //json = gson.toJson(json); + + if (json != null && !json.trim().equals("")) { + String c_fullpath = " "; + String c_columnname = " "; + String c_tablename = " "; + String c_operator = " "; + String c_dimcode = " "; + String aggType = " "; + + try { + json = json.trim(); + JsonElement jelement = JsonParser.parseString(json); + //JsonElement jelement = new JsonParser().parse(json); + + JsonArray jarray = jelement.getAsJsonArray(); + JsonObject jobject = jarray.get(0).getAsJsonObject(); + + + + aggType = jobject.get("dataOption").getAsString(); + + JsonObject jObj= jobject.get("sdxData").getAsJsonObject(); + JsonElement jObj2 = jObj.get("origData"); + jobject =jObj2.getAsJsonObject(); + c_fullpath = jobject.get("key").getAsString(); + c_columnname = jobject.get("column_name").getAsString(); + c_tablename = jobject.get("table_name").getAsString(); + c_operator = jobject.get("operator").getAsString(); + c_dimcode = jobject.get("dim_code").getAsString(); + } catch (Exception e) {} + + if (rpdoType.isVisible() == null) + rpdoType.setVisible(false); + if (rpdoType.isShared() == null) + rpdoType.setShared(false); + + + sql = "INSERT INTO " + dbluTable + + "(TABLE_INSTANCE_ID, TABLE_INSTANCE_NAME, COLUMN_NAME, C_FACTTABLECOLUMN, C_FULLPATH, AGG_TYPE,C_COLUMNNAME,C_TABLENAME,C_OPERATOR,C_DIMCODE,USER_ID ,GROUP_ID ,SET_INDEX,JSON_DATA,CREATE_DATE,UPDATE_DATE,DELETE_FLAG,USE_AS_COHORT,REQUIRED) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,'N',?)"; + numRowsAdded = jt.update(sql, + naxtTableInstanceID, + rpdoType.getTitle(), + rpdoType.getConcept().get(i).getName(), + "concept_cd", + c_fullpath, + aggType, + c_columnname, + c_tablename, + c_operator, + c_dimcode, + (rpdoType.isShared() == true?"@":userId), + projectPath, + i, + json, + now, + now, + (rpdoType.isVisible() == true?"Y":"N"), + (rpdoType.getConcept().get(i).isRequired()== true?"Y":"N") + ); + + log.info("setRPDO - Number of rows added: " + numRowsAdded); + } + } + + // Always save regardless of isVisible is set + //if (rpdoType.isVisible()) + //{ + //Remove existing + try { + sql = "DELETE FROM " + breakdownTable + + " WHERE NAME = ? and USER_ID = ? "; + + jt.update(sql, + naxtTableInstanceID, + (rpdoType.isShared() == true?"@":userId)); + + //Remove existing + sql = "DELETE FROM " + resultTypeTable + + " WHERE NAME = ? and CLASSNAME = 'edu.harvard.i2b2.crc.dao.setfinder.QueryResultUserCreated' "; + + jt.update(sql, + naxtTableInstanceID); + } catch (Exception e) + { + e.printStackTrace(); + } + //Insert + sql = "INSERT INTO " + breakdownTable + + "(NAME, VALUE, CREATE_DATE, UPDATE_DATE, USER_ID) VALUES (?,?,?,?,?) "; + jt.update(sql, + naxtTableInstanceID, + "RPDO()", + now, + now, + (rpdoType.isShared() == true?"@":userId)); + + + sql = "SELECT MAX(RESULT_TYPE_ID) from " + resultTypeTable; + int resultTypeId = jt.queryForObject(sql, Integer.class) + 1; + + + //Insert + sql = "INSERT INTO " + resultTypeTable + + "(RESULT_TYPE_ID, NAME, DESCRIPTION, DISPLAY_TYPE_ID, VISUAL_ATTRIBUTE_TYPE_ID, USER_ROLE_CD, CLASSNAME) VALUES (?,?,?,?,?,?,?) "; + jt.update(sql, + resultTypeId, + naxtTableInstanceID, + rpdoType.getTitle(), + "CATNUM", + "LU", + null, + "edu.harvard.i2b2.crc.dao.setfinder.QueryResultUserCreated"); + + //} + return numRowsAdded; + } + + + //rpdoType.getcFacttablecolumn(),rpdoType.getcTablename(),rpdoType.getColumnName(),rpdoType.getcFullpath(), rpdoType.getcColumnname(),rpdoType.getcColumndatatype(), rpdoType.getcOperator(), rpdoType.getcDimcode(), rpdoType.getAggType(), rpdoType.getConstrainByDateTo(), rpdoType.getConstrainByDateFrom(), rpdoType.getConstrainByValueOperator(), + // rpdoType.getConstrainByValueConstraint(), rpdoType.getConstrainByValueUnitOfMeasure(), rpdoType.getConstrainByValueType(), + + //rpdoType.getCreateDate(), rpdoType.getUpdateDate() + //, rpdoType.getDeleteFlag() + //, rpdoType.getConstrainByIndexdateColumnname(), rpdoType.getConstrainByIndexdateFromDays(), rpdoType.getConstrainByIndexdateToDays(), rpdoType.getUseAsCohort() + + public int getRPDORename(Integer id, String title) { + int numRowsAdded = 0; + + String sql = "UPDATE " + dbluTable + + " SET TABLE_INSTANCE_NAME = ? WHERE TABLE_INSTANCE_ID = ? and USER_ID = ?"; + numRowsAdded = jt.update(sql, + title, + id, + userId + ); + return numRowsAdded; + } + + public int getRPDODelete(Integer id) { + int numRowsAdded = 0; + + String sql = "UPDATE " + dbluTable + + " SET DELETE_FLAG = 'Y' WHERE TABLE_INSTANCE_ID = ? and USER_ID = ?"; + numRowsAdded = jt.update(sql, + id, + userId + ); + return numRowsAdded; + } + + /* + public int setRPDO(final SetRpdoType dblookupType) throws DataAccessException, I2B2Exception { + List queryResult = getDblookup(dblookupType); + if (null == queryResult || (0 == queryResult.size())) { + return insertRPDO(dblookupType); + } else { + return updateDblookup(dblookupType); + } + } + + public int insertRPDO(final SetRpdoType rpdoType) throws DataAccessException, I2B2Exception { + int numRowsAdded = 0; + String sql = "INSERT INTO " + dbluTable + + "(TABLE_INSTANCE_ID ,TABLE_INSTANCE_NAME ,USER_ID ,GROUP_ID ,SET_INDEX ,C_FACTTABLECOLUMN ,C_TABLENAME ,COLUMN_NAME ,C_FULLPATH ,C_COLUMNNAME ,C_COLUMNDATATYPE ,C_OPERATOR ,C_DIMCODE ,AGG_TYPE ,CONSTRAIN_BY_DATE_TO ,CONSTRAIN_BY_DATE_FROM ,CONSTRAIN_BY_VALUE_OPERATOR ,CONSTRAIN_BY_VALUE_CONSTRAINT ,CONSTRAIN_BY_VALUE_UNIT_OF_MEASURE ,CONSTRAIN_BY_VALUE_TYPE ,CREATE_DATE ,DELETE_DATE ,DELETE_FLAG ,GENERATED_SQL ,CONSTRAIN_BY_INDEXDATE_COLUMNNAME ,CONSTRAIN_BY_INDEXDATE_FROM_DAYS ,CONSTRAIN_BY_INDEXDATE_TO_DAYS ,USE_AS_COHORT) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; + numRowsAdded = jt.update(sql, + dblookupType.getDomainId(), + slashSandwich(dblookupType.getProjectPath()), + dblookupType.getOwnerId(), + dblookupType.getDbFullschema(), + dblookupType.getDbDatasource(), + dblookupType.getDbServertype(), + dblookupType.getDbNicename(), + dblookupType.getDbTooltip(), + dblookupType.getComment(), + Calendar.getInstance().getTime(), + Calendar.getInstance().getTime(), + dblookupType.getStatusCd() + ); + log.info("insertDblookup - Number of rows added: " + numRowsAdded); + return numRowsAdded; + } + + public int updateDblookup(final SetDblookupType dblookupType) throws DataAccessException, I2B2Exception { + int numRowsSet = 0; + String sql = "UPDATE " + dbluTable + + "SET c_db_fullschema=?, c_db_datasource=?, c_db_servertype=?, c_db_nicename=?, c_db_tooltip=?, c_comment=?, c_change_date=?, c_status_cd=? WHERE c_project_path=? AND " + + key; + numRowsSet = jt.update(sql, + dblookupType.getDbFullschema(), + dblookupType.getDbDatasource(), + dblookupType.getDbServertype(), + dblookupType.getDbNicename(), + dblookupType.getDbTooltip(), + dblookupType.getComment(), + Calendar.getInstance().getTime(), + dblookupType.getStatusCd(), + slashSandwich(dblookupType.getProjectPath()), + dblookupType.getDomainId(), + dblookupType.getOwnerId() + ); + log.info("updateDblookup - Number of rows updated: " + numRowsSet); + return numRowsSet; + } + + public int deleteDblookup(final DeleteDblookupType dblookupType) throws DataAccessException, I2B2Exception { + int numRowsDeleted = 0; + String sql = "DELETE FROM " + dbluTable + " WHERE c_project_path=? AND " + key; + try { + numRowsDeleted = jt.update(sql, slashSandwich(dblookupType.getProjectPath()), dblookupType.getDomainId(), dblookupType.getOwnerId()); + } catch (DataAccessException e) { + log.error(e.getMessage()); + e.printStackTrace(); + throw new I2B2DAOException("Database error"); + } + return numRowsDeleted; + } + */ +} + + + +class getMapperRPDOs implements RowMapper { + @Override + public RpdoType mapRow(ResultSet rs, int rowNum) throws SQLException { + RpdoType dblu = new RpdoType(); + //dblu.setDomainId(rs.getString("c_domain_id")); + //String sql = "select distinct table_instance_id, table_instance_name, max(set_index) as set_index, user_id, create_date " + + dblu.setId(rs.getInt("table_instance_id")); + dblu.setTitle(rs.getString("table_instance_name")); + dblu.setCreatorId(rs.getString("user_id")); + dblu.setColumnCount((rs.getInt("set_index")+1) + ""); + dblu.setCreateDate(rs.getTimestamp("create_date")); + if (rs.getString("user_id").equals("@")) + dblu.setShared(true); + else + dblu.setShared(false); + + return dblu; + } +} + +class getMapperRPDO implements RowMapper { + @Override + public RpdoTable mapRow(ResultSet rs, int rowNum) throws SQLException { + RpdoTable dblu = new RpdoTable(); + //dblu.setDomainId(rs.getString("c_domain_id")); + dblu.setId(rs.getInt("table_instance_id")); + dblu.setTitle(rs.getString("table_instance_name")); + dblu.setColumnName(rs.getString("column_name")); + dblu.setCreatorId(rs.getString("user_id")); + // dblu.setGroupId(rs.getString("group_id")); + dblu.setColumnCount(rs.getString("set_index")); + dblu.setConcept(rs.getString("json_data")); + if (dblu.getId() == -1 || (rs.getString("required") != null && rs.getString("required").equals("Y"))) + dblu.setRequired(true); + else + dblu.setRequired(false); + + // dblu.setJsonData(rs.getString("json_data")); + /* + dblu.setcFacttablecolumn(rs.getString("c_facttablecolumn")); + dblu.setcTablename(rs.getString("c_tablename")); + dblu.setColumnName(rs.getString("column_name")); + dblu.setcFullpath(rs.getString("c_fullpath")); + dblu.setcColumnname(rs.getString("c_columnname")); + dblu.setcColumndatatype(rs.getString("c_columndatatype")); + dblu.setcOperator(rs.getString("c_operator")); + dblu.setcDimcode(rs.getString("c_dimcode")); + dblu.setAggType(rs.getString("agg_type")); + dblu.setConstrainByDateTo(rs.getTimestamp("constrain_by_date_to")); + dblu.setConstrainByDateFrom(rs.getTimestamp("constrain_by_date_from")); + dblu.setConstrainByValueOperator(rs.getString("constrain_by_value_operator")); + dblu.setConstrainByValueConstraint(rs.getString("constrain_by_value_constraint")); + dblu.setConstrainByValueUnitOfMeasure(rs.getString("constrain_by_value_unit_of_measure")); + dblu.setConstrainByValueType(rs.getString("constrain_by_value_type")); + */ + if (rs.getString("user_id").equals("@")) + dblu.setShared(true); + else + dblu.setShared(false); + //dblu.setShared(true); + dblu.setCreateDate(rs.getTimestamp("create_date")); + dblu.setUpdateDate(rs.getTimestamp("update_date")); + // dblu.setDeleteFlag(rs.getString("delete_flag")); + // dblu.setGeneratedSql(rs.getString("generated_sql")); + // dblu.setConstrainByIndexdateColumnname(rs.getString("constrain_by_indexdate_columnname")); + // dblu.setConstrainByIndexdateFromDays(rs.getInt("constrain_by_indexdate_from_days")); + // dblu.setConstrainByIndexdateToDays(rs.getInt("constrain_by_indexdate_to_days")); + // dblu.setUseAsCohort(rs.getString("use_as_cohort")); + return dblu; + } +} + + diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/SQLServerDAOFactory.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/SQLServerDAOFactory.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/SQLServerDAOFactory.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/SQLServerDAOFactory.java index d260ad91..2e28abbf --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/SQLServerDAOFactory.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/SQLServerDAOFactory.java @@ -1,349 +1,349 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao; - -import javax.sql.DataSource; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.ServiceLocator; -import edu.harvard.i2b2.crc.dao.pdo.IMetadataDao; -import edu.harvard.i2b2.crc.dao.pdo.IPageDao; -import edu.harvard.i2b2.crc.dao.pdo.IPdoQueryEidDao; -import edu.harvard.i2b2.crc.dao.pdo.IPdoQueryPidDao; -import edu.harvard.i2b2.crc.dao.pdo.MetadataDao; -import edu.harvard.i2b2.crc.dao.pdo.ObservationFactDao; -import edu.harvard.i2b2.crc.dao.pdo.PageTotalDao; -import edu.harvard.i2b2.crc.dao.pdo.PdoQueryConceptDao; -import edu.harvard.i2b2.crc.dao.pdo.PdoQueryEidDao; -import edu.harvard.i2b2.crc.dao.pdo.PdoQueryModifierDao; -import edu.harvard.i2b2.crc.dao.pdo.PdoQueryPatientDao; -import edu.harvard.i2b2.crc.dao.pdo.PdoQueryPidDao; -import edu.harvard.i2b2.crc.dao.pdo.PdoQueryProviderDao; -import edu.harvard.i2b2.crc.dao.pdo.PdoQueryVisitDao; -import edu.harvard.i2b2.crc.dao.pdo.TablePdoQueryConceptDao; -import edu.harvard.i2b2.crc.dao.pdo.TablePdoQueryModifierDao; -import edu.harvard.i2b2.crc.dao.pdo.TablePdoQueryPatientDao; -import edu.harvard.i2b2.crc.dao.pdo.TablePdoQueryProviderDao; -import edu.harvard.i2b2.crc.dao.pdo.TablePdoQueryVisitDao; -import edu.harvard.i2b2.crc.dao.role.IPriviledgeDao; -import edu.harvard.i2b2.crc.dao.role.PriviledgeSpringDao; -import edu.harvard.i2b2.crc.dao.setfinder.AnalysisPluginSpringDao; -import edu.harvard.i2b2.crc.dao.setfinder.EncounterSetCollectionSpringDao; -import edu.harvard.i2b2.crc.dao.setfinder.IAnalysisPluginDao; -import edu.harvard.i2b2.crc.dao.setfinder.IEncounterSetCollectionDao; -import edu.harvard.i2b2.crc.dao.setfinder.IPatientSetCollectionDao; -import edu.harvard.i2b2.crc.dao.setfinder.IQueryBreakdownTypeDao; -import edu.harvard.i2b2.crc.dao.setfinder.IQueryInstanceDao; -import edu.harvard.i2b2.crc.dao.setfinder.IQueryMasterDao; -import edu.harvard.i2b2.crc.dao.setfinder.IQueryPdoMasterDao; -import edu.harvard.i2b2.crc.dao.setfinder.IQueryRequestDao; -import edu.harvard.i2b2.crc.dao.setfinder.IQueryResultInstanceDao; -import edu.harvard.i2b2.crc.dao.setfinder.IQueryResultTypeDao; -import edu.harvard.i2b2.crc.dao.setfinder.IQueryStatusTypeDao; -import edu.harvard.i2b2.crc.dao.setfinder.IXmlResultDao; -import edu.harvard.i2b2.crc.dao.setfinder.PatientSetCollectionSpringDao; -import edu.harvard.i2b2.crc.dao.setfinder.QueryBreakdownTypeSpringDao; -import edu.harvard.i2b2.crc.dao.setfinder.QueryInstanceSpringDao; -import edu.harvard.i2b2.crc.dao.setfinder.QueryMasterSpringDao; -import edu.harvard.i2b2.crc.dao.setfinder.QueryPdoMasterSpringDao; -import edu.harvard.i2b2.crc.dao.setfinder.QueryRequestSpringDao; -import edu.harvard.i2b2.crc.dao.setfinder.QueryResultInstanceSpringDao; -import edu.harvard.i2b2.crc.dao.setfinder.QueryResultTypeSpringDao; -import edu.harvard.i2b2.crc.dao.setfinder.QueryStatusTypeSpringDao; -import edu.harvard.i2b2.crc.dao.setfinder.XmlResultSpringDao; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - -public class SQLServerDAOFactory implements IDAOFactory { - - private DataSourceLookup dataSourceLookup = null, - originalDataSourceLookup = null; - private DataSource dataSource = null; - private QueryProcessorUtil crcUtil = null; - /** log **/ - protected final static Log log = LogFactory - .getLog(SQLServerDAOFactory.class); - - public SQLServerDAOFactory(DataSourceLookup dataSourceLookup, - DataSourceLookup originalDataSourceLookup) throws I2B2DAOException { - - this.dataSourceLookup = dataSourceLookup; - this.originalDataSourceLookup = originalDataSourceLookup; - crcUtil = QueryProcessorUtil.getInstance(); - String dataSourceName = dataSourceLookup.getDataSource(); - log.info("Using datasource " + dataSourceName); - try { - // dataSource = (DataSource) - // crcUtil.getSpringDataSource(dataSourceName); - dataSource = ServiceLocator.getInstance().getAppServerDataSource( - dataSourceName); - } catch (I2B2Exception i2b2Ex) { - log.error(i2b2Ex); - throw new I2B2DAOException( - "Error getting application/spring datasource " - + dataSourceName + " : " + i2b2Ex.getMessage(), - i2b2Ex); - } - - } - - // - public class SQLPatientDataDAOFactory implements PatientDataDAOFactory { - private DataSourceLookup dataSourceLookup = null, - orignalDataSourceLookup = null; - private DataSource dataSource = null; - - public SQLPatientDataDAOFactory(DataSource dataSource, - DataSourceLookup dataSourceLookup, - DataSourceLookup orignalDataSourceLookup) { - this.dataSourceLookup = dataSourceLookup; - this.dataSource = dataSource; - this.orignalDataSourceLookup = dataSourceLookup; - - } - - @Override - public ObservationFactDao getObservationFactDAO() { - // TODO Auto-generated method stub - // - return new ObservationFactDao(dataSourceLookup, dataSource); - // return null; - - } - - @Override - public PdoQueryConceptDao getPdoQueryConceptDAO() { - // TODO Auto-generated method stub - return new PdoQueryConceptDao(dataSourceLookup, dataSource); - // return null; - } - - @Override - public PdoQueryModifierDao getPdoQueryModifierDAO() { - // TODO Auto-generated method stub - return new PdoQueryModifierDao(dataSourceLookup, dataSource); - // return null; - } - - @Override - public PdoQueryPatientDao getPdoQueryPatientDAO() { - // TODO Auto-generated method stub - return new PdoQueryPatientDao(dataSourceLookup, dataSource); - // return null; - } - - @Override - public PdoQueryProviderDao getPdoQueryProviderDAO() { - // TODO Auto-generated method stub - return new PdoQueryProviderDao(dataSourceLookup, dataSource); - } - - @Override - public PdoQueryVisitDao getPdoQueryVisitDAO() { - // TODO Auto-generated method stub - return new PdoQueryVisitDao(dataSourceLookup, dataSource); - } - - @Override - public TablePdoQueryConceptDao getTablePdoQueryConceptDAO() { - // TODO Auto-generated method stub - return new TablePdoQueryConceptDao(dataSourceLookup, dataSource); - } - - @Override - public TablePdoQueryModifierDao getTablePdoQueryModifierDAO() { - // TODO Auto-generated method stub - return new TablePdoQueryModifierDao(dataSourceLookup, dataSource); - } - - @Override - public TablePdoQueryPatientDao getTablePdoQueryPatientDAO() { - // TODO Auto-generated method stub - return new TablePdoQueryPatientDao(dataSourceLookup, dataSource); - } - - @Override - public TablePdoQueryProviderDao getTablePdoQueryProviderDAO() { - // TODO Auto-generated method stub - return new TablePdoQueryProviderDao(dataSourceLookup, dataSource); - } - - @Override - public TablePdoQueryVisitDao getTablePdoQueryVisitDAO() { - // TODO Auto-generated method stub - return new TablePdoQueryVisitDao(dataSourceLookup, dataSource); - } - - @Override - public DataSourceLookup getDataSourceLookup() { - return dataSourceLookup; - } - - @Override - public DataSourceLookup getOriginalDataSourceLookup() { - return originalDataSourceLookup; - } - - @Override - public DataSource getDataSource() { - return dataSource; - } - - @Override - public IPageDao getPageDAO() { - // TODO Auto-generated method stub - return new PageTotalDao(dataSourceLookup, dataSource); - } - - @Override - public IPdoQueryPidDao getPdoQueryPidDAO() { - return new PdoQueryPidDao(dataSourceLookup, dataSource); - } - - @Override - public IPdoQueryEidDao getPdoQueryEidDAO() { - return new PdoQueryEidDao(dataSourceLookup, dataSource); - } - - @Override - public IMetadataDao getMetadataDAO() { - return new MetadataDao(dataSourceLookup, dataSource); - } - - } - - public class SQLSetFinderDAOFactory implements SetFinderDAOFactory { - private DataSourceLookup dataSourceLookup = null, - orignalDataSourceLookup = null; - private DataSource dataSource = null; - - public SQLSetFinderDAOFactory(DataSource dataSource, - DataSourceLookup dataSourceLookup, - DataSourceLookup orignalDataSourceLookup) { - this.dataSourceLookup = dataSourceLookup; - this.dataSource = dataSource; - this.orignalDataSourceLookup = dataSourceLookup; - - } - - @Override - public IXmlResultDao getXmlResultDao() { - // TODO Auto-generated method stub - return new XmlResultSpringDao(dataSource, dataSourceLookup); - } - - @Override - public IPatientSetCollectionDao getPatientSetCollectionDAO() { - // TODO Auto-generated method stub - return new PatientSetCollectionSpringDao(dataSource, - dataSourceLookup); - } - - @Override - public IEncounterSetCollectionDao getEncounterSetCollectionDAO() { - // TODO Auto-generated method stub - return new EncounterSetCollectionSpringDao(dataSource, - dataSourceLookup); - } - - @Override - public IQueryResultInstanceDao getPatientSetResultDAO() { - // TODO Auto-generated method stub - return new QueryResultInstanceSpringDao(dataSource, - dataSourceLookup); - } - - @Override - public IQueryInstanceDao getQueryInstanceDAO() { - // TODO Auto-generated method stub - return new QueryInstanceSpringDao(dataSource, dataSourceLookup); - } - - @Override - public IQueryMasterDao getQueryMasterDAO() { - // TODO Auto-generated method stub - return new QueryMasterSpringDao(dataSource, dataSourceLookup); - } - - @Override - public IQueryPdoMasterDao getQueryPdoMasterDAO() { - // TODO Auto-generated method stub - return new QueryPdoMasterSpringDao(dataSource, dataSourceLookup); - } - - @Override - public IQueryRequestDao getQueryRequestDAO() { - // TODO Auto-generated method stub - return new QueryRequestSpringDao(dataSource, dataSourceLookup); - } - - @Override - public DataSourceLookup getDataSourceLookup() { - return dataSourceLookup; - } - - @Override - public DataSourceLookup getOriginalDataSourceLookup() { - return originalDataSourceLookup; - } - - @Override - public DataSource getDataSource() { - return dataSource; - } - - - @Override - public IQueryResultTypeDao getQueryResultTypeDao() { - - return new QueryResultTypeSpringDao(dataSource, dataSourceLookup); - } - - @Override - public IQueryStatusTypeDao getQueryStatusTypeDao() { - - return new QueryStatusTypeSpringDao(dataSource, dataSourceLookup); - } - - @Override - public IAnalysisPluginDao getAnalysisPluginDao() { - return new AnalysisPluginSpringDao(dataSource, dataSourceLookup); - } - - @Override - public IPriviledgeDao getPriviledgeDao() { - return new PriviledgeSpringDao(dataSource, dataSourceLookup); - } - - @Override - public IQueryBreakdownTypeDao getQueryBreakdownTypeDao() { - return new QueryBreakdownTypeSpringDao(dataSource, dataSourceLookup); - } - - } - - @Override - public PatientDataDAOFactory getPatientDataDAOFactory() { - // TODO Auto-generated method stub - return new SQLPatientDataDAOFactory(dataSource, dataSourceLookup, - originalDataSourceLookup); - } - - @Override - public SetFinderDAOFactory getSetFinderDAOFactory() { - // TODO Auto-generated method stub - return new SQLSetFinderDAOFactory(dataSource, dataSourceLookup, - originalDataSourceLookup); - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao; + +import javax.sql.DataSource; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.ServiceLocator; +import edu.harvard.i2b2.crc.dao.pdo.IMetadataDao; +import edu.harvard.i2b2.crc.dao.pdo.IPageDao; +import edu.harvard.i2b2.crc.dao.pdo.IPdoQueryEidDao; +import edu.harvard.i2b2.crc.dao.pdo.IPdoQueryPidDao; +import edu.harvard.i2b2.crc.dao.pdo.MetadataDao; +import edu.harvard.i2b2.crc.dao.pdo.ObservationFactDao; +import edu.harvard.i2b2.crc.dao.pdo.PageTotalDao; +import edu.harvard.i2b2.crc.dao.pdo.PdoQueryConceptDao; +import edu.harvard.i2b2.crc.dao.pdo.PdoQueryEidDao; +import edu.harvard.i2b2.crc.dao.pdo.PdoQueryModifierDao; +import edu.harvard.i2b2.crc.dao.pdo.PdoQueryPatientDao; +import edu.harvard.i2b2.crc.dao.pdo.PdoQueryPidDao; +import edu.harvard.i2b2.crc.dao.pdo.PdoQueryProviderDao; +import edu.harvard.i2b2.crc.dao.pdo.PdoQueryVisitDao; +import edu.harvard.i2b2.crc.dao.pdo.TablePdoQueryConceptDao; +import edu.harvard.i2b2.crc.dao.pdo.TablePdoQueryModifierDao; +import edu.harvard.i2b2.crc.dao.pdo.TablePdoQueryPatientDao; +import edu.harvard.i2b2.crc.dao.pdo.TablePdoQueryProviderDao; +import edu.harvard.i2b2.crc.dao.pdo.TablePdoQueryVisitDao; +import edu.harvard.i2b2.crc.dao.role.IPriviledgeDao; +import edu.harvard.i2b2.crc.dao.role.PriviledgeSpringDao; +import edu.harvard.i2b2.crc.dao.setfinder.AnalysisPluginSpringDao; +import edu.harvard.i2b2.crc.dao.setfinder.EncounterSetCollectionSpringDao; +import edu.harvard.i2b2.crc.dao.setfinder.IAnalysisPluginDao; +import edu.harvard.i2b2.crc.dao.setfinder.IEncounterSetCollectionDao; +import edu.harvard.i2b2.crc.dao.setfinder.IPatientSetCollectionDao; +import edu.harvard.i2b2.crc.dao.setfinder.IQueryBreakdownTypeDao; +import edu.harvard.i2b2.crc.dao.setfinder.IQueryInstanceDao; +import edu.harvard.i2b2.crc.dao.setfinder.IQueryMasterDao; +import edu.harvard.i2b2.crc.dao.setfinder.IQueryPdoMasterDao; +import edu.harvard.i2b2.crc.dao.setfinder.IQueryRequestDao; +import edu.harvard.i2b2.crc.dao.setfinder.IQueryResultInstanceDao; +import edu.harvard.i2b2.crc.dao.setfinder.IQueryResultTypeDao; +import edu.harvard.i2b2.crc.dao.setfinder.IQueryStatusTypeDao; +import edu.harvard.i2b2.crc.dao.setfinder.IXmlResultDao; +import edu.harvard.i2b2.crc.dao.setfinder.PatientSetCollectionSpringDao; +import edu.harvard.i2b2.crc.dao.setfinder.QueryBreakdownTypeSpringDao; +import edu.harvard.i2b2.crc.dao.setfinder.QueryInstanceSpringDao; +import edu.harvard.i2b2.crc.dao.setfinder.QueryMasterSpringDao; +import edu.harvard.i2b2.crc.dao.setfinder.QueryPdoMasterSpringDao; +import edu.harvard.i2b2.crc.dao.setfinder.QueryRequestSpringDao; +import edu.harvard.i2b2.crc.dao.setfinder.QueryResultInstanceSpringDao; +import edu.harvard.i2b2.crc.dao.setfinder.QueryResultTypeSpringDao; +import edu.harvard.i2b2.crc.dao.setfinder.QueryStatusTypeSpringDao; +import edu.harvard.i2b2.crc.dao.setfinder.XmlResultSpringDao; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + +public class SQLServerDAOFactory implements IDAOFactory { + + private DataSourceLookup dataSourceLookup = null, + originalDataSourceLookup = null; + private DataSource dataSource = null; + private QueryProcessorUtil crcUtil = null; + /** log **/ + protected final static Log log = LogFactory + .getLog(SQLServerDAOFactory.class); + + public SQLServerDAOFactory(DataSourceLookup dataSourceLookup, + DataSourceLookup originalDataSourceLookup) throws I2B2DAOException { + + this.dataSourceLookup = dataSourceLookup; + this.originalDataSourceLookup = originalDataSourceLookup; + crcUtil = QueryProcessorUtil.getInstance(); + String dataSourceName = dataSourceLookup.getDataSource(); + log.info("Using datasource " + dataSourceName); + try { + // dataSource = (DataSource) + // crcUtil.getSpringDataSource(dataSourceName); + dataSource = ServiceLocator.getInstance().getAppServerDataSource( + dataSourceName); + } catch (I2B2Exception i2b2Ex) { + log.error(i2b2Ex); + throw new I2B2DAOException( + "Error getting application/spring datasource " + + dataSourceName + " : " + i2b2Ex.getMessage(), + i2b2Ex); + } + + } + + // + public class SQLPatientDataDAOFactory implements PatientDataDAOFactory { + private DataSourceLookup dataSourceLookup = null, + orignalDataSourceLookup = null; + private DataSource dataSource = null; + + public SQLPatientDataDAOFactory(DataSource dataSource, + DataSourceLookup dataSourceLookup, + DataSourceLookup orignalDataSourceLookup) { + this.dataSourceLookup = dataSourceLookup; + this.dataSource = dataSource; + this.orignalDataSourceLookup = dataSourceLookup; + + } + + @Override + public ObservationFactDao getObservationFactDAO() { + // TODO Auto-generated method stub + // + return new ObservationFactDao(dataSourceLookup, dataSource); + // return null; + + } + + @Override + public PdoQueryConceptDao getPdoQueryConceptDAO() { + // TODO Auto-generated method stub + return new PdoQueryConceptDao(dataSourceLookup, dataSource); + // return null; + } + + @Override + public PdoQueryModifierDao getPdoQueryModifierDAO() { + // TODO Auto-generated method stub + return new PdoQueryModifierDao(dataSourceLookup, dataSource); + // return null; + } + + @Override + public PdoQueryPatientDao getPdoQueryPatientDAO() { + // TODO Auto-generated method stub + return new PdoQueryPatientDao(dataSourceLookup, dataSource); + // return null; + } + + @Override + public PdoQueryProviderDao getPdoQueryProviderDAO() { + // TODO Auto-generated method stub + return new PdoQueryProviderDao(dataSourceLookup, dataSource); + } + + @Override + public PdoQueryVisitDao getPdoQueryVisitDAO() { + // TODO Auto-generated method stub + return new PdoQueryVisitDao(dataSourceLookup, dataSource); + } + + @Override + public TablePdoQueryConceptDao getTablePdoQueryConceptDAO() { + // TODO Auto-generated method stub + return new TablePdoQueryConceptDao(dataSourceLookup, dataSource); + } + + @Override + public TablePdoQueryModifierDao getTablePdoQueryModifierDAO() { + // TODO Auto-generated method stub + return new TablePdoQueryModifierDao(dataSourceLookup, dataSource); + } + + @Override + public TablePdoQueryPatientDao getTablePdoQueryPatientDAO() { + // TODO Auto-generated method stub + return new TablePdoQueryPatientDao(dataSourceLookup, dataSource); + } + + @Override + public TablePdoQueryProviderDao getTablePdoQueryProviderDAO() { + // TODO Auto-generated method stub + return new TablePdoQueryProviderDao(dataSourceLookup, dataSource); + } + + @Override + public TablePdoQueryVisitDao getTablePdoQueryVisitDAO() { + // TODO Auto-generated method stub + return new TablePdoQueryVisitDao(dataSourceLookup, dataSource); + } + + @Override + public DataSourceLookup getDataSourceLookup() { + return dataSourceLookup; + } + + @Override + public DataSourceLookup getOriginalDataSourceLookup() { + return originalDataSourceLookup; + } + + @Override + public DataSource getDataSource() { + return dataSource; + } + + @Override + public IPageDao getPageDAO() { + // TODO Auto-generated method stub + return new PageTotalDao(dataSourceLookup, dataSource); + } + + @Override + public IPdoQueryPidDao getPdoQueryPidDAO() { + return new PdoQueryPidDao(dataSourceLookup, dataSource); + } + + @Override + public IPdoQueryEidDao getPdoQueryEidDAO() { + return new PdoQueryEidDao(dataSourceLookup, dataSource); + } + + @Override + public IMetadataDao getMetadataDAO() { + return new MetadataDao(dataSourceLookup, dataSource); + } + + } + + public class SQLSetFinderDAOFactory implements SetFinderDAOFactory { + private DataSourceLookup dataSourceLookup = null, + orignalDataSourceLookup = null; + private DataSource dataSource = null; + + public SQLSetFinderDAOFactory(DataSource dataSource, + DataSourceLookup dataSourceLookup, + DataSourceLookup orignalDataSourceLookup) { + this.dataSourceLookup = dataSourceLookup; + this.dataSource = dataSource; + this.orignalDataSourceLookup = dataSourceLookup; + + } + + @Override + public IXmlResultDao getXmlResultDao() { + // TODO Auto-generated method stub + return new XmlResultSpringDao(dataSource, dataSourceLookup); + } + + @Override + public IPatientSetCollectionDao getPatientSetCollectionDAO() { + // TODO Auto-generated method stub + return new PatientSetCollectionSpringDao(dataSource, + dataSourceLookup); + } + + @Override + public IEncounterSetCollectionDao getEncounterSetCollectionDAO() { + // TODO Auto-generated method stub + return new EncounterSetCollectionSpringDao(dataSource, + dataSourceLookup); + } + + @Override + public IQueryResultInstanceDao getPatientSetResultDAO() { + // TODO Auto-generated method stub + return new QueryResultInstanceSpringDao(dataSource, + dataSourceLookup); + } + + @Override + public IQueryInstanceDao getQueryInstanceDAO() { + // TODO Auto-generated method stub + return new QueryInstanceSpringDao(dataSource, dataSourceLookup); + } + + @Override + public IQueryMasterDao getQueryMasterDAO() { + // TODO Auto-generated method stub + return new QueryMasterSpringDao(dataSource, dataSourceLookup); + } + + @Override + public IQueryPdoMasterDao getQueryPdoMasterDAO() { + // TODO Auto-generated method stub + return new QueryPdoMasterSpringDao(dataSource, dataSourceLookup); + } + + @Override + public IQueryRequestDao getQueryRequestDAO() { + // TODO Auto-generated method stub + return new QueryRequestSpringDao(dataSource, dataSourceLookup); + } + + @Override + public DataSourceLookup getDataSourceLookup() { + return dataSourceLookup; + } + + @Override + public DataSourceLookup getOriginalDataSourceLookup() { + return originalDataSourceLookup; + } + + @Override + public DataSource getDataSource() { + return dataSource; + } + + + @Override + public IQueryResultTypeDao getQueryResultTypeDao() { + + return new QueryResultTypeSpringDao(dataSource, dataSourceLookup); + } + + @Override + public IQueryStatusTypeDao getQueryStatusTypeDao() { + + return new QueryStatusTypeSpringDao(dataSource, dataSourceLookup); + } + + @Override + public IAnalysisPluginDao getAnalysisPluginDao() { + return new AnalysisPluginSpringDao(dataSource, dataSourceLookup); + } + + @Override + public IPriviledgeDao getPriviledgeDao() { + return new PriviledgeSpringDao(dataSource, dataSourceLookup); + } + + @Override + public IQueryBreakdownTypeDao getQueryBreakdownTypeDao() { + return new QueryBreakdownTypeSpringDao(dataSource, dataSourceLookup); + } + + } + + @Override + public PatientDataDAOFactory getPatientDataDAOFactory() { + // TODO Auto-generated method stub + return new SQLPatientDataDAOFactory(dataSource, dataSourceLookup, + originalDataSourceLookup); + } + + @Override + public SetFinderDAOFactory getSetFinderDAOFactory() { + // TODO Auto-generated method stub + return new SQLSetFinderDAOFactory(dataSource, dataSourceLookup, + originalDataSourceLookup); + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/SQLServerDataSourceLookupDAO.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/SQLServerDataSourceLookupDAO.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/SQLServerDataSourceLookupDAO.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/SQLServerDataSourceLookupDAO.java index 8b2a6116..7812cde1 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/SQLServerDataSourceLookupDAO.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/SQLServerDataSourceLookupDAO.java @@ -1,45 +1,45 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao; - -import java.util.List; - -import javax.sql.DataSource; - -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; - -public class SQLServerDataSourceLookupDAO extends DataSourceLookupDAO { - - public SQLServerDataSourceLookupDAO(DataSource dataSource,String schemaName) { - - } - - @Override - public List getDbLookupByHiveOwner(String hiveId, - String ownerId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List getDbLookupByHive(String hiveId) { - // TODO Auto-generated method stub - return null; - } - - - @Override - public List getDbLookupByHiveProjectOwner(String hiveId, - String projectId, String ownerId) { - // TODO Auto-generated method stub - return null; - } - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao; + +import java.util.List; + +import javax.sql.DataSource; + +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; + +public class SQLServerDataSourceLookupDAO extends DataSourceLookupDAO { + + public SQLServerDataSourceLookupDAO(DataSource dataSource,String schemaName) { + + } + + @Override + public List getDbLookupByHiveOwner(String hiveId, + String ownerId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List getDbLookupByHive(String hiveId) { + // TODO Auto-generated method stub + return null; + } + + + @Override + public List getDbLookupByHiveProjectOwner(String hiveId, + String projectId, String ownerId) { + // TODO Auto-generated method stub + return null; + } + + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/SetFinderDAOFactory.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/SetFinderDAOFactory.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/SetFinderDAOFactory.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/SetFinderDAOFactory.java index 1912c9ae..4c91f35e --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/SetFinderDAOFactory.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/SetFinderDAOFactory.java @@ -1,60 +1,60 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao; - -import javax.sql.DataSource; - -import edu.harvard.i2b2.crc.dao.role.IPriviledgeDao; -import edu.harvard.i2b2.crc.dao.setfinder.IAnalysisPluginDao; -import edu.harvard.i2b2.crc.dao.setfinder.IEncounterSetCollectionDao; -import edu.harvard.i2b2.crc.dao.setfinder.IPatientSetCollectionDao; -import edu.harvard.i2b2.crc.dao.setfinder.IQueryBreakdownTypeDao; -import edu.harvard.i2b2.crc.dao.setfinder.IQueryInstanceDao; -import edu.harvard.i2b2.crc.dao.setfinder.IQueryMasterDao; -import edu.harvard.i2b2.crc.dao.setfinder.IQueryPdoMasterDao; -import edu.harvard.i2b2.crc.dao.setfinder.IQueryRequestDao; -import edu.harvard.i2b2.crc.dao.setfinder.IQueryResultInstanceDao; -import edu.harvard.i2b2.crc.dao.setfinder.IQueryResultTypeDao; -import edu.harvard.i2b2.crc.dao.setfinder.IQueryStatusTypeDao; -import edu.harvard.i2b2.crc.dao.setfinder.IXmlResultDao; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; - -public interface SetFinderDAOFactory { - public IQueryRequestDao getQueryRequestDAO(); - - public IQueryMasterDao getQueryMasterDAO(); - - public IQueryPdoMasterDao getQueryPdoMasterDAO(); - - public IQueryInstanceDao getQueryInstanceDAO(); - - public IQueryResultInstanceDao getPatientSetResultDAO(); - - public IPatientSetCollectionDao getPatientSetCollectionDAO(); - - public IEncounterSetCollectionDao getEncounterSetCollectionDAO(); - - public IXmlResultDao getXmlResultDao(); - - public IQueryStatusTypeDao getQueryStatusTypeDao(); - - public IQueryResultTypeDao getQueryResultTypeDao(); - - public IAnalysisPluginDao getAnalysisPluginDao(); - - public IPriviledgeDao getPriviledgeDao(); - - public IQueryBreakdownTypeDao getQueryBreakdownTypeDao(); - - public DataSourceLookup getDataSourceLookup(); - - public DataSourceLookup getOriginalDataSourceLookup(); - - public DataSource getDataSource(); -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao; + +import javax.sql.DataSource; + +import edu.harvard.i2b2.crc.dao.role.IPriviledgeDao; +import edu.harvard.i2b2.crc.dao.setfinder.IAnalysisPluginDao; +import edu.harvard.i2b2.crc.dao.setfinder.IEncounterSetCollectionDao; +import edu.harvard.i2b2.crc.dao.setfinder.IPatientSetCollectionDao; +import edu.harvard.i2b2.crc.dao.setfinder.IQueryBreakdownTypeDao; +import edu.harvard.i2b2.crc.dao.setfinder.IQueryInstanceDao; +import edu.harvard.i2b2.crc.dao.setfinder.IQueryMasterDao; +import edu.harvard.i2b2.crc.dao.setfinder.IQueryPdoMasterDao; +import edu.harvard.i2b2.crc.dao.setfinder.IQueryRequestDao; +import edu.harvard.i2b2.crc.dao.setfinder.IQueryResultInstanceDao; +import edu.harvard.i2b2.crc.dao.setfinder.IQueryResultTypeDao; +import edu.harvard.i2b2.crc.dao.setfinder.IQueryStatusTypeDao; +import edu.harvard.i2b2.crc.dao.setfinder.IXmlResultDao; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; + +public interface SetFinderDAOFactory { + public IQueryRequestDao getQueryRequestDAO(); + + public IQueryMasterDao getQueryMasterDAO(); + + public IQueryPdoMasterDao getQueryPdoMasterDAO(); + + public IQueryInstanceDao getQueryInstanceDAO(); + + public IQueryResultInstanceDao getPatientSetResultDAO(); + + public IPatientSetCollectionDao getPatientSetCollectionDAO(); + + public IEncounterSetCollectionDao getEncounterSetCollectionDAO(); + + public IXmlResultDao getXmlResultDao(); + + public IQueryStatusTypeDao getQueryStatusTypeDao(); + + public IQueryResultTypeDao getQueryResultTypeDao(); + + public IAnalysisPluginDao getAnalysisPluginDao(); + + public IPriviledgeDao getPriviledgeDao(); + + public IQueryBreakdownTypeDao getQueryBreakdownTypeDao(); + + public DataSourceLookup getDataSourceLookup(); + + public DataSourceLookup getOriginalDataSourceLookup(); + + public DataSource getDataSource(); +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/mapper/HiveCellParam.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/mapper/HiveCellParam.java similarity index 88% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/mapper/HiveCellParam.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/mapper/HiveCellParam.java index a8e94623..9573e739 100644 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/mapper/HiveCellParam.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/mapper/HiveCellParam.java @@ -1,21 +1,20 @@ -package edu.harvard.i2b2.crc.dao.mapper; - -import java.sql.ResultSet; -import java.sql.SQLException; -import org.springframework.jdbc.core.RowMapper; - -import edu.harvard.i2b2.crc.datavo.pm.ParamType; - -public class HiveCellParam { //implements RowMapper{ - - public ParamType mapRow(ResultSet rs, int rowNum) throws SQLException { - - ParamType param = new ParamType(); - param.setId(rs.getInt("id")); - param.setName(rs.getString("param_name_cd")); - param.setValue(rs.getString("value")); - param.setDatatype(rs.getString("datatype_cd")); - return param; - - } -} +package edu.harvard.i2b2.crc.dao.mapper; + +import java.sql.ResultSet; +import java.sql.SQLException; + +import edu.harvard.i2b2.crc.datavo.pm.ParamType; + +public class HiveCellParam { //implements RowMapper{ + + public ParamType mapRow(ResultSet rs, int rowNum) throws SQLException { + + ParamType param = new ParamType(); + param.setId(rs.getInt("id")); + param.setName(rs.getString("param_name_cd")); + param.setValue(rs.getString("value")); + param.setDatatype(rs.getString("datatype_cd")); + return param; + + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/DimensionTable.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/DimensionTable.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/DimensionTable.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/DimensionTable.java index 242ab000..0166dfc4 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/DimensionTable.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/DimensionTable.java @@ -1,16 +1,16 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.pdo; - -public class DimensionTable { - - public static final String PATIENT_DIMENSION = "PATIENT_DIMENSION"; - public static final String VISIT_DIMENSION = "VISIT_DIMENSION"; - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.pdo; + +public class DimensionTable { + + public static final String PATIENT_DIMENSION = "PATIENT_DIMENSION"; + public static final String VISIT_DIMENSION = "VISIT_DIMENSION"; + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/I2B2PdoFactory.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/I2B2PdoFactory.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/I2B2PdoFactory.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/I2B2PdoFactory.java index 461c629e..0eeecefc --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/I2B2PdoFactory.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/I2B2PdoFactory.java @@ -1,739 +1,739 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao.pdo; - -import java.io.IOException; -import java.sql.Clob; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.Date; -import java.util.Iterator; -import java.util.List; - -import edu.harvard.i2b2.common.util.db.JDBCUtil; -import edu.harvard.i2b2.common.util.jaxb.DTOFactory; -import edu.harvard.i2b2.crc.datavo.pdo.BlobType; -import edu.harvard.i2b2.crc.datavo.pdo.ConceptType; -import edu.harvard.i2b2.crc.datavo.pdo.EventType; -import edu.harvard.i2b2.crc.datavo.pdo.ModifierType; -import edu.harvard.i2b2.crc.datavo.pdo.ObservationType; -import edu.harvard.i2b2.crc.datavo.pdo.ObserverType; -import edu.harvard.i2b2.crc.datavo.pdo.ParamType; -import edu.harvard.i2b2.crc.datavo.pdo.PatientIdType; -import edu.harvard.i2b2.crc.datavo.pdo.PatientType; - -/** - * Class to build individual sections of plain pdo xml like - * patient,concept,observationfact from the given {@link java.sql.ResultSet} - * - * $Id: I2B2PdoFactory.java,v 1.19 2009/11/14 16:53:58 rk903 Exp $ - * - * @author rkuttan - */ -public class I2B2PdoFactory { - - private DTOFactory dtoFactory = new DTOFactory(); - - /** - * Inner class to build observation fact in Plain PDO format - */ - public class ObservationFactBuilder { - /** detail flag **/ - boolean obsFactDetailFlag = false; - /** blob flag **/ - boolean obsFactBlobFlag = false; - /** status flag **/ - boolean obsFactStatusFlag = false; - - String dbType = null; - - /** - * Parameter constructor - * - * @param detailFlag - * @param blobFlag - * @param statusFlag - */ - public ObservationFactBuilder(boolean detailFlag, boolean blobFlag, - boolean statusFlag, String dbType) { - this.obsFactDetailFlag = detailFlag; - this.obsFactBlobFlag = blobFlag; - this.obsFactStatusFlag = statusFlag; - this.dbType = dbType; - } - - /** - * Read one record from resultset and build observation fact - * - * @param rowSet - * resultset - * @return Observation fact set - * @throws SQLException - * @throws IOException - */ - public ObservationType buildObservationSet(ResultSet rowSet) - throws SQLException, IOException { - ObservationType observationFactType = new ObservationType(); - PatientIdType patientIdType = new PatientIdType(); - patientIdType.setValue(rowSet.getString("obs_patient_num")); - - observationFactType.setPatientId(patientIdType); - ObservationType.EventId eventId = new ObservationType.EventId(); - eventId.setValue(rowSet.getString("obs_encounter_num")); - observationFactType.setEventId(eventId); - ObservationType.ConceptCd conceptCd = new ObservationType.ConceptCd(); - conceptCd.setValue(rowSet.getString("obs_concept_cd")); - observationFactType.setConceptCd(conceptCd); - - ObservationType.ModifierCd modifierCd = new ObservationType.ModifierCd(); - modifierCd.setValue(rowSet.getString("obs_modifier_cd")); - observationFactType.setModifierCd(modifierCd); - - ObservationType.InstanceNum instanceNum = new ObservationType.InstanceNum(); - instanceNum.setValue(rowSet.getString("obs_instance_num")); - observationFactType.setInstanceNum(instanceNum); - - Date startDate = rowSet.getTimestamp("obs_start_date"); - - if (startDate != null) { - observationFactType.setStartDate(dtoFactory - .getXMLGregorianCalendar(startDate.getTime())); - } - - ObservationType.ObserverCd observerCd = new ObservationType.ObserverCd(); - observerCd - .setValue(((rowSet.getString("obs_provider_id") != null) ? rowSet - .getString("obs_provider_id") - : "")); - observationFactType.setObserverCd(observerCd); - - if (obsFactDetailFlag) { - Date endDate = rowSet.getTimestamp("obs_end_date"); - - if (endDate != null) { - observationFactType.setEndDate(dtoFactory - .getXMLGregorianCalendar(endDate.getTime())); - } - - observationFactType.setValuetypeCd(rowSet - .getString("obs_valtype_cd")); - observationFactType.setTvalChar((rowSet - .getString("obs_tval_char") != null) ? rowSet - .getString("obs_tval_char") : ""); - - ObservationType.NvalNum valNum = new ObservationType.NvalNum(); - valNum.setValue(rowSet.getBigDecimal("obs_nval_num")); - observationFactType.setNvalNum(valNum); - - ObservationType.ValueflagCd valueFlagCd = new ObservationType.ValueflagCd(); - valueFlagCd.setValue(rowSet.getString("obs_valueflag_cd")); - observationFactType.setValueflagCd(valueFlagCd); - - observationFactType.setQuantityNum(rowSet - .getBigDecimal("obs_quantity_num")); - - observationFactType - .setUnitsCd(rowSet.getString("obs_units_cd")); - - ObservationType.LocationCd locationCd = new ObservationType.LocationCd(); - locationCd.setValue(rowSet.getString("obs_location_cd")); - observationFactType.setLocationCd(locationCd); - observationFactType.setConfidenceNum(rowSet - .getBigDecimal("obs_confidence_num")); - // Double confidenceNum = - // rowSet.getDouble("obs_confidence_num"); - } - - if (obsFactBlobFlag) { - if (dbType.equalsIgnoreCase("POSTGRESQL")) - { - String clob = rowSet.getString("obs_observation_blob"); - if (clob !=null) - { - BlobType blobType = new BlobType(); - blobType.getContent().add(clob); - observationFactType.setObservationBlob(blobType); - - } - - } else { - Clob observationClob = rowSet.getClob("obs_observation_blob"); - - if (observationClob != null) { - BlobType blobType = new BlobType(); - blobType.getContent().add( - JDBCUtil.getClobStringWithLinebreak(observationClob)); - observationFactType.setObservationBlob(blobType); - } - } - } - - if (obsFactStatusFlag) { - if (rowSet.getTimestamp("obs_update_date") != null) { - observationFactType.setUpdateDate(dtoFactory - .getXMLGregorianCalendar(rowSet.getTimestamp( - "obs_update_date").getTime())); - } - - if (rowSet.getTimestamp("obs_download_date") != null) { - observationFactType.setDownloadDate(dtoFactory - .getXMLGregorianCalendar(rowSet.getTimestamp( - "obs_download_date").getTime())); - } - - if (rowSet.getTimestamp("obs_import_date") != null) { - observationFactType.setImportDate(dtoFactory - .getXMLGregorianCalendar(rowSet.getTimestamp( - "obs_import_date").getTime())); - } - - observationFactType.setSourcesystemCd(rowSet - .getString("obs_sourcesystem_cd")); - observationFactType.setUploadId(rowSet - .getString("obs_upload_id")); - } - - return observationFactType; - } - } - - /** - * Inner class to build Patient dimension in Plain PDO format - */ - public class PatientBuilder { - boolean patientDetailFlag = false; - boolean patientBlobFlag = false; - boolean patientStatusFlag = false; - String dbType = null; - - /** - * Patameter constructor - * - * @param detailFlag - * @param blobFlag - * @param statusFlag - */ - public PatientBuilder(boolean detailFlag, boolean blobFlag, - boolean statusFlag, String dbType) { - this.patientDetailFlag = detailFlag; - this.patientBlobFlag = blobFlag; - this.patientStatusFlag = statusFlag; - this.dbType = dbType; - } - - /** - * Function reads single row from the resultset and builds patient - * dimension - * - * @param rowSet - * @return Patient dimension type - * @throws SQLException - * @throws IOException - */ - public PatientType buildPatientSet(ResultSet rowSet, List metaDataParamList) - throws SQLException, IOException { - PatientType patientDimensionType = new PatientType(); - PatientIdType patientIdType = new PatientIdType(); - patientIdType.setValue(rowSet.getString("patient_patient_num")); - patientDimensionType.setPatientId(patientIdType); - - List paramTypeList = patientDimensionType.getParam(); - ParamType paramType = null; - if (patientDetailFlag) { - - - - for (Iterator metaParamIterator = metaDataParamList.iterator(); metaParamIterator.hasNext();) { - ParamType metaParamType = metaParamIterator.next(); - ParamTypeValueBuilder paramValBuilder = new ParamTypeValueBuilder(); - paramTypeList.add(paramValBuilder.buildParamType(metaParamType,"patient_",null,rowSet)); - } - } - - - - - if (patientBlobFlag) { - if (dbType.equalsIgnoreCase("POSTGRESQL")) - { - String clob = rowSet.getString("patient_patient_blob"); - if (clob !=null) - { - BlobType blobType = new BlobType(); - blobType.getContent().add(clob); - patientDimensionType.setPatientBlob(blobType); - - } - - } else { - Clob patientClob = rowSet.getClob("patient_patient_blob"); - - if (patientClob != null) { - BlobType patientBlobType = new BlobType(); - patientBlobType.getContent().add( - JDBCUtil.getClobStringWithLinebreak(patientClob)); - patientDimensionType.setPatientBlob(patientBlobType); - } - } - } - - if (patientStatusFlag) { - if (rowSet.getTimestamp("patient_update_date") != null) { - patientDimensionType.setUpdateDate(dtoFactory - .getXMLGregorianCalendar(rowSet.getTimestamp( - "patient_update_date").getTime())); - } - - if (rowSet.getTimestamp("patient_download_date") != null) { - patientDimensionType.setDownloadDate(dtoFactory - .getXMLGregorianCalendar(rowSet.getTimestamp( - "patient_download_date").getTime())); - } - - if (rowSet.getTimestamp("patient_import_date") != null) { - patientDimensionType.setImportDate(dtoFactory - .getXMLGregorianCalendar(rowSet.getTimestamp( - "patient_import_date").getTime())); - } - - patientDimensionType.setSourcesystemCd(rowSet - .getString("patient_sourcesystem_cd")); - patientDimensionType.setUploadId(rowSet - .getString("patient_upload_id")); - } - - return patientDimensionType; - } - } - - /** - * Inner class to build provider dimension in plain pdo format - */ - public class ProviderBuilder { - boolean providerDetailFlag = false; - boolean providerBlobFlag = false; - boolean providerStatusFlag = false; - String dbType = null; - - /** - * Parameter constructor - * - * @param detailFlag - * @param blobFlag - * @param statusFlag - */ - public ProviderBuilder(boolean detailFlag, boolean blobFlag, - boolean statusFlag, String dbType) { - this.providerDetailFlag = detailFlag; - this.providerBlobFlag = blobFlag; - this.providerStatusFlag = statusFlag; - this.dbType = dbType; - } - - /** - * Reads single row from resultset and builds provider dimension - * - * @param rowSet - * @return - * @throws SQLException - * @throws IOException - */ - public ObserverType buildObserverSet(ResultSet rowSet) - throws SQLException, IOException { - ObserverType providerDimensionType = new ObserverType(); - providerDimensionType.setObserverCd(rowSet - .getString("provider_provider_id")); - providerDimensionType.setObserverPath(rowSet - .getString("provider_provider_path")); - - if (providerDetailFlag) { - providerDimensionType.setNameChar(rowSet - .getString("provider_name_char")); - } - - if (providerBlobFlag) { - if (dbType.equalsIgnoreCase("POSTGRESQL")) - { - String clob = rowSet.getString("provider_provider_blob"); - if (clob !=null) - { - BlobType blobType = new BlobType(); - blobType.getContent().add(clob); - providerDimensionType.setObserverBlob(blobType); - - } - - } else { - Clob providerClob = rowSet.getClob("provider_provider_blob"); - - if (providerClob != null) { - BlobType providerBlobType = new BlobType(); - providerBlobType.getContent().add( - JDBCUtil.getClobStringWithLinebreak(providerClob)); - providerDimensionType.setObserverBlob(providerBlobType); - } - } - } - - if (providerStatusFlag) { - if (rowSet.getTimestamp("provider_update_date") != null) { - providerDimensionType.setUpdateDate(dtoFactory - .getXMLGregorianCalendar(rowSet.getTimestamp( - "provider_update_date").getTime())); - } - - if (rowSet.getTimestamp("provider_download_date") != null) { - providerDimensionType.setDownloadDate(dtoFactory - .getXMLGregorianCalendar(rowSet.getTimestamp( - "provider_download_date").getTime())); - } - - if (rowSet.getTimestamp("provider_import_date") != null) { - providerDimensionType.setImportDate(dtoFactory - .getXMLGregorianCalendar(rowSet.getTimestamp( - "provider_import_date").getTime())); - } - - providerDimensionType.setSourcesystemCd(rowSet - .getString("provider_sourcesystem_cd")); - providerDimensionType.setUploadId(rowSet - .getString("provider_upload_id")); - } - - return providerDimensionType; - } - } - - /** - * Inner class to build concept dimension in plain pdo format - */ - public class ConceptBuilder { - boolean conceptDetailFlag = false; - boolean conceptBlobFlag = false; - boolean conceptStatusFlag = false; - String dbType = null; - /** - * Parameter Constuctor - * - * @param detailFlag - * @param blobFlag - * @param statusFlag - */ - public ConceptBuilder(boolean detailFlag, boolean blobFlag, - boolean statusFlag, String dbType) { - this.conceptDetailFlag = detailFlag; - this.conceptBlobFlag = blobFlag; - this.conceptStatusFlag = statusFlag; - this.dbType = dbType; - } - - /** - * Reads one row from result set and builds concept dimension - * - * @param rowSet - * @return - * @throws SQLException - * @throws IOException - */ - public ConceptType buildConceptSet(ResultSet rowSet) - throws SQLException, IOException { - ConceptType conceptDimensionType = new ConceptType(); - - conceptDimensionType.setConceptCd(rowSet - .getString("concept_concept_cd")); - - if (conceptDetailFlag) { - conceptDimensionType.setConceptCd(rowSet - .getString("concept_concept_cd")); - conceptDimensionType.setConceptPath(rowSet - .getString("concept_concept_path")); - conceptDimensionType.setNameChar(rowSet - .getString("concept_name_char")); - } - - if (conceptBlobFlag) { - if (dbType.equalsIgnoreCase("POSTGRESQL")) - { - String clob = rowSet.getString("concept_concept_blob"); - if (clob !=null) - { - BlobType blobType = new BlobType(); - blobType.getContent().add(clob); - conceptDimensionType.setConceptBlob(blobType); - - } - - } else { - - Clob conceptClob = rowSet.getClob("concept_concept_blob"); - - if (conceptClob != null) { - BlobType conceptBlobType = new BlobType(); - conceptBlobType.getContent().add( - JDBCUtil.getClobStringWithLinebreak(conceptClob)); - conceptDimensionType.setConceptBlob(conceptBlobType); - } - } - } - - if (conceptStatusFlag) { - if (rowSet.getTimestamp("concept_update_date") != null) { - conceptDimensionType.setUpdateDate(dtoFactory - .getXMLGregorianCalendar(rowSet.getTimestamp( - "concept_update_date").getTime())); - } - - if (rowSet.getTimestamp("concept_download_date") != null) { - conceptDimensionType.setDownloadDate(dtoFactory - .getXMLGregorianCalendar(rowSet.getTimestamp( - "concept_download_date").getTime())); - } - - if (rowSet.getTimestamp("concept_import_date") != null) { - conceptDimensionType.setImportDate(dtoFactory - .getXMLGregorianCalendar(rowSet.getTimestamp( - "concept_import_date").getTime())); - } - - conceptDimensionType.setSourcesystemCd(rowSet - .getString("concept_sourcesystem_cd")); - conceptDimensionType.setUploadId(rowSet - .getString("concept_upload_id")); - } - - return conceptDimensionType; - } - } - - - /** - * Inner class to build concept dimension in plain pdo format - */ - public class ModifierBuilder { - boolean modifierDetailFlag = false; - boolean modifierBlobFlag = false; - boolean modifierStatusFlag = false; - String dbType = null; - - /** - * Parameter Constuctor - * - * @param detailFlag - * @param blobFlag - * @param statusFlag - */ - public ModifierBuilder(boolean detailFlag, boolean blobFlag, - boolean statusFlag, String dbType) { - this.modifierDetailFlag = detailFlag; - this.modifierBlobFlag = blobFlag; - this.modifierStatusFlag = statusFlag; - this.dbType = dbType; - } - - /** - * Reads one row from result set and builds concept dimension - * - * @param rowSet - * @return - * @throws SQLException - * @throws IOException - */ - public ModifierType buildModifierSet(ResultSet rowSet) - throws SQLException, IOException { - ModifierType modifierDimensionType = new ModifierType(); - - modifierDimensionType.setModifierCd(rowSet - .getString("modifier_modifier_cd")); - - if (modifierDetailFlag) { - modifierDimensionType.setModifierCd(rowSet - .getString("modifier_modifier_cd")); - modifierDimensionType.setModifierPath(rowSet - .getString("modifier_modifier_path")); - modifierDimensionType.setNameChar(rowSet - .getString("modifier_name_char")); - } - - if (modifierBlobFlag) { - if (dbType.equalsIgnoreCase("POSTGRESQL")) - { - String clob = rowSet.getString("modifier_modifier_blob"); - if (clob !=null) - { - BlobType blobType = new BlobType(); - blobType.getContent().add(clob); - modifierDimensionType.setModifierBlob(blobType); - - } - - } else { - - Clob modifierClob = rowSet.getClob("modifier_modifier_blob"); - - if (modifierClob != null) { - BlobType modifierBlobType = new BlobType(); - modifierBlobType.getContent().add( - JDBCUtil.getClobStringWithLinebreak(modifierClob)); - modifierDimensionType.setModifierBlob(modifierBlobType); - } - } - } - - if (modifierStatusFlag) { - if (rowSet.getTimestamp("modifier_update_date") != null) { - modifierDimensionType.setUpdateDate(dtoFactory - .getXMLGregorianCalendar(rowSet.getTimestamp( - "modifier_update_date").getTime())); - } - - if (rowSet.getTimestamp("modifier_download_date") != null) { - modifierDimensionType.setDownloadDate(dtoFactory - .getXMLGregorianCalendar(rowSet.getTimestamp( - "modifier_download_date").getTime())); - } - - if (rowSet.getTimestamp("modifier_import_date") != null) { - modifierDimensionType.setImportDate(dtoFactory - .getXMLGregorianCalendar(rowSet.getTimestamp( - "modifier_import_date").getTime())); - } - - modifierDimensionType.setSourcesystemCd(rowSet - .getString("modifier_sourcesystem_cd")); - modifierDimensionType.setUploadId(rowSet - .getString("modifier_upload_id")); - } - - return modifierDimensionType; - } - } - - /** - * Inner class to build visit dimension in plain pdo format - */ - public class EventBuilder { - boolean eventDetailFlag = false; - boolean eventBlobFlag = false; - boolean eventStatusFlag = false; - String dbType = null; - - public EventBuilder(boolean detailFlag, boolean blobFlag, - boolean statusFlag, String dbType) { - this.eventDetailFlag = detailFlag; - this.eventBlobFlag = blobFlag; - this.eventStatusFlag = statusFlag; - this.dbType = dbType; - } - - /** - * Reads one row from result set and builds visit/event dimension - * - * @param rowSet - * @return - * @throws SQLException - * @throws IOException - */ - public EventType buildEventSet(ResultSet rowSet,List metaDataParamList) throws SQLException, - IOException { - EventType visitDimensionType = new EventType(); - - PatientIdType patientIdType = new PatientIdType(); - patientIdType.setValue(rowSet.getString("visit_patient_num")); - visitDimensionType.setPatientId(patientIdType); - EventType.EventId eventId = new EventType.EventId(); - eventId.setValue(rowSet.getString("visit_encounter_num")); - visitDimensionType.setEventId(eventId); - - if (eventDetailFlag) { - - - Date startDate = rowSet.getTimestamp("visit_start_date"); - - if (startDate != null) { - visitDimensionType.setStartDate(dtoFactory - .getXMLGregorianCalendar(startDate.getTime())); - } - - Date endDate = rowSet.getTimestamp("visit_end_date"); - - if (endDate != null) { - visitDimensionType.setEndDate(dtoFactory - .getXMLGregorianCalendar(endDate.getTime())); - } - for (Iterator metaParamIterator = metaDataParamList.iterator(); metaParamIterator.hasNext();) { - ParamType metaParamType = metaParamIterator.next(); - ParamTypeValueBuilder paramValBuilder = new ParamTypeValueBuilder(); - visitDimensionType.getParam().add(paramValBuilder.buildParamType(metaParamType,"visit_",null,rowSet)); - } - - } - - if (eventBlobFlag) { - if (dbType.equalsIgnoreCase("POSTGRESQL")) - { - String clob = rowSet.getString("visit_visit_blob"); - if (clob !=null) - { - BlobType blobType = new BlobType(); - blobType.getContent().add(clob); - visitDimensionType.setEventBlob(blobType); - - } - - } else { - - Clob visitClob = rowSet.getClob("visit_visit_blob"); - - if (visitClob != null) { - BlobType visitBlobType = new BlobType(); - visitBlobType.getContent().add( - JDBCUtil.getClobStringWithLinebreak(visitClob)); - visitDimensionType.setEventBlob(visitBlobType); - } - } - } - - - - - if (eventStatusFlag) { - if (rowSet.getTimestamp("visit_update_date") != null) { - visitDimensionType.setUpdateDate(dtoFactory - .getXMLGregorianCalendar(rowSet.getTimestamp( - "visit_update_date").getTime())); - } - - if (rowSet.getTimestamp("visit_download_date") != null) { - visitDimensionType.setDownloadDate(dtoFactory - .getXMLGregorianCalendar(rowSet.getTimestamp( - "visit_download_date").getTime())); - } - - if (rowSet.getTimestamp("visit_import_date") != null) { - visitDimensionType.setImportDate(dtoFactory - .getXMLGregorianCalendar(rowSet.getTimestamp( - "visit_import_date").getTime())); - } - - visitDimensionType.setSourcesystemCd(rowSet - .getString("visit_sourcesystem_cd")); - visitDimensionType.setUploadId(rowSet - .getString("visit_upload_id")); - } - - return visitDimensionType; - } - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao.pdo; + +import java.io.IOException; +import java.sql.Clob; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Date; +import java.util.Iterator; +import java.util.List; + +import edu.harvard.i2b2.common.util.db.JDBCUtil; +import edu.harvard.i2b2.common.util.jaxb.DTOFactory; +import edu.harvard.i2b2.crc.datavo.pdo.BlobType; +import edu.harvard.i2b2.crc.datavo.pdo.ConceptType; +import edu.harvard.i2b2.crc.datavo.pdo.EventType; +import edu.harvard.i2b2.crc.datavo.pdo.ModifierType; +import edu.harvard.i2b2.crc.datavo.pdo.ObservationType; +import edu.harvard.i2b2.crc.datavo.pdo.ObserverType; +import edu.harvard.i2b2.crc.datavo.pdo.ParamType; +import edu.harvard.i2b2.crc.datavo.pdo.PatientIdType; +import edu.harvard.i2b2.crc.datavo.pdo.PatientType; + +/** + * Class to build individual sections of plain pdo xml like + * patient,concept,observationfact from the given {@link java.sql.ResultSet} + * + * $Id: I2B2PdoFactory.java,v 1.19 2009/11/14 16:53:58 rk903 Exp $ + * + * @author rkuttan + */ +public class I2B2PdoFactory { + + private DTOFactory dtoFactory = new DTOFactory(); + + /** + * Inner class to build observation fact in Plain PDO format + */ + public class ObservationFactBuilder { + /** detail flag **/ + boolean obsFactDetailFlag = false; + /** blob flag **/ + boolean obsFactBlobFlag = false; + /** status flag **/ + boolean obsFactStatusFlag = false; + + String dbType = null; + + /** + * Parameter constructor + * + * @param detailFlag + * @param blobFlag + * @param statusFlag + */ + public ObservationFactBuilder(boolean detailFlag, boolean blobFlag, + boolean statusFlag, String dbType) { + this.obsFactDetailFlag = detailFlag; + this.obsFactBlobFlag = blobFlag; + this.obsFactStatusFlag = statusFlag; + this.dbType = dbType; + } + + /** + * Read one record from resultset and build observation fact + * + * @param rowSet + * resultset + * @return Observation fact set + * @throws SQLException + * @throws IOException + */ + public ObservationType buildObservationSet(ResultSet rowSet) + throws SQLException, IOException { + ObservationType observationFactType = new ObservationType(); + PatientIdType patientIdType = new PatientIdType(); + patientIdType.setValue(rowSet.getString("obs_patient_num")); + + observationFactType.setPatientId(patientIdType); + ObservationType.EventId eventId = new ObservationType.EventId(); + eventId.setValue(rowSet.getString("obs_encounter_num")); + observationFactType.setEventId(eventId); + ObservationType.ConceptCd conceptCd = new ObservationType.ConceptCd(); + conceptCd.setValue(rowSet.getString("obs_concept_cd")); + observationFactType.setConceptCd(conceptCd); + + ObservationType.ModifierCd modifierCd = new ObservationType.ModifierCd(); + modifierCd.setValue(rowSet.getString("obs_modifier_cd")); + observationFactType.setModifierCd(modifierCd); + + ObservationType.InstanceNum instanceNum = new ObservationType.InstanceNum(); + instanceNum.setValue(rowSet.getString("obs_instance_num")); + observationFactType.setInstanceNum(instanceNum); + + Date startDate = rowSet.getTimestamp("obs_start_date"); + + if (startDate != null) { + observationFactType.setStartDate(dtoFactory + .getXMLGregorianCalendar(startDate.getTime())); + } + + ObservationType.ObserverCd observerCd = new ObservationType.ObserverCd(); + observerCd + .setValue(((rowSet.getString("obs_provider_id") != null) ? rowSet + .getString("obs_provider_id") + : "")); + observationFactType.setObserverCd(observerCd); + + if (obsFactDetailFlag) { + Date endDate = rowSet.getTimestamp("obs_end_date"); + + if (endDate != null) { + observationFactType.setEndDate(dtoFactory + .getXMLGregorianCalendar(endDate.getTime())); + } + + observationFactType.setValuetypeCd(rowSet + .getString("obs_valtype_cd")); + observationFactType.setTvalChar((rowSet + .getString("obs_tval_char") != null) ? rowSet + .getString("obs_tval_char") : ""); + + ObservationType.NvalNum valNum = new ObservationType.NvalNum(); + valNum.setValue(rowSet.getBigDecimal("obs_nval_num")); + observationFactType.setNvalNum(valNum); + + ObservationType.ValueflagCd valueFlagCd = new ObservationType.ValueflagCd(); + valueFlagCd.setValue(rowSet.getString("obs_valueflag_cd")); + observationFactType.setValueflagCd(valueFlagCd); + + observationFactType.setQuantityNum(rowSet + .getBigDecimal("obs_quantity_num")); + + observationFactType + .setUnitsCd(rowSet.getString("obs_units_cd")); + + ObservationType.LocationCd locationCd = new ObservationType.LocationCd(); + locationCd.setValue(rowSet.getString("obs_location_cd")); + observationFactType.setLocationCd(locationCd); + observationFactType.setConfidenceNum(rowSet + .getBigDecimal("obs_confidence_num")); + // Double confidenceNum = + // rowSet.getDouble("obs_confidence_num"); + } + + if (obsFactBlobFlag) { + if (dbType.equalsIgnoreCase("POSTGRESQL")) + { + String clob = rowSet.getString("obs_observation_blob"); + if (clob !=null) + { + BlobType blobType = new BlobType(); + blobType.getContent().add(clob); + observationFactType.setObservationBlob(blobType); + + } + + } else { + Clob observationClob = rowSet.getClob("obs_observation_blob"); + + if (observationClob != null) { + BlobType blobType = new BlobType(); + blobType.getContent().add( + JDBCUtil.getClobStringWithLinebreak(observationClob)); + observationFactType.setObservationBlob(blobType); + } + } + } + + if (obsFactStatusFlag) { + if (rowSet.getTimestamp("obs_update_date") != null) { + observationFactType.setUpdateDate(dtoFactory + .getXMLGregorianCalendar(rowSet.getTimestamp( + "obs_update_date").getTime())); + } + + if (rowSet.getTimestamp("obs_download_date") != null) { + observationFactType.setDownloadDate(dtoFactory + .getXMLGregorianCalendar(rowSet.getTimestamp( + "obs_download_date").getTime())); + } + + if (rowSet.getTimestamp("obs_import_date") != null) { + observationFactType.setImportDate(dtoFactory + .getXMLGregorianCalendar(rowSet.getTimestamp( + "obs_import_date").getTime())); + } + + observationFactType.setSourcesystemCd(rowSet + .getString("obs_sourcesystem_cd")); + observationFactType.setUploadId(rowSet + .getString("obs_upload_id")); + } + + return observationFactType; + } + } + + /** + * Inner class to build Patient dimension in Plain PDO format + */ + public class PatientBuilder { + boolean patientDetailFlag = false; + boolean patientBlobFlag = false; + boolean patientStatusFlag = false; + String dbType = null; + + /** + * Patameter constructor + * + * @param detailFlag + * @param blobFlag + * @param statusFlag + */ + public PatientBuilder(boolean detailFlag, boolean blobFlag, + boolean statusFlag, String dbType) { + this.patientDetailFlag = detailFlag; + this.patientBlobFlag = blobFlag; + this.patientStatusFlag = statusFlag; + this.dbType = dbType; + } + + /** + * Function reads single row from the resultset and builds patient + * dimension + * + * @param rowSet + * @return Patient dimension type + * @throws SQLException + * @throws IOException + */ + public PatientType buildPatientSet(ResultSet rowSet, List metaDataParamList) + throws SQLException, IOException { + PatientType patientDimensionType = new PatientType(); + PatientIdType patientIdType = new PatientIdType(); + patientIdType.setValue(rowSet.getString("patient_patient_num")); + patientDimensionType.setPatientId(patientIdType); + + List paramTypeList = patientDimensionType.getParam(); + ParamType paramType = null; + if (patientDetailFlag) { + + + + for (Iterator metaParamIterator = metaDataParamList.iterator(); metaParamIterator.hasNext();) { + ParamType metaParamType = metaParamIterator.next(); + ParamTypeValueBuilder paramValBuilder = new ParamTypeValueBuilder(); + paramTypeList.add(paramValBuilder.buildParamType(metaParamType,"patient_",null,rowSet)); + } + } + + + + + if (patientBlobFlag) { + if (dbType.equalsIgnoreCase("POSTGRESQL")) + { + String clob = rowSet.getString("patient_patient_blob"); + if (clob !=null) + { + BlobType blobType = new BlobType(); + blobType.getContent().add(clob); + patientDimensionType.setPatientBlob(blobType); + + } + + } else { + Clob patientClob = rowSet.getClob("patient_patient_blob"); + + if (patientClob != null) { + BlobType patientBlobType = new BlobType(); + patientBlobType.getContent().add( + JDBCUtil.getClobStringWithLinebreak(patientClob)); + patientDimensionType.setPatientBlob(patientBlobType); + } + } + } + + if (patientStatusFlag) { + if (rowSet.getTimestamp("patient_update_date") != null) { + patientDimensionType.setUpdateDate(dtoFactory + .getXMLGregorianCalendar(rowSet.getTimestamp( + "patient_update_date").getTime())); + } + + if (rowSet.getTimestamp("patient_download_date") != null) { + patientDimensionType.setDownloadDate(dtoFactory + .getXMLGregorianCalendar(rowSet.getTimestamp( + "patient_download_date").getTime())); + } + + if (rowSet.getTimestamp("patient_import_date") != null) { + patientDimensionType.setImportDate(dtoFactory + .getXMLGregorianCalendar(rowSet.getTimestamp( + "patient_import_date").getTime())); + } + + patientDimensionType.setSourcesystemCd(rowSet + .getString("patient_sourcesystem_cd")); + patientDimensionType.setUploadId(rowSet + .getString("patient_upload_id")); + } + + return patientDimensionType; + } + } + + /** + * Inner class to build provider dimension in plain pdo format + */ + public class ProviderBuilder { + boolean providerDetailFlag = false; + boolean providerBlobFlag = false; + boolean providerStatusFlag = false; + String dbType = null; + + /** + * Parameter constructor + * + * @param detailFlag + * @param blobFlag + * @param statusFlag + */ + public ProviderBuilder(boolean detailFlag, boolean blobFlag, + boolean statusFlag, String dbType) { + this.providerDetailFlag = detailFlag; + this.providerBlobFlag = blobFlag; + this.providerStatusFlag = statusFlag; + this.dbType = dbType; + } + + /** + * Reads single row from resultset and builds provider dimension + * + * @param rowSet + * @return + * @throws SQLException + * @throws IOException + */ + public ObserverType buildObserverSet(ResultSet rowSet) + throws SQLException, IOException { + ObserverType providerDimensionType = new ObserverType(); + providerDimensionType.setObserverCd(rowSet + .getString("provider_provider_id")); + providerDimensionType.setObserverPath(rowSet + .getString("provider_provider_path")); + + if (providerDetailFlag) { + providerDimensionType.setNameChar(rowSet + .getString("provider_name_char")); + } + + if (providerBlobFlag) { + if (dbType.equalsIgnoreCase("POSTGRESQL")) + { + String clob = rowSet.getString("provider_provider_blob"); + if (clob !=null) + { + BlobType blobType = new BlobType(); + blobType.getContent().add(clob); + providerDimensionType.setObserverBlob(blobType); + + } + + } else { + Clob providerClob = rowSet.getClob("provider_provider_blob"); + + if (providerClob != null) { + BlobType providerBlobType = new BlobType(); + providerBlobType.getContent().add( + JDBCUtil.getClobStringWithLinebreak(providerClob)); + providerDimensionType.setObserverBlob(providerBlobType); + } + } + } + + if (providerStatusFlag) { + if (rowSet.getTimestamp("provider_update_date") != null) { + providerDimensionType.setUpdateDate(dtoFactory + .getXMLGregorianCalendar(rowSet.getTimestamp( + "provider_update_date").getTime())); + } + + if (rowSet.getTimestamp("provider_download_date") != null) { + providerDimensionType.setDownloadDate(dtoFactory + .getXMLGregorianCalendar(rowSet.getTimestamp( + "provider_download_date").getTime())); + } + + if (rowSet.getTimestamp("provider_import_date") != null) { + providerDimensionType.setImportDate(dtoFactory + .getXMLGregorianCalendar(rowSet.getTimestamp( + "provider_import_date").getTime())); + } + + providerDimensionType.setSourcesystemCd(rowSet + .getString("provider_sourcesystem_cd")); + providerDimensionType.setUploadId(rowSet + .getString("provider_upload_id")); + } + + return providerDimensionType; + } + } + + /** + * Inner class to build concept dimension in plain pdo format + */ + public class ConceptBuilder { + boolean conceptDetailFlag = false; + boolean conceptBlobFlag = false; + boolean conceptStatusFlag = false; + String dbType = null; + /** + * Parameter Constuctor + * + * @param detailFlag + * @param blobFlag + * @param statusFlag + */ + public ConceptBuilder(boolean detailFlag, boolean blobFlag, + boolean statusFlag, String dbType) { + this.conceptDetailFlag = detailFlag; + this.conceptBlobFlag = blobFlag; + this.conceptStatusFlag = statusFlag; + this.dbType = dbType; + } + + /** + * Reads one row from result set and builds concept dimension + * + * @param rowSet + * @return + * @throws SQLException + * @throws IOException + */ + public ConceptType buildConceptSet(ResultSet rowSet) + throws SQLException, IOException { + ConceptType conceptDimensionType = new ConceptType(); + + conceptDimensionType.setConceptCd(rowSet + .getString("concept_concept_cd")); + + if (conceptDetailFlag) { + conceptDimensionType.setConceptCd(rowSet + .getString("concept_concept_cd")); + conceptDimensionType.setConceptPath(rowSet + .getString("concept_concept_path")); + conceptDimensionType.setNameChar(rowSet + .getString("concept_name_char")); + } + + if (conceptBlobFlag) { + if (dbType.equalsIgnoreCase("POSTGRESQL")) + { + String clob = rowSet.getString("concept_concept_blob"); + if (clob !=null) + { + BlobType blobType = new BlobType(); + blobType.getContent().add(clob); + conceptDimensionType.setConceptBlob(blobType); + + } + + } else { + + Clob conceptClob = rowSet.getClob("concept_concept_blob"); + + if (conceptClob != null) { + BlobType conceptBlobType = new BlobType(); + conceptBlobType.getContent().add( + JDBCUtil.getClobStringWithLinebreak(conceptClob)); + conceptDimensionType.setConceptBlob(conceptBlobType); + } + } + } + + if (conceptStatusFlag) { + if (rowSet.getTimestamp("concept_update_date") != null) { + conceptDimensionType.setUpdateDate(dtoFactory + .getXMLGregorianCalendar(rowSet.getTimestamp( + "concept_update_date").getTime())); + } + + if (rowSet.getTimestamp("concept_download_date") != null) { + conceptDimensionType.setDownloadDate(dtoFactory + .getXMLGregorianCalendar(rowSet.getTimestamp( + "concept_download_date").getTime())); + } + + if (rowSet.getTimestamp("concept_import_date") != null) { + conceptDimensionType.setImportDate(dtoFactory + .getXMLGregorianCalendar(rowSet.getTimestamp( + "concept_import_date").getTime())); + } + + conceptDimensionType.setSourcesystemCd(rowSet + .getString("concept_sourcesystem_cd")); + conceptDimensionType.setUploadId(rowSet + .getString("concept_upload_id")); + } + + return conceptDimensionType; + } + } + + + /** + * Inner class to build concept dimension in plain pdo format + */ + public class ModifierBuilder { + boolean modifierDetailFlag = false; + boolean modifierBlobFlag = false; + boolean modifierStatusFlag = false; + String dbType = null; + + /** + * Parameter Constuctor + * + * @param detailFlag + * @param blobFlag + * @param statusFlag + */ + public ModifierBuilder(boolean detailFlag, boolean blobFlag, + boolean statusFlag, String dbType) { + this.modifierDetailFlag = detailFlag; + this.modifierBlobFlag = blobFlag; + this.modifierStatusFlag = statusFlag; + this.dbType = dbType; + } + + /** + * Reads one row from result set and builds concept dimension + * + * @param rowSet + * @return + * @throws SQLException + * @throws IOException + */ + public ModifierType buildModifierSet(ResultSet rowSet) + throws SQLException, IOException { + ModifierType modifierDimensionType = new ModifierType(); + + modifierDimensionType.setModifierCd(rowSet + .getString("modifier_modifier_cd")); + + if (modifierDetailFlag) { + modifierDimensionType.setModifierCd(rowSet + .getString("modifier_modifier_cd")); + modifierDimensionType.setModifierPath(rowSet + .getString("modifier_modifier_path")); + modifierDimensionType.setNameChar(rowSet + .getString("modifier_name_char")); + } + + if (modifierBlobFlag) { + if (dbType.equalsIgnoreCase("POSTGRESQL")) + { + String clob = rowSet.getString("modifier_modifier_blob"); + if (clob !=null) + { + BlobType blobType = new BlobType(); + blobType.getContent().add(clob); + modifierDimensionType.setModifierBlob(blobType); + + } + + } else { + + Clob modifierClob = rowSet.getClob("modifier_modifier_blob"); + + if (modifierClob != null) { + BlobType modifierBlobType = new BlobType(); + modifierBlobType.getContent().add( + JDBCUtil.getClobStringWithLinebreak(modifierClob)); + modifierDimensionType.setModifierBlob(modifierBlobType); + } + } + } + + if (modifierStatusFlag) { + if (rowSet.getTimestamp("modifier_update_date") != null) { + modifierDimensionType.setUpdateDate(dtoFactory + .getXMLGregorianCalendar(rowSet.getTimestamp( + "modifier_update_date").getTime())); + } + + if (rowSet.getTimestamp("modifier_download_date") != null) { + modifierDimensionType.setDownloadDate(dtoFactory + .getXMLGregorianCalendar(rowSet.getTimestamp( + "modifier_download_date").getTime())); + } + + if (rowSet.getTimestamp("modifier_import_date") != null) { + modifierDimensionType.setImportDate(dtoFactory + .getXMLGregorianCalendar(rowSet.getTimestamp( + "modifier_import_date").getTime())); + } + + modifierDimensionType.setSourcesystemCd(rowSet + .getString("modifier_sourcesystem_cd")); + modifierDimensionType.setUploadId(rowSet + .getString("modifier_upload_id")); + } + + return modifierDimensionType; + } + } + + /** + * Inner class to build visit dimension in plain pdo format + */ + public class EventBuilder { + boolean eventDetailFlag = false; + boolean eventBlobFlag = false; + boolean eventStatusFlag = false; + String dbType = null; + + public EventBuilder(boolean detailFlag, boolean blobFlag, + boolean statusFlag, String dbType) { + this.eventDetailFlag = detailFlag; + this.eventBlobFlag = blobFlag; + this.eventStatusFlag = statusFlag; + this.dbType = dbType; + } + + /** + * Reads one row from result set and builds visit/event dimension + * + * @param rowSet + * @return + * @throws SQLException + * @throws IOException + */ + public EventType buildEventSet(ResultSet rowSet,List metaDataParamList) throws SQLException, + IOException { + EventType visitDimensionType = new EventType(); + + PatientIdType patientIdType = new PatientIdType(); + patientIdType.setValue(rowSet.getString("visit_patient_num")); + visitDimensionType.setPatientId(patientIdType); + EventType.EventId eventId = new EventType.EventId(); + eventId.setValue(rowSet.getString("visit_encounter_num")); + visitDimensionType.setEventId(eventId); + + if (eventDetailFlag) { + + + Date startDate = rowSet.getTimestamp("visit_start_date"); + + if (startDate != null) { + visitDimensionType.setStartDate(dtoFactory + .getXMLGregorianCalendar(startDate.getTime())); + } + + Date endDate = rowSet.getTimestamp("visit_end_date"); + + if (endDate != null) { + visitDimensionType.setEndDate(dtoFactory + .getXMLGregorianCalendar(endDate.getTime())); + } + for (Iterator metaParamIterator = metaDataParamList.iterator(); metaParamIterator.hasNext();) { + ParamType metaParamType = metaParamIterator.next(); + ParamTypeValueBuilder paramValBuilder = new ParamTypeValueBuilder(); + visitDimensionType.getParam().add(paramValBuilder.buildParamType(metaParamType,"visit_",null,rowSet)); + } + + } + + if (eventBlobFlag) { + if (dbType.equalsIgnoreCase("POSTGRESQL")) + { + String clob = rowSet.getString("visit_visit_blob"); + if (clob !=null) + { + BlobType blobType = new BlobType(); + blobType.getContent().add(clob); + visitDimensionType.setEventBlob(blobType); + + } + + } else { + + Clob visitClob = rowSet.getClob("visit_visit_blob"); + + if (visitClob != null) { + BlobType visitBlobType = new BlobType(); + visitBlobType.getContent().add( + JDBCUtil.getClobStringWithLinebreak(visitClob)); + visitDimensionType.setEventBlob(visitBlobType); + } + } + } + + + + + if (eventStatusFlag) { + if (rowSet.getTimestamp("visit_update_date") != null) { + visitDimensionType.setUpdateDate(dtoFactory + .getXMLGregorianCalendar(rowSet.getTimestamp( + "visit_update_date").getTime())); + } + + if (rowSet.getTimestamp("visit_download_date") != null) { + visitDimensionType.setDownloadDate(dtoFactory + .getXMLGregorianCalendar(rowSet.getTimestamp( + "visit_download_date").getTime())); + } + + if (rowSet.getTimestamp("visit_import_date") != null) { + visitDimensionType.setImportDate(dtoFactory + .getXMLGregorianCalendar(rowSet.getTimestamp( + "visit_import_date").getTime())); + } + + visitDimensionType.setSourcesystemCd(rowSet + .getString("visit_sourcesystem_cd")); + visitDimensionType.setUploadId(rowSet + .getString("visit_upload_id")); + } + + return visitDimensionType; + } + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/IMetadataDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/IMetadataDao.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/IMetadataDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/IMetadataDao.java index 81bb7743..d618d8e7 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/IMetadataDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/IMetadataDao.java @@ -1,19 +1,19 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.pdo; - -import java.util.Map; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; - -public interface IMetadataDao { - - public Map getMetadataForOptionalField(String tableName) throws I2B2DAOException; - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.pdo; + +import java.util.Map; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; + +public interface IMetadataDao { + + public Map getMetadataForOptionalField(String tableName) throws I2B2DAOException; + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/IObservationFactDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/IObservationFactDao.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/IObservationFactDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/IObservationFactDao.java index ad6c5ed2..65f44660 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/IObservationFactDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/IObservationFactDao.java @@ -1,32 +1,32 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.pdo; - -import edu.harvard.i2b2.crc.datavo.pdo.PatientDataType; -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.crc.datavo.pdo.query.FactPrimaryKeyType; -import edu.harvard.i2b2.crc.datavo.pdo.query.OutputOptionType; - -public interface IObservationFactDao { - - /** - * Function returns Observation fact from the primary key. - *

    Required fields : patient_num, concept_cd, encounter_num - *

    Optional field : provider_id,start_date - * @param factPrimaryKey - * @param factOutputOption - * @return PatientDataType - * @throws I2B2Exception - */ - public PatientDataType getObservationFactByPrimaryKey( - FactPrimaryKeyType factPrimaryKey, OutputOptionType factOutputOption) - throws I2B2DAOException; - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.pdo; + +import edu.harvard.i2b2.crc.datavo.pdo.PatientDataType; +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.crc.datavo.pdo.query.FactPrimaryKeyType; +import edu.harvard.i2b2.crc.datavo.pdo.query.OutputOptionType; + +public interface IObservationFactDao { + + /** + * Function returns Observation fact from the primary key. + *

    Required fields : patient_num, concept_cd, encounter_num + *

    Optional field : provider_id,start_date + * @param factPrimaryKey + * @param factOutputOption + * @return PatientDataType + * @throws I2B2Exception + */ + public PatientDataType getObservationFactByPrimaryKey( + FactPrimaryKeyType factPrimaryKey, OutputOptionType factOutputOption) + throws I2B2DAOException; + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/IPageDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/IPageDao.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/IPageDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/IPageDao.java index c4b9c070..e34f7b39 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/IPageDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/IPageDao.java @@ -1,34 +1,34 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.pdo; - -import java.util.HashMap; -import java.util.List; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.crc.dao.pdo.input.IFactRelatedQueryHandler; -import edu.harvard.i2b2.crc.dao.pdo.input.IInputOptionListHandler; -import edu.harvard.i2b2.crc.datavo.pdo.query.PanelType; - -public interface IPageDao { - - public long getTotalForAllPanel(List panelSqlList, - List sqlParamCountList, - IInputOptionListHandler inputOptionListHandler) - throws I2B2DAOException; - - public String buildTotalSql(IFactRelatedQueryHandler factHandler, - PanelType panel) throws I2B2DAOException; - - public HashMap getMinIndexAndCountAllPanel(List panelSqlList, - List sqlParamCountList, - IInputOptionListHandler inputOptionListHandler) - throws I2B2DAOException; - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.pdo; + +import java.util.HashMap; +import java.util.List; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.crc.dao.pdo.input.IFactRelatedQueryHandler; +import edu.harvard.i2b2.crc.dao.pdo.input.IInputOptionListHandler; +import edu.harvard.i2b2.crc.datavo.pdo.query.PanelType; + +public interface IPageDao { + + public long getTotalForAllPanel(List panelSqlList, + List sqlParamCountList, + IInputOptionListHandler inputOptionListHandler) + throws I2B2DAOException; + + public String buildTotalSql(IFactRelatedQueryHandler factHandler, + PanelType panel) throws I2B2DAOException; + + public HashMap getMinIndexAndCountAllPanel(List panelSqlList, + List sqlParamCountList, + IInputOptionListHandler inputOptionListHandler) + throws I2B2DAOException; + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/IPdoQueryConceptDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/IPdoQueryConceptDao.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/IPdoQueryConceptDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/IPdoQueryConceptDao.java index bf852bed..f3fbc476 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/IPdoQueryConceptDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/IPdoQueryConceptDao.java @@ -1,63 +1,63 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.pdo; - -import java.util.List; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.crc.dao.pdo.input.IInputOptionListHandler; -import edu.harvard.i2b2.crc.datavo.pdo.ConceptSet; -import edu.harvard.i2b2.crc.datavo.pdo.PatientDataType; - -public interface IPdoQueryConceptDao { - - /** - * Get concepts detail from concept code list - * - * @param conceptCdList - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return {@link PatientDataType.ConceptDimensionSet} - * @throws I2B2DAOException - */ - public ConceptSet getConceptByConceptCd(List conceptCdList, - boolean detailFlag, boolean blobFlag, boolean statusFlag) - throws I2B2DAOException; - - /** - * Get concept children by item key - * - * @param itemKey - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return - * @throws I2B2DAOException - */ - public ConceptSet getChildrentByItemKey(String itemKey, boolean detailFlag, - boolean blobFlag, boolean statusFlag) throws I2B2DAOException; - - /** - * Get Concept set based on the fact's filter - * - * @param panelSqlList - * @param sqlParamCountList - * @param inputOptionListHandler - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return - * @throws I2B2DAOException - */ - public ConceptSet getConceptByFact(List panelSqlList, - List sqlParamCountList, - IInputOptionListHandler inputOptionListHandler, boolean detailFlag, - boolean blobFlag, boolean statusFlag) throws I2B2DAOException; -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.pdo; + +import java.util.List; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.crc.dao.pdo.input.IInputOptionListHandler; +import edu.harvard.i2b2.crc.datavo.pdo.ConceptSet; +import edu.harvard.i2b2.crc.datavo.pdo.PatientDataType; + +public interface IPdoQueryConceptDao { + + /** + * Get concepts detail from concept code list + * + * @param conceptCdList + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return {@link PatientDataType.ConceptDimensionSet} + * @throws I2B2DAOException + */ + public ConceptSet getConceptByConceptCd(List conceptCdList, + boolean detailFlag, boolean blobFlag, boolean statusFlag) + throws I2B2DAOException; + + /** + * Get concept children by item key + * + * @param itemKey + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return + * @throws I2B2DAOException + */ + public ConceptSet getChildrentByItemKey(String itemKey, boolean detailFlag, + boolean blobFlag, boolean statusFlag) throws I2B2DAOException; + + /** + * Get Concept set based on the fact's filter + * + * @param panelSqlList + * @param sqlParamCountList + * @param inputOptionListHandler + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return + * @throws I2B2DAOException + */ + public ConceptSet getConceptByFact(List panelSqlList, + List sqlParamCountList, + IInputOptionListHandler inputOptionListHandler, boolean detailFlag, + boolean blobFlag, boolean statusFlag) throws I2B2DAOException; +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/IPdoQueryEidDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/IPdoQueryEidDao.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/IPdoQueryEidDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/IPdoQueryEidDao.java index 9333b244..2eff76f1 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/IPdoQueryEidDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/IPdoQueryEidDao.java @@ -1,81 +1,81 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.pdo; - -import java.util.List; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.crc.dao.pdo.input.IInputOptionListHandler; -import edu.harvard.i2b2.crc.datavo.pdo.EidSet; -import edu.harvard.i2b2.crc.datavo.pdo.query.EidListType; -import edu.harvard.i2b2.crc.datavo.pdo.query.PatientListType; - -public interface IPdoQueryEidDao { - - /** - * Get Eid set based on the fact's filter - * - * @param panelSqlList - * @param sqlParamCountList - * @param inputOptionListHandler - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return - * @throws I2B2DAOException - */ - public EidSet getEidByFact(List panelSqlList, - List sqlParamCountList, - IInputOptionListHandler inputOptionListHandler, boolean detailFlag, - boolean blobFlag, boolean statusFlag) throws I2B2DAOException; - - /** - * Function to return patient dimension data for given list of patient num - * - * @param patientNumList - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return PatientDataType.PatientDimensionSet - * @throws Exception - */ - public EidSet getEidByEncounterNum(List encounterNumList, - boolean detailFlag, boolean blobFlag, boolean statusFlag) - throws I2B2DAOException; - - /** - * Get Patient dimension data based on patientlist present in input option - * list - * - * @param patientListType - * {@link PatientListType} - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return PatientDataType.PatientDimensionSet - * @throws I2B2DAOException - */ - public EidSet getEidFromPatientSet(PatientListType patientListType, - boolean detailFlag, boolean blobFlag, boolean statusFlag) - throws I2B2DAOException; - - /** - * Function to return patient dimension data for given list of pid list - * - * @param pidList - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return PatientDataType.PatientDimensionSet - * @throws Exception - */ - public EidSet getEidByEidList(EidListType eidList, boolean detailFlag, - boolean blobFlag, boolean statusFlag) throws I2B2DAOException; - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.pdo; + +import java.util.List; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.crc.dao.pdo.input.IInputOptionListHandler; +import edu.harvard.i2b2.crc.datavo.pdo.EidSet; +import edu.harvard.i2b2.crc.datavo.pdo.query.EidListType; +import edu.harvard.i2b2.crc.datavo.pdo.query.PatientListType; + +public interface IPdoQueryEidDao { + + /** + * Get Eid set based on the fact's filter + * + * @param panelSqlList + * @param sqlParamCountList + * @param inputOptionListHandler + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return + * @throws I2B2DAOException + */ + public EidSet getEidByFact(List panelSqlList, + List sqlParamCountList, + IInputOptionListHandler inputOptionListHandler, boolean detailFlag, + boolean blobFlag, boolean statusFlag) throws I2B2DAOException; + + /** + * Function to return patient dimension data for given list of patient num + * + * @param patientNumList + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return PatientDataType.PatientDimensionSet + * @throws Exception + */ + public EidSet getEidByEncounterNum(List encounterNumList, + boolean detailFlag, boolean blobFlag, boolean statusFlag) + throws I2B2DAOException; + + /** + * Get Patient dimension data based on patientlist present in input option + * list + * + * @param patientListType + * {@link PatientListType} + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return PatientDataType.PatientDimensionSet + * @throws I2B2DAOException + */ + public EidSet getEidFromPatientSet(PatientListType patientListType, + boolean detailFlag, boolean blobFlag, boolean statusFlag) + throws I2B2DAOException; + + /** + * Function to return patient dimension data for given list of pid list + * + * @param pidList + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return PatientDataType.PatientDimensionSet + * @throws Exception + */ + public EidSet getEidByEidList(EidListType eidList, boolean detailFlag, + boolean blobFlag, boolean statusFlag) throws I2B2DAOException; + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/IPdoQueryModifierDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/IPdoQueryModifierDao.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/IPdoQueryModifierDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/IPdoQueryModifierDao.java index 290551e8..ebbd28b8 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/IPdoQueryModifierDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/IPdoQueryModifierDao.java @@ -1,51 +1,51 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.pdo; - -import java.util.List; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.crc.dao.pdo.input.IInputOptionListHandler; -import edu.harvard.i2b2.crc.datavo.pdo.ModifierSet; -import edu.harvard.i2b2.crc.datavo.pdo.PatientDataType; - -public interface IPdoQueryModifierDao { - - /** - * Get modifiers detail from modifier code list - * - * @param modifierCdList - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return {@link PatientDataType.ModifierDimensionSet} - * @throws I2B2DAOException - */ - public ModifierSet getModifierByModifierCd(List modifierCdList, - boolean detailFlag, boolean blobFlag, boolean statusFlag) - throws I2B2DAOException; - - - /** - * Get Modifier set based on the fact's filter - * - * @param panelSqlList - * @param sqlParamCountList - * @param inputOptionListHandler - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return - * @throws I2B2DAOException - */ - public ModifierSet getModifierByFact(List panelSqlList, - List sqlParamCountList, - IInputOptionListHandler inputOptionListHandler, boolean detailFlag, - boolean blobFlag, boolean statusFlag) throws I2B2DAOException; -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.pdo; + +import java.util.List; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.crc.dao.pdo.input.IInputOptionListHandler; +import edu.harvard.i2b2.crc.datavo.pdo.ModifierSet; +import edu.harvard.i2b2.crc.datavo.pdo.PatientDataType; + +public interface IPdoQueryModifierDao { + + /** + * Get modifiers detail from modifier code list + * + * @param modifierCdList + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return {@link PatientDataType.ModifierDimensionSet} + * @throws I2B2DAOException + */ + public ModifierSet getModifierByModifierCd(List modifierCdList, + boolean detailFlag, boolean blobFlag, boolean statusFlag) + throws I2B2DAOException; + + + /** + * Get Modifier set based on the fact's filter + * + * @param panelSqlList + * @param sqlParamCountList + * @param inputOptionListHandler + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return + * @throws I2B2DAOException + */ + public ModifierSet getModifierByFact(List panelSqlList, + List sqlParamCountList, + IInputOptionListHandler inputOptionListHandler, boolean detailFlag, + boolean blobFlag, boolean statusFlag) throws I2B2DAOException; +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/IPdoQueryPatientDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/IPdoQueryPatientDao.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/IPdoQueryPatientDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/IPdoQueryPatientDao.java index a5aaed35..cfe0d6d5 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/IPdoQueryPatientDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/IPdoQueryPatientDao.java @@ -1,87 +1,87 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.pdo; - -import java.util.List; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.crc.dao.pdo.input.IInputOptionListHandler; -import edu.harvard.i2b2.crc.datavo.pdo.ParamType; -import edu.harvard.i2b2.crc.datavo.pdo.PatientSet; -import edu.harvard.i2b2.crc.datavo.pdo.query.EventListType; -import edu.harvard.i2b2.crc.datavo.pdo.query.PatientListType; - -public interface IPdoQueryPatientDao { - - public void setMetaDataParamList(List metaDataParamList); - - /** - * Get Patient set based on the fact's filter - * - * @param panelSqlList - * @param sqlParamCountList - * @param inputOptionListHandler - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return - * @throws I2B2DAOException - */ - public PatientSet getPatientByFact(List panelSqlList, - List sqlParamCountList, - IInputOptionListHandler inputOptionListHandler, boolean detailFlag, - boolean blobFlag, boolean statusFlag) throws I2B2DAOException; - - /** - * Function to return patient dimension data for given list of patient num - * - * @param patientNumList - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return PatientDataType.PatientDimensionSet - * @throws Exception - */ - public PatientSet getPatientByPatientNum(List patientNumList, - boolean detailFlag, boolean blobFlag, boolean statusFlag) - throws I2B2DAOException; - - /** - * Get Patient dimension data based on patientlist present in input option - * list - * - * @param patientListType - * {@link PatientListType} - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return PatientDataType.PatientDimensionSet - * @throws I2B2DAOException - */ - public PatientSet getPatientFromPatientSet(PatientListType patientListType, - boolean detailFlag, boolean blobFlag, boolean statusFlag) - throws I2B2DAOException; - - /** - * Get Patient dimension data based on visitlist present in input option - * list - * - * @param eventListType - * {@link EventListType} - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return PatientDataType.PatientDimensionSet - * @throws I2B2DAOException - */ - public PatientSet getPatientFromVisitSet(EventListType visitListType, - boolean detailFlag, boolean blobFlag, boolean statusFlag) - throws I2B2DAOException; - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.pdo; + +import java.util.List; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.crc.dao.pdo.input.IInputOptionListHandler; +import edu.harvard.i2b2.crc.datavo.pdo.ParamType; +import edu.harvard.i2b2.crc.datavo.pdo.PatientSet; +import edu.harvard.i2b2.crc.datavo.pdo.query.EventListType; +import edu.harvard.i2b2.crc.datavo.pdo.query.PatientListType; + +public interface IPdoQueryPatientDao { + + public void setMetaDataParamList(List metaDataParamList); + + /** + * Get Patient set based on the fact's filter + * + * @param panelSqlList + * @param sqlParamCountList + * @param inputOptionListHandler + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return + * @throws I2B2DAOException + */ + public PatientSet getPatientByFact(List panelSqlList, + List sqlParamCountList, + IInputOptionListHandler inputOptionListHandler, boolean detailFlag, + boolean blobFlag, boolean statusFlag) throws I2B2DAOException; + + /** + * Function to return patient dimension data for given list of patient num + * + * @param patientNumList + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return PatientDataType.PatientDimensionSet + * @throws Exception + */ + public PatientSet getPatientByPatientNum(List patientNumList, + boolean detailFlag, boolean blobFlag, boolean statusFlag) + throws I2B2DAOException; + + /** + * Get Patient dimension data based on patientlist present in input option + * list + * + * @param patientListType + * {@link PatientListType} + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return PatientDataType.PatientDimensionSet + * @throws I2B2DAOException + */ + public PatientSet getPatientFromPatientSet(PatientListType patientListType, + boolean detailFlag, boolean blobFlag, boolean statusFlag) + throws I2B2DAOException; + + /** + * Get Patient dimension data based on visitlist present in input option + * list + * + * @param eventListType + * {@link EventListType} + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return PatientDataType.PatientDimensionSet + * @throws I2B2DAOException + */ + public PatientSet getPatientFromVisitSet(EventListType visitListType, + boolean detailFlag, boolean blobFlag, boolean statusFlag) + throws I2B2DAOException; + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/IPdoQueryPidDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/IPdoQueryPidDao.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/IPdoQueryPidDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/IPdoQueryPidDao.java index fe1d3970..31a98ebf --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/IPdoQueryPidDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/IPdoQueryPidDao.java @@ -1,81 +1,81 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.pdo; - -import java.util.List; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.crc.dao.pdo.input.IInputOptionListHandler; -import edu.harvard.i2b2.crc.datavo.pdo.PidSet; -import edu.harvard.i2b2.crc.datavo.pdo.query.PatientListType; -import edu.harvard.i2b2.crc.datavo.pdo.query.PidListType; - -public interface IPdoQueryPidDao { - - /** - * Get Pid set based on the fact's filter - * - * @param panelSqlList - * @param sqlParamCountList - * @param inputOptionListHandler - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return - * @throws I2B2DAOException - */ - public PidSet getPidByFact(List panelSqlList, - List sqlParamCountList, - IInputOptionListHandler inputOptionListHandler, boolean detailFlag, - boolean blobFlag, boolean statusFlag) throws I2B2DAOException; - - /** - * Function to return patient dimension data for given list of patient num - * - * @param patientNumList - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return PatientDataType.PatientDimensionSet - * @throws Exception - */ - public PidSet getPidByPatientNum(List patientNumList, - boolean detailFlag, boolean blobFlag, boolean statusFlag) - throws I2B2DAOException; - - /** - * Get Patient dimension data based on patientlist present in input option - * list - * - * @param patientListType - * {@link PatientListType} - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return PatientDataType.PatientDimensionSet - * @throws I2B2DAOException - */ - public PidSet getPidFromPatientSet(PatientListType patientListType, - boolean detailFlag, boolean blobFlag, boolean statusFlag) - throws I2B2DAOException; - - /** - * Function to return patient dimension data for given list of pid list - * - * @param pidList - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return PatientDataType.PatientDimensionSet - * @throws Exception - */ - public PidSet getPidByPidList(PidListType pidList, boolean detailFlag, - boolean blobFlag, boolean statusFlag) throws I2B2DAOException; - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.pdo; + +import java.util.List; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.crc.dao.pdo.input.IInputOptionListHandler; +import edu.harvard.i2b2.crc.datavo.pdo.PidSet; +import edu.harvard.i2b2.crc.datavo.pdo.query.PatientListType; +import edu.harvard.i2b2.crc.datavo.pdo.query.PidListType; + +public interface IPdoQueryPidDao { + + /** + * Get Pid set based on the fact's filter + * + * @param panelSqlList + * @param sqlParamCountList + * @param inputOptionListHandler + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return + * @throws I2B2DAOException + */ + public PidSet getPidByFact(List panelSqlList, + List sqlParamCountList, + IInputOptionListHandler inputOptionListHandler, boolean detailFlag, + boolean blobFlag, boolean statusFlag) throws I2B2DAOException; + + /** + * Function to return patient dimension data for given list of patient num + * + * @param patientNumList + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return PatientDataType.PatientDimensionSet + * @throws Exception + */ + public PidSet getPidByPatientNum(List patientNumList, + boolean detailFlag, boolean blobFlag, boolean statusFlag) + throws I2B2DAOException; + + /** + * Get Patient dimension data based on patientlist present in input option + * list + * + * @param patientListType + * {@link PatientListType} + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return PatientDataType.PatientDimensionSet + * @throws I2B2DAOException + */ + public PidSet getPidFromPatientSet(PatientListType patientListType, + boolean detailFlag, boolean blobFlag, boolean statusFlag) + throws I2B2DAOException; + + /** + * Function to return patient dimension data for given list of pid list + * + * @param pidList + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return PatientDataType.PatientDimensionSet + * @throws Exception + */ + public PidSet getPidByPidList(PidListType pidList, boolean detailFlag, + boolean blobFlag, boolean statusFlag) throws I2B2DAOException; + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/IPdoQueryProviderDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/IPdoQueryProviderDao.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/IPdoQueryProviderDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/IPdoQueryProviderDao.java index a990192b..2b62d0b3 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/IPdoQueryProviderDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/IPdoQueryProviderDao.java @@ -1,51 +1,51 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.pdo; - -import java.util.List; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.crc.dao.pdo.input.IInputOptionListHandler; -import edu.harvard.i2b2.crc.datavo.pdo.ObserverSet; - -public interface IPdoQueryProviderDao { - - /** - * Get Observer set based on the fact's filter - * - * @param panelSqlList - * @param sqlParamCountList - * @param inputOptionListHandler - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return - * @throws I2B2DAOException - */ - public ObserverSet getProviderByFact(List panelSqlList, - List sqlParamCountList, - IInputOptionListHandler inputOptionListHandler, boolean detailFlag, - boolean blobFlag, boolean statusFlag) throws I2B2DAOException; - - /** - * Function to return provider/observer section of plain pdo for the given - * id list - * - * @param providerIdList - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return PatientDataType.ProviderDimensionSet - * @throws I2B2DAOException - */ - public ObserverSet getProviderById(List providerIdList, - boolean detailFlag, boolean blobFlag, boolean statusFlag) - throws I2B2DAOException; - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.pdo; + +import java.util.List; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.crc.dao.pdo.input.IInputOptionListHandler; +import edu.harvard.i2b2.crc.datavo.pdo.ObserverSet; + +public interface IPdoQueryProviderDao { + + /** + * Get Observer set based on the fact's filter + * + * @param panelSqlList + * @param sqlParamCountList + * @param inputOptionListHandler + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return + * @throws I2B2DAOException + */ + public ObserverSet getProviderByFact(List panelSqlList, + List sqlParamCountList, + IInputOptionListHandler inputOptionListHandler, boolean detailFlag, + boolean blobFlag, boolean statusFlag) throws I2B2DAOException; + + /** + * Function to return provider/observer section of plain pdo for the given + * id list + * + * @param providerIdList + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return PatientDataType.ProviderDimensionSet + * @throws I2B2DAOException + */ + public ObserverSet getProviderById(List providerIdList, + boolean detailFlag, boolean blobFlag, boolean statusFlag) + throws I2B2DAOException; + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/IPdoQueryVisitDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/IPdoQueryVisitDao.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/IPdoQueryVisitDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/IPdoQueryVisitDao.java index 8e05afd8..d6812d96 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/IPdoQueryVisitDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/IPdoQueryVisitDao.java @@ -1,83 +1,83 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.pdo; - -import java.util.List; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.crc.dao.pdo.input.IInputOptionListHandler; -import edu.harvard.i2b2.crc.datavo.pdo.EventSet; -import edu.harvard.i2b2.crc.datavo.pdo.ParamType; -import edu.harvard.i2b2.crc.datavo.pdo.query.EventListType; -import edu.harvard.i2b2.crc.datavo.pdo.query.PatientListType; - -public interface IPdoQueryVisitDao { - - - - public void setMetaDataParamList(List metaDataParamList); - - /** - * Get Visit set based on the fact's filter - * - * @param panelSqlList - * @param sqlParamCountList - * @param inputOptionListHandler - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return - * @throws I2B2DAOException - */ - public EventSet getVisitByFact(List panelSqlList, - List sqlParamCountList, - IInputOptionListHandler inputOptionListHandler, boolean detailFlag, - boolean blobFlag, boolean statusFlag) throws I2B2DAOException; - - /** - * Function to return list of eventset for given encounter number list - * - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @exception I2B2DAOException - */ - public EventSet getVisitsByEncounterNum(List encounterNumList, - boolean detailFlag, boolean blobFlag, boolean statusFlag) - throws I2B2DAOException; - - /** - * Get visit dimension data base on visit list - * (InputOptionList.getVisitListType()) - * - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return I2B2DAOException - * @throws Exception - */ - public EventSet getVisitDimensionSetFromVisitList( - EventListType visitListType, boolean detailFlag, boolean blobFlag, - boolean statusFlag) throws I2B2DAOException; - - /** - * Get visit dimension from patientlist (InputOptionList.getPatientList()) - * - * @param patientListType - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return PatientDataType.VisitDimensionSet - * @throws I2B2DAOException - */ - public EventSet getVisitDimensionSetFromPatientList( - PatientListType patientListType, boolean detailFlag, - boolean blobFlag, boolean statusFlag) throws I2B2DAOException; - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.pdo; + +import java.util.List; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.crc.dao.pdo.input.IInputOptionListHandler; +import edu.harvard.i2b2.crc.datavo.pdo.EventSet; +import edu.harvard.i2b2.crc.datavo.pdo.ParamType; +import edu.harvard.i2b2.crc.datavo.pdo.query.EventListType; +import edu.harvard.i2b2.crc.datavo.pdo.query.PatientListType; + +public interface IPdoQueryVisitDao { + + + + public void setMetaDataParamList(List metaDataParamList); + + /** + * Get Visit set based on the fact's filter + * + * @param panelSqlList + * @param sqlParamCountList + * @param inputOptionListHandler + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return + * @throws I2B2DAOException + */ + public EventSet getVisitByFact(List panelSqlList, + List sqlParamCountList, + IInputOptionListHandler inputOptionListHandler, boolean detailFlag, + boolean blobFlag, boolean statusFlag) throws I2B2DAOException; + + /** + * Function to return list of eventset for given encounter number list + * + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @exception I2B2DAOException + */ + public EventSet getVisitsByEncounterNum(List encounterNumList, + boolean detailFlag, boolean blobFlag, boolean statusFlag) + throws I2B2DAOException; + + /** + * Get visit dimension data base on visit list + * (InputOptionList.getVisitListType()) + * + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return I2B2DAOException + * @throws Exception + */ + public EventSet getVisitDimensionSetFromVisitList( + EventListType visitListType, boolean detailFlag, boolean blobFlag, + boolean statusFlag) throws I2B2DAOException; + + /** + * Get visit dimension from patientlist (InputOptionList.getPatientList()) + * + * @param patientListType + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return PatientDataType.VisitDimensionSet + * @throws I2B2DAOException + */ + public EventSet getVisitDimensionSetFromPatientList( + PatientListType patientListType, boolean detailFlag, + boolean blobFlag, boolean statusFlag) throws I2B2DAOException; + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/ITablePdoQueryConceptDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/ITablePdoQueryConceptDao.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/ITablePdoQueryConceptDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/ITablePdoQueryConceptDao.java index 8f9c308d..5eba84b2 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/ITablePdoQueryConceptDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/ITablePdoQueryConceptDao.java @@ -1,50 +1,50 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.pdo; - -import java.util.List; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.crc.dao.pdo.input.IInputOptionListHandler; -import edu.harvard.i2b2.crc.datavo.pdo.ConceptSet; - -public interface ITablePdoQueryConceptDao { - - /** - * Get Concept set based on the fact's filter - * - * @param panelSqlList - * @param sqlParamCountList - * @param inputOptionListHandler - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return - * @throws I2B2DAOException - */ - public ConceptSet getConceptByFact(List panelSqlList, - List sqlParamCountList, - IInputOptionListHandler inputOptionListHandler, boolean detailFlag, - boolean blobFlag, boolean statusFlag) throws I2B2DAOException; - - /** - * Function returns concepts based on list of concept codes - * - * @param conceptCdList - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return ConceptSet - * @throws I2B2DAOException - */ - public ConceptSet getConceptByConceptCd(List conceptCdList, - boolean detailFlag, boolean blobFlag, boolean statusFlag) - throws I2B2DAOException; - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.pdo; + +import java.util.List; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.crc.dao.pdo.input.IInputOptionListHandler; +import edu.harvard.i2b2.crc.datavo.pdo.ConceptSet; + +public interface ITablePdoQueryConceptDao { + + /** + * Get Concept set based on the fact's filter + * + * @param panelSqlList + * @param sqlParamCountList + * @param inputOptionListHandler + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return + * @throws I2B2DAOException + */ + public ConceptSet getConceptByFact(List panelSqlList, + List sqlParamCountList, + IInputOptionListHandler inputOptionListHandler, boolean detailFlag, + boolean blobFlag, boolean statusFlag) throws I2B2DAOException; + + /** + * Function returns concepts based on list of concept codes + * + * @param conceptCdList + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return ConceptSet + * @throws I2B2DAOException + */ + public ConceptSet getConceptByConceptCd(List conceptCdList, + boolean detailFlag, boolean blobFlag, boolean statusFlag) + throws I2B2DAOException; + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/ITablePdoQueryModifierDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/ITablePdoQueryModifierDao.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/ITablePdoQueryModifierDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/ITablePdoQueryModifierDao.java index d84395e5..514fb312 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/ITablePdoQueryModifierDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/ITablePdoQueryModifierDao.java @@ -1,50 +1,50 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.pdo; - -import java.util.List; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.crc.dao.pdo.input.IInputOptionListHandler; -import edu.harvard.i2b2.crc.datavo.pdo.ModifierSet; - -public interface ITablePdoQueryModifierDao { - - /** - * Get Concept set based on the fact's filter - * - * @param panelSqlList - * @param sqlParamCountList - * @param inputOptionListHandler - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return - * @throws I2B2DAOException - */ - public ModifierSet getModifierByFact(List panelSqlList, - List sqlParamCountList, - IInputOptionListHandler inputOptionListHandler, boolean detailFlag, - boolean blobFlag, boolean statusFlag) throws I2B2DAOException; - - /** - * Function returns modifiers based on list of modifier codes - * - * @param modifierCdList - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return ModifierSet - * @throws I2B2DAOException - */ - public ModifierSet getModifierByModifierCd(List modifierCdList, - boolean detailFlag, boolean blobFlag, boolean statusFlag) - throws I2B2DAOException; - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.pdo; + +import java.util.List; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.crc.dao.pdo.input.IInputOptionListHandler; +import edu.harvard.i2b2.crc.datavo.pdo.ModifierSet; + +public interface ITablePdoQueryModifierDao { + + /** + * Get Concept set based on the fact's filter + * + * @param panelSqlList + * @param sqlParamCountList + * @param inputOptionListHandler + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return + * @throws I2B2DAOException + */ + public ModifierSet getModifierByFact(List panelSqlList, + List sqlParamCountList, + IInputOptionListHandler inputOptionListHandler, boolean detailFlag, + boolean blobFlag, boolean statusFlag) throws I2B2DAOException; + + /** + * Function returns modifiers based on list of modifier codes + * + * @param modifierCdList + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return ModifierSet + * @throws I2B2DAOException + */ + public ModifierSet getModifierByModifierCd(List modifierCdList, + boolean detailFlag, boolean blobFlag, boolean statusFlag) + throws I2B2DAOException; + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/ITablePdoQueryPatientDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/ITablePdoQueryPatientDao.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/ITablePdoQueryPatientDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/ITablePdoQueryPatientDao.java index b7a55b6a..629909eb --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/ITablePdoQueryPatientDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/ITablePdoQueryPatientDao.java @@ -1,84 +1,84 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.pdo; - -import java.util.List; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.crc.dao.pdo.input.IInputOptionListHandler; -import edu.harvard.i2b2.crc.datavo.pdo.ParamType; -import edu.harvard.i2b2.crc.datavo.pdo.PatientSet; -import edu.harvard.i2b2.crc.datavo.pdo.query.EventListType; -import edu.harvard.i2b2.crc.datavo.pdo.query.PatientListType; - -public interface ITablePdoQueryPatientDao { - - /** - * Function returns Patient information for given list of patient number in - * TablePDO format - * - * @param patientNumList - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return - * @throws I2B2DAOException - */ - public PatientSet getPatientByPatientNum(List patientNumList, - boolean detailFlag, boolean blobFlag, boolean statusFlag) - throws I2B2DAOException; - - /** - * - * @param patientListType - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return - * @throws I2B2DAOException - */ - public PatientSet getPatientFromPatientSet(PatientListType patientListType, - boolean detailFlag, boolean blobFlag, boolean statusFlag) - throws I2B2DAOException; - - /** - * Function returns patient information for given list of encounters - * - * @param visitListType - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return PatientSet - * @throws I2B2DAOException - */ - public PatientSet getPatientFromVisitSet(EventListType visitListType, - boolean detailFlag, boolean blobFlag, boolean statusFlag) - throws I2B2DAOException; - - /** - * Get Patient set based on the fact's filter - * - * @param panelSqlList - * @param sqlParamCountList - * @param inputOptionListHandler - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return - * @throws I2B2DAOException - */ - public PatientSet getPatientByFact(List panelSqlList, - List sqlParamCountList, - IInputOptionListHandler inputOptionListHandler, boolean detailFlag, - boolean blobFlag, boolean statusFlag) throws I2B2DAOException; - - - public void setMetaDataParamList(List metaDataParamList); - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.pdo; + +import java.util.List; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.crc.dao.pdo.input.IInputOptionListHandler; +import edu.harvard.i2b2.crc.datavo.pdo.ParamType; +import edu.harvard.i2b2.crc.datavo.pdo.PatientSet; +import edu.harvard.i2b2.crc.datavo.pdo.query.EventListType; +import edu.harvard.i2b2.crc.datavo.pdo.query.PatientListType; + +public interface ITablePdoQueryPatientDao { + + /** + * Function returns Patient information for given list of patient number in + * TablePDO format + * + * @param patientNumList + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return + * @throws I2B2DAOException + */ + public PatientSet getPatientByPatientNum(List patientNumList, + boolean detailFlag, boolean blobFlag, boolean statusFlag) + throws I2B2DAOException; + + /** + * + * @param patientListType + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return + * @throws I2B2DAOException + */ + public PatientSet getPatientFromPatientSet(PatientListType patientListType, + boolean detailFlag, boolean blobFlag, boolean statusFlag) + throws I2B2DAOException; + + /** + * Function returns patient information for given list of encounters + * + * @param visitListType + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return PatientSet + * @throws I2B2DAOException + */ + public PatientSet getPatientFromVisitSet(EventListType visitListType, + boolean detailFlag, boolean blobFlag, boolean statusFlag) + throws I2B2DAOException; + + /** + * Get Patient set based on the fact's filter + * + * @param panelSqlList + * @param sqlParamCountList + * @param inputOptionListHandler + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return + * @throws I2B2DAOException + */ + public PatientSet getPatientByFact(List panelSqlList, + List sqlParamCountList, + IInputOptionListHandler inputOptionListHandler, boolean detailFlag, + boolean blobFlag, boolean statusFlag) throws I2B2DAOException; + + + public void setMetaDataParamList(List metaDataParamList); + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/ITablePdoQueryProviderDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/ITablePdoQueryProviderDao.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/ITablePdoQueryProviderDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/ITablePdoQueryProviderDao.java index 61934113..0f7b7c99 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/ITablePdoQueryProviderDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/ITablePdoQueryProviderDao.java @@ -1,38 +1,38 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.pdo; - -import java.util.List; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.crc.dao.pdo.input.IInputOptionListHandler; -import edu.harvard.i2b2.crc.datavo.pdo.ObserverSet; - -public interface ITablePdoQueryProviderDao { - - public ObserverSet getProviderByFact(List panelSqlList, - List sqlParamCountList, - IInputOptionListHandler inputOptionListHandler, boolean detailFlag, - boolean blobFlag, boolean statusFlag) throws I2B2DAOException; - - /** - * Returns observerset for the given list of provider id - * - * @param providerIdList - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return ObserverSet - * @throws I2B2DAOException - */ - public ObserverSet getProviderById(List providerIdList, - boolean detailFlag, boolean blobFlag, boolean statusFlag) - throws I2B2DAOException; - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.pdo; + +import java.util.List; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.crc.dao.pdo.input.IInputOptionListHandler; +import edu.harvard.i2b2.crc.datavo.pdo.ObserverSet; + +public interface ITablePdoQueryProviderDao { + + public ObserverSet getProviderByFact(List panelSqlList, + List sqlParamCountList, + IInputOptionListHandler inputOptionListHandler, boolean detailFlag, + boolean blobFlag, boolean statusFlag) throws I2B2DAOException; + + /** + * Returns observerset for the given list of provider id + * + * @param providerIdList + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return ObserverSet + * @throws I2B2DAOException + */ + public ObserverSet getProviderById(List providerIdList, + boolean detailFlag, boolean blobFlag, boolean statusFlag) + throws I2B2DAOException; + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/ITablePdoQueryVisitDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/ITablePdoQueryVisitDao.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/ITablePdoQueryVisitDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/ITablePdoQueryVisitDao.java index 317a877e..0ca25293 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/ITablePdoQueryVisitDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/ITablePdoQueryVisitDao.java @@ -1,71 +1,71 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.pdo; - -import java.util.List; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.crc.dao.pdo.input.IInputOptionListHandler; -import edu.harvard.i2b2.crc.datavo.pdo.EventSet; -import edu.harvard.i2b2.crc.datavo.pdo.ParamType; -import edu.harvard.i2b2.crc.datavo.pdo.query.EventListType; -import edu.harvard.i2b2.crc.datavo.pdo.query.PatientListType; - -public interface ITablePdoQueryVisitDao { - - /** - * Function to return EventSet from visit information - * - * @param encounterNumList - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return EventSet - * @throws I2B2DAOException - */ - public EventSet getVisitsByEncounterNum(List encounterNumList, - boolean detailFlag, boolean blobFlag, boolean statusFlag) - throws I2B2DAOException; - - /** - * Function to return EventSet from visit information - * - * @param visitListType - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return EventSet - * @throws I2B2DAOException - */ - public EventSet getVisitDimensionSetFromVisitList( - EventListType visitListType, boolean detailFlag, boolean blobFlag, - boolean statusFlag) throws I2B2DAOException; - - /** - * Function to return EventSet for given patient set - * - * @param patientListType - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return - * @throws I2B2DAOException - */ - public EventSet getVisitDimensionSetFromPatientList( - PatientListType patientListType, boolean detailFlag, - boolean blobFlag, boolean statusFlag) throws I2B2DAOException; - - public EventSet getVisitByFact(List panelSqlList, - List sqlParamCountList, - IInputOptionListHandler inputOptionListHandler, boolean detailFlag, - boolean blobFlag, boolean statusFlag) throws I2B2DAOException; - - public void setMetaDataParamList(List metaDataParamList); - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.pdo; + +import java.util.List; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.crc.dao.pdo.input.IInputOptionListHandler; +import edu.harvard.i2b2.crc.datavo.pdo.EventSet; +import edu.harvard.i2b2.crc.datavo.pdo.ParamType; +import edu.harvard.i2b2.crc.datavo.pdo.query.EventListType; +import edu.harvard.i2b2.crc.datavo.pdo.query.PatientListType; + +public interface ITablePdoQueryVisitDao { + + /** + * Function to return EventSet from visit information + * + * @param encounterNumList + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return EventSet + * @throws I2B2DAOException + */ + public EventSet getVisitsByEncounterNum(List encounterNumList, + boolean detailFlag, boolean blobFlag, boolean statusFlag) + throws I2B2DAOException; + + /** + * Function to return EventSet from visit information + * + * @param visitListType + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return EventSet + * @throws I2B2DAOException + */ + public EventSet getVisitDimensionSetFromVisitList( + EventListType visitListType, boolean detailFlag, boolean blobFlag, + boolean statusFlag) throws I2B2DAOException; + + /** + * Function to return EventSet for given patient set + * + * @param patientListType + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return + * @throws I2B2DAOException + */ + public EventSet getVisitDimensionSetFromPatientList( + PatientListType patientListType, boolean detailFlag, + boolean blobFlag, boolean statusFlag) throws I2B2DAOException; + + public EventSet getVisitByFact(List panelSqlList, + List sqlParamCountList, + IInputOptionListHandler inputOptionListHandler, boolean detailFlag, + boolean blobFlag, boolean statusFlag) throws I2B2DAOException; + + public void setMetaDataParamList(List metaDataParamList); + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/MetaDataTypeMapper.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/MetaDataTypeMapper.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/MetaDataTypeMapper.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/MetaDataTypeMapper.java index c16817b3..65aa2fc9 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/MetaDataTypeMapper.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/MetaDataTypeMapper.java @@ -1,64 +1,64 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.pdo; - -import java.util.Arrays; -import java.util.List; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -public class MetaDataTypeMapper { - - /** log **/ - protected final Log log = LogFactory.getLog(getClass()); - - String stringDataType[] = {"varchar","varchar2","char","nchar"}; - String dateDataType[] = {"date","datetime"}; - String intDataType[] = {"int","number","bigint"}; - String decimalDataType[] = {"number","decimal","float"}; - List stringDataList,dateDataList,intDataList,decimalDataList; - - public MetaDataTypeMapper() { - stringDataList = Arrays.asList(stringDataType); - dateDataList = Arrays.asList(dateDataType); - intDataList = Arrays.asList(intDataType); - decimalDataList = Arrays.asList(decimalDataType); - - } - - public void fillXmlDataType(MetadataDao.TableMetaData[] tableMetaDataList, boolean tablePDOFlag) { - for (int i=0;i stringDataList,dateDataList,intDataList,decimalDataList; + + public MetaDataTypeMapper() { + stringDataList = Arrays.asList(stringDataType); + dateDataList = Arrays.asList(dateDataType); + intDataList = Arrays.asList(intDataType); + decimalDataList = Arrays.asList(decimalDataType); + + } + + public void fillXmlDataType(MetadataDao.TableMetaData[] tableMetaDataList, boolean tablePDOFlag) { + for (int i=0;i PATIENT_DIMENSION_REQUIRED_FIELDS = new ArrayList(); - private ArrayList VISIT_DIMENSION_REQUIRED_FIELDS = new ArrayList(); - private ArrayList VISIT_DIMENSION_REQUIRED_DETAIL_FIELDS = new ArrayList(); - private ArrayList PATIENT_DIMENSION_REQUIRED_DETAIL_FIELDS = new ArrayList(); - - private String[] patient_dim_required_field = new String[] { - "patient_num", "vital_status_cd", "birth_date", "death_date", "patient_blob", "update_date", - "download_date", "import_date", "sourcesystem_cd", "upload_id" }; - - private String[] patient_dim_detail_field = new String[] { - "vital_status_cd","birth_date"}; - - private String[] visit_dim_detail_field = new String[] {"active_status_cd"}; - - private String[] visit_dim_required_field = new String[] { "encounter_num", - "patient_num", "start_date", "end_date", "active_status_cd", "visit_blob", - "update_date", "download_date", "import_date", "sourcesystem_cd", - "upload_id" }; - - public final static String CRC_COLUMN_DESCRIPTOR = "crc_column_descriptor"; - - - - - private DataSourceLookup dataSourceLookup = null; - - public MetadataDao(DataSourceLookup dataSourceLookup, DataSource dataSource) { - this.dataSourceLookup = dataSourceLookup; - setDataSource(dataSource); - setDbSchemaName(dataSourceLookup.getFullSchema()); - PATIENT_DIMENSION_REQUIRED_FIELDS.addAll(Arrays - .asList(patient_dim_required_field)); - VISIT_DIMENSION_REQUIRED_FIELDS.addAll(Arrays - .asList(visit_dim_required_field)); - PATIENT_DIMENSION_REQUIRED_DETAIL_FIELDS.addAll(Arrays - .asList(patient_dim_detail_field)); - VISIT_DIMENSION_REQUIRED_DETAIL_FIELDS.addAll(Arrays - .asList(visit_dim_detail_field)); - } - - - - /* - * (non-Javadoc) - * - * @see edu.harvard.i2b2.crc.dao.pdo.IMetadataDao#blah(java.lang.String) - */ - @Override - public Map getMetadataForOptionalField(String tableName) - throws I2B2DAOException { - - ArrayList requiredFieldLookupList = null; - ArrayList requiredDetailFieldLookupList = null; - - if (tableName.equalsIgnoreCase(DimensionTable.PATIENT_DIMENSION)) { - requiredFieldLookupList = PATIENT_DIMENSION_REQUIRED_FIELDS; - requiredDetailFieldLookupList = PATIENT_DIMENSION_REQUIRED_DETAIL_FIELDS; - } else if (tableName.equalsIgnoreCase(DimensionTable.VISIT_DIMENSION)) { - requiredFieldLookupList = VISIT_DIMENSION_REQUIRED_FIELDS; - requiredDetailFieldLookupList = VISIT_DIMENSION_REQUIRED_DETAIL_FIELDS; - } - - Map columnMap = new HashMap(); - Connection conn = null; - Statement stmt = null; - try { - conn = getDataSource().getConnection(); - - Map columnDescriptorMap = getColumnDescription(conn, tableName) ; - - stmt = conn.createStatement(); - // Execute the query - ResultSet rs = stmt.executeQuery("SELECT * FROM " - + getDbSchemaName() + tableName + " WHERE 1 = 2"); - - // Get the metadata - ResultSetMetaData md = rs.getMetaData(); - - String columnName = "", columnType = ""; - int columnSize = 0; - // Print the column labels - for (int i = 1; i <= md.getColumnCount(); i++) { - TableMetaData tableMetaData = new TableMetaData(); - - boolean requiredDetailFieldFlag = false; - if (requiredDetailFieldLookupList.contains(md.getColumnLabel(i) - .toLowerCase())) { - requiredDetailFieldFlag = true; - } - if (requiredDetailFieldFlag || (!requiredFieldLookupList.contains(md.getColumnLabel(i) - .toLowerCase()))) { - columnName = md.getColumnLabel(i).toLowerCase(); - columnType = md.getColumnTypeName(i).toLowerCase(); - columnSize = md.getColumnDisplaySize(i); - - log.debug("column name " - + columnName); - log.debug(" column type name" - + columnType ); - log.debug(" column display type size " - + columnSize); - tableMetaData.column_name = columnName; - tableMetaData.column_type = columnType; - tableMetaData.column_comment = columnName; - tableMetaData.column_type_size = String.valueOf(columnSize); - tableMetaData.column_comment = columnDescriptorMap.get(columnName); - columnMap.put(columnName, tableMetaData); - } - } - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - log.error("", sqlEx); - throw new I2B2DAOException("", sqlEx); - } finally { - - try { - JDBCUtil.closeJdbcResource(null, stmt, conn); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - } - } - return columnMap; - } - - private Map getColumnDescription(Connection conn, String tableName) throws SQLException { - Map columnDescriptorMap = new HashMap(); - PreparedStatement pStmt = conn.prepareStatement("select * from " + getDbSchemaName() + "code_lookup where lower(table_cd) = ? and lower(code_cd) = ?"); - pStmt.setString(1, tableName.toLowerCase()); - pStmt.setString(2, CRC_COLUMN_DESCRIPTOR); - ResultSet resultSet = pStmt.executeQuery(); - String columnCd = null, columnDescriptor = null; - while (resultSet.next()) { - columnCd = resultSet.getString("column_cd"); - columnDescriptor = resultSet.getString("name_char"); - if (columnCd != null && columnDescriptor != null) { - columnDescriptorMap.put(columnCd.trim().toLowerCase() , columnDescriptor); - } - - } - return columnDescriptorMap; - } - - public class TableMetaData { - public String column_name; - public String column_type; - public String column_type_size; - public String column_comment; - public String column_xml_type; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.pdo; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +import javax.sql.DataSource; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.util.db.JDBCUtil; +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; + +public class MetadataDao extends CRCDAO implements IMetadataDao { + + /** log * */ + protected final Log log = LogFactory.getLog(getClass()); + + + + private ArrayList PATIENT_DIMENSION_REQUIRED_FIELDS = new ArrayList(); + private ArrayList VISIT_DIMENSION_REQUIRED_FIELDS = new ArrayList(); + private ArrayList VISIT_DIMENSION_REQUIRED_DETAIL_FIELDS = new ArrayList(); + private ArrayList PATIENT_DIMENSION_REQUIRED_DETAIL_FIELDS = new ArrayList(); + + private String[] patient_dim_required_field = new String[] { + "patient_num", "vital_status_cd", "birth_date", "death_date", "patient_blob", "update_date", + "download_date", "import_date", "sourcesystem_cd", "upload_id" }; + + private String[] patient_dim_detail_field = new String[] { + "vital_status_cd","birth_date"}; + + private String[] visit_dim_detail_field = new String[] {"active_status_cd"}; + + private String[] visit_dim_required_field = new String[] { "encounter_num", + "patient_num", "start_date", "end_date", "active_status_cd", "visit_blob", + "update_date", "download_date", "import_date", "sourcesystem_cd", + "upload_id" }; + + public final static String CRC_COLUMN_DESCRIPTOR = "crc_column_descriptor"; + + + + + private DataSourceLookup dataSourceLookup = null; + + public MetadataDao(DataSourceLookup dataSourceLookup, DataSource dataSource) { + this.dataSourceLookup = dataSourceLookup; + setDataSource(dataSource); + setDbSchemaName(dataSourceLookup.getFullSchema()); + PATIENT_DIMENSION_REQUIRED_FIELDS.addAll(Arrays + .asList(patient_dim_required_field)); + VISIT_DIMENSION_REQUIRED_FIELDS.addAll(Arrays + .asList(visit_dim_required_field)); + PATIENT_DIMENSION_REQUIRED_DETAIL_FIELDS.addAll(Arrays + .asList(patient_dim_detail_field)); + VISIT_DIMENSION_REQUIRED_DETAIL_FIELDS.addAll(Arrays + .asList(visit_dim_detail_field)); + } + + + + /* + * (non-Javadoc) + * + * @see edu.harvard.i2b2.crc.dao.pdo.IMetadataDao#blah(java.lang.String) + */ + @Override + public Map getMetadataForOptionalField(String tableName) + throws I2B2DAOException { + + ArrayList requiredFieldLookupList = null; + ArrayList requiredDetailFieldLookupList = null; + + if (tableName.equalsIgnoreCase(DimensionTable.PATIENT_DIMENSION)) { + requiredFieldLookupList = PATIENT_DIMENSION_REQUIRED_FIELDS; + requiredDetailFieldLookupList = PATIENT_DIMENSION_REQUIRED_DETAIL_FIELDS; + } else if (tableName.equalsIgnoreCase(DimensionTable.VISIT_DIMENSION)) { + requiredFieldLookupList = VISIT_DIMENSION_REQUIRED_FIELDS; + requiredDetailFieldLookupList = VISIT_DIMENSION_REQUIRED_DETAIL_FIELDS; + } + + Map columnMap = new HashMap(); + Connection conn = null; + Statement stmt = null; + try { + conn = getDataSource().getConnection(); + + Map columnDescriptorMap = getColumnDescription(conn, tableName) ; + + stmt = conn.createStatement(); + // Execute the query + ResultSet rs = stmt.executeQuery("SELECT * FROM " + + getDbSchemaName() + tableName + " WHERE 1 = 2"); + + // Get the metadata + ResultSetMetaData md = rs.getMetaData(); + + String columnName = "", columnType = ""; + int columnSize = 0; + // Print the column labels + for (int i = 1; i <= md.getColumnCount(); i++) { + TableMetaData tableMetaData = new TableMetaData(); + + boolean requiredDetailFieldFlag = false; + if (requiredDetailFieldLookupList.contains(md.getColumnLabel(i) + .toLowerCase())) { + requiredDetailFieldFlag = true; + } + if (requiredDetailFieldFlag || (!requiredFieldLookupList.contains(md.getColumnLabel(i) + .toLowerCase()))) { + columnName = md.getColumnLabel(i).toLowerCase(); + columnType = md.getColumnTypeName(i).toLowerCase(); + columnSize = md.getColumnDisplaySize(i); + + log.debug("column name " + + columnName); + log.debug(" column type name" + + columnType ); + log.debug(" column display type size " + + columnSize); + tableMetaData.column_name = columnName; + tableMetaData.column_type = columnType; + tableMetaData.column_comment = columnName; + tableMetaData.column_type_size = String.valueOf(columnSize); + tableMetaData.column_comment = columnDescriptorMap.get(columnName); + columnMap.put(columnName, tableMetaData); + } + } + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + log.error("", sqlEx); + throw new I2B2DAOException("", sqlEx); + } finally { + + try { + JDBCUtil.closeJdbcResource(null, stmt, conn); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + } + } + return columnMap; + } + + private Map getColumnDescription(Connection conn, String tableName) throws SQLException { + Map columnDescriptorMap = new HashMap(); + PreparedStatement pStmt = conn.prepareStatement("select * from " + getDbSchemaName() + "code_lookup where lower(table_cd) = ? and lower(code_cd) = ?"); + pStmt.setString(1, tableName.toLowerCase()); + pStmt.setString(2, CRC_COLUMN_DESCRIPTOR); + ResultSet resultSet = pStmt.executeQuery(); + String columnCd = null, columnDescriptor = null; + while (resultSet.next()) { + columnCd = resultSet.getString("column_cd"); + columnDescriptor = resultSet.getString("name_char"); + if (columnCd != null && columnDescriptor != null) { + columnDescriptorMap.put(columnCd.trim().toLowerCase() , columnDescriptor); + } + + } + return columnDescriptorMap; + } + + public class TableMetaData { + public String column_name; + public String column_type; + public String column_type_size; + public String column_comment; + public String column_xml_type; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/ObservationFactDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/ObservationFactDao.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/ObservationFactDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/ObservationFactDao.java index 0b116005..3fdaf61d --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/ObservationFactDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/ObservationFactDao.java @@ -1,319 +1,319 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao.pdo; - -import java.io.IOException; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.text.SimpleDateFormat; -import java.util.GregorianCalendar; -import java.util.Iterator; - -import javax.sql.DataSource; -import javax.xml.stream.XMLStreamException; - -import org.apache.axis2.AxisFault; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.exception.StackTraceUtil; -import edu.harvard.i2b2.common.util.db.JDBCUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.dao.pdo.output.ObservationFactFactRelated; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.ConceptNotFoundException; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.OntologyException; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; -import edu.harvard.i2b2.crc.datavo.ontology.DerivedFactColumnsType; -import edu.harvard.i2b2.crc.datavo.pdo.ObservationSet; -import edu.harvard.i2b2.crc.datavo.pdo.ObservationType; -import edu.harvard.i2b2.crc.datavo.pdo.PatientDataType; -import edu.harvard.i2b2.crc.datavo.pdo.query.FactPrimaryKeyType; -import edu.harvard.i2b2.crc.datavo.pdo.query.OutputOptionType; -import edu.harvard.i2b2.crc.delegate.ontology.CallOntologyUtil; -import edu.harvard.i2b2.crc.util.PMServiceAccountUtil; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - -/** - * DAO class for observation fact $Id: ObservationFactDao.java,v 1.13 2008/07/21 - * 19:53:40 rk903 Exp $ - * - * @author rkuttan - * @see FactPrimaryKeyType - * @see OutputOptionType - */ -public class ObservationFactDao extends CRCDAO implements IObservationFactDao { - - private DataSourceLookup dataSourceLookup = null; - - public ObservationFactDao(DataSourceLookup dataSourceLookup, - DataSource dataSource) { - setDataSource(dataSource); - setDbSchemaName(dataSourceLookup.getFullSchema()); - this.dataSourceLookup = dataSourceLookup; - } - - /** - * Function returns Observation fact from the primary key. - *

    - * Required fields : patient_num, concept_cd, encounter_num - *

    - * Optional field : provider_id,start_date - * - * @param factPrimaryKey - * @param factOutputOption - * @return PatientDataType - * @throws I2B2Exception - */ - @Override - public PatientDataType getObservationFactByPrimaryKey( - FactPrimaryKeyType factPrimaryKey, OutputOptionType factOutputOption) - throws I2B2DAOException { - PatientDataType patientDataType = new PatientDataType(); - - ObservationFactFactRelated factRelated = new ObservationFactFactRelated( - factOutputOption); - - String defaultTableName = getDbSchemaName() + "observation_fact"; - - String sql = " SELECT " + factRelated.getSelectClause() + " \n " - + " FROM " + defaultTableName + " obs \n" - + " WHERE obs.encounter_num = ? AND \n " - + " obs.patient_num = ? AND \n" + " obs.concept_cd = ? \n"; - - if (factPrimaryKey.getObserverId() != null) { - sql += " AND obs.provider_id = ? \n"; - } - - // make given start date to 'mm-dd-yyyy hh24:mi' format - if (factPrimaryKey.getStartDate() != null) { - GregorianCalendar gc = factPrimaryKey.getStartDate() - .toGregorianCalendar(); - String sqlFormatedStartDate = ""; - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE)) { - SimpleDateFormat dateFormat = new SimpleDateFormat( - "dd-MMM-yyyy HH:mm:ss"); - sqlFormatedStartDate = dateFormat.format(gc.getTime()); - sql += (" AND obs.start_date = to_date('" - + sqlFormatedStartDate + " ', 'DD-MON-YYYY HH24:MI:SS') "); - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER) || dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) { - SimpleDateFormat dateFormat = new SimpleDateFormat( - "yyyy-MM-dd'T'HH:mm:ss"); - sqlFormatedStartDate = dateFormat.format(gc.getTime()); - sql += (" AND obs.start_date = '" + sqlFormatedStartDate + "'"); - } - } - - if (factPrimaryKey.getModifierCd() != null) { - sql += " AND obs.modifier_cd = ? "; - } - if (factPrimaryKey.getInstanceNum() != null) { - sql += " AND obs.instance_num = ? "; - } - -// log.info("Pre Sql from ObservationFactDAO[" + sql + "]"); - - - int numDerivedTables = 1; - boolean derivedFactTable = QueryProcessorUtil.getInstance().getDerivedFactTable(); - String finalSql = sql; - if(derivedFactTable == true){ - // call ONT to get concept info - DerivedFactColumnsType columns = getFactColumnsFromOntologyCellByCode(factPrimaryKey.getConceptCd()); - - if(columns != null){ - numDerivedTables = columns.getDerivedFactTableColumn().size(); -// log.info("found " +numDerivedTables + " derived tables"); - // parse through solumns and build up replace string. - - Iterator it = columns.getDerivedFactTableColumn().iterator(); - String column = it.next(); -// log.info(column); - if(column.contains(".")) { - int lastIndex = column.lastIndexOf("."); - String tableName = this.getDbSchemaName() + (column.substring(0, lastIndex)); - log.info(tableName); - finalSql = finalSql.replace(defaultTableName, tableName); - } - while(it.hasNext()){ - column = it.next(); - if(column.contains(".")) { - int lastIndex = column.lastIndexOf("."); - String table = this.getDbSchemaName() + (column.substring(0, lastIndex)); - if(table != null) - finalSql += "\n union all \n"; - finalSql += sql.replace(defaultTableName, table); - } - - } - } - } - -// log.info("Generated Sql from ObservationFactDAO[" + finalSql + "]"); - - Connection conn = null; - PreparedStatement stmt = null; - - try { - // get db connection - // conn = getConnection(); - conn = getDataSource().getConnection(); - - // create prepared statement - stmt = conn.prepareStatement(finalSql); - int index = 1; - for (int i=0; i<= numDerivedTables -1; i++){ - stmt.setInt(i+index, Integer.parseInt(factPrimaryKey.getEventId())); - // log.info(i+index + " " + factPrimaryKey.getEventId()); - index++; - stmt.setInt(i+index , Integer.parseInt(factPrimaryKey.getPatientId())); - // log.info(i+index +" " + factPrimaryKey.getPatientId()); - index++; - stmt.setString(i+index, factPrimaryKey.getConceptCd()); - // log.info(i+index + " " + factPrimaryKey.getConceptCd()); - index++; - // if provider id is not null add it to sql parameter - if (factPrimaryKey.getObserverId() != null) { - stmt.setString(i+index, factPrimaryKey.getObserverId()); - // log.info(i+index + " " + factPrimaryKey.getObserverId()); - index++; - } - // if modifier cd is not null add it to sql parameter - if (factPrimaryKey.getModifierCd() != null) { - stmt.setString(i+index, factPrimaryKey.getModifierCd()); - // log.info(i + index +" " + factPrimaryKey.getModifierCd()); - index++; - } - if (factPrimaryKey.getInstanceNum() != null) { - int instanceNum = Integer.parseInt(factPrimaryKey - .getInstanceNum()); - stmt.setInt(i+index, instanceNum); - // log.info(i + index + " " + factPrimaryKey.getInstanceNum()); - index++; - } - - } - - // original (pre-OMOP) code - /* stmt.setInt(1, Integer.parseInt(factPrimaryKey.getEventId())); - stmt.setInt(2, Integer.parseInt(factPrimaryKey.getPatientId())); - stmt.setString(3, factPrimaryKey.getConceptCd()); - - int i = 4; - String providerId = factPrimaryKey.getObserverId(); - - // if provider id is not null add it to sql parameter - if (providerId != null) { - stmt.setString(i, providerId); - i++; - } - - // if modifier cd is not null add it to sql parameter - if (factPrimaryKey.getModifierCd() != null) { - stmt.setString(i, factPrimaryKey.getModifierCd()); - i++; - } - - if (factPrimaryKey.getInstanceNum() != null) { - int instanceNum = Integer.parseInt(factPrimaryKey - .getInstanceNum()); - i++; - stmt.setInt(i, instanceNum); - } - */ - - ResultSet resultSet = stmt.executeQuery(); - ObservationSet obsFactSet = new ObservationSet(); - - I2B2PdoFactory.ObservationFactBuilder observationFactBuilder = new I2B2PdoFactory().new ObservationFactBuilder( - factRelated.isSelectDetail(), factRelated.isSelectBlob(), - factRelated.isSelectStatus(), dataSourceLookup.getServerType()); - while (resultSet.next()) { - ObservationType observationFactType = observationFactBuilder - .buildObservationSet(resultSet); - obsFactSet.getObservation().add(observationFactType); - } - - patientDataType.getObservationSet().add(obsFactSet); - } catch (SQLException sqlEx) { - log.error(sqlEx); - throw new I2B2DAOException("", sqlEx); - } catch (IOException ioEx) { - log.error(ioEx); - throw new I2B2DAOException("", ioEx); - } finally { - try { - JDBCUtil.closeJdbcResource(null, stmt, conn); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - } - } - - return patientDataType; - } - - - - protected DerivedFactColumnsType getFactColumnsFromOntologyCellByCode(String conceptCd) - throws ConceptNotFoundException, OntologyException { - DerivedFactColumnsType factColumns = new DerivedFactColumnsType(); - try { - - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - String ontologyUrl = qpUtil - .getCRCPropertyValue(QueryProcessorUtil.ONTOLOGYCELL_ROOT_WS_URL_PROPERTIES); - - SecurityType securityType = PMServiceAccountUtil - .getServiceSecurityType(dataSourceLookup.getDomainId()); - - factColumns = CallOntologyUtil.callGetFactColumnsByConceptCd(conceptCd, - securityType, dataSourceLookup.getProjectPath(), - ontologyUrl +"/getCodeInfo"); - } catch (JAXBUtilException e) { - - log.error("Error while fetching metadata [" + conceptCd - + "] from ontology ", e); - throw new OntologyException("Error while fetching metadata [" - + conceptCd + "] from ontology " - + StackTraceUtil.getStackTrace(e)); - } catch (I2B2Exception e) { - log.error("Error while fetching metadata from ontology ", e); - throw new OntologyException("Error while fetching metadata [" - + conceptCd + "] from ontology " - + StackTraceUtil.getStackTrace(e)); - } catch (AxisFault e) { - log.error("Error while fetching metadata from ontology ", e); - throw new OntologyException("Error while fetching metadata [" - + conceptCd + "] from ontology " - + StackTraceUtil.getStackTrace(e)); - } catch (XMLStreamException e) { - log.error("Error while fetching metadata from ontology ", e); - throw new OntologyException("Error while fetching metadata [" - + conceptCd + "] from ontology " - + StackTraceUtil.getStackTrace(e)); - } - - return factColumns; - } - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao.pdo; + +import java.io.IOException; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.text.SimpleDateFormat; +import java.util.GregorianCalendar; +import java.util.Iterator; + +import javax.sql.DataSource; +import javax.xml.stream.XMLStreamException; + +import org.apache.axis2.AxisFault; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.exception.StackTraceUtil; +import edu.harvard.i2b2.common.util.db.JDBCUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.dao.pdo.output.ObservationFactFactRelated; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.ConceptNotFoundException; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.OntologyException; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; +import edu.harvard.i2b2.crc.datavo.ontology.DerivedFactColumnsType; +import edu.harvard.i2b2.crc.datavo.pdo.ObservationSet; +import edu.harvard.i2b2.crc.datavo.pdo.ObservationType; +import edu.harvard.i2b2.crc.datavo.pdo.PatientDataType; +import edu.harvard.i2b2.crc.datavo.pdo.query.FactPrimaryKeyType; +import edu.harvard.i2b2.crc.datavo.pdo.query.OutputOptionType; +import edu.harvard.i2b2.crc.delegate.ontology.CallOntologyUtil; +import edu.harvard.i2b2.crc.util.PMServiceAccountUtil; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + +/** + * DAO class for observation fact $Id: ObservationFactDao.java,v 1.13 2008/07/21 + * 19:53:40 rk903 Exp $ + * + * @author rkuttan + * @see FactPrimaryKeyType + * @see OutputOptionType + */ +public class ObservationFactDao extends CRCDAO implements IObservationFactDao { + + private DataSourceLookup dataSourceLookup = null; + + public ObservationFactDao(DataSourceLookup dataSourceLookup, + DataSource dataSource) { + setDataSource(dataSource); + setDbSchemaName(dataSourceLookup.getFullSchema()); + this.dataSourceLookup = dataSourceLookup; + } + + /** + * Function returns Observation fact from the primary key. + *

    + * Required fields : patient_num, concept_cd, encounter_num + *

    + * Optional field : provider_id,start_date + * + * @param factPrimaryKey + * @param factOutputOption + * @return PatientDataType + * @throws I2B2Exception + */ + @Override + public PatientDataType getObservationFactByPrimaryKey( + FactPrimaryKeyType factPrimaryKey, OutputOptionType factOutputOption) + throws I2B2DAOException { + PatientDataType patientDataType = new PatientDataType(); + + ObservationFactFactRelated factRelated = new ObservationFactFactRelated( + factOutputOption); + + String defaultTableName = getDbSchemaName() + "observation_fact"; + + String sql = " SELECT " + factRelated.getSelectClause() + " \n " + + " FROM " + defaultTableName + " obs \n" + + " WHERE obs.encounter_num = ? AND \n " + + " obs.patient_num = ? AND \n" + " obs.concept_cd = ? \n"; + + if (factPrimaryKey.getObserverId() != null) { + sql += " AND obs.provider_id = ? \n"; + } + + // make given start date to 'mm-dd-yyyy hh24:mi' format + if (factPrimaryKey.getStartDate() != null) { + GregorianCalendar gc = factPrimaryKey.getStartDate() + .toGregorianCalendar(); + String sqlFormatedStartDate = ""; + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.ORACLE)) { + SimpleDateFormat dateFormat = new SimpleDateFormat( + "dd-MMM-yyyy HH:mm:ss"); + sqlFormatedStartDate = dateFormat.format(gc.getTime()); + sql += (" AND obs.start_date = to_date('" + + sqlFormatedStartDate + " ', 'DD-MON-YYYY HH24:MI:SS') "); + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER) || dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) { + SimpleDateFormat dateFormat = new SimpleDateFormat( + "yyyy-MM-dd'T'HH:mm:ss"); + sqlFormatedStartDate = dateFormat.format(gc.getTime()); + sql += (" AND obs.start_date = '" + sqlFormatedStartDate + "'"); + } + } + + if (factPrimaryKey.getModifierCd() != null) { + sql += " AND obs.modifier_cd = ? "; + } + if (factPrimaryKey.getInstanceNum() != null) { + sql += " AND obs.instance_num = ? "; + } + +// log.info("Pre Sql from ObservationFactDAO[" + sql + "]"); + + + int numDerivedTables = 1; + boolean derivedFactTable = QueryProcessorUtil.getInstance().getDerivedFactTable(); + String finalSql = sql; + if(derivedFactTable == true){ + // call ONT to get concept info + DerivedFactColumnsType columns = getFactColumnsFromOntologyCellByCode(factPrimaryKey.getConceptCd()); + + if(columns != null){ + numDerivedTables = columns.getDerivedFactTableColumn().size(); +// log.info("found " +numDerivedTables + " derived tables"); + // parse through solumns and build up replace string. + + Iterator it = columns.getDerivedFactTableColumn().iterator(); + String column = it.next(); +// log.info(column); + if(column.contains(".")) { + int lastIndex = column.lastIndexOf("."); + String tableName = this.getDbSchemaName() + (column.substring(0, lastIndex)); + log.info(tableName); + finalSql = finalSql.replace(defaultTableName, tableName); + } + while(it.hasNext()){ + column = it.next(); + if(column.contains(".")) { + int lastIndex = column.lastIndexOf("."); + String table = this.getDbSchemaName() + (column.substring(0, lastIndex)); + if(table != null) + finalSql += "\n union all \n"; + finalSql += sql.replace(defaultTableName, table); + } + + } + } + } + +// log.info("Generated Sql from ObservationFactDAO[" + finalSql + "]"); + + Connection conn = null; + PreparedStatement stmt = null; + + try { + // get db connection + // conn = getConnection(); + conn = getDataSource().getConnection(); + + // create prepared statement + stmt = conn.prepareStatement(finalSql); + int index = 1; + for (int i=0; i<= numDerivedTables -1; i++){ + stmt.setInt(i+index, Integer.parseInt(factPrimaryKey.getEventId())); + // log.info(i+index + " " + factPrimaryKey.getEventId()); + index++; + stmt.setInt(i+index , Integer.parseInt(factPrimaryKey.getPatientId())); + // log.info(i+index +" " + factPrimaryKey.getPatientId()); + index++; + stmt.setString(i+index, factPrimaryKey.getConceptCd()); + // log.info(i+index + " " + factPrimaryKey.getConceptCd()); + index++; + // if provider id is not null add it to sql parameter + if (factPrimaryKey.getObserverId() != null) { + stmt.setString(i+index, factPrimaryKey.getObserverId()); + // log.info(i+index + " " + factPrimaryKey.getObserverId()); + index++; + } + // if modifier cd is not null add it to sql parameter + if (factPrimaryKey.getModifierCd() != null) { + stmt.setString(i+index, factPrimaryKey.getModifierCd()); + // log.info(i + index +" " + factPrimaryKey.getModifierCd()); + index++; + } + if (factPrimaryKey.getInstanceNum() != null) { + int instanceNum = Integer.parseInt(factPrimaryKey + .getInstanceNum()); + stmt.setInt(i+index, instanceNum); + // log.info(i + index + " " + factPrimaryKey.getInstanceNum()); + index++; + } + + } + + // original (pre-OMOP) code + /* stmt.setInt(1, Integer.parseInt(factPrimaryKey.getEventId())); + stmt.setInt(2, Integer.parseInt(factPrimaryKey.getPatientId())); + stmt.setString(3, factPrimaryKey.getConceptCd()); + + int i = 4; + String providerId = factPrimaryKey.getObserverId(); + + // if provider id is not null add it to sql parameter + if (providerId != null) { + stmt.setString(i, providerId); + i++; + } + + // if modifier cd is not null add it to sql parameter + if (factPrimaryKey.getModifierCd() != null) { + stmt.setString(i, factPrimaryKey.getModifierCd()); + i++; + } + + if (factPrimaryKey.getInstanceNum() != null) { + int instanceNum = Integer.parseInt(factPrimaryKey + .getInstanceNum()); + i++; + stmt.setInt(i, instanceNum); + } + */ + + ResultSet resultSet = stmt.executeQuery(); + ObservationSet obsFactSet = new ObservationSet(); + + I2B2PdoFactory.ObservationFactBuilder observationFactBuilder = new I2B2PdoFactory().new ObservationFactBuilder( + factRelated.isSelectDetail(), factRelated.isSelectBlob(), + factRelated.isSelectStatus(), dataSourceLookup.getServerType()); + while (resultSet.next()) { + ObservationType observationFactType = observationFactBuilder + .buildObservationSet(resultSet); + obsFactSet.getObservation().add(observationFactType); + } + + patientDataType.getObservationSet().add(obsFactSet); + } catch (SQLException sqlEx) { + log.error(sqlEx); + throw new I2B2DAOException("", sqlEx); + } catch (IOException ioEx) { + log.error(ioEx); + throw new I2B2DAOException("", ioEx); + } finally { + try { + JDBCUtil.closeJdbcResource(null, stmt, conn); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + } + } + + return patientDataType; + } + + + + protected DerivedFactColumnsType getFactColumnsFromOntologyCellByCode(String conceptCd) + throws ConceptNotFoundException, OntologyException { + DerivedFactColumnsType factColumns = new DerivedFactColumnsType(); + try { + + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + String ontologyUrl = qpUtil + .getCRCPropertyValue(QueryProcessorUtil.ONTOLOGYCELL_ROOT_WS_URL_PROPERTIES); + + SecurityType securityType = PMServiceAccountUtil + .getServiceSecurityType(dataSourceLookup.getDomainId()); + + factColumns = CallOntologyUtil.callGetFactColumnsByConceptCd(conceptCd, + securityType, dataSourceLookup.getProjectPath(), + ontologyUrl +"/getCodeInfo"); + } catch (JAXBUtilException e) { + + log.error("Error while fetching metadata [" + conceptCd + + "] from ontology ", e); + throw new OntologyException("Error while fetching metadata [" + + conceptCd + "] from ontology " + + StackTraceUtil.getStackTrace(e)); + } catch (I2B2Exception e) { + log.error("Error while fetching metadata from ontology ", e); + throw new OntologyException("Error while fetching metadata [" + + conceptCd + "] from ontology " + + StackTraceUtil.getStackTrace(e)); + } catch (AxisFault e) { + log.error("Error while fetching metadata from ontology ", e); + throw new OntologyException("Error while fetching metadata [" + + conceptCd + "] from ontology " + + StackTraceUtil.getStackTrace(e)); + } catch (XMLStreamException e) { + log.error("Error while fetching metadata from ontology ", e); + throw new OntologyException("Error while fetching metadata [" + + conceptCd + "] from ontology " + + StackTraceUtil.getStackTrace(e)); + } + + return factColumns; + } + + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/PageTotalDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/PageTotalDao.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/PageTotalDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/PageTotalDao.java index 161f2d6f..2d884738 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/PageTotalDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/PageTotalDao.java @@ -1,333 +1,333 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.pdo; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.HashMap; -import java.util.List; - -import javax.sql.DataSource; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.util.db.JDBCUtil; -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.dao.pdo.input.IFactRelatedQueryHandler; -import edu.harvard.i2b2.crc.dao.pdo.input.IInputOptionListHandler; -import edu.harvard.i2b2.crc.dao.pdo.input.SQLServerFactRelatedQueryHandler; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.pdo.query.PanelType; - -public class PageTotalDao extends CRCDAO implements IPageDao { - - private DataSourceLookup dataSourceLookup = null; - - public PageTotalDao(DataSourceLookup dataSourceLookup, DataSource dataSource) { - setDataSource(dataSource); - setDbSchemaName(dataSourceLookup.getFullSchema()); - this.dataSourceLookup = dataSourceLookup; - } - - @Override - public long getTotalForAllPanel(List panelSqlList, - List sqlParamCountList, - IInputOptionListHandler inputOptionListHandler) - throws I2B2DAOException { - - long totalAcrossPanel = 0; - int i = 0, sqlParamCount = 0; - ResultSet resultSet = null; - Connection conn = null; - try { - // get connection - conn = this.getDataSource().getConnection(); - - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER) - && inputOptionListHandler.isEnumerationSet()) { - inputOptionListHandler.uploadEnumerationValueToTempTable(conn); - // sqlserverLoadTempTable(conn, inputOptionListHandler); - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE) - && inputOptionListHandler.isEnumerationSet()) { - inputOptionListHandler.uploadEnumerationValueToTempTable(conn); - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL) - && inputOptionListHandler.isEnumerationSet()) { - inputOptionListHandler.uploadEnumerationValueToTempTable(conn); - // sqlserverLoadTempTable(conn, inputOptionListHandler); - } - long startTime = System.currentTimeMillis(); - - // iterate sql - for (String singlePanelSql : panelSqlList) { - sqlParamCount = sqlParamCountList.get(i++); - resultSet = executeTotalSql(singlePanelSql, conn, - sqlParamCount, inputOptionListHandler); - resultSet.next(); - totalAcrossPanel += resultSet.getLong(1); - } - long endTime = System.currentTimeMillis(); - long totalTime = endTime - startTime; - log.debug("********* Time for the Total Sql ************ " - + totalTime); - } catch (SQLException sqlEx) { - throw new I2B2DAOException("", sqlEx); - } finally { - - try { - inputOptionListHandler.deleteTempTable(conn); - } catch (SQLException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - - // close connection - try { - JDBCUtil.closeJdbcResource(null, null, conn); - } catch (SQLException e) { - log.error("Error trying to close connection", e); - } - } - - return totalAcrossPanel; - } - - @Override - public HashMap getMinIndexAndCountAllPanel(List panelSqlList, - List sqlParamCountList, - IInputOptionListHandler inputOptionListHandler) - throws I2B2DAOException { - - int i = 0, sqlParamCount = 0; - ResultSet resultSet = null; - Connection conn = null; - HashMap minAndTotalMap = new HashMap(); - int minIndex = 0, tempMinIndex = 0; - long minIndexTotal = 0, tempMinIndexTotal = 0; - - try { - // get connection - conn = this.getDataSource().getConnection(); - - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER) - && inputOptionListHandler.isEnumerationSet()) { - // upLoadTempTableForMin(conn, inputOptionListHandler); - // sqlserverLoadTempTable(conn, inputOptionListHandler); - inputOptionListHandler.uploadEnumerationValueToTempTable(conn); - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE) - && inputOptionListHandler.isEnumerationSet()) { - // oracleLoadTempTable(conn, inputOptionListHandler); - inputOptionListHandler.uploadEnumerationValueToTempTable(conn); - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL) - && inputOptionListHandler.isEnumerationSet()) { - // upLoadTempTableForMin(conn, inputOptionListHandler); - // sqlserverLoadTempTable(conn, inputOptionListHandler); - inputOptionListHandler.uploadEnumerationValueToTempTable(conn); - } - - boolean firstTimeFlag = true; - // iterate sql - for (String singlePanelSql : panelSqlList) { - sqlParamCount = sqlParamCountList.get(i++); - resultSet = executeTotalSql(singlePanelSql, conn, - sqlParamCount, inputOptionListHandler); - resultSet.next(); - tempMinIndex = resultSet.getInt(1); - tempMinIndexTotal = resultSet.getLong(2); - if (firstTimeFlag) { - minIndex = tempMinIndex; - minIndexTotal = tempMinIndexTotal; - firstTimeFlag = false; - } else if (minIndexTotal < tempMinIndexTotal) { - minIndex = tempMinIndex; - minIndexTotal = tempMinIndexTotal; - } - } - } catch (SQLException sqlEx) { - throw new I2B2DAOException("", sqlEx); - } finally { - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER)) { - deleteTempTable(conn); - if (inputOptionListHandler.isEnumerationSet()) { - deleteTemp1Table(conn); - } - } - // close connection - try { - JDBCUtil.closeJdbcResource(null, null, conn); - } catch (SQLException e) { - log.error("Error trying to close connection", e); - } - } - - minAndTotalMap.put("MIN_INDEX", minIndex); - minAndTotalMap.put("MIN_INDEX_TOTAL", minIndexTotal); - - return minAndTotalMap; - } - - private ResultSet executeTotalSql(String totalSql, Connection conn, - int sqlParamCount, IInputOptionListHandler inputOptionListHandler) - throws SQLException { - - PreparedStatement stmt = conn.prepareStatement(totalSql); - ResultSet resultSet = null; - - log.debug(totalSql + " [ " + sqlParamCount + " ]"); - if (inputOptionListHandler.isCollectionId()) { - for (int i = 1; i <= sqlParamCount; i++) { - stmt.setInt(i, Integer.parseInt(inputOptionListHandler - .getCollectionId())); - } - } - - resultSet = stmt.executeQuery(); - - return resultSet; - } - - public void sqlserverLoadTempTable(Connection conn, - IInputOptionListHandler inputOptionListHandler) throws SQLException { - // sqlserver - upLoadTempTable(conn, inputOptionListHandler); - - } - - @Override - public String buildTotalSql(IFactRelatedQueryHandler factHandler, - PanelType panel) throws I2B2DAOException { - // call factrelatedhandler to build sql - return factHandler.buildTotalQuery(panel, - PdoQueryHandler.PLAIN_PDO_TYPE); - } - - public void getSelect() { - } - - public void getFrom() { - } - - public void getWhere() { - } - - private void upLoadTempTable(Connection conn, - IInputOptionListHandler inputOptionListHandler) throws SQLException { - List enumList = inputOptionListHandler.getEnumerationList(); - // create temp table - java.sql.Statement tempStmt = conn.createStatement(); - String createTempInputListTable = "create table " - + SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE - + " ( char_param1 varchar(100) )"; - tempStmt.executeUpdate(createTempInputListTable); - // load to temp table - // TempInputListInsert inputListInserter = new - // TempInputListInsert(dataSource,TEMP_PDO_INPUTLIST_TABLE); - // inputListInserter.setBatchSize(100); - int i = 0; - for (String singleValue : enumList) { - tempStmt.addBatch("insert into " - + SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE - + " values ('" + singleValue + "' )"); - i++; - if (i % 100 == 0) { - tempStmt.executeBatch(); - - } - } - tempStmt.executeBatch(); - } - - private void upLoadTempTableForMin(Connection conn, - IInputOptionListHandler inputOptionListHandler) throws SQLException { - List enumList = inputOptionListHandler.getEnumerationList(); - deleteTempTable(conn); - // create temp table - java.sql.Statement tempStmt = conn.createStatement(); - String createTempInputListTable = "create table " - + SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE - + " (set_index int, char_param1 varchar(100) )"; - tempStmt.executeUpdate(createTempInputListTable); - // load to temp table - // TempInputListInsert inputListInserter = new - // TempInputListInsert(dataSource,TEMP_PDO_INPUTLIST_TABLE); - // inputListInserter.setBatchSize(100); - int i = 0, j = 1; - for (String singleValue : enumList) { - tempStmt.addBatch("insert into " - + SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE - + "(set_index,char_param1) values (" + j++ + ",'" - + singleValue + "' )"); - i++; - if (i % 100 == 0) { - tempStmt.executeBatch(); - - } - } - tempStmt.executeBatch(); - } - - private void deleteTempTable(Connection conn) { - - Statement deleteStmt = null; - try { - deleteStmt = conn.createStatement(); - - //conn - // .createStatement() - deleteStmt.executeUpdate( - "drop table " - + SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE); - } catch (SQLException sqle) { - ; - } finally { - try { - if(deleteStmt != null) - deleteStmt.close(); - } catch (SQLException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - } - - private void deleteTemp1Table(Connection conn) { - - Statement deleteStmt = null; - try { - deleteStmt = conn.createStatement(); - // conn - // .createStatement() - deleteStmt.executeUpdate( - "drop table " - + SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE); - } catch (SQLException sqle) { - ; - } finally { - try { - if(deleteStmt != null) - deleteStmt.close(); - } catch (SQLException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.pdo; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.HashMap; +import java.util.List; + +import javax.sql.DataSource; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.util.db.JDBCUtil; +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.dao.pdo.input.IFactRelatedQueryHandler; +import edu.harvard.i2b2.crc.dao.pdo.input.IInputOptionListHandler; +import edu.harvard.i2b2.crc.dao.pdo.input.SQLServerFactRelatedQueryHandler; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.pdo.query.PanelType; + +public class PageTotalDao extends CRCDAO implements IPageDao { + + private DataSourceLookup dataSourceLookup = null; + + public PageTotalDao(DataSourceLookup dataSourceLookup, DataSource dataSource) { + setDataSource(dataSource); + setDbSchemaName(dataSourceLookup.getFullSchema()); + this.dataSourceLookup = dataSourceLookup; + } + + @Override + public long getTotalForAllPanel(List panelSqlList, + List sqlParamCountList, + IInputOptionListHandler inputOptionListHandler) + throws I2B2DAOException { + + long totalAcrossPanel = 0; + int i = 0, sqlParamCount = 0; + ResultSet resultSet = null; + Connection conn = null; + try { + // get connection + conn = this.getDataSource().getConnection(); + + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER) + && inputOptionListHandler.isEnumerationSet()) { + inputOptionListHandler.uploadEnumerationValueToTempTable(conn); + // sqlserverLoadTempTable(conn, inputOptionListHandler); + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.ORACLE) + && inputOptionListHandler.isEnumerationSet()) { + inputOptionListHandler.uploadEnumerationValueToTempTable(conn); + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL) + && inputOptionListHandler.isEnumerationSet()) { + inputOptionListHandler.uploadEnumerationValueToTempTable(conn); + // sqlserverLoadTempTable(conn, inputOptionListHandler); + } + long startTime = System.currentTimeMillis(); + + // iterate sql + for (String singlePanelSql : panelSqlList) { + sqlParamCount = sqlParamCountList.get(i++); + resultSet = executeTotalSql(singlePanelSql, conn, + sqlParamCount, inputOptionListHandler); + resultSet.next(); + totalAcrossPanel += resultSet.getLong(1); + } + long endTime = System.currentTimeMillis(); + long totalTime = endTime - startTime; + log.debug("********* Time for the Total Sql ************ " + + totalTime); + } catch (SQLException sqlEx) { + throw new I2B2DAOException("", sqlEx); + } finally { + + try { + inputOptionListHandler.deleteTempTable(conn); + } catch (SQLException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + + // close connection + try { + JDBCUtil.closeJdbcResource(null, null, conn); + } catch (SQLException e) { + log.error("Error trying to close connection", e); + } + } + + return totalAcrossPanel; + } + + @Override + public HashMap getMinIndexAndCountAllPanel(List panelSqlList, + List sqlParamCountList, + IInputOptionListHandler inputOptionListHandler) + throws I2B2DAOException { + + int i = 0, sqlParamCount = 0; + ResultSet resultSet = null; + Connection conn = null; + HashMap minAndTotalMap = new HashMap(); + int minIndex = 0, tempMinIndex = 0; + long minIndexTotal = 0, tempMinIndexTotal = 0; + + try { + // get connection + conn = this.getDataSource().getConnection(); + + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER) + && inputOptionListHandler.isEnumerationSet()) { + // upLoadTempTableForMin(conn, inputOptionListHandler); + // sqlserverLoadTempTable(conn, inputOptionListHandler); + inputOptionListHandler.uploadEnumerationValueToTempTable(conn); + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.ORACLE) + && inputOptionListHandler.isEnumerationSet()) { + // oracleLoadTempTable(conn, inputOptionListHandler); + inputOptionListHandler.uploadEnumerationValueToTempTable(conn); + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL) + && inputOptionListHandler.isEnumerationSet()) { + // upLoadTempTableForMin(conn, inputOptionListHandler); + // sqlserverLoadTempTable(conn, inputOptionListHandler); + inputOptionListHandler.uploadEnumerationValueToTempTable(conn); + } + + boolean firstTimeFlag = true; + // iterate sql + for (String singlePanelSql : panelSqlList) { + sqlParamCount = sqlParamCountList.get(i++); + resultSet = executeTotalSql(singlePanelSql, conn, + sqlParamCount, inputOptionListHandler); + resultSet.next(); + tempMinIndex = resultSet.getInt(1); + tempMinIndexTotal = resultSet.getLong(2); + if (firstTimeFlag) { + minIndex = tempMinIndex; + minIndexTotal = tempMinIndexTotal; + firstTimeFlag = false; + } else if (minIndexTotal < tempMinIndexTotal) { + minIndex = tempMinIndex; + minIndexTotal = tempMinIndexTotal; + } + } + } catch (SQLException sqlEx) { + throw new I2B2DAOException("", sqlEx); + } finally { + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER)) { + deleteTempTable(conn); + if (inputOptionListHandler.isEnumerationSet()) { + deleteTemp1Table(conn); + } + } + // close connection + try { + JDBCUtil.closeJdbcResource(null, null, conn); + } catch (SQLException e) { + log.error("Error trying to close connection", e); + } + } + + minAndTotalMap.put("MIN_INDEX", minIndex); + minAndTotalMap.put("MIN_INDEX_TOTAL", minIndexTotal); + + return minAndTotalMap; + } + + private ResultSet executeTotalSql(String totalSql, Connection conn, + int sqlParamCount, IInputOptionListHandler inputOptionListHandler) + throws SQLException { + + PreparedStatement stmt = conn.prepareStatement(totalSql); + ResultSet resultSet = null; + + log.debug(totalSql + " [ " + sqlParamCount + " ]"); + if (inputOptionListHandler.isCollectionId()) { + for (int i = 1; i <= sqlParamCount; i++) { + stmt.setInt(i, Integer.parseInt(inputOptionListHandler + .getCollectionId())); + } + } + + resultSet = stmt.executeQuery(); + + return resultSet; + } + + public void sqlserverLoadTempTable(Connection conn, + IInputOptionListHandler inputOptionListHandler) throws SQLException { + // sqlserver + upLoadTempTable(conn, inputOptionListHandler); + + } + + @Override + public String buildTotalSql(IFactRelatedQueryHandler factHandler, + PanelType panel) throws I2B2DAOException { + // call factrelatedhandler to build sql + return factHandler.buildTotalQuery(panel, + PdoQueryHandler.PLAIN_PDO_TYPE); + } + + public void getSelect() { + } + + public void getFrom() { + } + + public void getWhere() { + } + + private void upLoadTempTable(Connection conn, + IInputOptionListHandler inputOptionListHandler) throws SQLException { + List enumList = inputOptionListHandler.getEnumerationList(); + // create temp table + java.sql.Statement tempStmt = conn.createStatement(); + String createTempInputListTable = "create table " + + SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE + + " ( char_param1 varchar(100) )"; + tempStmt.executeUpdate(createTempInputListTable); + // load to temp table + // TempInputListInsert inputListInserter = new + // TempInputListInsert(dataSource,TEMP_PDO_INPUTLIST_TABLE); + // inputListInserter.setBatchSize(100); + int i = 0; + for (String singleValue : enumList) { + tempStmt.addBatch("insert into " + + SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE + + " values ('" + singleValue + "' )"); + i++; + if (i % 100 == 0) { + tempStmt.executeBatch(); + + } + } + tempStmt.executeBatch(); + } + + private void upLoadTempTableForMin(Connection conn, + IInputOptionListHandler inputOptionListHandler) throws SQLException { + List enumList = inputOptionListHandler.getEnumerationList(); + deleteTempTable(conn); + // create temp table + java.sql.Statement tempStmt = conn.createStatement(); + String createTempInputListTable = "create table " + + SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE + + " (set_index int, char_param1 varchar(100) )"; + tempStmt.executeUpdate(createTempInputListTable); + // load to temp table + // TempInputListInsert inputListInserter = new + // TempInputListInsert(dataSource,TEMP_PDO_INPUTLIST_TABLE); + // inputListInserter.setBatchSize(100); + int i = 0, j = 1; + for (String singleValue : enumList) { + tempStmt.addBatch("insert into " + + SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE + + "(set_index,char_param1) values (" + j++ + ",'" + + singleValue + "' )"); + i++; + if (i % 100 == 0) { + tempStmt.executeBatch(); + + } + } + tempStmt.executeBatch(); + } + + private void deleteTempTable(Connection conn) { + + Statement deleteStmt = null; + try { + deleteStmt = conn.createStatement(); + + //conn + // .createStatement() + deleteStmt.executeUpdate( + "drop table " + + SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE); + } catch (SQLException sqle) { + ; + } finally { + try { + if(deleteStmt != null) + deleteStmt.close(); + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + } + + private void deleteTemp1Table(Connection conn) { + + Statement deleteStmt = null; + try { + deleteStmt = conn.createStatement(); + // conn + // .createStatement() + deleteStmt.executeUpdate( + "drop table " + + SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE); + } catch (SQLException sqle) { + ; + } finally { + try { + if(deleteStmt != null) + deleteStmt.close(); + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/ParamTypeValueBuilder.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/ParamTypeValueBuilder.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/ParamTypeValueBuilder.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/ParamTypeValueBuilder.java index 053c2114..b5dfe512 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/ParamTypeValueBuilder.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/ParamTypeValueBuilder.java @@ -1,54 +1,54 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.pdo; - -import java.util.Date; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.List; - -import edu.harvard.i2b2.common.util.jaxb.DTOFactory; -import edu.harvard.i2b2.crc.datavo.pdo.ParamType; - -public class ParamTypeValueBuilder { - private DTOFactory dtoFactory = new DTOFactory(); - - public List buildParamType(ResultSet resultSet, MetadataDao.TableMetaData tableMetaData) { - return null; - } - - public ParamType buildParamType(ParamType metaParamType,String fieldPrefix, String lookupFieldSuffix, ResultSet rowSet) throws SQLException { - ParamType paramType = new ParamType(); - - paramType.setColumn(metaParamType.getColumn()); - paramType.setColumnDescriptor(metaParamType.getColumnDescriptor()); - - if (lookupFieldSuffix != null && !metaParamType.getType().startsWith("defaulted:")) { - paramType.setName(rowSet.getString(metaParamType.getColumn() + lookupFieldSuffix )); - } - if (metaParamType.getType().startsWith("defaulted:")) { - paramType.setType(metaParamType.getType().substring(10)); - } else { - paramType.setType(metaParamType.getType()); - } - //paramType.setValue(rowSet.getString(fieldPrefix + metaParamType.getColumn())); - - if (metaParamType.getType().equalsIgnoreCase("dateTime")) { - Date paramDate = rowSet.getTimestamp(fieldPrefix + metaParamType.getColumn()); - if (paramDate != null) { - paramType.setValue(dtoFactory.getXMLGregorianCalendar(paramDate.getTime()).toXMLFormat()); - } - } else { - paramType.setValue(rowSet.getString(fieldPrefix + metaParamType.getColumn())); - } - - return paramType; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.pdo; + +import java.util.Date; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.List; + +import edu.harvard.i2b2.common.util.jaxb.DTOFactory; +import edu.harvard.i2b2.crc.datavo.pdo.ParamType; + +public class ParamTypeValueBuilder { + private DTOFactory dtoFactory = new DTOFactory(); + + public List buildParamType(ResultSet resultSet, MetadataDao.TableMetaData tableMetaData) { + return null; + } + + public ParamType buildParamType(ParamType metaParamType,String fieldPrefix, String lookupFieldSuffix, ResultSet rowSet) throws SQLException { + ParamType paramType = new ParamType(); + + paramType.setColumn(metaParamType.getColumn()); + paramType.setColumnDescriptor(metaParamType.getColumnDescriptor()); + + if (lookupFieldSuffix != null && !metaParamType.getType().startsWith("defaulted:")) { + paramType.setName(rowSet.getString(metaParamType.getColumn() + lookupFieldSuffix )); + } + if (metaParamType.getType().startsWith("defaulted:")) { + paramType.setType(metaParamType.getType().substring(10)); + } else { + paramType.setType(metaParamType.getType()); + } + //paramType.setValue(rowSet.getString(fieldPrefix + metaParamType.getColumn())); + + if (metaParamType.getType().equalsIgnoreCase("dateTime")) { + Date paramDate = rowSet.getTimestamp(fieldPrefix + metaParamType.getColumn()); + if (paramDate != null) { + paramType.setValue(dtoFactory.getXMLGregorianCalendar(paramDate.getTime()).toXMLFormat()); + } + } else { + paramType.setValue(rowSet.getString(fieldPrefix + metaParamType.getColumn())); + } + + return paramType; + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/PdoQueryConceptDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/PdoQueryConceptDao.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/PdoQueryConceptDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/PdoQueryConceptDao.java index bf7b3538..424f6817 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/PdoQueryConceptDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/PdoQueryConceptDao.java @@ -1,419 +1,419 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao.pdo; - -import java.io.IOException; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.List; - -import javax.sql.DataSource; - -import oracle.sql.ArrayDescriptor; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -//import org.jboss.resource.adapter.jdbc.WrappedConnection; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.util.db.JDBCUtil; -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.dao.pdo.input.FactRelatedQueryHandler; -import edu.harvard.i2b2.crc.dao.pdo.input.IInputOptionListHandler; -import edu.harvard.i2b2.crc.dao.pdo.input.SQLServerFactRelatedQueryHandler; -import edu.harvard.i2b2.crc.dao.pdo.output.ConceptFactRelated; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.pdo.ConceptSet; -import edu.harvard.i2b2.crc.datavo.pdo.ConceptType; -import edu.harvard.i2b2.crc.datavo.pdo.PatientDataType; - -/** - * This class handles Concept dimension query's related to PDO request $Id: - * PdoQueryConceptDao.java,v 1.11 2008/03/19 22:42:08 rk903 Exp $ - * - * @author rkuttan - */ -public class PdoQueryConceptDao extends CRCDAO implements IPdoQueryConceptDao { - - private DataSourceLookup dataSourceLookup = null; - - public PdoQueryConceptDao(DataSourceLookup dataSourceLookup, - DataSource dataSource) { - this.dataSourceLookup = dataSourceLookup; - setDataSource(dataSource); - setDbSchemaName(dataSourceLookup.getFullSchema()); - } - - /** log * */ - protected final Log log = LogFactory.getLog(getClass()); - - /** - * Get concepts detail from concept code list - * - * @param conceptCdList - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return {@link PatientDataType.ConceptDimensionSet} - * @throws I2B2DAOException - */ - @Override - public ConceptSet getConceptByConceptCd(List conceptCdList, - boolean detailFlag, boolean blobFlag, boolean statusFlag) - throws I2B2DAOException { - - ConceptSet conceptDimensionSet = new ConceptSet(); - log.debug("Size of input concept cd list " + conceptCdList.size()); - Connection conn = null; - PreparedStatement query = null; - String tempTableName = ""; - try { - conn = getDataSource().getConnection(); - ConceptFactRelated conceptFactRelated = new ConceptFactRelated( - buildOutputOptionType(detailFlag, blobFlag, statusFlag)); - - String selectClause = conceptFactRelated.getSelectClause(); - String serverType = dataSourceLookup.getServerType(); - if (serverType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { - // get oracle connection from jboss wrapped connection - // Otherwise Jboss wrapped connection fails when using oracle - // Arrays - oracle.jdbc.driver.OracleConnection conn1 =null; - //(oracle.jdbc.driver.OracleConnection) ((WrappedConnection) conn) - // .getUnderlyingConnection(); - String finalSql = "SELECT " - + selectClause - + " FROM " - + getDbSchemaName() - + "concept_dimension concept WHERE concept.concept_cd IN (SELECT * FROM TABLE (?))"; - log.debug("Pdo Concept sql [" + finalSql + "]"); - query = conn1.prepareStatement(finalSql); - - ArrayDescriptor desc = ArrayDescriptor.createDescriptor( - "QT_PDO_QRY_STRING_ARRAY", conn1); - - oracle.sql.ARRAY paramArray = new oracle.sql.ARRAY(desc, conn1, - conceptCdList.toArray(new String[] {})); - query.setArray(1, paramArray); - } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.SQLSERVER) || - serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { - log.debug("creating temp table"); - java.sql.Statement tempStmt = conn.createStatement(); - if (serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) - tempTableName = SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE.substring(1); - else - tempTableName = SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE; - try { - tempStmt.executeUpdate("drop table " + tempTableName); - } catch (SQLException sqlex) { - ; - } - - uploadTempTable(tempStmt, tempTableName, conceptCdList, serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)); - String finalSql = "SELECT " - + selectClause - + " FROM " - + getDbSchemaName() - + "concept_dimension concept WHERE concept.concept_cd IN (select distinct char_param1 FROM " - + tempTableName + ") order by concept_path"; - log.debug("Executing [" + finalSql + "]"); - - query = conn.prepareStatement(finalSql); - - } - ResultSet resultSet = query.executeQuery(); - - I2B2PdoFactory.ConceptBuilder conceptBuilder = new I2B2PdoFactory().new ConceptBuilder( - detailFlag, blobFlag, statusFlag, dataSourceLookup.getServerType()); - while (resultSet.next()) { - ConceptType conceptDimensionType = conceptBuilder - .buildConceptSet(resultSet); - conceptDimensionSet.getConcept().add(conceptDimensionType); - } - - } catch (SQLException sqlEx) { - log.error("", sqlEx); - throw new I2B2DAOException("", sqlEx); - } catch (IOException ioEx) { - log.error("", ioEx); - throw new I2B2DAOException("", ioEx); - } finally { - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER)) { - PdoTempTableUtil tempUtil = new PdoTempTableUtil(); - tempUtil.deleteTempTableSqlServer(conn, tempTableName); - } - try { - JDBCUtil.closeJdbcResource(null, query, conn); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - } - } - return conceptDimensionSet; - } - - /** - * Get concept children by item key - * - * @param itemKey - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return - * @throws I2B2DAOException - */ - @Override - public ConceptSet getChildrentByItemKey(String itemKey, boolean detailFlag, - boolean blobFlag, boolean statusFlag) throws I2B2DAOException { - ConceptSet conceptDimensionSet = new ConceptSet(); - if (itemKey != null) { - if (itemKey.lastIndexOf('\\') == itemKey.length() - 1) { - itemKey = itemKey + "%"; - } else { - log.debug("Adding \\ at the end of the Concept path "); - itemKey = itemKey + "\\%"; - } - } - log.debug("getChildrenByItemKey [" + itemKey + "]"); - Connection conn = null; - PreparedStatement query = null; - try { - conn = getDataSource().getConnection(); - ConceptFactRelated conceptFactRelated = new ConceptFactRelated( - buildOutputOptionType(detailFlag, blobFlag, statusFlag)); - - String selectClause = conceptFactRelated.getSelectClause(); - String serverType = dataSourceLookup.getServerType(); - String finalSql = ""; - if (serverType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { - finalSql = "Select * from (SELECT " - + " RowNum RowNum, " - + selectClause - + " FROM " - + getDbSchemaName() - + "concept_dimension concept WHERE concept_path LIKE ? order by concept_path) "; - - } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.SQLSERVER)) { - finalSql = "Select * from ( SELECT " - + selectClause - + " ROW_NUMBER() OVER (ORDER BY concept_path) AS RowNum" - + " FROM " - + getDbSchemaName() - + "concept_dimension concept WHERE concept_path LIKE ? order by concept_path) "; - - } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { - finalSql = "Select * from ( SELECT " - + selectClause - + " ROW_NUMBER() OVER (ORDER BY concept_path) AS RowNum" - + " FROM " - + getDbSchemaName() - + "concept_dimension concept WHERE concept_path LIKE ? order by concept_path) "; - itemKey = itemKey.replaceAll("\\\\", "\\\\\\\\"); - } - log.debug("Pdo Concept sql [" + finalSql + "]"); - query = conn.prepareStatement(finalSql); - query.setString(1, itemKey); - ResultSet resultSet = query.executeQuery(); - - I2B2PdoFactory.ConceptBuilder conceptBuilder = new I2B2PdoFactory().new ConceptBuilder( - detailFlag, blobFlag, statusFlag, dataSourceLookup.getServerType()); - while (resultSet.next()) { - ConceptType conceptDimensionType = conceptBuilder - .buildConceptSet(resultSet); - conceptDimensionSet.getConcept().add(conceptDimensionType); - } - - } catch (SQLException sqlEx) { - log.error("", sqlEx); - throw new I2B2DAOException("", sqlEx); - } catch (IOException ioEx) { - log.error("", ioEx); - throw new I2B2DAOException("", ioEx); - } finally { - - try { - JDBCUtil.closeJdbcResource(null, query, conn); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - } - } - return conceptDimensionSet; - } - - private void uploadTempTable(Statement tempStmt, String tempTable, - List patientNumList, boolean isPostgresql) throws SQLException { - String createTempInputListTable = "create " - + (isPostgresql ? " temp ": "" ) - + " table " + tempTable - + " ( char_param1 varchar(100) )"; - tempStmt.executeUpdate(createTempInputListTable); - log.debug("created temp table" + tempTable); - PreparedStatement preparedStmt = tempStmt.getConnection() - .prepareStatement("insert into " + tempTable + " values (?)"); - // load to temp table - // TempInputListInsert inputListInserter = new - // TempInputListInsert(dataSource,TEMP_PDO_INPUTLIST_TABLE); - // inputListInserter.setBatchSize(100); - int i = 0; - for (String singleValue : patientNumList) { - preparedStmt.setString(1, singleValue); - preparedStmt.addBatch(); - log.debug("adding batch [" + i + "] " + singleValue); - i++; - if (i % 100 == 0) { - log.debug("batch insert [" + i + "]"); - preparedStmt.executeBatch(); - - } - } - log.debug("batch insert [" + i + "]"); - preparedStmt.executeBatch(); - } - - @Override - public ConceptSet getConceptByFact(List panelSqlList, - List sqlParamCountList, - IInputOptionListHandler inputOptionListHandler, boolean detailFlag, - boolean blobFlag, boolean statusFlag) throws I2B2DAOException { - - ConceptSet conceptSet = new ConceptSet(); - I2B2PdoFactory.ConceptBuilder conceptBuilder = new I2B2PdoFactory().new ConceptBuilder( - detailFlag, blobFlag, statusFlag, dataSourceLookup.getServerType()); - ConceptFactRelated conceptFactRelated = new ConceptFactRelated( - buildOutputOptionType(detailFlag, blobFlag, statusFlag)); - String selectClause = conceptFactRelated.getSelectClause(); - String serverType = dataSourceLookup.getServerType(); - String tempTable = ""; - Connection conn = null; - PreparedStatement query = null; - try { - conn = dataSource.getConnection(); - if (serverType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { - tempTable = FactRelatedQueryHandler.TEMP_FACT_PARAM_TABLE; - } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.SQLSERVER) || - serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { - log.debug("creating temp table"); - java.sql.Statement tempStmt = conn.createStatement(); - if (serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) - tempTable = SQLServerFactRelatedQueryHandler.TEMP_FACT_PARAM_TABLE.substring(1); - else - tempTable = SQLServerFactRelatedQueryHandler.TEMP_FACT_PARAM_TABLE; - try { - tempStmt.executeUpdate("drop table " + tempTable); - } catch (SQLException sqlex) { - ; - } - String createTempInputListTable = "create " - + (serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL) ? " temp ": "" ) - + " table " - + tempTable - + " ( set_index int, char_param1 varchar(500) )"; - - tempStmt.executeUpdate(createTempInputListTable); - log.debug("created temp table" + tempTable); - } - // if the inputlist is enumeration, then upload the enumerated input - // to temp table. - // the uploaded enumerated input will be used in the fact join. - if (inputOptionListHandler.isEnumerationSet()) { - inputOptionListHandler.uploadEnumerationValueToTempTable(conn); - } - String insertSql = ""; - int i = 0; - int sqlParamCount = 0; - ResultSet resultSet = null; - for (String panelSql : panelSqlList) { - insertSql = " insert into " - + tempTable - + "(char_param1) select distinct obs_concept_cd from ( " - + panelSql + ") b"; - - log.debug("Executing SQL [ " + insertSql + "]"); - sqlParamCount = sqlParamCountList.get(i++); - // conn.createStatement().executeUpdate(insertSql); - executeTotalSql(insertSql, conn, sqlParamCount, - inputOptionListHandler); - - } - - String finalSql = "SELECT " - + selectClause - + " FROM " - + getDbSchemaName() - + "concept_dimension concept where concept_cd in (select distinct char_param1 from " - + tempTable + ") order by concept_path"; - log.debug("Executing SQL [" + finalSql + "]"); - - - query = conn.prepareStatement(finalSql); - - resultSet = query.executeQuery(); - - while (resultSet.next()) { - ConceptType concept = conceptBuilder.buildConceptSet(resultSet); - conceptSet.getConcept().add(concept); - } - } catch (SQLException sqlEx) { - log.error("", sqlEx); - throw new I2B2DAOException("sql exception", sqlEx); - } catch (IOException ioEx) { - log.error("", ioEx); - throw new I2B2DAOException("IO exception", ioEx); - } finally { - PdoTempTableUtil tempUtil = new PdoTempTableUtil(); - tempUtil.clearTempTable(dataSourceLookup.getServerType(), conn, tempTable); - - if (inputOptionListHandler != null - && inputOptionListHandler.isEnumerationSet()) { - try { - inputOptionListHandler.deleteTempTable(conn); - } catch (SQLException e) { - - e.printStackTrace(); - } - } - try { - - JDBCUtil.closeJdbcResource(null, query, conn); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - } - } - return conceptSet; - } - - private void executeTotalSql(String totalSql, Connection conn, - int sqlParamCount, IInputOptionListHandler inputOptionListHandler) - throws SQLException { - - PreparedStatement stmt = conn.prepareStatement(totalSql); - - log.debug(totalSql + " [ " + sqlParamCount + " ]"); - if (inputOptionListHandler.isCollectionId()) { - for (int i = 1; i <= sqlParamCount; i++) { - stmt.setInt(i, Integer.parseInt(inputOptionListHandler - .getCollectionId())); - } - } - - stmt.executeUpdate(); - - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao.pdo; + +import java.io.IOException; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.List; + +import javax.sql.DataSource; + +import oracle.sql.ArrayDescriptor; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +//import org.jboss.resource.adapter.jdbc.WrappedConnection; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.util.db.JDBCUtil; +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.dao.pdo.input.FactRelatedQueryHandler; +import edu.harvard.i2b2.crc.dao.pdo.input.IInputOptionListHandler; +import edu.harvard.i2b2.crc.dao.pdo.input.SQLServerFactRelatedQueryHandler; +import edu.harvard.i2b2.crc.dao.pdo.output.ConceptFactRelated; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.pdo.ConceptSet; +import edu.harvard.i2b2.crc.datavo.pdo.ConceptType; +import edu.harvard.i2b2.crc.datavo.pdo.PatientDataType; + +/** + * This class handles Concept dimension query's related to PDO request $Id: + * PdoQueryConceptDao.java,v 1.11 2008/03/19 22:42:08 rk903 Exp $ + * + * @author rkuttan + */ +public class PdoQueryConceptDao extends CRCDAO implements IPdoQueryConceptDao { + + private DataSourceLookup dataSourceLookup = null; + + public PdoQueryConceptDao(DataSourceLookup dataSourceLookup, + DataSource dataSource) { + this.dataSourceLookup = dataSourceLookup; + setDataSource(dataSource); + setDbSchemaName(dataSourceLookup.getFullSchema()); + } + + /** log * */ + protected final Log log = LogFactory.getLog(getClass()); + + /** + * Get concepts detail from concept code list + * + * @param conceptCdList + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return {@link PatientDataType.ConceptDimensionSet} + * @throws I2B2DAOException + */ + @Override + public ConceptSet getConceptByConceptCd(List conceptCdList, + boolean detailFlag, boolean blobFlag, boolean statusFlag) + throws I2B2DAOException { + + ConceptSet conceptDimensionSet = new ConceptSet(); + log.debug("Size of input concept cd list " + conceptCdList.size()); + Connection conn = null; + PreparedStatement query = null; + String tempTableName = ""; + try { + conn = getDataSource().getConnection(); + ConceptFactRelated conceptFactRelated = new ConceptFactRelated( + buildOutputOptionType(detailFlag, blobFlag, statusFlag)); + + String selectClause = conceptFactRelated.getSelectClause(); + String serverType = dataSourceLookup.getServerType(); + if (serverType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { + // get oracle connection from jboss wrapped connection + // Otherwise Jboss wrapped connection fails when using oracle + // Arrays + oracle.jdbc.driver.OracleConnection conn1 =null; + //(oracle.jdbc.driver.OracleConnection) ((WrappedConnection) conn) + // .getUnderlyingConnection(); + String finalSql = "SELECT " + + selectClause + + " FROM " + + getDbSchemaName() + + "concept_dimension concept WHERE concept.concept_cd IN (SELECT * FROM TABLE (?))"; + log.debug("Pdo Concept sql [" + finalSql + "]"); + query = conn1.prepareStatement(finalSql); + + ArrayDescriptor desc = ArrayDescriptor.createDescriptor( + "QT_PDO_QRY_STRING_ARRAY", conn1); + + oracle.sql.ARRAY paramArray = new oracle.sql.ARRAY(desc, conn1, + conceptCdList.toArray(new String[] {})); + query.setArray(1, paramArray); + } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.SQLSERVER) || + serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { + log.debug("creating temp table"); + java.sql.Statement tempStmt = conn.createStatement(); + if (serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) + tempTableName = SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE.substring(1); + else + tempTableName = SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE; + try { + tempStmt.executeUpdate("drop table " + tempTableName); + } catch (SQLException sqlex) { + ; + } + + uploadTempTable(tempStmt, tempTableName, conceptCdList, serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)); + String finalSql = "SELECT " + + selectClause + + " FROM " + + getDbSchemaName() + + "concept_dimension concept WHERE concept.concept_cd IN (select distinct char_param1 FROM " + + tempTableName + ") order by concept_path"; + log.debug("Executing [" + finalSql + "]"); + + query = conn.prepareStatement(finalSql); + + } + ResultSet resultSet = query.executeQuery(); + + I2B2PdoFactory.ConceptBuilder conceptBuilder = new I2B2PdoFactory().new ConceptBuilder( + detailFlag, blobFlag, statusFlag, dataSourceLookup.getServerType()); + while (resultSet.next()) { + ConceptType conceptDimensionType = conceptBuilder + .buildConceptSet(resultSet); + conceptDimensionSet.getConcept().add(conceptDimensionType); + } + + } catch (SQLException sqlEx) { + log.error("", sqlEx); + throw new I2B2DAOException("", sqlEx); + } catch (IOException ioEx) { + log.error("", ioEx); + throw new I2B2DAOException("", ioEx); + } finally { + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER)) { + PdoTempTableUtil tempUtil = new PdoTempTableUtil(); + tempUtil.deleteTempTableSqlServer(conn, tempTableName); + } + try { + JDBCUtil.closeJdbcResource(null, query, conn); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + } + } + return conceptDimensionSet; + } + + /** + * Get concept children by item key + * + * @param itemKey + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return + * @throws I2B2DAOException + */ + @Override + public ConceptSet getChildrentByItemKey(String itemKey, boolean detailFlag, + boolean blobFlag, boolean statusFlag) throws I2B2DAOException { + ConceptSet conceptDimensionSet = new ConceptSet(); + if (itemKey != null) { + if (itemKey.lastIndexOf('\\') == itemKey.length() - 1) { + itemKey = itemKey + "%"; + } else { + log.debug("Adding \\ at the end of the Concept path "); + itemKey = itemKey + "\\%"; + } + } + log.debug("getChildrenByItemKey [" + itemKey + "]"); + Connection conn = null; + PreparedStatement query = null; + try { + conn = getDataSource().getConnection(); + ConceptFactRelated conceptFactRelated = new ConceptFactRelated( + buildOutputOptionType(detailFlag, blobFlag, statusFlag)); + + String selectClause = conceptFactRelated.getSelectClause(); + String serverType = dataSourceLookup.getServerType(); + String finalSql = ""; + if (serverType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { + finalSql = "Select * from (SELECT " + + " RowNum RowNum, " + + selectClause + + " FROM " + + getDbSchemaName() + + "concept_dimension concept WHERE concept_path LIKE ? order by concept_path) "; + + } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.SQLSERVER)) { + finalSql = "Select * from ( SELECT " + + selectClause + + " ROW_NUMBER() OVER (ORDER BY concept_path) AS RowNum" + + " FROM " + + getDbSchemaName() + + "concept_dimension concept WHERE concept_path LIKE ? order by concept_path) "; + + } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { + finalSql = "Select * from ( SELECT " + + selectClause + + " ROW_NUMBER() OVER (ORDER BY concept_path) AS RowNum" + + " FROM " + + getDbSchemaName() + + "concept_dimension concept WHERE concept_path LIKE ? order by concept_path) "; + itemKey = itemKey.replaceAll("\\\\", "\\\\\\\\"); + } + log.debug("Pdo Concept sql [" + finalSql + "]"); + query = conn.prepareStatement(finalSql); + query.setString(1, itemKey); + ResultSet resultSet = query.executeQuery(); + + I2B2PdoFactory.ConceptBuilder conceptBuilder = new I2B2PdoFactory().new ConceptBuilder( + detailFlag, blobFlag, statusFlag, dataSourceLookup.getServerType()); + while (resultSet.next()) { + ConceptType conceptDimensionType = conceptBuilder + .buildConceptSet(resultSet); + conceptDimensionSet.getConcept().add(conceptDimensionType); + } + + } catch (SQLException sqlEx) { + log.error("", sqlEx); + throw new I2B2DAOException("", sqlEx); + } catch (IOException ioEx) { + log.error("", ioEx); + throw new I2B2DAOException("", ioEx); + } finally { + + try { + JDBCUtil.closeJdbcResource(null, query, conn); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + } + } + return conceptDimensionSet; + } + + private void uploadTempTable(Statement tempStmt, String tempTable, + List patientNumList, boolean isPostgresql) throws SQLException { + String createTempInputListTable = "create " + + (isPostgresql ? " temp ": "" ) + + " table " + tempTable + + " ( char_param1 varchar(100) )"; + tempStmt.executeUpdate(createTempInputListTable); + log.debug("created temp table" + tempTable); + PreparedStatement preparedStmt = tempStmt.getConnection() + .prepareStatement("insert into " + tempTable + " values (?)"); + // load to temp table + // TempInputListInsert inputListInserter = new + // TempInputListInsert(dataSource,TEMP_PDO_INPUTLIST_TABLE); + // inputListInserter.setBatchSize(100); + int i = 0; + for (String singleValue : patientNumList) { + preparedStmt.setString(1, singleValue); + preparedStmt.addBatch(); + log.debug("adding batch [" + i + "] " + singleValue); + i++; + if (i % 100 == 0) { + log.debug("batch insert [" + i + "]"); + preparedStmt.executeBatch(); + + } + } + log.debug("batch insert [" + i + "]"); + preparedStmt.executeBatch(); + } + + @Override + public ConceptSet getConceptByFact(List panelSqlList, + List sqlParamCountList, + IInputOptionListHandler inputOptionListHandler, boolean detailFlag, + boolean blobFlag, boolean statusFlag) throws I2B2DAOException { + + ConceptSet conceptSet = new ConceptSet(); + I2B2PdoFactory.ConceptBuilder conceptBuilder = new I2B2PdoFactory().new ConceptBuilder( + detailFlag, blobFlag, statusFlag, dataSourceLookup.getServerType()); + ConceptFactRelated conceptFactRelated = new ConceptFactRelated( + buildOutputOptionType(detailFlag, blobFlag, statusFlag)); + String selectClause = conceptFactRelated.getSelectClause(); + String serverType = dataSourceLookup.getServerType(); + String tempTable = ""; + Connection conn = null; + PreparedStatement query = null; + try { + conn = dataSource.getConnection(); + if (serverType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { + tempTable = FactRelatedQueryHandler.TEMP_FACT_PARAM_TABLE; + } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.SQLSERVER) || + serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { + log.debug("creating temp table"); + java.sql.Statement tempStmt = conn.createStatement(); + if (serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) + tempTable = SQLServerFactRelatedQueryHandler.TEMP_FACT_PARAM_TABLE.substring(1); + else + tempTable = SQLServerFactRelatedQueryHandler.TEMP_FACT_PARAM_TABLE; + try { + tempStmt.executeUpdate("drop table " + tempTable); + } catch (SQLException sqlex) { + ; + } + String createTempInputListTable = "create " + + (serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL) ? " temp ": "" ) + + " table " + + tempTable + + " ( set_index int, char_param1 varchar(500) )"; + + tempStmt.executeUpdate(createTempInputListTable); + log.debug("created temp table" + tempTable); + } + // if the inputlist is enumeration, then upload the enumerated input + // to temp table. + // the uploaded enumerated input will be used in the fact join. + if (inputOptionListHandler.isEnumerationSet()) { + inputOptionListHandler.uploadEnumerationValueToTempTable(conn); + } + String insertSql = ""; + int i = 0; + int sqlParamCount = 0; + ResultSet resultSet = null; + for (String panelSql : panelSqlList) { + insertSql = " insert into " + + tempTable + + "(char_param1) select distinct obs_concept_cd from ( " + + panelSql + ") b"; + + log.debug("Executing SQL [ " + insertSql + "]"); + sqlParamCount = sqlParamCountList.get(i++); + // conn.createStatement().executeUpdate(insertSql); + executeTotalSql(insertSql, conn, sqlParamCount, + inputOptionListHandler); + + } + + String finalSql = "SELECT " + + selectClause + + " FROM " + + getDbSchemaName() + + "concept_dimension concept where concept_cd in (select distinct char_param1 from " + + tempTable + ") order by concept_path"; + log.debug("Executing SQL [" + finalSql + "]"); + + + query = conn.prepareStatement(finalSql); + + resultSet = query.executeQuery(); + + while (resultSet.next()) { + ConceptType concept = conceptBuilder.buildConceptSet(resultSet); + conceptSet.getConcept().add(concept); + } + } catch (SQLException sqlEx) { + log.error("", sqlEx); + throw new I2B2DAOException("sql exception", sqlEx); + } catch (IOException ioEx) { + log.error("", ioEx); + throw new I2B2DAOException("IO exception", ioEx); + } finally { + PdoTempTableUtil tempUtil = new PdoTempTableUtil(); + tempUtil.clearTempTable(dataSourceLookup.getServerType(), conn, tempTable); + + if (inputOptionListHandler != null + && inputOptionListHandler.isEnumerationSet()) { + try { + inputOptionListHandler.deleteTempTable(conn); + } catch (SQLException e) { + + e.printStackTrace(); + } + } + try { + + JDBCUtil.closeJdbcResource(null, query, conn); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + } + } + return conceptSet; + } + + private void executeTotalSql(String totalSql, Connection conn, + int sqlParamCount, IInputOptionListHandler inputOptionListHandler) + throws SQLException { + + PreparedStatement stmt = conn.prepareStatement(totalSql); + + log.debug(totalSql + " [ " + sqlParamCount + " ]"); + if (inputOptionListHandler.isCollectionId()) { + for (int i = 1; i <= sqlParamCount; i++) { + stmt.setInt(i, Integer.parseInt(inputOptionListHandler + .getCollectionId())); + } + } + + stmt.executeUpdate(); + + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/PdoQueryEidDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/PdoQueryEidDao.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/PdoQueryEidDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/PdoQueryEidDao.java index 0d5265a6..75ad0a0d --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/PdoQueryEidDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/PdoQueryEidDao.java @@ -1,623 +1,623 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao.pdo; - -import java.io.IOException; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.List; - -import javax.sql.DataSource; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import oracle.sql.ArrayDescriptor; - -//import org.jboss.resource.adapter.jdbc.WrappedConnection; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.util.db.JDBCUtil; -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.dao.pdo.input.EidListTypeHandler; -import edu.harvard.i2b2.crc.dao.pdo.input.FactRelatedQueryHandler; -import edu.harvard.i2b2.crc.dao.pdo.input.IInputOptionListHandler; -import edu.harvard.i2b2.crc.dao.pdo.input.PatientListTypeHandler; -import edu.harvard.i2b2.crc.dao.pdo.input.SQLServerFactRelatedQueryHandler; -import edu.harvard.i2b2.crc.dao.pdo.output.EidFactRelated; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.pdo.EidSet; -import edu.harvard.i2b2.crc.datavo.pdo.EidType; -import edu.harvard.i2b2.crc.datavo.pdo.query.EidListType; -import edu.harvard.i2b2.crc.datavo.pdo.query.PatientListType; -import edu.harvard.i2b2.crc.datavo.pdo.query.PidListType; -import edu.harvard.i2b2.crc.datavo.pdo.query.PidListType.Pid; -import edu.harvard.i2b2.crc.loader.delegate.LoaderQueryRequestDelegate; - -/** - * Class to build patient section of plain pdo $Id: PdoQueryPatientDao.java,v - * 1.11 2008/03/19 22:42:08 rk903 Exp $ - * - * @author rkuttan - */ -public class PdoQueryEidDao extends CRCDAO implements IPdoQueryEidDao { - - private DataSourceLookup dataSourceLookup = null; - protected static Log logesapi = LogFactory.getLog(PdoQueryEidDao.class); - - public PdoQueryEidDao(DataSourceLookup dataSourceLookup, - DataSource dataSource) { - setDataSource(dataSource); - setDbSchemaName(dataSourceLookup.getFullSchema()); - this.dataSourceLookup = dataSourceLookup; - } - - /** - * Function to return patient dimension data for given list of patient num - * - * @param patientNumList - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return PatientDataType.PatientDimensionSet - * @throws Exception - */ - @Override - public EidSet getEidByEncounterNum(List encounterNumList, - boolean detailFlag, boolean blobFlag, boolean statusFlag) - throws I2B2DAOException { - - Connection conn = null; - PreparedStatement query = null; - EidSet eidSet = new EidSet(); - - try { - // execute fullsql - conn = getDataSource().getConnection(); - EidFactRelated eidRelated = new EidFactRelated( - buildOutputOptionType(detailFlag, blobFlag, statusFlag)); - String selectClause = eidRelated.getSelectClause(); - ResultSet resultSet = null; - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE)) { - - String finalSql = "SELECT " - + selectClause - + " FROM " - + getDbSchemaName() - + "encounter_mapping em WHERE em.encounter_num IN (SELECT * FROM TABLE (cast (? as QT_PDO_QRY_STRING_ARRAY))) order by em_encounter_num"; - log.debug("Executing [" + finalSql + "]"); - - oracle.jdbc.driver.OracleConnection conn1 = null;// (oracle.jdbc.driver.OracleConnection) ((WrappedConnection) conn) - // .getUnderlyingConnection(); - query = conn.prepareStatement(finalSql); - ArrayDescriptor desc = ArrayDescriptor.createDescriptor( - "QT_PDO_QRY_STRING_ARRAY", conn1); - - oracle.sql.ARRAY paramArray = new oracle.sql.ARRAY(desc, conn1, - encounterNumList.toArray(new String[] {})); - query.setArray(1, paramArray); - resultSet = query.executeQuery(); - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER) || dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL) ) { - // create temp table - // load to temp table - // execute sql - log.debug("creating temp table"); - java.sql.Statement tempStmt = conn.createStatement(); - - uploadTempTable(tempStmt, encounterNumList, dataSourceLookup.getServerType().equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)); - String finalSql = "SELECT " - + selectClause - + " FROM " - + getDbSchemaName() - + "encounter_mapping em WHERE em.encounter_num IN (select distinct char_param1 FROM " - + SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE - + ") order by em_encounter_num"; - log.debug("Size of the encounter list " - + encounterNumList.size()); - log.debug("Executing [" + finalSql + "]"); - - query = conn.prepareStatement(finalSql); - resultSet = query.executeQuery(); - } - - RPDRPdoFactory.EidBuilder eidBuilder = new RPDRPdoFactory.EidBuilder( - detailFlag, blobFlag, statusFlag); - eidSet = buildEidSetFromResultSet(resultSet, eidBuilder); - - } catch (SQLException ex) { - log.error("", ex); - throw new I2B2DAOException("sql exception", ex); - } catch (IOException ioex) { - log.error("", ioex); - throw new I2B2DAOException("io exception", ioex); - } catch (Throwable t) { - t.printStackTrace(); - } finally { - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER)) { - deleteTempTable( - conn, - SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE); - } - try { - JDBCUtil.closeJdbcResource(null, query, conn); - - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - } - - } - return eidSet; - } - - /** - * Get Patient dimension data based on patientlist present in input option - * list - * - * @param patientListType - * {@link PatientListType} - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return PatientDataType.PatientDimensionSet - * @throws I2B2DAOException - */ - @Override - public EidSet getEidFromPatientSet(PatientListType patientListType, - boolean detailFlag, boolean blobFlag, boolean statusFlag) - throws I2B2DAOException { - - PatientListTypeHandler patientListTypeHandler = new PatientListTypeHandler( - dataSourceLookup, patientListType); - String inSqlClause = patientListTypeHandler.generateWhereClauseSql(); - - EidFactRelated eidRelated = new EidFactRelated(buildOutputOptionType( - detailFlag, blobFlag, statusFlag)); - String selectClause = eidRelated.getSelectClause(); - String mainSqlString = " SELECT " + selectClause + " FROM " - + getDbSchemaName() + "encounter_mapping em," - + getDbSchemaName() - + "visit_dimension vd WHERE vd.patient_num IN ( "; - mainSqlString += inSqlClause; - mainSqlString += " ) and vd.encounter_num = em.encounter_num order by em_encounter_num \n"; - - EidSet eidSet = new EidSet(); - Connection conn = null; - PreparedStatement preparedStmt = null; - try { - // execute fullsql - conn = getDataSource().getConnection(); - - log.debug("Executing sql[" + mainSqlString + "]"); - - if (patientListTypeHandler.isCollectionId()) { - String patientSetCollectionId = patientListTypeHandler - .getCollectionId(); - preparedStmt = conn.prepareStatement(mainSqlString); - preparedStmt.setString(1, patientSetCollectionId); - - } else if (patientListTypeHandler.isEnumerationSet()) { - String serverType = dataSourceLookup.getServerType(); - patientListTypeHandler.uploadEnumerationValueToTempTable(conn); - preparedStmt = conn.prepareStatement(mainSqlString); - - } else { - preparedStmt = conn.prepareStatement(mainSqlString); - } - ResultSet resultSet = preparedStmt.executeQuery(); - RPDRPdoFactory.EidBuilder pidBuilder = new RPDRPdoFactory.EidBuilder( - detailFlag, blobFlag, statusFlag); - eidSet = buildEidSetFromResultSet(resultSet, pidBuilder); - - } catch (SQLException sqlEx) { - log.error("", sqlEx); - throw new I2B2DAOException("SQLException", sqlEx); - } catch (IOException ioex) { - log.error("", ioex); - throw new I2B2DAOException("io exception", ioex); - } finally { - if (patientListTypeHandler.isEnumerationSet()) { - try { - patientListTypeHandler.deleteTempTable(conn); - } catch (SQLException e) { - - e.printStackTrace(); - } - } - try { - JDBCUtil.closeJdbcResource(null, preparedStmt, conn); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - } - } - return eidSet; - } - - /** - * Function to return patient dimension data for given list of pid list - * - * @param pidList - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return PatientDataType.PatientDimensionSet - * @throws Exception - */ - @Override - public EidSet getEidByEidList(EidListType eidList, boolean detailFlag, - boolean blobFlag, boolean statusFlag) throws I2B2DAOException { - - Connection conn = null; - PreparedStatement query = null; - EidSet eidSet = new EidSet(); - EidListTypeHandler eidListHandler = new EidListTypeHandler( - dataSourceLookup, eidList); - try { - // execute fullsql - conn = getDataSource().getConnection(); - EidFactRelated eidRelated = new EidFactRelated( - buildOutputOptionType(detailFlag, blobFlag, statusFlag)); - String selectClause = eidRelated.getSelectClause(); - - ResultSet resultSet = null; - - // create temp table - // load to temp table - // execute sql - log.debug("creating temp table"); - java.sql.Statement tempStmt = conn.createStatement(); - - eidListHandler.uploadEnumerationValueToTempTable(conn); - String tempTableName = eidListHandler.getTempTableName(); - String finalSql = "SELECT " - + selectClause - + " FROM " - + getDbSchemaName() - + "encounter_mapping em where encounter_num in ( " - + " select encounter_num FROM " - + getDbSchemaName() - + "encounter_mapping em " - + " WHERE exists " - + "(select char_param2 FROM " - + tempTableName - + " where em.encounter_ide = char_param1 and em.encounter_ide_source = char_param2 ) " - + ") order by em_encounter_num"; - log.debug("Executing [" + finalSql + "]"); - - query = conn.prepareStatement(finalSql); - resultSet = query.executeQuery(); - - RPDRPdoFactory.EidBuilder eidBuilder = new RPDRPdoFactory.EidBuilder( - detailFlag, blobFlag, statusFlag); - eidSet = buildEidSetFromResultSet(resultSet, eidBuilder); - - } catch (SQLException ex) { - log.error("", ex); - throw new I2B2DAOException("sql exception", ex); - } catch (IOException ioex) { - log.error("", ioex); - throw new I2B2DAOException("io exception", ioex); - } catch (Throwable t) { - t.printStackTrace(); - } finally { - - try { - eidListHandler.deleteTempTable(conn); - } catch (SQLException e) { - - e.printStackTrace(); - } - - try { - JDBCUtil.closeJdbcResource(null, query, conn); - - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - } - - } - return eidSet; - } - - private EidSet buildEidSetFromResultSet(ResultSet resultSet, - RPDRPdoFactory.EidBuilder eidBuilder) throws SQLException, - IOException { - String prevPatientNum = ""; - EidType eidType = new EidType(); - EidSet eidSet = new EidSet(); - boolean firstFlag = true; - EidType.EventId singleEventId = new EidType.EventId(); - EidType singleEidType = null; - EidType.EventMapId eidMapId = null; - String tempSinglePidType = null; - while (resultSet.next()) { - singleEidType = eidBuilder.buildEidSet(resultSet); - eidMapId = singleEidType.getEventMapId().get(0); - log.debug("Building pidMapId " + eidMapId.getValue() - + " " + singleEidType.getEventId().getValue() + " " - + eidMapId.getSource()); - tempSinglePidType = singleEidType.getEventId().getValue(); - - if (prevPatientNum.equals(singleEidType.getEventId().getValue())) { - if (!eidMapId.getSource().equalsIgnoreCase("hive")) { - eidType.getEventMapId().add(eidMapId); - } - } else { - if (firstFlag) { - if (!eidMapId.getSource().equalsIgnoreCase("hive")) { - eidType.getEventMapId().add(eidMapId); - } - - // pidType.getPatientMapId().add(pidMapId); - firstFlag = false; - } else { - - eidSet.getEid().add(eidType); - singleEventId = new EidType.EventId(); - eidType = new EidType(); - if (!eidMapId.getSource().equalsIgnoreCase("hive")) { - eidType.getEventMapId().add(eidMapId); - } - } - } - if (eidMapId.getSource().equalsIgnoreCase("hive")) { - singleEventId.setSource(eidMapId.getSource()); - singleEventId.setValue(eidMapId.getValue()); - singleEventId.setPatientId(eidMapId.getPatientId()); - singleEventId.setPatientIdSource(eidMapId.getPatientIdSource()); - singleEventId.setSourcesystemCd(eidMapId.getSourcesystemCd()); - singleEventId.setStatus(eidMapId.getStatus()); - singleEventId.setUploadId(eidMapId.getUploadId()); - singleEventId.setUpdateDate(eidMapId.getUpdateDate()); - singleEventId.setImportDate(eidMapId.getImportDate()); - singleEventId.setDownloadDate(eidMapId.getDownloadDate()); - eidType.setEventId(singleEventId); - } - prevPatientNum = tempSinglePidType; - - } - // eidType.setEventId(singleEventId); - if ((eidType.getEventId() != null && eidType.getEventId().getValue() != null) - || (eidType.getEventMapId() != null && eidType.getEventMapId() - .size() > 0)) { - eidSet.getEid().add(eidType); - } - return eidSet; - } - - private void uploadTempTable(Statement tempStmt, List patientNumList, boolean isPostgresql) - throws SQLException { - String createTempInputListTable = "create " - + (isPostgresql ? " temp ": "" ) - + " table " - + SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE - + " ( char_param1 varchar(100) )"; - tempStmt.executeUpdate(createTempInputListTable); - log.debug("created temp table" - + SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE); - // load to temp table - // TempInputListInsert inputListInserter = new - // TempInputListInsert(dataSource,TEMP_PDO_INPUTLIST_TABLE); - // inputListInserter.setBatchSize(100); - int i = 0; - for (String singleValue : patientNumList) { - tempStmt.addBatch("insert into " - + SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE - + " values ('" + singleValue + "' )"); - log.debug("adding batch" + singleValue); - i++; - if (i % 100 == 0) { - log.debug("batch insert"); - tempStmt.executeBatch(); - - } - } - log.debug("batch insert1"); - tempStmt.executeBatch(); - } - - private void deleteTempTable(Connection conn, String tempTableName) { - - Statement deleteStmt = null; - try { - deleteStmt = conn.createStatement(); - //conn.createStatement().executeUpdate("drop table " + tempTableName); - deleteStmt.executeUpdate("drop table " + tempTableName); - - } catch (SQLException sqle) { - ; - } finally { - try { - if(deleteStmt != null) - deleteStmt.close(); - } catch (SQLException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - } - - private void upLoadEidListToTempTable(Connection conn, - String tempTableName, PidListType pidListType) throws SQLException { - - // create temp table - java.sql.Statement tempStmt = conn.createStatement(); - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER)) { - String createTempInputListTable = "create table " - + SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE - + " (set_index int, char_param1 varchar(200), char_param2 varchar(200) )"; - tempStmt.executeUpdate(createTempInputListTable); - } - // load to temp table - // TempInputListInsert inputListInserter = new - // TempInputListInsert(dataSource,TEMP_PDO_INPUTLIST_TABLE); - // inputListInserter.setBatchSize(100); - int i = 0, j = 1; - for (Pid pid : pidListType.getPid()) { - tempStmt.addBatch("insert into " + tempTableName - + "(set_index,char_param1,char_param2) values (" - + pid.getIndex() + ",'" + pid.getSource() + "','" - + pid.getValue() + "')"); - i++; - if (i % 100 == 0) { - tempStmt.executeBatch(); - - } - } - tempStmt.executeBatch(); - } - - @Override - public EidSet getEidByFact(List panelSqlList, - List sqlParamCountList, - IInputOptionListHandler inputOptionListHandler, boolean detailFlag, - boolean blobFlag, boolean statusFlag) throws I2B2DAOException { - EidSet eidSet = new EidSet(); - RPDRPdoFactory.EidBuilder eidBuilder = new RPDRPdoFactory.EidBuilder( - detailFlag, blobFlag, statusFlag); - EidFactRelated eidFactRelated = new EidFactRelated( - buildOutputOptionType(detailFlag, blobFlag, statusFlag)); - String selectClause = eidFactRelated.getSelectClause(); - - String serverType = dataSourceLookup.getServerType(); - String tempTable = ""; - Connection conn = null; - PreparedStatement query = null; - try { - conn = dataSource.getConnection(); - if (serverType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { - tempTable = FactRelatedQueryHandler.TEMP_PARAM_TABLE; - } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.SQLSERVER) || - serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { - log.debug("creating temp table"); - java.sql.Statement tempStmt = conn.createStatement(); - if (serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) - tempTable = SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE.substring(1); - else - tempTable = SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE; - try { - tempStmt.executeUpdate("drop table " + tempTable); - } catch (SQLException sqlex) { - ; - } - String createTempInputListTable = "create table " + tempTable - + " ( set_index int, char_param1 varchar(500) )"; - tempStmt.executeUpdate(createTempInputListTable); - log.debug("created temp table" + tempTable); - } - // if the inputlist is enumeration, then upload the enumerated input - // to temp table. - // the uploaded enumerated input will be used in the fact join. - if (inputOptionListHandler.isEnumerationSet()) { - inputOptionListHandler.uploadEnumerationValueToTempTable(conn); - } - String insertSql = ""; - int i = 0; - int sqlParamCount = 0; - ResultSet resultSet = null; - for (String panelSql : panelSqlList) { - insertSql = " insert into " - + tempTable - + "(char_param1) select distinct obs_encounter_num from ( " - + panelSql + ") b"; - - log.debug("Executing SQL [ " + insertSql + "]"); - sqlParamCount = sqlParamCountList.get(i++); - // conn.createStatement().executeUpdate(insertSql); - executeUpdateSql(insertSql, conn, sqlParamCount, - inputOptionListHandler); - - } - - String finalSql = "SELECT " - + selectClause - + " FROM " - + getDbSchemaName() - + "encounter_mapping em " - + " where encounter_num in (select distinct char_param1 from " - + tempTable + ") order by encounter_num"; - log.debug("Executing SQL [" + finalSql + "]"); - log.debug("Final Sql " + finalSql); - - query = conn.prepareStatement(finalSql); - - resultSet = query.executeQuery(); - - // while (resultSet.next()) { - // EidType eid = eidBuilder.buildEidSet(resultSet); - // eidSet.getEid().add(eid); - // } - eidSet = buildEidSetFromResultSet(resultSet, eidBuilder); - } catch (SQLException sqlEx) { - log.error("", sqlEx); - throw new I2B2DAOException("sql exception", sqlEx); - } catch (IOException ioEx) { - log.error("", ioEx); - throw new I2B2DAOException("IO exception", ioEx); - } finally { - - PdoTempTableUtil tempUtil = new PdoTempTableUtil(); - tempUtil.clearTempTable(dataSourceLookup.getServerType(), conn, tempTable); - - if (inputOptionListHandler != null - && inputOptionListHandler.isEnumerationSet()) { - try { - inputOptionListHandler.deleteTempTable(conn); - } catch (SQLException e) { - - e.printStackTrace(); - } - } - try { - - JDBCUtil.closeJdbcResource(null, query, conn); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - } - } - return eidSet; - - } - - - - private void executeUpdateSql(String totalSql, Connection conn, - int sqlParamCount, IInputOptionListHandler inputOptionListHandler) - throws SQLException { - - PreparedStatement stmt = conn.prepareStatement(totalSql); - - log.debug(totalSql + " [ " + sqlParamCount + " ]"); - if (inputOptionListHandler.isCollectionId()) { - for (int i = 1; i <= sqlParamCount; i++) { - stmt.setInt(i, Integer.parseInt(inputOptionListHandler - .getCollectionId())); - } - } - - int updatedRow = stmt.executeUpdate(); - log.debug("Total encounter num inserted [" + updatedRow + "]"); - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao.pdo; + +import java.io.IOException; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.List; + +import javax.sql.DataSource; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import oracle.sql.ArrayDescriptor; + +//import org.jboss.resource.adapter.jdbc.WrappedConnection; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.util.db.JDBCUtil; +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.dao.pdo.input.EidListTypeHandler; +import edu.harvard.i2b2.crc.dao.pdo.input.FactRelatedQueryHandler; +import edu.harvard.i2b2.crc.dao.pdo.input.IInputOptionListHandler; +import edu.harvard.i2b2.crc.dao.pdo.input.PatientListTypeHandler; +import edu.harvard.i2b2.crc.dao.pdo.input.SQLServerFactRelatedQueryHandler; +import edu.harvard.i2b2.crc.dao.pdo.output.EidFactRelated; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.pdo.EidSet; +import edu.harvard.i2b2.crc.datavo.pdo.EidType; +import edu.harvard.i2b2.crc.datavo.pdo.query.EidListType; +import edu.harvard.i2b2.crc.datavo.pdo.query.PatientListType; +import edu.harvard.i2b2.crc.datavo.pdo.query.PidListType; +import edu.harvard.i2b2.crc.datavo.pdo.query.PidListType.Pid; +import edu.harvard.i2b2.crc.loader.delegate.LoaderQueryRequestDelegate; + +/** + * Class to build patient section of plain pdo $Id: PdoQueryPatientDao.java,v + * 1.11 2008/03/19 22:42:08 rk903 Exp $ + * + * @author rkuttan + */ +public class PdoQueryEidDao extends CRCDAO implements IPdoQueryEidDao { + + private DataSourceLookup dataSourceLookup = null; + protected static Log logesapi = LogFactory.getLog(PdoQueryEidDao.class); + + public PdoQueryEidDao(DataSourceLookup dataSourceLookup, + DataSource dataSource) { + setDataSource(dataSource); + setDbSchemaName(dataSourceLookup.getFullSchema()); + this.dataSourceLookup = dataSourceLookup; + } + + /** + * Function to return patient dimension data for given list of patient num + * + * @param patientNumList + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return PatientDataType.PatientDimensionSet + * @throws Exception + */ + @Override + public EidSet getEidByEncounterNum(List encounterNumList, + boolean detailFlag, boolean blobFlag, boolean statusFlag) + throws I2B2DAOException { + + Connection conn = null; + PreparedStatement query = null; + EidSet eidSet = new EidSet(); + + try { + // execute fullsql + conn = getDataSource().getConnection(); + EidFactRelated eidRelated = new EidFactRelated( + buildOutputOptionType(detailFlag, blobFlag, statusFlag)); + String selectClause = eidRelated.getSelectClause(); + ResultSet resultSet = null; + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.ORACLE)) { + + String finalSql = "SELECT " + + selectClause + + " FROM " + + getDbSchemaName() + + "encounter_mapping em WHERE em.encounter_num IN (SELECT * FROM TABLE (cast (? as QT_PDO_QRY_STRING_ARRAY))) order by em_encounter_num"; + log.debug("Executing [" + finalSql + "]"); + + oracle.jdbc.driver.OracleConnection conn1 = null;// (oracle.jdbc.driver.OracleConnection) ((WrappedConnection) conn) + // .getUnderlyingConnection(); + query = conn.prepareStatement(finalSql); + ArrayDescriptor desc = ArrayDescriptor.createDescriptor( + "QT_PDO_QRY_STRING_ARRAY", conn1); + + oracle.sql.ARRAY paramArray = new oracle.sql.ARRAY(desc, conn1, + encounterNumList.toArray(new String[] {})); + query.setArray(1, paramArray); + resultSet = query.executeQuery(); + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER) || dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL) ) { + // create temp table + // load to temp table + // execute sql + log.debug("creating temp table"); + java.sql.Statement tempStmt = conn.createStatement(); + + uploadTempTable(tempStmt, encounterNumList, dataSourceLookup.getServerType().equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)); + String finalSql = "SELECT " + + selectClause + + " FROM " + + getDbSchemaName() + + "encounter_mapping em WHERE em.encounter_num IN (select distinct char_param1 FROM " + + SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE + + ") order by em_encounter_num"; + log.debug("Size of the encounter list " + + encounterNumList.size()); + log.debug("Executing [" + finalSql + "]"); + + query = conn.prepareStatement(finalSql); + resultSet = query.executeQuery(); + } + + RPDRPdoFactory.EidBuilder eidBuilder = new RPDRPdoFactory.EidBuilder( + detailFlag, blobFlag, statusFlag); + eidSet = buildEidSetFromResultSet(resultSet, eidBuilder); + + } catch (SQLException ex) { + log.error("", ex); + throw new I2B2DAOException("sql exception", ex); + } catch (IOException ioex) { + log.error("", ioex); + throw new I2B2DAOException("io exception", ioex); + } catch (Throwable t) { + t.printStackTrace(); + } finally { + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER)) { + deleteTempTable( + conn, + SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE); + } + try { + JDBCUtil.closeJdbcResource(null, query, conn); + + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + } + + } + return eidSet; + } + + /** + * Get Patient dimension data based on patientlist present in input option + * list + * + * @param patientListType + * {@link PatientListType} + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return PatientDataType.PatientDimensionSet + * @throws I2B2DAOException + */ + @Override + public EidSet getEidFromPatientSet(PatientListType patientListType, + boolean detailFlag, boolean blobFlag, boolean statusFlag) + throws I2B2DAOException { + + PatientListTypeHandler patientListTypeHandler = new PatientListTypeHandler( + dataSourceLookup, patientListType); + String inSqlClause = patientListTypeHandler.generateWhereClauseSql(); + + EidFactRelated eidRelated = new EidFactRelated(buildOutputOptionType( + detailFlag, blobFlag, statusFlag)); + String selectClause = eidRelated.getSelectClause(); + String mainSqlString = " SELECT " + selectClause + " FROM " + + getDbSchemaName() + "encounter_mapping em," + + getDbSchemaName() + + "visit_dimension vd WHERE vd.patient_num IN ( "; + mainSqlString += inSqlClause; + mainSqlString += " ) and vd.encounter_num = em.encounter_num order by em_encounter_num \n"; + + EidSet eidSet = new EidSet(); + Connection conn = null; + PreparedStatement preparedStmt = null; + try { + // execute fullsql + conn = getDataSource().getConnection(); + + log.debug("Executing sql[" + mainSqlString + "]"); + + if (patientListTypeHandler.isCollectionId()) { + String patientSetCollectionId = patientListTypeHandler + .getCollectionId(); + preparedStmt = conn.prepareStatement(mainSqlString); + preparedStmt.setString(1, patientSetCollectionId); + + } else if (patientListTypeHandler.isEnumerationSet()) { + String serverType = dataSourceLookup.getServerType(); + patientListTypeHandler.uploadEnumerationValueToTempTable(conn); + preparedStmt = conn.prepareStatement(mainSqlString); + + } else { + preparedStmt = conn.prepareStatement(mainSqlString); + } + ResultSet resultSet = preparedStmt.executeQuery(); + RPDRPdoFactory.EidBuilder pidBuilder = new RPDRPdoFactory.EidBuilder( + detailFlag, blobFlag, statusFlag); + eidSet = buildEidSetFromResultSet(resultSet, pidBuilder); + + } catch (SQLException sqlEx) { + log.error("", sqlEx); + throw new I2B2DAOException("SQLException", sqlEx); + } catch (IOException ioex) { + log.error("", ioex); + throw new I2B2DAOException("io exception", ioex); + } finally { + if (patientListTypeHandler.isEnumerationSet()) { + try { + patientListTypeHandler.deleteTempTable(conn); + } catch (SQLException e) { + + e.printStackTrace(); + } + } + try { + JDBCUtil.closeJdbcResource(null, preparedStmt, conn); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + } + } + return eidSet; + } + + /** + * Function to return patient dimension data for given list of pid list + * + * @param pidList + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return PatientDataType.PatientDimensionSet + * @throws Exception + */ + @Override + public EidSet getEidByEidList(EidListType eidList, boolean detailFlag, + boolean blobFlag, boolean statusFlag) throws I2B2DAOException { + + Connection conn = null; + PreparedStatement query = null; + EidSet eidSet = new EidSet(); + EidListTypeHandler eidListHandler = new EidListTypeHandler( + dataSourceLookup, eidList); + try { + // execute fullsql + conn = getDataSource().getConnection(); + EidFactRelated eidRelated = new EidFactRelated( + buildOutputOptionType(detailFlag, blobFlag, statusFlag)); + String selectClause = eidRelated.getSelectClause(); + + ResultSet resultSet = null; + + // create temp table + // load to temp table + // execute sql + log.debug("creating temp table"); + java.sql.Statement tempStmt = conn.createStatement(); + + eidListHandler.uploadEnumerationValueToTempTable(conn); + String tempTableName = eidListHandler.getTempTableName(); + String finalSql = "SELECT " + + selectClause + + " FROM " + + getDbSchemaName() + + "encounter_mapping em where encounter_num in ( " + + " select encounter_num FROM " + + getDbSchemaName() + + "encounter_mapping em " + + " WHERE exists " + + "(select char_param2 FROM " + + tempTableName + + " where em.encounter_ide = char_param1 and em.encounter_ide_source = char_param2 ) " + + ") order by em_encounter_num"; + log.debug("Executing [" + finalSql + "]"); + + query = conn.prepareStatement(finalSql); + resultSet = query.executeQuery(); + + RPDRPdoFactory.EidBuilder eidBuilder = new RPDRPdoFactory.EidBuilder( + detailFlag, blobFlag, statusFlag); + eidSet = buildEidSetFromResultSet(resultSet, eidBuilder); + + } catch (SQLException ex) { + log.error("", ex); + throw new I2B2DAOException("sql exception", ex); + } catch (IOException ioex) { + log.error("", ioex); + throw new I2B2DAOException("io exception", ioex); + } catch (Throwable t) { + t.printStackTrace(); + } finally { + + try { + eidListHandler.deleteTempTable(conn); + } catch (SQLException e) { + + e.printStackTrace(); + } + + try { + JDBCUtil.closeJdbcResource(null, query, conn); + + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + } + + } + return eidSet; + } + + private EidSet buildEidSetFromResultSet(ResultSet resultSet, + RPDRPdoFactory.EidBuilder eidBuilder) throws SQLException, + IOException { + String prevPatientNum = ""; + EidType eidType = new EidType(); + EidSet eidSet = new EidSet(); + boolean firstFlag = true; + EidType.EventId singleEventId = new EidType.EventId(); + EidType singleEidType = null; + EidType.EventMapId eidMapId = null; + String tempSinglePidType = null; + while (resultSet.next()) { + singleEidType = eidBuilder.buildEidSet(resultSet); + eidMapId = singleEidType.getEventMapId().get(0); + log.debug("Building pidMapId " + eidMapId.getValue() + + " " + singleEidType.getEventId().getValue() + " " + + eidMapId.getSource()); + tempSinglePidType = singleEidType.getEventId().getValue(); + + if (prevPatientNum.equals(singleEidType.getEventId().getValue())) { + if (!eidMapId.getSource().equalsIgnoreCase("hive")) { + eidType.getEventMapId().add(eidMapId); + } + } else { + if (firstFlag) { + if (!eidMapId.getSource().equalsIgnoreCase("hive")) { + eidType.getEventMapId().add(eidMapId); + } + + // pidType.getPatientMapId().add(pidMapId); + firstFlag = false; + } else { + + eidSet.getEid().add(eidType); + singleEventId = new EidType.EventId(); + eidType = new EidType(); + if (!eidMapId.getSource().equalsIgnoreCase("hive")) { + eidType.getEventMapId().add(eidMapId); + } + } + } + if (eidMapId.getSource().equalsIgnoreCase("hive")) { + singleEventId.setSource(eidMapId.getSource()); + singleEventId.setValue(eidMapId.getValue()); + singleEventId.setPatientId(eidMapId.getPatientId()); + singleEventId.setPatientIdSource(eidMapId.getPatientIdSource()); + singleEventId.setSourcesystemCd(eidMapId.getSourcesystemCd()); + singleEventId.setStatus(eidMapId.getStatus()); + singleEventId.setUploadId(eidMapId.getUploadId()); + singleEventId.setUpdateDate(eidMapId.getUpdateDate()); + singleEventId.setImportDate(eidMapId.getImportDate()); + singleEventId.setDownloadDate(eidMapId.getDownloadDate()); + eidType.setEventId(singleEventId); + } + prevPatientNum = tempSinglePidType; + + } + // eidType.setEventId(singleEventId); + if ((eidType.getEventId() != null && eidType.getEventId().getValue() != null) + || (eidType.getEventMapId() != null && eidType.getEventMapId() + .size() > 0)) { + eidSet.getEid().add(eidType); + } + return eidSet; + } + + private void uploadTempTable(Statement tempStmt, List patientNumList, boolean isPostgresql) + throws SQLException { + String createTempInputListTable = "create " + + (isPostgresql ? " temp ": "" ) + + " table " + + SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE + + " ( char_param1 varchar(100) )"; + tempStmt.executeUpdate(createTempInputListTable); + log.debug("created temp table" + + SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE); + // load to temp table + // TempInputListInsert inputListInserter = new + // TempInputListInsert(dataSource,TEMP_PDO_INPUTLIST_TABLE); + // inputListInserter.setBatchSize(100); + int i = 0; + for (String singleValue : patientNumList) { + tempStmt.addBatch("insert into " + + SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE + + " values ('" + singleValue + "' )"); + log.debug("adding batch" + singleValue); + i++; + if (i % 100 == 0) { + log.debug("batch insert"); + tempStmt.executeBatch(); + + } + } + log.debug("batch insert1"); + tempStmt.executeBatch(); + } + + private void deleteTempTable(Connection conn, String tempTableName) { + + Statement deleteStmt = null; + try { + deleteStmt = conn.createStatement(); + //conn.createStatement().executeUpdate("drop table " + tempTableName); + deleteStmt.executeUpdate("drop table " + tempTableName); + + } catch (SQLException sqle) { + ; + } finally { + try { + if(deleteStmt != null) + deleteStmt.close(); + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + } + + private void upLoadEidListToTempTable(Connection conn, + String tempTableName, PidListType pidListType) throws SQLException { + + // create temp table + java.sql.Statement tempStmt = conn.createStatement(); + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER)) { + String createTempInputListTable = "create table " + + SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE + + " (set_index int, char_param1 varchar(200), char_param2 varchar(200) )"; + tempStmt.executeUpdate(createTempInputListTable); + } + // load to temp table + // TempInputListInsert inputListInserter = new + // TempInputListInsert(dataSource,TEMP_PDO_INPUTLIST_TABLE); + // inputListInserter.setBatchSize(100); + int i = 0, j = 1; + for (Pid pid : pidListType.getPid()) { + tempStmt.addBatch("insert into " + tempTableName + + "(set_index,char_param1,char_param2) values (" + + pid.getIndex() + ",'" + pid.getSource() + "','" + + pid.getValue() + "')"); + i++; + if (i % 100 == 0) { + tempStmt.executeBatch(); + + } + } + tempStmt.executeBatch(); + } + + @Override + public EidSet getEidByFact(List panelSqlList, + List sqlParamCountList, + IInputOptionListHandler inputOptionListHandler, boolean detailFlag, + boolean blobFlag, boolean statusFlag) throws I2B2DAOException { + EidSet eidSet = new EidSet(); + RPDRPdoFactory.EidBuilder eidBuilder = new RPDRPdoFactory.EidBuilder( + detailFlag, blobFlag, statusFlag); + EidFactRelated eidFactRelated = new EidFactRelated( + buildOutputOptionType(detailFlag, blobFlag, statusFlag)); + String selectClause = eidFactRelated.getSelectClause(); + + String serverType = dataSourceLookup.getServerType(); + String tempTable = ""; + Connection conn = null; + PreparedStatement query = null; + try { + conn = dataSource.getConnection(); + if (serverType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { + tempTable = FactRelatedQueryHandler.TEMP_PARAM_TABLE; + } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.SQLSERVER) || + serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { + log.debug("creating temp table"); + java.sql.Statement tempStmt = conn.createStatement(); + if (serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) + tempTable = SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE.substring(1); + else + tempTable = SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE; + try { + tempStmt.executeUpdate("drop table " + tempTable); + } catch (SQLException sqlex) { + ; + } + String createTempInputListTable = "create table " + tempTable + + " ( set_index int, char_param1 varchar(500) )"; + tempStmt.executeUpdate(createTempInputListTable); + log.debug("created temp table" + tempTable); + } + // if the inputlist is enumeration, then upload the enumerated input + // to temp table. + // the uploaded enumerated input will be used in the fact join. + if (inputOptionListHandler.isEnumerationSet()) { + inputOptionListHandler.uploadEnumerationValueToTempTable(conn); + } + String insertSql = ""; + int i = 0; + int sqlParamCount = 0; + ResultSet resultSet = null; + for (String panelSql : panelSqlList) { + insertSql = " insert into " + + tempTable + + "(char_param1) select distinct obs_encounter_num from ( " + + panelSql + ") b"; + + log.debug("Executing SQL [ " + insertSql + "]"); + sqlParamCount = sqlParamCountList.get(i++); + // conn.createStatement().executeUpdate(insertSql); + executeUpdateSql(insertSql, conn, sqlParamCount, + inputOptionListHandler); + + } + + String finalSql = "SELECT " + + selectClause + + " FROM " + + getDbSchemaName() + + "encounter_mapping em " + + " where encounter_num in (select distinct char_param1 from " + + tempTable + ") order by encounter_num"; + log.debug("Executing SQL [" + finalSql + "]"); + log.debug("Final Sql " + finalSql); + + query = conn.prepareStatement(finalSql); + + resultSet = query.executeQuery(); + + // while (resultSet.next()) { + // EidType eid = eidBuilder.buildEidSet(resultSet); + // eidSet.getEid().add(eid); + // } + eidSet = buildEidSetFromResultSet(resultSet, eidBuilder); + } catch (SQLException sqlEx) { + log.error("", sqlEx); + throw new I2B2DAOException("sql exception", sqlEx); + } catch (IOException ioEx) { + log.error("", ioEx); + throw new I2B2DAOException("IO exception", ioEx); + } finally { + + PdoTempTableUtil tempUtil = new PdoTempTableUtil(); + tempUtil.clearTempTable(dataSourceLookup.getServerType(), conn, tempTable); + + if (inputOptionListHandler != null + && inputOptionListHandler.isEnumerationSet()) { + try { + inputOptionListHandler.deleteTempTable(conn); + } catch (SQLException e) { + + e.printStackTrace(); + } + } + try { + + JDBCUtil.closeJdbcResource(null, query, conn); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + } + } + return eidSet; + + } + + + + private void executeUpdateSql(String totalSql, Connection conn, + int sqlParamCount, IInputOptionListHandler inputOptionListHandler) + throws SQLException { + + PreparedStatement stmt = conn.prepareStatement(totalSql); + + log.debug(totalSql + " [ " + sqlParamCount + " ]"); + if (inputOptionListHandler.isCollectionId()) { + for (int i = 1; i <= sqlParamCount; i++) { + stmt.setInt(i, Integer.parseInt(inputOptionListHandler + .getCollectionId())); + } + } + + int updatedRow = stmt.executeUpdate(); + log.debug("Total encounter num inserted [" + updatedRow + "]"); + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/PdoQueryHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/PdoQueryHandler.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/PdoQueryHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/PdoQueryHandler.java index ca029b75..f304cd05 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/PdoQueryHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/PdoQueryHandler.java @@ -1,1075 +1,1075 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao.pdo; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.dao.PatientDataDAOFactory; -import edu.harvard.i2b2.crc.dao.pdo.input.FactRelatedQueryHandler; -import edu.harvard.i2b2.crc.dao.pdo.input.IFactRelatedQueryHandler; -import edu.harvard.i2b2.crc.dao.pdo.input.IInputOptionListHandler; -import edu.harvard.i2b2.crc.dao.pdo.input.PDOFactory; -import edu.harvard.i2b2.crc.dao.pdo.input.SQLServerFactRelatedQueryHandler; -import edu.harvard.i2b2.crc.dao.pdo.output.ConceptFactRelated; -import edu.harvard.i2b2.crc.dao.pdo.output.EidFactRelated; -import edu.harvard.i2b2.crc.dao.pdo.output.ModifierFactRelated; -import edu.harvard.i2b2.crc.dao.pdo.output.ObservationFactFactRelated; -import edu.harvard.i2b2.crc.dao.pdo.output.PatientFactRelated; -import edu.harvard.i2b2.crc.dao.pdo.output.PidFactRelated; -import edu.harvard.i2b2.crc.dao.pdo.output.ProviderFactRelated; -import edu.harvard.i2b2.crc.dao.pdo.output.VisitFactRelated; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.ontology.XmlValueType; -import edu.harvard.i2b2.crc.datavo.pdo.ConceptSet; -import edu.harvard.i2b2.crc.datavo.pdo.EidSet; -import edu.harvard.i2b2.crc.datavo.pdo.EventSet; -import edu.harvard.i2b2.crc.datavo.pdo.ModifierSet; -import edu.harvard.i2b2.crc.datavo.pdo.ObservationSet; -import edu.harvard.i2b2.crc.datavo.pdo.ObserverSet; -import edu.harvard.i2b2.crc.datavo.pdo.ParamType; -import edu.harvard.i2b2.crc.datavo.pdo.PatientDataType; -import edu.harvard.i2b2.crc.datavo.pdo.PatientSet; -import edu.harvard.i2b2.crc.datavo.pdo.PidSet; -import edu.harvard.i2b2.crc.datavo.pdo.query.EidListType; -import edu.harvard.i2b2.crc.datavo.pdo.query.EventListType; -import edu.harvard.i2b2.crc.datavo.pdo.query.FilterListType; -import edu.harvard.i2b2.crc.datavo.pdo.query.InputOptionListType; -import edu.harvard.i2b2.crc.datavo.pdo.query.OutputOptionListType; -import edu.harvard.i2b2.crc.datavo.pdo.query.PanelType; -import edu.harvard.i2b2.crc.datavo.pdo.query.PatientListType; -import edu.harvard.i2b2.crc.datavo.pdo.query.PidListType; -import edu.harvard.i2b2.crc.datavo.pdo.query.PidListType.Pid; - -/** - * Main class for PDO queries. - * - *

    - * The is the main class to handle pdo query's. It reads input,filter and output - * option list from pdo request and delegate to following class to build - * individual PDO sections. - * - * Observation Fact = {@link FactRelatedQueryHandler} PatientSet = {@list - * PatientSection} ObservationSet ={@list ObservationSection} ObserverSet = - * {@list ObserverSection} ConceptSet = {@list ConceptSection} - * - *

    - * Sample PDO request sections: - *

    - * Input list: - * 184 - * - * - *

    - * Filter list: \i2b2\Diagnoses\ - * - * - *

    - * Output Option List: - * $Id: PdoQueryHandler.java,v 1.12 2008/07/21 19:53:40 - * rk903 Exp $ - * - * @author rkuttan - * @see FactRelatedQueryHandler - * @see PatientFactRelated - * @see ProviderFactRelated - * @see VisitFactRelated - * @see ObservationFactFactRelated - */ -public class PdoQueryHandler { - /** logger **/ - protected final Log log = LogFactory.getLog(getClass()); - - /** Table pdo type value used internally **/ - public static final String TABLE_PDO_TYPE = "TABLE_PDO_TYPE"; - /** Plain pdo type value used internally **/ - public static final String PLAIN_PDO_TYPE = "PLAIN_PDO_TYPE"; - /** PDO request input list **/ - private InputOptionListType inputList = null; - /** PDO request input list before paging **/ - private InputOptionListType origInputList = null; - /** PDO request filter list **/ - private FilterListType filterList = null; - /** PDO output option list **/ - private OutputOptionListType outputOptionList = null; - /** Observation helper to build observation section in pdo **/ - private VisitFactRelated visitFactRelated = null; - /** Observer helper class to build Observer section in pdo **/ - private ProviderFactRelated providerFactRelated = null; - /** Patient helper class to build patient section in pdo **/ - private PatientFactRelated patientFactRelated = null; - /** Concept helper class to build concept section in pdo **/ - private ConceptFactRelated conceptFactRelated = null; - /** Modifier helper class to build concept section in pdo **/ - private ModifierFactRelated modifierFactRelated = null; - /** Observation fact helper class to build observationfact **/ - private ObservationFactFactRelated obsFactFactRelated = null; - private PidFactRelated pidFactRelated = null; - private EidFactRelated eidFactRelated = null; - /** instance variable for pdo type **/ - private String pdoType = null; - /** instance variable to hold plain pdo **/ - private PatientDataType plainPdoType = null; - /** instance variable to hold table pdo **/ - private PatientDataType tablePdoType = null; - - private PatientDataDAOFactory pdoDaoFactory = null; - - private Map projectParamMap = null; - private Map modifierMetadataXmlMap = null; - private String requestVersion = ""; - private List patientMetaDataParamType = null, visitMetaDataParamType = null; - - - - /** - * Parameter constructor to initialize helper classes - * - * @param pdoType - * @param inputList - * @param filterList - * @param outputOptionList - * @throws I2B2Exception - */ - public PdoQueryHandler(PatientDataDAOFactory pdoDaoFactory, String pdoType, - InputOptionListType origInputList, InputOptionListType inputList, - FilterListType filterList, OutputOptionListType outputOptionList) - throws I2B2DAOException { - if (pdoType == null) { - throw new I2B2DAOException("Input pdoType should not be null"); - } - - if (!(pdoType.equalsIgnoreCase(PLAIN_PDO_TYPE) || pdoType - .equalsIgnoreCase(TABLE_PDO_TYPE))) { - throw new I2B2DAOException("Invalid pdoType : " + pdoType); - } - - if (outputOptionList == null) { - throw new I2B2DAOException( - "Input output option list should not be null"); - } - - - this.pdoDaoFactory = pdoDaoFactory; - this.pdoType = pdoType; - this.origInputList = origInputList; - this.inputList = inputList; - this.filterList = filterList; - this.outputOptionList = outputOptionList; - - visitFactRelated = new VisitFactRelated(outputOptionList.getEventSet()); - providerFactRelated = new ProviderFactRelated(outputOptionList - .getObserverSetUsingFilterList()); - patientFactRelated = new PatientFactRelated(outputOptionList - .getPatientSet()); - conceptFactRelated = new ConceptFactRelated(outputOptionList - .getConceptSetUsingFilterList()); - modifierFactRelated = new ModifierFactRelated(outputOptionList - .getModifierSetUsingFilterList()); - obsFactFactRelated = new ObservationFactFactRelated(outputOptionList - .getObservationSet()); - pidFactRelated = new PidFactRelated(outputOptionList.getPidSet()); - eidFactRelated = new EidFactRelated(outputOptionList.getEidSet()); - - } - - public void setProjectParamMap(Map projectParamMap) { - this.projectParamMap = projectParamMap; - } - - public void setModifierMetadataXmlMap(Map modifierMetadataXmlMap) { - this.modifierMetadataXmlMap = modifierMetadataXmlMap; - } - - public void setRequestVersion(String requestVersion) { - this.requestVersion = requestVersion; - } - - public void setDimensionMetaDataParamList(List patientMetaDataParamType, List visitMetaDataParamType) { - this.patientMetaDataParamType = patientMetaDataParamType; - this.visitMetaDataParamType = visitMetaDataParamType; - - } - - /** - * Method to find if input list is pid set - * - * @return boolean - */ - public boolean isGetPDOFromPIDSet() { - if (inputList.getPidList() != null) { - return true; - } else { - return false; - } - } - - /** - * Method to find if input list is patient set - * - * @return boolean - */ - public boolean isGetPDOFromPatientSet() { - if (inputList.getPatientList() != null) { - return true; - } else { - return false; - } - } - - /** - * Method to find if input list is visit set - * - * @return boolean - */ - public boolean isGetPDOFromVisitSet() { - if (inputList.getEventList() != null) { - return true; - } else { - return false; - } - } - - /** - * Method to find if input list is pid set - * - * @return boolean - */ - public boolean isGetPDOFromPidSet() { - if (inputList.getPidList() != null) { - return true; - } else { - return false; - } - } - - /** - * Method to find if input list is eid set - * - * @return boolean - */ - public boolean isGetPDOFromEidSet() { - if (inputList.getEidList() != null) { - return true; - } else { - return false; - } - } - - /** - * Returns TablePDO - * - * @return TablePatientDataType - */ - public PatientDataType getTablePdo() { - return tablePdoType; - } - - /** - * Returns PlainPDO - * - * @return PatientDataType - */ - public PatientDataType getPlainPdo() { - return plainPdoType; - } - - - /** - * - * @throws Exception - */ - public void processPDORequest() throws Exception { - tablePdoType = new PatientDataType(); - plainPdoType = new PatientDataType(); - - // check if obsrvation_fact tag present - boolean obsFactSelected = obsFactFactRelated.isSelected(); - - // check if provider or concept present - boolean providerSelected = providerFactRelated.isSelected(); - boolean conceptSelected = conceptFactRelated.isSelected(); - boolean modifierSelected = modifierFactRelated.isSelected(); - - // check if patient present - boolean patientSelected = patientFactRelated.isSelected(); - - // check if visit present - boolean visitSelected = visitFactRelated.isSelected(); - boolean pidSelected = pidFactRelated.isSelected(); - boolean eidSelected = eidFactRelated.isSelected(); - - boolean patientFromFact = patientFactRelated.isFactRelated(); - boolean visitFromFact = visitFactRelated.isFactRelated(); - boolean pidFromFact = pidFactRelated.isFactRelated(); - boolean eidFromFact = eidFactRelated.isFactRelated(); - - IFactRelatedQueryHandler factRelatedQry = null; - - // PatientDataType patientDataType = new PatientDataType(); - - // check if this is a fact related query - if (obsFactSelected || providerSelected || conceptSelected - || patientFromFact || visitFromFact || pidFromFact - || eidFromFact || modifierSelected) { - - DataSourceLookup dataSourceLookup = pdoDaoFactory - .getDataSourceLookup(); - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE) || - dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) { - factRelatedQry = new FactRelatedQueryHandler(pdoDaoFactory - .getDataSourceLookup(), inputList, filterList, - outputOptionList); - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER)) { - factRelatedQry = new SQLServerFactRelatedQueryHandler( - pdoDaoFactory.getDataSourceLookup(), inputList, - filterList, outputOptionList); - } - //set project param map - factRelatedQry.setProjectParamMap(this.projectParamMap); - factRelatedQry.setModifierMetadataXmlMap(modifierMetadataXmlMap); - factRelatedQry.setRequestVersion(this.requestVersion); - - // execute query - if (pdoType.equalsIgnoreCase(TABLE_PDO_TYPE)) { - List tableObservationSet = factRelatedQry - .getTablePdoObservationFact(); - if (obsFactSelected) { - tablePdoType.getObservationSet() - .addAll(tableObservationSet); - } - } else { - List plainPdoObservationSet = factRelatedQry - .getPdoObservationFact(); - - if (obsFactSelected) { - plainPdoType.getObservationSet().addAll( - plainPdoObservationSet); - } - } - } - - // check if observer section is specified in outputoption - if (providerSelected) { - ProviderSection providerSection = new ProviderSection(pdoType, - factRelatedQry); - providerSection.generateSet(); - - if (pdoType.equalsIgnoreCase(TABLE_PDO_TYPE)) { - tablePdoType.setObserverSet(providerSection - .getTableProviderSet()); - } else { - plainPdoType.setObserverSet(providerSection - .getPlainProviderSet()); - } - } - - // check if concept section is specified in outputoption - if (conceptSelected) { - ConceptSection cs = new ConceptSection(pdoType, factRelatedQry); - cs.generateSet(); - - if (pdoType.equalsIgnoreCase(TABLE_PDO_TYPE)) { - tablePdoType.setConceptSet(cs.getTableConceptSet()); - } else { - plainPdoType.setConceptSet(cs.getPlainConceptSet()); - } - } - - // check if modifier section is specified in outputoption - if (modifierSelected) { - ModifierSection ms = new ModifierSection(pdoType, factRelatedQry); - ms.generateSet(); - - if (pdoType.equalsIgnoreCase(TABLE_PDO_TYPE)) { - tablePdoType.setModifierSet(ms.getTableModifierSet()); - } else { - plainPdoType.setModifierSet(ms.getPlainModifierSet()); - } - } - - // check if patient section is specified in outputoption - if (patientSelected) { - PatientSection ps = new PatientSection(pdoType, factRelatedQry, - patientFromFact, isGetPDOFromVisitSet(), - isGetPDOFromPatientSet(), isGetPDOFromPIDSet(), patientMetaDataParamType); - ps.generateSet(); - - if (pdoType.equalsIgnoreCase(TABLE_PDO_TYPE)) { - tablePdoType.setPatientSet(ps.getTablePatientSet()); - } else { - plainPdoType.setPatientSet(ps.getPlainPatientSet()); - } - } - - // check if observation section is specified in outputoption - if (visitSelected) { - VisitSection vs = new VisitSection(pdoType, factRelatedQry, - visitFromFact, isGetPDOFromVisitSet(), - isGetPDOFromPatientSet(),visitMetaDataParamType); - vs.generateSet(); - - if (pdoType.equalsIgnoreCase(TABLE_PDO_TYPE)) { - tablePdoType.setEventSet(vs.getTableEventSet()); - } else { - plainPdoType.setEventSet(vs.getPlainVisitSet()); - } - } - - // check if pid section is specified in outputoption - if (pidSelected) { - PidSection pids = new PidSection(pdoType, factRelatedQry, - pidFromFact, isGetPDOFromPatientSet(), isGetPDOFromPidSet()); - pids.generateSet(); - if (pdoType.equalsIgnoreCase(TABLE_PDO_TYPE)) { - tablePdoType.setPidSet(pids.getPidSet()); - } else { - plainPdoType.setPidSet(pids.getPidSet()); - } - } - - // check if eid section is specified in outputoption - if (eidSelected) { - EidSection eids = new EidSection(pdoType, factRelatedQry, - eidFromFact, isGetPDOFromPatientSet(), isGetPDOFromEidSet()); - eids.generateSet(); - if (pdoType.equalsIgnoreCase(TABLE_PDO_TYPE)) { - tablePdoType.setEidSet(eids.getEidSet()); - } else { - plainPdoType.setEidSet(eids.getEidSet()); - - } - } - - } - - private class EidSection { - IFactRelatedQueryHandler factRelatedQry = null; - EidSet eidSet = null; - String pType = null; - boolean pidFromFact = false; - boolean fromPatientSet = false; - boolean fromEidSet = false; - - // TODO , boolean fromPidSet - public EidSection(String pType, - IFactRelatedQueryHandler factRelatedQry, boolean pidFromFact, - boolean fromPatientSet, boolean fromEidSet) { - this.factRelatedQry = factRelatedQry; - this.pType = pType; - this.pidFromFact = pidFromFact; - this.fromPatientSet = fromPatientSet; - this.fromEidSet = fromEidSet; - } - - /** - * - * @throws I2B2Exception - */ - public void generateSet() throws I2B2Exception { - // check if provider selected - IPdoQueryEidDao eidDao = pdoDaoFactory.getPdoQueryEidDAO(); - - boolean detailFlag = pidFactRelated.isSelectDetail(); - boolean blobFlag = pidFactRelated.isSelectBlob(); - boolean statusFlag = pidFactRelated.isSelectStatus(); - if (pidFromFact) { - List encounterNumFactList = factRelatedQry - .getVisitFactList(); - List panelSqlList = factRelatedQry.getPanelSqlList(); - - String panelSql = null; - - List sqlParamCountList = new ArrayList(); - for (PanelType panel : filterList.getPanel()) { - - int sqlParamCount = panel.getItem().size(); - if (panel.getInvert() == 1) { - sqlParamCount++; - } - sqlParamCountList.add(sqlParamCount); - - } - IInputOptionListHandler inputOptionListHandler = PDOFactory - .buildInputListHandler(inputList, pdoDaoFactory - .getDataSourceLookup()); - - eidSet = eidDao.getEidByFact(panelSqlList, sqlParamCountList, - inputOptionListHandler, detailFlag, blobFlag, - statusFlag); - - } else if (fromPatientSet) { - PatientListType patientListType = inputList.getPatientList(); - eidSet = eidDao.getEidFromPatientSet(patientListType, - detailFlag, blobFlag, statusFlag); - } else if (fromEidSet) { - EidListType eidListType = inputList.getEidList(); - eidSet = eidDao.getEidByEidList(eidListType, detailFlag, - blobFlag, statusFlag); - } - - } - - public EidSet getEidSet() { - return eidSet; - } - - } - - private class PidSection { - IFactRelatedQueryHandler factRelatedQry = null; - PidSet pidSet = null; - String pType = null; - boolean pidFromFact = false; - boolean fromPatientSet = false; - boolean fromPidSet = false; - - // TODO , boolean fromPidSet - public PidSection(String pType, - IFactRelatedQueryHandler factRelatedQry, boolean pidFromFact, - boolean fromPatientSet, boolean fromPidSet) { - this.factRelatedQry = factRelatedQry; - this.pType = pType; - this.pidFromFact = pidFromFact; - this.fromPatientSet = fromPatientSet; - this.fromPidSet = fromPidSet; - } - - /** - * - * @throws I2B2Exception - */ - public void generateSet() throws I2B2Exception { - // check if provider selected - IPdoQueryPidDao pidDao = pdoDaoFactory.getPdoQueryPidDAO(); - - boolean detailFlag = pidFactRelated.isSelectDetail(); - boolean blobFlag = pidFactRelated.isSelectBlob(); - boolean statusFlag = pidFactRelated.isSelectStatus(); - if (pidFromFact) { - List patientNumFactList = factRelatedQry - .getPatientFactList(); - log.debug("Patient fact list size" - + patientNumFactList.size()); - List panelSqlList = factRelatedQry.getPanelSqlList(); - - String panelSql = null; - - List sqlParamCountList = new ArrayList(); - for (PanelType panel : filterList.getPanel()) { - - int sqlParamCount = panel.getItem().size(); - if (panel.getInvert() == 1) { - sqlParamCount++; - } - sqlParamCountList.add(sqlParamCount); - - } - IInputOptionListHandler inputOptionListHandler = PDOFactory - .buildInputListHandler(inputList, pdoDaoFactory - .getDataSourceLookup()); - - pidSet = pidDao.getPidByFact(panelSqlList, sqlParamCountList, - inputOptionListHandler, detailFlag, blobFlag, - statusFlag); - } else if (fromPatientSet) { - PatientListType patientListType = inputList.getPatientList(); - pidSet = pidDao.getPidFromPatientSet(patientListType, - detailFlag, blobFlag, statusFlag); - } else if (fromPidSet) { - PidListType pidListType = inputList.getPidList(); - pidSet = pidDao.getPidByPidList(pidListType, detailFlag, - blobFlag, statusFlag); - } - - } - - public PidSet getPidSet() { - return pidSet; - } - - } - - /** - * - */ - private class ProviderSection { - IFactRelatedQueryHandler factRelatedQry = null; - ObserverSet providerDimensionSet = null; - ObserverSet observerSet = null; - String pType = null; - - public ProviderSection(String pType, - IFactRelatedQueryHandler factRelatedQry) { - this.factRelatedQry = factRelatedQry; - this.pType = pType; - } - - /** - * - * @throws I2B2Exception - */ - public void generateSet() throws I2B2Exception { - // check if provider selected - IPdoQueryProviderDao providerDao = pdoDaoFactory - .getPdoQueryProviderDAO(); - ITablePdoQueryProviderDao tableProviderDao = pdoDaoFactory - .getTablePdoQueryProviderDAO(); - - boolean detailFlag = providerFactRelated.isSelectDetail(); - boolean blobFlag = providerFactRelated.isSelectBlob(); - boolean statusFlag = providerFactRelated.isSelectStatus(); - - List panelSqlList = factRelatedQry.getPanelSqlList(); - - String panelSql = null; - - List sqlParamCountList = new ArrayList(); - for (PanelType panel : filterList.getPanel()) { - - int sqlParamCount = panel.getItem().size(); - if (panel.getInvert() == 1) { - sqlParamCount++; - } - sqlParamCountList.add(sqlParamCount); - - } - IInputOptionListHandler inputOptionListHandler = PDOFactory - .buildInputListHandler(origInputList, pdoDaoFactory - .getDataSourceLookup()); - - if (pType.equalsIgnoreCase(TABLE_PDO_TYPE)) { - - observerSet = tableProviderDao.getProviderByFact(panelSqlList, - sqlParamCountList, inputOptionListHandler, detailFlag, - blobFlag, statusFlag); - - } else { - providerDimensionSet = providerDao.getProviderByFact( - panelSqlList, sqlParamCountList, - inputOptionListHandler, detailFlag, blobFlag, - statusFlag); - - } - - } - - public ObserverSet getTableProviderSet() { - return observerSet; - } - - public ObserverSet getPlainProviderSet() { - return providerDimensionSet; - } - } - - private class ConceptSection { - IFactRelatedQueryHandler factRelatedQry = null; - String pType = null; - ConceptSet conceptSet = null; - ConceptSet conceptDimensionSet = null; - - public ConceptSection(String pType, - IFactRelatedQueryHandler factRelatedQry) { - this.factRelatedQry = factRelatedQry; - this.pType = pType; - } - - public void generateSet() throws I2B2Exception { - // check if concept selected - List conceptFactList = factRelatedQry.getConceptFactList(); - IPdoQueryConceptDao conceptDao = pdoDaoFactory - .getPdoQueryConceptDAO(); - ITablePdoQueryConceptDao tableConceptDao = pdoDaoFactory - .getTablePdoQueryConceptDAO(); - boolean detailFlag = conceptFactRelated.isSelectDetail(); - boolean blobFlag = conceptFactRelated.isSelectBlob(); - boolean statusFlag = conceptFactRelated.isSelectStatus(); - - List panelSqlList = factRelatedQry.getPanelSqlList(); - - String panelSql = null; - - List sqlParamCountList = new ArrayList(); - for (PanelType panel : filterList.getPanel()) { - - int sqlParamCount = panel.getItem().size(); - if (panel.getInvert() == 1) { - sqlParamCount++; - } - sqlParamCountList.add(sqlParamCount); - - } - IInputOptionListHandler inputOptionListHandler = PDOFactory - .buildInputListHandler(origInputList, pdoDaoFactory - .getDataSourceLookup()); - - if (pType.equalsIgnoreCase(TABLE_PDO_TYPE)) { - - conceptSet = tableConceptDao.getConceptByFact(panelSqlList, - sqlParamCountList, inputOptionListHandler, detailFlag, - blobFlag, statusFlag); - - } else { - conceptDimensionSet = conceptDao.getConceptByFact(panelSqlList, - sqlParamCountList, inputOptionListHandler, detailFlag, - blobFlag, statusFlag); - } - } - - public ConceptSet getTableConceptSet() { - return conceptSet; - } - - public ConceptSet getPlainConceptSet() { - return conceptDimensionSet; - } - } - - private class ModifierSection { - IFactRelatedQueryHandler factRelatedQry = null; - String pType = null; - ModifierSet modifierSet = null; - ModifierSet modifierDimensionSet = null; - - public ModifierSection(String pType, - IFactRelatedQueryHandler factRelatedQry) { - this.factRelatedQry = factRelatedQry; - this.pType = pType; - } - - public void generateSet() throws I2B2Exception { - // check if modifier selected - List modifierFactList = factRelatedQry.getModifierFactList(); - IPdoQueryModifierDao modifierDao = pdoDaoFactory - .getPdoQueryModifierDAO(); - ITablePdoQueryModifierDao tableModifierDao = pdoDaoFactory - .getTablePdoQueryModifierDAO(); - boolean detailFlag = conceptFactRelated.isSelectDetail(); - boolean blobFlag = conceptFactRelated.isSelectBlob(); - boolean statusFlag = conceptFactRelated.isSelectStatus(); - - List panelSqlList = factRelatedQry.getPanelSqlList(); - - String panelSql = null; - - List sqlParamCountList = new ArrayList(); - for (PanelType panel : filterList.getPanel()) { - - int sqlParamCount = panel.getItem().size(); - if (panel.getInvert() == 1) { - sqlParamCount++; - } - sqlParamCountList.add(sqlParamCount); - - } - IInputOptionListHandler inputOptionListHandler = PDOFactory - .buildInputListHandler(origInputList, pdoDaoFactory - .getDataSourceLookup()); - - if (pType.equalsIgnoreCase(TABLE_PDO_TYPE)) { - - modifierSet = tableModifierDao.getModifierByFact(panelSqlList, - sqlParamCountList, inputOptionListHandler, detailFlag, - blobFlag, statusFlag); - - } else { - modifierDimensionSet = modifierDao.getModifierByFact(panelSqlList, - sqlParamCountList, inputOptionListHandler, detailFlag, - blobFlag, statusFlag); - } - } - - public ModifierSet getTableModifierSet() { - return modifierSet; - } - - public ModifierSet getPlainModifierSet() { - return modifierDimensionSet; - } - } - - private class PatientSection { - IFactRelatedQueryHandler factRelatedQry = null; - boolean patientFromFact = false; - boolean fromVisitSet = false; - boolean fromPatientSet = false; - boolean fromPIDSet = false; - PatientSet patientDimensionSet = null; - PatientSet patientSet = null; - String pType = null; - List patientMetaDataType = null; - - public PatientSection(String pType, - IFactRelatedQueryHandler factRelatedQry, - boolean patientFromFact, boolean fromVisitSet, - boolean fromPatientSet, boolean fromPIDSet, List patientMetaDataType) { - this.factRelatedQry = factRelatedQry; - this.patientFromFact = patientFromFact; - this.fromVisitSet = fromVisitSet; - this.fromPatientSet = fromPatientSet; - this.fromPIDSet = fromPIDSet; - this.pType = pType; - this.patientMetaDataType = patientMetaDataType; - } - - public void generateSet() throws Exception { - IPdoQueryPatientDao pdoQueryPatientDao = pdoDaoFactory - .getPdoQueryPatientDAO(); - pdoQueryPatientDao.setMetaDataParamList(this.patientMetaDataType); - ITablePdoQueryPatientDao tablePdoQueryPatientDao = pdoDaoFactory - .getTablePdoQueryPatientDAO(); - tablePdoQueryPatientDao.setMetaDataParamList(this.patientMetaDataType); - - // check if patient dimension is in output option - boolean detailFlag = patientFactRelated.isSelectDetail(); - - // check if patient dimension is in output option - boolean blobFlag = patientFactRelated.isSelectBlob(); - - // check if patient dimension is in output option - boolean statusFlag = patientFactRelated.isSelectStatus(); - - if (patientFromFact) { - List patientFactList = factRelatedQry - .getPatientFactList(); - log.debug("Patient fact list size" - + patientFactList.size()); - - List panelSqlList = factRelatedQry.getPanelSqlList(); - - String panelSql = null; - - List sqlParamCountList = new ArrayList(); - for (PanelType panel : filterList.getPanel()) { - - int sqlParamCount = panel.getItem().size(); - if (panel.getInvert() == 1) { - sqlParamCount++; - } - sqlParamCountList.add(sqlParamCount); - - } - IInputOptionListHandler inputOptionListHandler = PDOFactory - .buildInputListHandler(inputList, pdoDaoFactory - .getDataSourceLookup()); - - if (pType.equalsIgnoreCase(TABLE_PDO_TYPE)) { - - patientSet = tablePdoQueryPatientDao.getPatientByFact( - panelSqlList, sqlParamCountList, - inputOptionListHandler, detailFlag, blobFlag, - statusFlag); - - } else { - patientDimensionSet = pdoQueryPatientDao.getPatientByFact( - panelSqlList, sqlParamCountList, - inputOptionListHandler, detailFlag, blobFlag, - statusFlag); - } - - } else { - // if visit list get patient list from the visit list and pass - // it to patient dimention - // if patient list do direct query from patient dimension - if (fromPatientSet) { - PatientListType patientListType = inputList - .getPatientList(); - - if (pType.equalsIgnoreCase(TABLE_PDO_TYPE)) { - patientSet = tablePdoQueryPatientDao - .getPatientFromPatientSet(patientListType, - detailFlag, blobFlag, statusFlag); - } else { - patientDimensionSet = pdoQueryPatientDao - .getPatientFromPatientSet(patientListType, - detailFlag, blobFlag, statusFlag); - } - } else if (fromPIDSet) { - PidListType pidListType = inputList.getPidList(); - List patientList = new ArrayList(); - - for (Pid pids : pidListType.getPid()) - { - patientList.add(pids.getValue()); - - - } - - - if (pType.equalsIgnoreCase(TABLE_PDO_TYPE)) { - patientSet = tablePdoQueryPatientDao - .getPatientByPatientNum(patientList, - detailFlag, blobFlag, statusFlag); - } else { - patientDimensionSet = pdoQueryPatientDao - .getPatientByPatientNum(patientList, - detailFlag, blobFlag, statusFlag); - } - } else if (fromVisitSet) { - EventListType visitListType = inputList.getEventList(); - - if (pType.equalsIgnoreCase(TABLE_PDO_TYPE)) { - patientSet = tablePdoQueryPatientDao - .getPatientFromVisitSet(visitListType, - detailFlag, blobFlag, statusFlag); - } else { - patientDimensionSet = pdoQueryPatientDao - .getPatientFromVisitSet(visitListType, - detailFlag, blobFlag, statusFlag); - } - } - } - } - - public PatientSet getTablePatientSet() { - return patientSet; - } - - public PatientSet getPlainPatientSet() { - return patientDimensionSet; - } - } - - private class VisitSection { - boolean visitFromFact = false; - boolean fromVisitSet = false; - boolean fromPatientSet = false; - IFactRelatedQueryHandler factRelatedQry = null; - EventSet visitDimensionSet = null; - EventSet eventSet = null; - String pType = null; - List visitMetaDataParamList = null; - - public VisitSection(String pType, - IFactRelatedQueryHandler factRelatedQry, boolean visitFromFact, - boolean fromVisitSet, boolean fromPatientSet,List visitMetaDataParamList) { - this.factRelatedQry = factRelatedQry; - this.visitFromFact = visitFromFact; - this.fromVisitSet = fromVisitSet; - this.fromPatientSet = fromPatientSet; - this.pType = pType; - this.visitMetaDataParamList = visitMetaDataParamList; - } - - public void generateSet() throws Exception { - IPdoQueryVisitDao pdoQueryVisitDao = pdoDaoFactory - .getPdoQueryVisitDAO(); - pdoQueryVisitDao.setMetaDataParamList(visitMetaDataParamList); - - ITablePdoQueryVisitDao tablePdoQueryVisitDao = pdoDaoFactory - .getTablePdoQueryVisitDAO(); - tablePdoQueryVisitDao.setMetaDataParamList(this.visitMetaDataParamList); - - // check if visit is in output option - boolean detailFlag = visitFactRelated.isSelectDetail(); - - // check if visit is in output option - boolean blobFlag = visitFactRelated.isSelectBlob(); - - // check if visit is in output option - boolean statusFlag = visitFactRelated.isSelectStatus(); - - if (visitFromFact) { - List visitFactList = factRelatedQry.getVisitFactList(); - - List panelSqlList = factRelatedQry.getPanelSqlList(); - - String panelSql = null; - - List sqlParamCountList = new ArrayList(); - for (PanelType panel : filterList.getPanel()) { - - int sqlParamCount = panel.getItem().size(); - if (panel.getInvert() == 1) { - sqlParamCount++; - } - sqlParamCountList.add(sqlParamCount); - - } - IInputOptionListHandler inputOptionListHandler = PDOFactory - .buildInputListHandler(inputList, pdoDaoFactory - .getDataSourceLookup()); - - if (pType.equalsIgnoreCase(TABLE_PDO_TYPE)) { - - eventSet = tablePdoQueryVisitDao.getVisitByFact( - panelSqlList, sqlParamCountList, - inputOptionListHandler, detailFlag, blobFlag, - statusFlag); - - } else { - visitDimensionSet = pdoQueryVisitDao.getVisitByFact( - panelSqlList, sqlParamCountList, - inputOptionListHandler, detailFlag, blobFlag, - statusFlag); - } - - } else { - // check if input is visit or patient list - if (fromVisitSet) { - EventListType visitListType = inputList.getEventList(); - - if (pType.equalsIgnoreCase(TABLE_PDO_TYPE)) { - eventSet = tablePdoQueryVisitDao - .getVisitDimensionSetFromVisitList( - visitListType, detailFlag, blobFlag, - statusFlag); - } else { - visitDimensionSet = pdoQueryVisitDao - .getVisitDimensionSetFromVisitList( - visitListType, detailFlag, blobFlag, - statusFlag); - } - } else if (fromPatientSet) { - PatientListType patientListType = inputList - .getPatientList(); - - if (pType.equalsIgnoreCase(TABLE_PDO_TYPE)) { - eventSet = tablePdoQueryVisitDao - .getVisitDimensionSetFromPatientList( - patientListType, detailFlag, blobFlag, - statusFlag); - } else { - visitDimensionSet = pdoQueryVisitDao - .getVisitDimensionSetFromPatientList( - patientListType, detailFlag, blobFlag, - statusFlag); - } - } - } - } - - public EventSet getTableEventSet() { - return eventSet; - } - - public EventSet getPlainVisitSet() { - return visitDimensionSet; - } - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao.pdo; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.dao.PatientDataDAOFactory; +import edu.harvard.i2b2.crc.dao.pdo.input.FactRelatedQueryHandler; +import edu.harvard.i2b2.crc.dao.pdo.input.IFactRelatedQueryHandler; +import edu.harvard.i2b2.crc.dao.pdo.input.IInputOptionListHandler; +import edu.harvard.i2b2.crc.dao.pdo.input.PDOFactory; +import edu.harvard.i2b2.crc.dao.pdo.input.SQLServerFactRelatedQueryHandler; +import edu.harvard.i2b2.crc.dao.pdo.output.ConceptFactRelated; +import edu.harvard.i2b2.crc.dao.pdo.output.EidFactRelated; +import edu.harvard.i2b2.crc.dao.pdo.output.ModifierFactRelated; +import edu.harvard.i2b2.crc.dao.pdo.output.ObservationFactFactRelated; +import edu.harvard.i2b2.crc.dao.pdo.output.PatientFactRelated; +import edu.harvard.i2b2.crc.dao.pdo.output.PidFactRelated; +import edu.harvard.i2b2.crc.dao.pdo.output.ProviderFactRelated; +import edu.harvard.i2b2.crc.dao.pdo.output.VisitFactRelated; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.ontology.XmlValueType; +import edu.harvard.i2b2.crc.datavo.pdo.ConceptSet; +import edu.harvard.i2b2.crc.datavo.pdo.EidSet; +import edu.harvard.i2b2.crc.datavo.pdo.EventSet; +import edu.harvard.i2b2.crc.datavo.pdo.ModifierSet; +import edu.harvard.i2b2.crc.datavo.pdo.ObservationSet; +import edu.harvard.i2b2.crc.datavo.pdo.ObserverSet; +import edu.harvard.i2b2.crc.datavo.pdo.ParamType; +import edu.harvard.i2b2.crc.datavo.pdo.PatientDataType; +import edu.harvard.i2b2.crc.datavo.pdo.PatientSet; +import edu.harvard.i2b2.crc.datavo.pdo.PidSet; +import edu.harvard.i2b2.crc.datavo.pdo.query.EidListType; +import edu.harvard.i2b2.crc.datavo.pdo.query.EventListType; +import edu.harvard.i2b2.crc.datavo.pdo.query.FilterListType; +import edu.harvard.i2b2.crc.datavo.pdo.query.InputOptionListType; +import edu.harvard.i2b2.crc.datavo.pdo.query.OutputOptionListType; +import edu.harvard.i2b2.crc.datavo.pdo.query.PanelType; +import edu.harvard.i2b2.crc.datavo.pdo.query.PatientListType; +import edu.harvard.i2b2.crc.datavo.pdo.query.PidListType; +import edu.harvard.i2b2.crc.datavo.pdo.query.PidListType.Pid; + +/** + * Main class for PDO queries. + * + *

    + * The is the main class to handle pdo query's. It reads input,filter and output + * option list from pdo request and delegate to following class to build + * individual PDO sections. + * + * Observation Fact = {@link FactRelatedQueryHandler} PatientSet = {@list + * PatientSection} ObservationSet ={@list ObservationSection} ObserverSet = + * {@list ObserverSection} ConceptSet = {@list ConceptSection} + * + *

    + * Sample PDO request sections: + *

    + * Input list: + * 184 + * + * + *

    + * Filter list: \i2b2\Diagnoses\ + * + * + *

    + * Output Option List: + * $Id: PdoQueryHandler.java,v 1.12 2008/07/21 19:53:40 + * rk903 Exp $ + * + * @author rkuttan + * @see FactRelatedQueryHandler + * @see PatientFactRelated + * @see ProviderFactRelated + * @see VisitFactRelated + * @see ObservationFactFactRelated + */ +public class PdoQueryHandler { + /** logger **/ + protected final Log log = LogFactory.getLog(getClass()); + + /** Table pdo type value used internally **/ + public static final String TABLE_PDO_TYPE = "TABLE_PDO_TYPE"; + /** Plain pdo type value used internally **/ + public static final String PLAIN_PDO_TYPE = "PLAIN_PDO_TYPE"; + /** PDO request input list **/ + private InputOptionListType inputList = null; + /** PDO request input list before paging **/ + private InputOptionListType origInputList = null; + /** PDO request filter list **/ + private FilterListType filterList = null; + /** PDO output option list **/ + private OutputOptionListType outputOptionList = null; + /** Observation helper to build observation section in pdo **/ + private VisitFactRelated visitFactRelated = null; + /** Observer helper class to build Observer section in pdo **/ + private ProviderFactRelated providerFactRelated = null; + /** Patient helper class to build patient section in pdo **/ + private PatientFactRelated patientFactRelated = null; + /** Concept helper class to build concept section in pdo **/ + private ConceptFactRelated conceptFactRelated = null; + /** Modifier helper class to build concept section in pdo **/ + private ModifierFactRelated modifierFactRelated = null; + /** Observation fact helper class to build observationfact **/ + private ObservationFactFactRelated obsFactFactRelated = null; + private PidFactRelated pidFactRelated = null; + private EidFactRelated eidFactRelated = null; + /** instance variable for pdo type **/ + private String pdoType = null; + /** instance variable to hold plain pdo **/ + private PatientDataType plainPdoType = null; + /** instance variable to hold table pdo **/ + private PatientDataType tablePdoType = null; + + private PatientDataDAOFactory pdoDaoFactory = null; + + private Map projectParamMap = null; + private Map modifierMetadataXmlMap = null; + private String requestVersion = ""; + private List patientMetaDataParamType = null, visitMetaDataParamType = null; + + + + /** + * Parameter constructor to initialize helper classes + * + * @param pdoType + * @param inputList + * @param filterList + * @param outputOptionList + * @throws I2B2Exception + */ + public PdoQueryHandler(PatientDataDAOFactory pdoDaoFactory, String pdoType, + InputOptionListType origInputList, InputOptionListType inputList, + FilterListType filterList, OutputOptionListType outputOptionList) + throws I2B2DAOException { + if (pdoType == null) { + throw new I2B2DAOException("Input pdoType should not be null"); + } + + if (!(pdoType.equalsIgnoreCase(PLAIN_PDO_TYPE) || pdoType + .equalsIgnoreCase(TABLE_PDO_TYPE))) { + throw new I2B2DAOException("Invalid pdoType : " + pdoType); + } + + if (outputOptionList == null) { + throw new I2B2DAOException( + "Input output option list should not be null"); + } + + + this.pdoDaoFactory = pdoDaoFactory; + this.pdoType = pdoType; + this.origInputList = origInputList; + this.inputList = inputList; + this.filterList = filterList; + this.outputOptionList = outputOptionList; + + visitFactRelated = new VisitFactRelated(outputOptionList.getEventSet()); + providerFactRelated = new ProviderFactRelated(outputOptionList + .getObserverSetUsingFilterList()); + patientFactRelated = new PatientFactRelated(outputOptionList + .getPatientSet()); + conceptFactRelated = new ConceptFactRelated(outputOptionList + .getConceptSetUsingFilterList()); + modifierFactRelated = new ModifierFactRelated(outputOptionList + .getModifierSetUsingFilterList()); + obsFactFactRelated = new ObservationFactFactRelated(outputOptionList + .getObservationSet()); + pidFactRelated = new PidFactRelated(outputOptionList.getPidSet()); + eidFactRelated = new EidFactRelated(outputOptionList.getEidSet()); + + } + + public void setProjectParamMap(Map projectParamMap) { + this.projectParamMap = projectParamMap; + } + + public void setModifierMetadataXmlMap(Map modifierMetadataXmlMap) { + this.modifierMetadataXmlMap = modifierMetadataXmlMap; + } + + public void setRequestVersion(String requestVersion) { + this.requestVersion = requestVersion; + } + + public void setDimensionMetaDataParamList(List patientMetaDataParamType, List visitMetaDataParamType) { + this.patientMetaDataParamType = patientMetaDataParamType; + this.visitMetaDataParamType = visitMetaDataParamType; + + } + + /** + * Method to find if input list is pid set + * + * @return boolean + */ + public boolean isGetPDOFromPIDSet() { + if (inputList.getPidList() != null) { + return true; + } else { + return false; + } + } + + /** + * Method to find if input list is patient set + * + * @return boolean + */ + public boolean isGetPDOFromPatientSet() { + if (inputList.getPatientList() != null) { + return true; + } else { + return false; + } + } + + /** + * Method to find if input list is visit set + * + * @return boolean + */ + public boolean isGetPDOFromVisitSet() { + if (inputList.getEventList() != null) { + return true; + } else { + return false; + } + } + + /** + * Method to find if input list is pid set + * + * @return boolean + */ + public boolean isGetPDOFromPidSet() { + if (inputList.getPidList() != null) { + return true; + } else { + return false; + } + } + + /** + * Method to find if input list is eid set + * + * @return boolean + */ + public boolean isGetPDOFromEidSet() { + if (inputList.getEidList() != null) { + return true; + } else { + return false; + } + } + + /** + * Returns TablePDO + * + * @return TablePatientDataType + */ + public PatientDataType getTablePdo() { + return tablePdoType; + } + + /** + * Returns PlainPDO + * + * @return PatientDataType + */ + public PatientDataType getPlainPdo() { + return plainPdoType; + } + + + /** + * + * @throws Exception + */ + public void processPDORequest() throws Exception { + tablePdoType = new PatientDataType(); + plainPdoType = new PatientDataType(); + + // check if obsrvation_fact tag present + boolean obsFactSelected = obsFactFactRelated.isSelected(); + + // check if provider or concept present + boolean providerSelected = providerFactRelated.isSelected(); + boolean conceptSelected = conceptFactRelated.isSelected(); + boolean modifierSelected = modifierFactRelated.isSelected(); + + // check if patient present + boolean patientSelected = patientFactRelated.isSelected(); + + // check if visit present + boolean visitSelected = visitFactRelated.isSelected(); + boolean pidSelected = pidFactRelated.isSelected(); + boolean eidSelected = eidFactRelated.isSelected(); + + boolean patientFromFact = patientFactRelated.isFactRelated(); + boolean visitFromFact = visitFactRelated.isFactRelated(); + boolean pidFromFact = pidFactRelated.isFactRelated(); + boolean eidFromFact = eidFactRelated.isFactRelated(); + + IFactRelatedQueryHandler factRelatedQry = null; + + // PatientDataType patientDataType = new PatientDataType(); + + // check if this is a fact related query + if (obsFactSelected || providerSelected || conceptSelected + || patientFromFact || visitFromFact || pidFromFact + || eidFromFact || modifierSelected) { + + DataSourceLookup dataSourceLookup = pdoDaoFactory + .getDataSourceLookup(); + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.ORACLE) || + dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) { + factRelatedQry = new FactRelatedQueryHandler(pdoDaoFactory + .getDataSourceLookup(), inputList, filterList, + outputOptionList); + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER)) { + factRelatedQry = new SQLServerFactRelatedQueryHandler( + pdoDaoFactory.getDataSourceLookup(), inputList, + filterList, outputOptionList); + } + //set project param map + factRelatedQry.setProjectParamMap(this.projectParamMap); + factRelatedQry.setModifierMetadataXmlMap(modifierMetadataXmlMap); + factRelatedQry.setRequestVersion(this.requestVersion); + + // execute query + if (pdoType.equalsIgnoreCase(TABLE_PDO_TYPE)) { + List tableObservationSet = factRelatedQry + .getTablePdoObservationFact(); + if (obsFactSelected) { + tablePdoType.getObservationSet() + .addAll(tableObservationSet); + } + } else { + List plainPdoObservationSet = factRelatedQry + .getPdoObservationFact(); + + if (obsFactSelected) { + plainPdoType.getObservationSet().addAll( + plainPdoObservationSet); + } + } + } + + // check if observer section is specified in outputoption + if (providerSelected) { + ProviderSection providerSection = new ProviderSection(pdoType, + factRelatedQry); + providerSection.generateSet(); + + if (pdoType.equalsIgnoreCase(TABLE_PDO_TYPE)) { + tablePdoType.setObserverSet(providerSection + .getTableProviderSet()); + } else { + plainPdoType.setObserverSet(providerSection + .getPlainProviderSet()); + } + } + + // check if concept section is specified in outputoption + if (conceptSelected) { + ConceptSection cs = new ConceptSection(pdoType, factRelatedQry); + cs.generateSet(); + + if (pdoType.equalsIgnoreCase(TABLE_PDO_TYPE)) { + tablePdoType.setConceptSet(cs.getTableConceptSet()); + } else { + plainPdoType.setConceptSet(cs.getPlainConceptSet()); + } + } + + // check if modifier section is specified in outputoption + if (modifierSelected) { + ModifierSection ms = new ModifierSection(pdoType, factRelatedQry); + ms.generateSet(); + + if (pdoType.equalsIgnoreCase(TABLE_PDO_TYPE)) { + tablePdoType.setModifierSet(ms.getTableModifierSet()); + } else { + plainPdoType.setModifierSet(ms.getPlainModifierSet()); + } + } + + // check if patient section is specified in outputoption + if (patientSelected) { + PatientSection ps = new PatientSection(pdoType, factRelatedQry, + patientFromFact, isGetPDOFromVisitSet(), + isGetPDOFromPatientSet(), isGetPDOFromPIDSet(), patientMetaDataParamType); + ps.generateSet(); + + if (pdoType.equalsIgnoreCase(TABLE_PDO_TYPE)) { + tablePdoType.setPatientSet(ps.getTablePatientSet()); + } else { + plainPdoType.setPatientSet(ps.getPlainPatientSet()); + } + } + + // check if observation section is specified in outputoption + if (visitSelected) { + VisitSection vs = new VisitSection(pdoType, factRelatedQry, + visitFromFact, isGetPDOFromVisitSet(), + isGetPDOFromPatientSet(),visitMetaDataParamType); + vs.generateSet(); + + if (pdoType.equalsIgnoreCase(TABLE_PDO_TYPE)) { + tablePdoType.setEventSet(vs.getTableEventSet()); + } else { + plainPdoType.setEventSet(vs.getPlainVisitSet()); + } + } + + // check if pid section is specified in outputoption + if (pidSelected) { + PidSection pids = new PidSection(pdoType, factRelatedQry, + pidFromFact, isGetPDOFromPatientSet(), isGetPDOFromPidSet()); + pids.generateSet(); + if (pdoType.equalsIgnoreCase(TABLE_PDO_TYPE)) { + tablePdoType.setPidSet(pids.getPidSet()); + } else { + plainPdoType.setPidSet(pids.getPidSet()); + } + } + + // check if eid section is specified in outputoption + if (eidSelected) { + EidSection eids = new EidSection(pdoType, factRelatedQry, + eidFromFact, isGetPDOFromPatientSet(), isGetPDOFromEidSet()); + eids.generateSet(); + if (pdoType.equalsIgnoreCase(TABLE_PDO_TYPE)) { + tablePdoType.setEidSet(eids.getEidSet()); + } else { + plainPdoType.setEidSet(eids.getEidSet()); + + } + } + + } + + private class EidSection { + IFactRelatedQueryHandler factRelatedQry = null; + EidSet eidSet = null; + String pType = null; + boolean pidFromFact = false; + boolean fromPatientSet = false; + boolean fromEidSet = false; + + // TODO , boolean fromPidSet + public EidSection(String pType, + IFactRelatedQueryHandler factRelatedQry, boolean pidFromFact, + boolean fromPatientSet, boolean fromEidSet) { + this.factRelatedQry = factRelatedQry; + this.pType = pType; + this.pidFromFact = pidFromFact; + this.fromPatientSet = fromPatientSet; + this.fromEidSet = fromEidSet; + } + + /** + * + * @throws I2B2Exception + */ + public void generateSet() throws I2B2Exception { + // check if provider selected + IPdoQueryEidDao eidDao = pdoDaoFactory.getPdoQueryEidDAO(); + + boolean detailFlag = pidFactRelated.isSelectDetail(); + boolean blobFlag = pidFactRelated.isSelectBlob(); + boolean statusFlag = pidFactRelated.isSelectStatus(); + if (pidFromFact) { + List encounterNumFactList = factRelatedQry + .getVisitFactList(); + List panelSqlList = factRelatedQry.getPanelSqlList(); + + String panelSql = null; + + List sqlParamCountList = new ArrayList(); + for (PanelType panel : filterList.getPanel()) { + + int sqlParamCount = panel.getItem().size(); + if (panel.getInvert() == 1) { + sqlParamCount++; + } + sqlParamCountList.add(sqlParamCount); + + } + IInputOptionListHandler inputOptionListHandler = PDOFactory + .buildInputListHandler(inputList, pdoDaoFactory + .getDataSourceLookup()); + + eidSet = eidDao.getEidByFact(panelSqlList, sqlParamCountList, + inputOptionListHandler, detailFlag, blobFlag, + statusFlag); + + } else if (fromPatientSet) { + PatientListType patientListType = inputList.getPatientList(); + eidSet = eidDao.getEidFromPatientSet(patientListType, + detailFlag, blobFlag, statusFlag); + } else if (fromEidSet) { + EidListType eidListType = inputList.getEidList(); + eidSet = eidDao.getEidByEidList(eidListType, detailFlag, + blobFlag, statusFlag); + } + + } + + public EidSet getEidSet() { + return eidSet; + } + + } + + private class PidSection { + IFactRelatedQueryHandler factRelatedQry = null; + PidSet pidSet = null; + String pType = null; + boolean pidFromFact = false; + boolean fromPatientSet = false; + boolean fromPidSet = false; + + // TODO , boolean fromPidSet + public PidSection(String pType, + IFactRelatedQueryHandler factRelatedQry, boolean pidFromFact, + boolean fromPatientSet, boolean fromPidSet) { + this.factRelatedQry = factRelatedQry; + this.pType = pType; + this.pidFromFact = pidFromFact; + this.fromPatientSet = fromPatientSet; + this.fromPidSet = fromPidSet; + } + + /** + * + * @throws I2B2Exception + */ + public void generateSet() throws I2B2Exception { + // check if provider selected + IPdoQueryPidDao pidDao = pdoDaoFactory.getPdoQueryPidDAO(); + + boolean detailFlag = pidFactRelated.isSelectDetail(); + boolean blobFlag = pidFactRelated.isSelectBlob(); + boolean statusFlag = pidFactRelated.isSelectStatus(); + if (pidFromFact) { + List patientNumFactList = factRelatedQry + .getPatientFactList(); + log.debug("Patient fact list size" + + patientNumFactList.size()); + List panelSqlList = factRelatedQry.getPanelSqlList(); + + String panelSql = null; + + List sqlParamCountList = new ArrayList(); + for (PanelType panel : filterList.getPanel()) { + + int sqlParamCount = panel.getItem().size(); + if (panel.getInvert() == 1) { + sqlParamCount++; + } + sqlParamCountList.add(sqlParamCount); + + } + IInputOptionListHandler inputOptionListHandler = PDOFactory + .buildInputListHandler(inputList, pdoDaoFactory + .getDataSourceLookup()); + + pidSet = pidDao.getPidByFact(panelSqlList, sqlParamCountList, + inputOptionListHandler, detailFlag, blobFlag, + statusFlag); + } else if (fromPatientSet) { + PatientListType patientListType = inputList.getPatientList(); + pidSet = pidDao.getPidFromPatientSet(patientListType, + detailFlag, blobFlag, statusFlag); + } else if (fromPidSet) { + PidListType pidListType = inputList.getPidList(); + pidSet = pidDao.getPidByPidList(pidListType, detailFlag, + blobFlag, statusFlag); + } + + } + + public PidSet getPidSet() { + return pidSet; + } + + } + + /** + * + */ + private class ProviderSection { + IFactRelatedQueryHandler factRelatedQry = null; + ObserverSet providerDimensionSet = null; + ObserverSet observerSet = null; + String pType = null; + + public ProviderSection(String pType, + IFactRelatedQueryHandler factRelatedQry) { + this.factRelatedQry = factRelatedQry; + this.pType = pType; + } + + /** + * + * @throws I2B2Exception + */ + public void generateSet() throws I2B2Exception { + // check if provider selected + IPdoQueryProviderDao providerDao = pdoDaoFactory + .getPdoQueryProviderDAO(); + ITablePdoQueryProviderDao tableProviderDao = pdoDaoFactory + .getTablePdoQueryProviderDAO(); + + boolean detailFlag = providerFactRelated.isSelectDetail(); + boolean blobFlag = providerFactRelated.isSelectBlob(); + boolean statusFlag = providerFactRelated.isSelectStatus(); + + List panelSqlList = factRelatedQry.getPanelSqlList(); + + String panelSql = null; + + List sqlParamCountList = new ArrayList(); + for (PanelType panel : filterList.getPanel()) { + + int sqlParamCount = panel.getItem().size(); + if (panel.getInvert() == 1) { + sqlParamCount++; + } + sqlParamCountList.add(sqlParamCount); + + } + IInputOptionListHandler inputOptionListHandler = PDOFactory + .buildInputListHandler(origInputList, pdoDaoFactory + .getDataSourceLookup()); + + if (pType.equalsIgnoreCase(TABLE_PDO_TYPE)) { + + observerSet = tableProviderDao.getProviderByFact(panelSqlList, + sqlParamCountList, inputOptionListHandler, detailFlag, + blobFlag, statusFlag); + + } else { + providerDimensionSet = providerDao.getProviderByFact( + panelSqlList, sqlParamCountList, + inputOptionListHandler, detailFlag, blobFlag, + statusFlag); + + } + + } + + public ObserverSet getTableProviderSet() { + return observerSet; + } + + public ObserverSet getPlainProviderSet() { + return providerDimensionSet; + } + } + + private class ConceptSection { + IFactRelatedQueryHandler factRelatedQry = null; + String pType = null; + ConceptSet conceptSet = null; + ConceptSet conceptDimensionSet = null; + + public ConceptSection(String pType, + IFactRelatedQueryHandler factRelatedQry) { + this.factRelatedQry = factRelatedQry; + this.pType = pType; + } + + public void generateSet() throws I2B2Exception { + // check if concept selected + List conceptFactList = factRelatedQry.getConceptFactList(); + IPdoQueryConceptDao conceptDao = pdoDaoFactory + .getPdoQueryConceptDAO(); + ITablePdoQueryConceptDao tableConceptDao = pdoDaoFactory + .getTablePdoQueryConceptDAO(); + boolean detailFlag = conceptFactRelated.isSelectDetail(); + boolean blobFlag = conceptFactRelated.isSelectBlob(); + boolean statusFlag = conceptFactRelated.isSelectStatus(); + + List panelSqlList = factRelatedQry.getPanelSqlList(); + + String panelSql = null; + + List sqlParamCountList = new ArrayList(); + for (PanelType panel : filterList.getPanel()) { + + int sqlParamCount = panel.getItem().size(); + if (panel.getInvert() == 1) { + sqlParamCount++; + } + sqlParamCountList.add(sqlParamCount); + + } + IInputOptionListHandler inputOptionListHandler = PDOFactory + .buildInputListHandler(origInputList, pdoDaoFactory + .getDataSourceLookup()); + + if (pType.equalsIgnoreCase(TABLE_PDO_TYPE)) { + + conceptSet = tableConceptDao.getConceptByFact(panelSqlList, + sqlParamCountList, inputOptionListHandler, detailFlag, + blobFlag, statusFlag); + + } else { + conceptDimensionSet = conceptDao.getConceptByFact(panelSqlList, + sqlParamCountList, inputOptionListHandler, detailFlag, + blobFlag, statusFlag); + } + } + + public ConceptSet getTableConceptSet() { + return conceptSet; + } + + public ConceptSet getPlainConceptSet() { + return conceptDimensionSet; + } + } + + private class ModifierSection { + IFactRelatedQueryHandler factRelatedQry = null; + String pType = null; + ModifierSet modifierSet = null; + ModifierSet modifierDimensionSet = null; + + public ModifierSection(String pType, + IFactRelatedQueryHandler factRelatedQry) { + this.factRelatedQry = factRelatedQry; + this.pType = pType; + } + + public void generateSet() throws I2B2Exception { + // check if modifier selected + List modifierFactList = factRelatedQry.getModifierFactList(); + IPdoQueryModifierDao modifierDao = pdoDaoFactory + .getPdoQueryModifierDAO(); + ITablePdoQueryModifierDao tableModifierDao = pdoDaoFactory + .getTablePdoQueryModifierDAO(); + boolean detailFlag = conceptFactRelated.isSelectDetail(); + boolean blobFlag = conceptFactRelated.isSelectBlob(); + boolean statusFlag = conceptFactRelated.isSelectStatus(); + + List panelSqlList = factRelatedQry.getPanelSqlList(); + + String panelSql = null; + + List sqlParamCountList = new ArrayList(); + for (PanelType panel : filterList.getPanel()) { + + int sqlParamCount = panel.getItem().size(); + if (panel.getInvert() == 1) { + sqlParamCount++; + } + sqlParamCountList.add(sqlParamCount); + + } + IInputOptionListHandler inputOptionListHandler = PDOFactory + .buildInputListHandler(origInputList, pdoDaoFactory + .getDataSourceLookup()); + + if (pType.equalsIgnoreCase(TABLE_PDO_TYPE)) { + + modifierSet = tableModifierDao.getModifierByFact(panelSqlList, + sqlParamCountList, inputOptionListHandler, detailFlag, + blobFlag, statusFlag); + + } else { + modifierDimensionSet = modifierDao.getModifierByFact(panelSqlList, + sqlParamCountList, inputOptionListHandler, detailFlag, + blobFlag, statusFlag); + } + } + + public ModifierSet getTableModifierSet() { + return modifierSet; + } + + public ModifierSet getPlainModifierSet() { + return modifierDimensionSet; + } + } + + private class PatientSection { + IFactRelatedQueryHandler factRelatedQry = null; + boolean patientFromFact = false; + boolean fromVisitSet = false; + boolean fromPatientSet = false; + boolean fromPIDSet = false; + PatientSet patientDimensionSet = null; + PatientSet patientSet = null; + String pType = null; + List patientMetaDataType = null; + + public PatientSection(String pType, + IFactRelatedQueryHandler factRelatedQry, + boolean patientFromFact, boolean fromVisitSet, + boolean fromPatientSet, boolean fromPIDSet, List patientMetaDataType) { + this.factRelatedQry = factRelatedQry; + this.patientFromFact = patientFromFact; + this.fromVisitSet = fromVisitSet; + this.fromPatientSet = fromPatientSet; + this.fromPIDSet = fromPIDSet; + this.pType = pType; + this.patientMetaDataType = patientMetaDataType; + } + + public void generateSet() throws Exception { + IPdoQueryPatientDao pdoQueryPatientDao = pdoDaoFactory + .getPdoQueryPatientDAO(); + pdoQueryPatientDao.setMetaDataParamList(this.patientMetaDataType); + ITablePdoQueryPatientDao tablePdoQueryPatientDao = pdoDaoFactory + .getTablePdoQueryPatientDAO(); + tablePdoQueryPatientDao.setMetaDataParamList(this.patientMetaDataType); + + // check if patient dimension is in output option + boolean detailFlag = patientFactRelated.isSelectDetail(); + + // check if patient dimension is in output option + boolean blobFlag = patientFactRelated.isSelectBlob(); + + // check if patient dimension is in output option + boolean statusFlag = patientFactRelated.isSelectStatus(); + + if (patientFromFact) { + List patientFactList = factRelatedQry + .getPatientFactList(); + log.debug("Patient fact list size" + + patientFactList.size()); + + List panelSqlList = factRelatedQry.getPanelSqlList(); + + String panelSql = null; + + List sqlParamCountList = new ArrayList(); + for (PanelType panel : filterList.getPanel()) { + + int sqlParamCount = panel.getItem().size(); + if (panel.getInvert() == 1) { + sqlParamCount++; + } + sqlParamCountList.add(sqlParamCount); + + } + IInputOptionListHandler inputOptionListHandler = PDOFactory + .buildInputListHandler(inputList, pdoDaoFactory + .getDataSourceLookup()); + + if (pType.equalsIgnoreCase(TABLE_PDO_TYPE)) { + + patientSet = tablePdoQueryPatientDao.getPatientByFact( + panelSqlList, sqlParamCountList, + inputOptionListHandler, detailFlag, blobFlag, + statusFlag); + + } else { + patientDimensionSet = pdoQueryPatientDao.getPatientByFact( + panelSqlList, sqlParamCountList, + inputOptionListHandler, detailFlag, blobFlag, + statusFlag); + } + + } else { + // if visit list get patient list from the visit list and pass + // it to patient dimention + // if patient list do direct query from patient dimension + if (fromPatientSet) { + PatientListType patientListType = inputList + .getPatientList(); + + if (pType.equalsIgnoreCase(TABLE_PDO_TYPE)) { + patientSet = tablePdoQueryPatientDao + .getPatientFromPatientSet(patientListType, + detailFlag, blobFlag, statusFlag); + } else { + patientDimensionSet = pdoQueryPatientDao + .getPatientFromPatientSet(patientListType, + detailFlag, blobFlag, statusFlag); + } + } else if (fromPIDSet) { + PidListType pidListType = inputList.getPidList(); + List patientList = new ArrayList(); + + for (Pid pids : pidListType.getPid()) + { + patientList.add(pids.getValue()); + + + } + + + if (pType.equalsIgnoreCase(TABLE_PDO_TYPE)) { + patientSet = tablePdoQueryPatientDao + .getPatientByPatientNum(patientList, + detailFlag, blobFlag, statusFlag); + } else { + patientDimensionSet = pdoQueryPatientDao + .getPatientByPatientNum(patientList, + detailFlag, blobFlag, statusFlag); + } + } else if (fromVisitSet) { + EventListType visitListType = inputList.getEventList(); + + if (pType.equalsIgnoreCase(TABLE_PDO_TYPE)) { + patientSet = tablePdoQueryPatientDao + .getPatientFromVisitSet(visitListType, + detailFlag, blobFlag, statusFlag); + } else { + patientDimensionSet = pdoQueryPatientDao + .getPatientFromVisitSet(visitListType, + detailFlag, blobFlag, statusFlag); + } + } + } + } + + public PatientSet getTablePatientSet() { + return patientSet; + } + + public PatientSet getPlainPatientSet() { + return patientDimensionSet; + } + } + + private class VisitSection { + boolean visitFromFact = false; + boolean fromVisitSet = false; + boolean fromPatientSet = false; + IFactRelatedQueryHandler factRelatedQry = null; + EventSet visitDimensionSet = null; + EventSet eventSet = null; + String pType = null; + List visitMetaDataParamList = null; + + public VisitSection(String pType, + IFactRelatedQueryHandler factRelatedQry, boolean visitFromFact, + boolean fromVisitSet, boolean fromPatientSet,List visitMetaDataParamList) { + this.factRelatedQry = factRelatedQry; + this.visitFromFact = visitFromFact; + this.fromVisitSet = fromVisitSet; + this.fromPatientSet = fromPatientSet; + this.pType = pType; + this.visitMetaDataParamList = visitMetaDataParamList; + } + + public void generateSet() throws Exception { + IPdoQueryVisitDao pdoQueryVisitDao = pdoDaoFactory + .getPdoQueryVisitDAO(); + pdoQueryVisitDao.setMetaDataParamList(visitMetaDataParamList); + + ITablePdoQueryVisitDao tablePdoQueryVisitDao = pdoDaoFactory + .getTablePdoQueryVisitDAO(); + tablePdoQueryVisitDao.setMetaDataParamList(this.visitMetaDataParamList); + + // check if visit is in output option + boolean detailFlag = visitFactRelated.isSelectDetail(); + + // check if visit is in output option + boolean blobFlag = visitFactRelated.isSelectBlob(); + + // check if visit is in output option + boolean statusFlag = visitFactRelated.isSelectStatus(); + + if (visitFromFact) { + List visitFactList = factRelatedQry.getVisitFactList(); + + List panelSqlList = factRelatedQry.getPanelSqlList(); + + String panelSql = null; + + List sqlParamCountList = new ArrayList(); + for (PanelType panel : filterList.getPanel()) { + + int sqlParamCount = panel.getItem().size(); + if (panel.getInvert() == 1) { + sqlParamCount++; + } + sqlParamCountList.add(sqlParamCount); + + } + IInputOptionListHandler inputOptionListHandler = PDOFactory + .buildInputListHandler(inputList, pdoDaoFactory + .getDataSourceLookup()); + + if (pType.equalsIgnoreCase(TABLE_PDO_TYPE)) { + + eventSet = tablePdoQueryVisitDao.getVisitByFact( + panelSqlList, sqlParamCountList, + inputOptionListHandler, detailFlag, blobFlag, + statusFlag); + + } else { + visitDimensionSet = pdoQueryVisitDao.getVisitByFact( + panelSqlList, sqlParamCountList, + inputOptionListHandler, detailFlag, blobFlag, + statusFlag); + } + + } else { + // check if input is visit or patient list + if (fromVisitSet) { + EventListType visitListType = inputList.getEventList(); + + if (pType.equalsIgnoreCase(TABLE_PDO_TYPE)) { + eventSet = tablePdoQueryVisitDao + .getVisitDimensionSetFromVisitList( + visitListType, detailFlag, blobFlag, + statusFlag); + } else { + visitDimensionSet = pdoQueryVisitDao + .getVisitDimensionSetFromVisitList( + visitListType, detailFlag, blobFlag, + statusFlag); + } + } else if (fromPatientSet) { + PatientListType patientListType = inputList + .getPatientList(); + + if (pType.equalsIgnoreCase(TABLE_PDO_TYPE)) { + eventSet = tablePdoQueryVisitDao + .getVisitDimensionSetFromPatientList( + patientListType, detailFlag, blobFlag, + statusFlag); + } else { + visitDimensionSet = pdoQueryVisitDao + .getVisitDimensionSetFromPatientList( + patientListType, detailFlag, blobFlag, + statusFlag); + } + } + } + } + + public EventSet getTableEventSet() { + return eventSet; + } + + public EventSet getPlainVisitSet() { + return visitDimensionSet; + } + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/PdoQueryModifierDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/PdoQueryModifierDao.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/PdoQueryModifierDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/PdoQueryModifierDao.java index 3268e7e5..eb21ba36 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/PdoQueryModifierDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/PdoQueryModifierDao.java @@ -1,328 +1,328 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao.pdo; - -import java.io.IOException; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.List; - -import javax.sql.DataSource; - -import oracle.sql.ArrayDescriptor; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -//import org.jboss.resource.adapter.jdbc.WrappedConnection; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.util.db.JDBCUtil; -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.dao.pdo.input.FactRelatedQueryHandler; -import edu.harvard.i2b2.crc.dao.pdo.input.IInputOptionListHandler; -import edu.harvard.i2b2.crc.dao.pdo.input.SQLServerFactRelatedQueryHandler; -import edu.harvard.i2b2.crc.dao.pdo.output.ModifierFactRelated; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.pdo.ModifierSet; -import edu.harvard.i2b2.crc.datavo.pdo.ModifierType; -import edu.harvard.i2b2.crc.datavo.pdo.PatientDataType; - -/** - * This class handles Concept dimension query's related to PDO request $Id: - * PdoQueryConceptDao.java,v 1.11 2008/03/19 22:42:08 rk903 Exp $ - * - * @author rkuttan - */ -public class PdoQueryModifierDao extends CRCDAO implements IPdoQueryModifierDao { - - private DataSourceLookup dataSourceLookup = null; - - public PdoQueryModifierDao(DataSourceLookup dataSourceLookup, - DataSource dataSource) { - this.dataSourceLookup = dataSourceLookup; - setDataSource(dataSource); - setDbSchemaName(dataSourceLookup.getFullSchema()); - } - - /** log * */ - protected final Log log = LogFactory.getLog(getClass()); - - /** - * Get concepts detail from concept code list - * - * @param conceptCdList - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return {@link PatientDataType.ConceptDimensionSet} - * @throws I2B2DAOException - */ - @Override - public ModifierSet getModifierByModifierCd(List modifierCdList, - boolean detailFlag, boolean blobFlag, boolean statusFlag) - throws I2B2DAOException { - - ModifierSet modifierDimensionSet = new ModifierSet(); - log.debug("Size of input modifier cd list " + modifierCdList.size()); - Connection conn = null; - PreparedStatement query = null; - String tempTableName = ""; - try { - conn = getDataSource().getConnection(); - ModifierFactRelated modifierFactRelated = new ModifierFactRelated( - buildOutputOptionType(detailFlag, blobFlag, statusFlag)); - - String selectClause = modifierFactRelated.getSelectClause(); - String serverType = dataSourceLookup.getServerType(); - if (serverType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { - // get oracle connection from jboss wrapped connection - // Otherwise Jboss wrapped connection fails when using oracle - // Arrays - oracle.jdbc.driver.OracleConnection conn1 = null;// (oracle.jdbc.driver.OracleConnection) ((WrappedConnection) conn) - // .getUnderlyingConnection(); - String finalSql = "SELECT " - + selectClause - + " FROM " - + getDbSchemaName() - + "modifier_dimension modifier WHERE modifier.modifier_cd IN (SELECT * FROM TABLE (?))"; - log.debug("Pdo modifier sql [" + finalSql + "]"); - query = conn1.prepareStatement(finalSql); - - ArrayDescriptor desc = ArrayDescriptor.createDescriptor( - "QT_PDO_QRY_STRING_ARRAY", conn1); - - oracle.sql.ARRAY paramArray = new oracle.sql.ARRAY(desc, conn1, - modifierCdList.toArray(new String[] {})); - query.setArray(1, paramArray); - } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.SQLSERVER) || - serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { - log.debug("creating temp table"); - java.sql.Statement tempStmt = conn.createStatement(); - if (serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) - tempTableName = SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE.substring(1); - else - tempTableName = SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE; - try { - tempStmt.executeUpdate("drop table " + tempTableName); - } catch (SQLException sqlex) { - ; - } - - uploadTempTable(tempStmt, tempTableName, modifierCdList, serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)); - String finalSql = "SELECT " - + selectClause - + " FROM " - + getDbSchemaName() - + "modifier_dimension modifier WHERE modifier.modifier_cd IN (select distinct char_param1 FROM " - + tempTableName + ") order by modifier_path"; - log.debug("Executing [" + finalSql + "]"); - - query = conn.prepareStatement(finalSql); - - } - ResultSet resultSet = query.executeQuery(); - - I2B2PdoFactory.ModifierBuilder modifierBuilder = new I2B2PdoFactory().new ModifierBuilder( - detailFlag, blobFlag, statusFlag, dataSourceLookup.getServerType()); - while (resultSet.next()) { - ModifierType modifierDimensionType = modifierBuilder - .buildModifierSet(resultSet); - modifierDimensionSet.getModifier().add(modifierDimensionType); - } - - } catch (SQLException sqlEx) { - log.error("", sqlEx); - throw new I2B2DAOException("", sqlEx); - } catch (IOException ioEx) { - log.error("", ioEx); - throw new I2B2DAOException("", ioEx); - } finally { - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER)) { - PdoTempTableUtil tempUtil = new PdoTempTableUtil(); - tempUtil.deleteTempTableSqlServer(conn, tempTableName); - } - try { - JDBCUtil.closeJdbcResource(null, query, conn); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - } - } - return modifierDimensionSet; - } - - - - private void uploadTempTable(Statement tempStmt, String tempTable, - List patientNumList, boolean isPostgresql) throws SQLException { - String createTempInputListTable = "create " - + (isPostgresql ? " temp ": "" ) - + " table " + tempTable - + " ( char_param1 varchar(100) )"; - tempStmt.executeUpdate(createTempInputListTable); - log.debug("created temp table" + tempTable); - PreparedStatement preparedStmt = tempStmt.getConnection() - .prepareStatement("insert into " + tempTable + " values (?)"); - // load to temp table - // TempInputListInsert inputListInserter = new - // TempInputListInsert(dataSource,TEMP_PDO_INPUTLIST_TABLE); - // inputListInserter.setBatchSize(100); - int i = 0; - for (String singleValue : patientNumList) { - preparedStmt.setString(1, singleValue); - preparedStmt.addBatch(); - log.debug("adding batch [" + i + "] " + singleValue); - i++; - if (i % 100 == 0) { - log.debug("batch insert [" + i + "]"); - preparedStmt.executeBatch(); - - } - } - log.debug("batch insert [" + i + "]"); - preparedStmt.executeBatch(); - } - - @Override - public ModifierSet getModifierByFact(List panelSqlList, - List sqlParamCountList, - IInputOptionListHandler inputOptionListHandler, boolean detailFlag, - boolean blobFlag, boolean statusFlag) throws I2B2DAOException { - - ModifierSet modifierSet = new ModifierSet(); - I2B2PdoFactory.ModifierBuilder modifierBuilder = new I2B2PdoFactory().new ModifierBuilder( - detailFlag, blobFlag, statusFlag, dataSourceLookup.getServerType()); - ModifierFactRelated modifierFactRelated = new ModifierFactRelated( - buildOutputOptionType(detailFlag, blobFlag, statusFlag)); - String selectClause = modifierFactRelated.getSelectClause(); - String serverType = dataSourceLookup.getServerType(); - String tempTable = ""; - Connection conn = null; - PreparedStatement query = null; - try { - conn = dataSource.getConnection(); - if (serverType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { - tempTable = FactRelatedQueryHandler.TEMP_FACT_PARAM_TABLE; - } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.SQLSERVER) || - serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { - log.debug("creating temp table"); - java.sql.Statement tempStmt = conn.createStatement(); - if (serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) - tempTable = SQLServerFactRelatedQueryHandler.TEMP_FACT_PARAM_TABLE.substring(1); - else - tempTable = SQLServerFactRelatedQueryHandler.TEMP_FACT_PARAM_TABLE; - try { - tempStmt.executeUpdate("drop table " + tempTable); - } catch (SQLException sqlex) { - ; - } - String createTempInputListTable = "create table " + tempTable - + " ( set_index int, char_param1 varchar(500) )"; - tempStmt.executeUpdate(createTempInputListTable); - log.debug("created temp table" + tempTable); - } - // if the inputlist is enumeration, then upload the enumerated input - // to temp table. - // the uploaded enumerated input will be used in the fact join. - if (inputOptionListHandler.isEnumerationSet()) { - inputOptionListHandler.uploadEnumerationValueToTempTable(conn); - } - String insertSql = ""; - int i = 0; - int sqlParamCount = 0; - ResultSet resultSet = null; - for (String panelSql : panelSqlList) { - insertSql = " insert into " - + tempTable - + "(char_param1) select distinct obs_modifier_cd from ( " - + panelSql + ") b"; - - log.debug("Executing SQL [ " + insertSql + "]"); - sqlParamCount = sqlParamCountList.get(i++); - // conn.createStatement().executeUpdate(insertSql); - executeTotalSql(insertSql, conn, sqlParamCount, - inputOptionListHandler); - - } - - String finalSql = "SELECT " - + selectClause - + " FROM " - + getDbSchemaName() - + "modifier_dimension modifier where modifier_cd in (select distinct char_param1 from " - + tempTable + ") order by modifier_path"; - log.debug("Executing SQL [" + finalSql + "]"); - log.debug("Final Sql " + finalSql); - - query = conn.prepareStatement(finalSql); - - resultSet = query.executeQuery(); - - while (resultSet.next()) { - ModifierType modifier = modifierBuilder.buildModifierSet(resultSet); - modifierSet.getModifier().add(modifier); - } - } catch (SQLException sqlEx) { - log.error("", sqlEx); - throw new I2B2DAOException("sql exception", sqlEx); - } catch (IOException ioEx) { - log.error("", ioEx); - throw new I2B2DAOException("IO exception", ioEx); - } finally { - PdoTempTableUtil tempUtil = new PdoTempTableUtil(); - tempUtil.clearTempTable(dataSourceLookup.getServerType(), conn, tempTable); - - if (inputOptionListHandler != null - && inputOptionListHandler.isEnumerationSet()) { - try { - inputOptionListHandler.deleteTempTable(conn); - } catch (SQLException e) { - - e.printStackTrace(); - } - } - try { - - JDBCUtil.closeJdbcResource(null, query, conn); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - } - } - return modifierSet; - } - - private void executeTotalSql(String totalSql, Connection conn, - int sqlParamCount, IInputOptionListHandler inputOptionListHandler) - throws SQLException { - - PreparedStatement stmt = conn.prepareStatement(totalSql); - - log.debug(totalSql + " [ " + sqlParamCount + " ]"); - if (inputOptionListHandler.isCollectionId()) { - for (int i = 1; i <= sqlParamCount; i++) { - stmt.setInt(i, Integer.parseInt(inputOptionListHandler - .getCollectionId())); - } - } - - stmt.executeUpdate(); - - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao.pdo; + +import java.io.IOException; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.List; + +import javax.sql.DataSource; + +import oracle.sql.ArrayDescriptor; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +//import org.jboss.resource.adapter.jdbc.WrappedConnection; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.util.db.JDBCUtil; +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.dao.pdo.input.FactRelatedQueryHandler; +import edu.harvard.i2b2.crc.dao.pdo.input.IInputOptionListHandler; +import edu.harvard.i2b2.crc.dao.pdo.input.SQLServerFactRelatedQueryHandler; +import edu.harvard.i2b2.crc.dao.pdo.output.ModifierFactRelated; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.pdo.ModifierSet; +import edu.harvard.i2b2.crc.datavo.pdo.ModifierType; +import edu.harvard.i2b2.crc.datavo.pdo.PatientDataType; + +/** + * This class handles Concept dimension query's related to PDO request $Id: + * PdoQueryConceptDao.java,v 1.11 2008/03/19 22:42:08 rk903 Exp $ + * + * @author rkuttan + */ +public class PdoQueryModifierDao extends CRCDAO implements IPdoQueryModifierDao { + + private DataSourceLookup dataSourceLookup = null; + + public PdoQueryModifierDao(DataSourceLookup dataSourceLookup, + DataSource dataSource) { + this.dataSourceLookup = dataSourceLookup; + setDataSource(dataSource); + setDbSchemaName(dataSourceLookup.getFullSchema()); + } + + /** log * */ + protected final Log log = LogFactory.getLog(getClass()); + + /** + * Get concepts detail from concept code list + * + * @param conceptCdList + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return {@link PatientDataType.ConceptDimensionSet} + * @throws I2B2DAOException + */ + @Override + public ModifierSet getModifierByModifierCd(List modifierCdList, + boolean detailFlag, boolean blobFlag, boolean statusFlag) + throws I2B2DAOException { + + ModifierSet modifierDimensionSet = new ModifierSet(); + log.debug("Size of input modifier cd list " + modifierCdList.size()); + Connection conn = null; + PreparedStatement query = null; + String tempTableName = ""; + try { + conn = getDataSource().getConnection(); + ModifierFactRelated modifierFactRelated = new ModifierFactRelated( + buildOutputOptionType(detailFlag, blobFlag, statusFlag)); + + String selectClause = modifierFactRelated.getSelectClause(); + String serverType = dataSourceLookup.getServerType(); + if (serverType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { + // get oracle connection from jboss wrapped connection + // Otherwise Jboss wrapped connection fails when using oracle + // Arrays + oracle.jdbc.driver.OracleConnection conn1 = null;// (oracle.jdbc.driver.OracleConnection) ((WrappedConnection) conn) + // .getUnderlyingConnection(); + String finalSql = "SELECT " + + selectClause + + " FROM " + + getDbSchemaName() + + "modifier_dimension modifier WHERE modifier.modifier_cd IN (SELECT * FROM TABLE (?))"; + log.debug("Pdo modifier sql [" + finalSql + "]"); + query = conn1.prepareStatement(finalSql); + + ArrayDescriptor desc = ArrayDescriptor.createDescriptor( + "QT_PDO_QRY_STRING_ARRAY", conn1); + + oracle.sql.ARRAY paramArray = new oracle.sql.ARRAY(desc, conn1, + modifierCdList.toArray(new String[] {})); + query.setArray(1, paramArray); + } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.SQLSERVER) || + serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { + log.debug("creating temp table"); + java.sql.Statement tempStmt = conn.createStatement(); + if (serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) + tempTableName = SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE.substring(1); + else + tempTableName = SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE; + try { + tempStmt.executeUpdate("drop table " + tempTableName); + } catch (SQLException sqlex) { + ; + } + + uploadTempTable(tempStmt, tempTableName, modifierCdList, serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)); + String finalSql = "SELECT " + + selectClause + + " FROM " + + getDbSchemaName() + + "modifier_dimension modifier WHERE modifier.modifier_cd IN (select distinct char_param1 FROM " + + tempTableName + ") order by modifier_path"; + log.debug("Executing [" + finalSql + "]"); + + query = conn.prepareStatement(finalSql); + + } + ResultSet resultSet = query.executeQuery(); + + I2B2PdoFactory.ModifierBuilder modifierBuilder = new I2B2PdoFactory().new ModifierBuilder( + detailFlag, blobFlag, statusFlag, dataSourceLookup.getServerType()); + while (resultSet.next()) { + ModifierType modifierDimensionType = modifierBuilder + .buildModifierSet(resultSet); + modifierDimensionSet.getModifier().add(modifierDimensionType); + } + + } catch (SQLException sqlEx) { + log.error("", sqlEx); + throw new I2B2DAOException("", sqlEx); + } catch (IOException ioEx) { + log.error("", ioEx); + throw new I2B2DAOException("", ioEx); + } finally { + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER)) { + PdoTempTableUtil tempUtil = new PdoTempTableUtil(); + tempUtil.deleteTempTableSqlServer(conn, tempTableName); + } + try { + JDBCUtil.closeJdbcResource(null, query, conn); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + } + } + return modifierDimensionSet; + } + + + + private void uploadTempTable(Statement tempStmt, String tempTable, + List patientNumList, boolean isPostgresql) throws SQLException { + String createTempInputListTable = "create " + + (isPostgresql ? " temp ": "" ) + + " table " + tempTable + + " ( char_param1 varchar(100) )"; + tempStmt.executeUpdate(createTempInputListTable); + log.debug("created temp table" + tempTable); + PreparedStatement preparedStmt = tempStmt.getConnection() + .prepareStatement("insert into " + tempTable + " values (?)"); + // load to temp table + // TempInputListInsert inputListInserter = new + // TempInputListInsert(dataSource,TEMP_PDO_INPUTLIST_TABLE); + // inputListInserter.setBatchSize(100); + int i = 0; + for (String singleValue : patientNumList) { + preparedStmt.setString(1, singleValue); + preparedStmt.addBatch(); + log.debug("adding batch [" + i + "] " + singleValue); + i++; + if (i % 100 == 0) { + log.debug("batch insert [" + i + "]"); + preparedStmt.executeBatch(); + + } + } + log.debug("batch insert [" + i + "]"); + preparedStmt.executeBatch(); + } + + @Override + public ModifierSet getModifierByFact(List panelSqlList, + List sqlParamCountList, + IInputOptionListHandler inputOptionListHandler, boolean detailFlag, + boolean blobFlag, boolean statusFlag) throws I2B2DAOException { + + ModifierSet modifierSet = new ModifierSet(); + I2B2PdoFactory.ModifierBuilder modifierBuilder = new I2B2PdoFactory().new ModifierBuilder( + detailFlag, blobFlag, statusFlag, dataSourceLookup.getServerType()); + ModifierFactRelated modifierFactRelated = new ModifierFactRelated( + buildOutputOptionType(detailFlag, blobFlag, statusFlag)); + String selectClause = modifierFactRelated.getSelectClause(); + String serverType = dataSourceLookup.getServerType(); + String tempTable = ""; + Connection conn = null; + PreparedStatement query = null; + try { + conn = dataSource.getConnection(); + if (serverType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { + tempTable = FactRelatedQueryHandler.TEMP_FACT_PARAM_TABLE; + } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.SQLSERVER) || + serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { + log.debug("creating temp table"); + java.sql.Statement tempStmt = conn.createStatement(); + if (serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) + tempTable = SQLServerFactRelatedQueryHandler.TEMP_FACT_PARAM_TABLE.substring(1); + else + tempTable = SQLServerFactRelatedQueryHandler.TEMP_FACT_PARAM_TABLE; + try { + tempStmt.executeUpdate("drop table " + tempTable); + } catch (SQLException sqlex) { + ; + } + String createTempInputListTable = "create table " + tempTable + + " ( set_index int, char_param1 varchar(500) )"; + tempStmt.executeUpdate(createTempInputListTable); + log.debug("created temp table" + tempTable); + } + // if the inputlist is enumeration, then upload the enumerated input + // to temp table. + // the uploaded enumerated input will be used in the fact join. + if (inputOptionListHandler.isEnumerationSet()) { + inputOptionListHandler.uploadEnumerationValueToTempTable(conn); + } + String insertSql = ""; + int i = 0; + int sqlParamCount = 0; + ResultSet resultSet = null; + for (String panelSql : panelSqlList) { + insertSql = " insert into " + + tempTable + + "(char_param1) select distinct obs_modifier_cd from ( " + + panelSql + ") b"; + + log.debug("Executing SQL [ " + insertSql + "]"); + sqlParamCount = sqlParamCountList.get(i++); + // conn.createStatement().executeUpdate(insertSql); + executeTotalSql(insertSql, conn, sqlParamCount, + inputOptionListHandler); + + } + + String finalSql = "SELECT " + + selectClause + + " FROM " + + getDbSchemaName() + + "modifier_dimension modifier where modifier_cd in (select distinct char_param1 from " + + tempTable + ") order by modifier_path"; + log.debug("Executing SQL [" + finalSql + "]"); + log.debug("Final Sql " + finalSql); + + query = conn.prepareStatement(finalSql); + + resultSet = query.executeQuery(); + + while (resultSet.next()) { + ModifierType modifier = modifierBuilder.buildModifierSet(resultSet); + modifierSet.getModifier().add(modifier); + } + } catch (SQLException sqlEx) { + log.error("", sqlEx); + throw new I2B2DAOException("sql exception", sqlEx); + } catch (IOException ioEx) { + log.error("", ioEx); + throw new I2B2DAOException("IO exception", ioEx); + } finally { + PdoTempTableUtil tempUtil = new PdoTempTableUtil(); + tempUtil.clearTempTable(dataSourceLookup.getServerType(), conn, tempTable); + + if (inputOptionListHandler != null + && inputOptionListHandler.isEnumerationSet()) { + try { + inputOptionListHandler.deleteTempTable(conn); + } catch (SQLException e) { + + e.printStackTrace(); + } + } + try { + + JDBCUtil.closeJdbcResource(null, query, conn); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + } + } + return modifierSet; + } + + private void executeTotalSql(String totalSql, Connection conn, + int sqlParamCount, IInputOptionListHandler inputOptionListHandler) + throws SQLException { + + PreparedStatement stmt = conn.prepareStatement(totalSql); + + log.debug(totalSql + " [ " + sqlParamCount + " ]"); + if (inputOptionListHandler.isCollectionId()) { + for (int i = 1; i <= sqlParamCount; i++) { + stmt.setInt(i, Integer.parseInt(inputOptionListHandler + .getCollectionId())); + } + } + + stmt.executeUpdate(); + + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/PdoQueryPatientDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/PdoQueryPatientDao.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/PdoQueryPatientDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/PdoQueryPatientDao.java index 269abca5..033cf5b3 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/PdoQueryPatientDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/PdoQueryPatientDao.java @@ -1,558 +1,558 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao.pdo; - -import java.io.IOException; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.List; - -import javax.sql.DataSource; - - - -//import org.jboss.resource.adapter.jdbc.WrappedConnection; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.util.db.JDBCUtil; -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.dao.pdo.input.FactRelatedQueryHandler; -import edu.harvard.i2b2.crc.dao.pdo.input.IInputOptionListHandler; -import edu.harvard.i2b2.crc.dao.pdo.input.PatientListTypeHandler; -import edu.harvard.i2b2.crc.dao.pdo.input.SQLServerFactRelatedQueryHandler; -import edu.harvard.i2b2.crc.dao.pdo.input.VisitListTypeHandler; -import edu.harvard.i2b2.crc.dao.pdo.output.PatientFactRelated; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.pdo.ParamType; -import edu.harvard.i2b2.crc.datavo.pdo.PatientSet; -import edu.harvard.i2b2.crc.datavo.pdo.PatientType; -import edu.harvard.i2b2.crc.datavo.pdo.query.EventListType; -import edu.harvard.i2b2.crc.datavo.pdo.query.PatientListType; - -/** - * Class to build patient section of plain pdo $Id: PdoQueryPatientDao.java,v - * 1.11 2008/03/19 22:42:08 rk903 Exp $ - * - * @author rkuttan - */ -public class PdoQueryPatientDao extends CRCDAO implements IPdoQueryPatientDao { - - private DataSourceLookup dataSourceLookup = null; - private List metaDataParamList = null; - - public PdoQueryPatientDao(DataSourceLookup dataSourceLookup, - DataSource dataSource) { - setDataSource(dataSource); - setDbSchemaName(dataSourceLookup.getFullSchema()); - this.dataSourceLookup = dataSourceLookup; - } - - @Override - public void setMetaDataParamList(List metaDataParamList) { - this.metaDataParamList = metaDataParamList; - } - - /** - * Function to return patient dimension data for given list of patient num - * - * @param patientNumList - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return PatientDataType.PatientDimensionSet - * @throws Exception - */ - @Override - public PatientSet getPatientByPatientNum(List patientNumList, - boolean detailFlag, boolean blobFlag, boolean statusFlag) - throws I2B2DAOException { - - Connection conn = null; - PreparedStatement query = null; - PatientSet patientDimensionSet = new PatientSet(); - - String tempTableName = ""; - try { - // execute fullsql - conn = getDataSource().getConnection(); - PatientFactRelated patientRelated = new PatientFactRelated( - buildOutputOptionType(detailFlag, blobFlag, statusFlag)); - patientRelated.setMetaDataParamList(this.metaDataParamList); - - String selectClause = patientRelated.getSelectClause(); - ResultSet resultSet = null; - /* - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE)) { - //oracle.jdbc.driver.OracleConnection conn1 = null;// (oracle.jdbc.driver.OracleConnection) ((WrappedConnection) conn) - //.getUnderlyingConnection(); - String finalSql = "SELECT " - + selectClause - + " FROM " - + getDbSchemaName() - + "patient_dimension patient WHERE patient.patient_num IN (SELECT * FROM TABLE (cast (? as QT_PDO_QRY_STRING_ARRAY))) order by 1"; - log.debug("Executing [" + finalSql + "]"); - query = conn.prepareStatement(finalSql); - - ArrayDescriptor desc = ArrayDescriptor.createDescriptor( - "QT_PDO_QRY_STRING_ARRAY", conn); - - oracle.sql.ARRAY paramArray = new oracle.sql.ARRAY(desc, conn, - patientNumList.toArray(new String[] {})); - query.setArray(1, paramArray); - resultSet = query.executeQuery(); - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER) || - dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) { - */ - // create temp table - // load to temp table - // execute sql - log.debug("creating temp table"); - java.sql.Statement tempStmt = conn.createStatement(); - - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) - tempTableName = SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE.substring(1); - else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER)) - tempTableName = this.getDbSchemaName() + SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE; - else - tempTableName = this.getDbSchemaName() - + FactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE; - - - try { - if (!dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE)) - tempStmt.executeUpdate("drop table " + tempTableName); - } catch (SQLException sqlex) { - ; - } - - uploadTempTable(tempStmt, tempTableName, patientNumList, dataSourceLookup.getServerType()); - String finalSql = "SELECT " - + selectClause - + " FROM " - + getDbSchemaName() - + "patient_dimension patient WHERE patient.patient_num IN (select distinct char_param1 FROM " - + tempTableName + ") order by patient_num"; - log.debug("Executing [" + finalSql + "]"); - - query = conn.prepareStatement(finalSql); - resultSet = query.executeQuery(); - //} - - I2B2PdoFactory.PatientBuilder patientBuilder = new I2B2PdoFactory().new PatientBuilder( - detailFlag, blobFlag, statusFlag, dataSourceLookup.getServerType()); - while (resultSet.next()) { - PatientType patientDimensionType = patientBuilder - .buildPatientSet(resultSet, this.metaDataParamList); - patientDimensionSet.getPatient().add(patientDimensionType); - } - - } catch (SQLException ex) { - log.error("", ex); - throw new I2B2DAOException("sql exception", ex); - } catch (IOException ioex) { - log.error("", ioex); - throw new I2B2DAOException("io exception", ioex); - } catch (Throwable t) { - t.printStackTrace(); - } finally { - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER)) { - PdoTempTableUtil tempUtil = new PdoTempTableUtil(); - tempUtil.deleteTempTableSqlServer(conn, tempTableName); - } - try { - JDBCUtil.closeJdbcResource(null, query, conn); - - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - } - - } - return patientDimensionSet; - } - - /** - * Get Patient dimension data based on patientlist present in input option - * list - * - * @param patientListType - * {@link PatientListType} - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return PatientDataType.PatientDimensionSet - * @throws I2B2DAOException - */ - @Override - public PatientSet getPatientFromPatientSet(PatientListType patientListType, - boolean detailFlag, boolean blobFlag, boolean statusFlag) - throws I2B2DAOException { - - PatientListTypeHandler patientListTypeHandler = new PatientListTypeHandler( - dataSourceLookup, patientListType); - String inSqlClause = patientListTypeHandler.generateWhereClauseSql(); - - PatientFactRelated patientRelated = new PatientFactRelated( - buildOutputOptionType(detailFlag, blobFlag, statusFlag)); - patientRelated.setMetaDataParamList(metaDataParamList); - - String selectClause = patientRelated.getSelectClause(); - String mainSqlString = " SELECT " + selectClause + " FROM " - + getDbSchemaName() - + "patient_dimension patient WHERE patient.patient_num IN ( "; - mainSqlString += inSqlClause; - mainSqlString += " ) order by patient_num \n"; - - PatientSet patientDimensionSet = new PatientSet(); - Connection conn = null; - PreparedStatement preparedStmt = null; - try { - // execute fullsql - conn = getDataSource().getConnection(); - - log.debug("Executing sql[" + mainSqlString + "]"); - - if (patientListTypeHandler.isCollectionId()) { - String patientSetCollectionId = patientListTypeHandler - .getCollectionId(); - preparedStmt = conn.prepareStatement(mainSqlString); - preparedStmt.setInt(1, Integer.parseInt(patientSetCollectionId)); - - } else if (patientListTypeHandler.isEnumerationSet()) { - - patientListTypeHandler.uploadEnumerationValueToTempTable(conn); - preparedStmt = conn.prepareStatement(mainSqlString); - - } else { - preparedStmt = conn.prepareStatement(mainSqlString); - } - ResultSet resultSet = preparedStmt.executeQuery(); - I2B2PdoFactory.PatientBuilder patientBuilder = new I2B2PdoFactory().new PatientBuilder( - detailFlag, blobFlag, statusFlag, dataSourceLookup.getServerType()); - while (resultSet.next()) { - PatientType patientDimensionType = patientBuilder - .buildPatientSet(resultSet, this.metaDataParamList); - patientDimensionSet.getPatient().add(patientDimensionType); - } - - } catch (SQLException sqlEx) { - log.error("", sqlEx); - throw new I2B2DAOException("SQLException", sqlEx); - } catch (IOException ioex) { - log.error("", ioex); - throw new I2B2DAOException("io exception", ioex); - } finally { - if (patientListTypeHandler.isEnumerationSet()) { - try { - patientListTypeHandler.deleteTempTable(conn); - } catch (SQLException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - try { - JDBCUtil.closeJdbcResource(null, preparedStmt, conn); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - } - } - return patientDimensionSet; - } - - /** - * Get Patient dimension data based on visitlist present in input option - * list - * - * @param eventListType - * {@link EventListType} - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return PatientDataType.PatientDimensionSet - * @throws I2B2DAOException - */ - @Override - public PatientSet getPatientFromVisitSet(EventListType visitListType, - boolean detailFlag, boolean blobFlag, boolean statusFlag) - throws I2B2DAOException { - - VisitListTypeHandler visitListTypeHandler = new VisitListTypeHandler( - dataSourceLookup, visitListType); - - String inSqlClause = null; - PatientFactRelated patientRelated = new PatientFactRelated( - buildOutputOptionType(detailFlag, blobFlag, statusFlag)); - patientRelated.setMetaDataParamList(metaDataParamList); - - String selectClause = patientRelated.getSelectClause(); - - String mainSqlString = " select " + selectClause + " from " - + getDbSchemaName() - + "patient_dimension patient where patient.patient_num in "; - - // if visit set id, then take patient num directly from - // qt_patient_enc_collection table, else go thru visit dimension to get - // patient num - if (visitListTypeHandler.isCollectionId()) { - inSqlClause = visitListTypeHandler.generatePatentSql(); - mainSqlString += " ( " + inSqlClause + " ) "; - } else { - inSqlClause = visitListTypeHandler.generateWhereClauseSql(); - mainSqlString += " (select distinct patient_num from " - + getDbSchemaName() + "visit_dimension where " - + " encounter_num in ( " + inSqlClause + " ))"; - } - mainSqlString += " order by patient_num"; - - PatientSet patientDimensionSet = new PatientSet(); - Connection conn = null; - PreparedStatement preparedStmt = null; - - try { - // execute fullsql - conn = getDataSource().getConnection(); - - log.debug("Executing sql [" + mainSqlString + "]"); - - if (visitListTypeHandler.isCollectionId()) { - String encounterSetCollectionId = visitListTypeHandler - .getCollectionId(); - preparedStmt = conn.prepareStatement(mainSqlString); - preparedStmt.setString(1, encounterSetCollectionId); - - } else if (visitListTypeHandler.isEnumerationSet()) { - String serverType = dataSourceLookup.getServerType(); - visitListTypeHandler.uploadEnumerationValueToTempTable(conn); - preparedStmt = conn.prepareStatement(mainSqlString); - - } else { - preparedStmt = conn.prepareStatement(mainSqlString); - } - - ResultSet resultSet = preparedStmt.executeQuery(); - I2B2PdoFactory.PatientBuilder patientBuilder = new I2B2PdoFactory().new PatientBuilder( - detailFlag, blobFlag, statusFlag, dataSourceLookup.getServerType()); - while (resultSet.next()) { - PatientType patientDimensionType = patientBuilder - .buildPatientSet(resultSet,this.metaDataParamList); - patientDimensionSet.getPatient().add(patientDimensionType); - } - - } catch (SQLException sqlEx) { - log.error("", sqlEx); - throw new I2B2DAOException("Sql exception", sqlEx); - } catch (IOException ioEx) { - log.error("", ioEx); - throw new I2B2DAOException("IO exception", ioEx); - } finally { - if (visitListTypeHandler.isEnumerationSet()) { - try { - visitListTypeHandler.deleteTempTable(conn); - } catch (SQLException e) { - - e.printStackTrace(); - } - } - try { - JDBCUtil.closeJdbcResource(null, preparedStmt, conn); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - } - } - - return patientDimensionSet; - - } - - private void uploadTempTable(Statement tempStmt, String tempTableName, - List patientNumList, String dbServer) throws SQLException { - if ( !dbServer.equalsIgnoreCase( - DAOFactoryHelper.ORACLE)) { - String createTempInputListTable = "create " - + (dbServer.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL) ? " temp ": "" ) - + " table " - + tempTableName - + " ( char_param1 varchar(100) )"; - tempStmt.executeUpdate(createTempInputListTable); - log.debug("created temp table" + tempTableName); - } - // load to temp table - // TempInputListInsert inputListInserter = new - // TempInputListInsert(dataSource,TEMP_PDO_INPUTLIST_TABLE); - // inputListInserter.setBatchSize(100); - int i = 0; - for (String singleValue : patientNumList) { - tempStmt.addBatch("insert into " + tempTableName + " values ('" - + singleValue + "' )"); - log.debug("adding batch" + singleValue); - i++; - if (i % 100 == 0) { - log.debug("batch insert"); - tempStmt.executeBatch(); - - } - } - log.debug("batch insert1"); - tempStmt.executeBatch(); - } - - - - @Override - public PatientSet getPatientByFact(List panelSqlList, - List sqlParamCountList, - IInputOptionListHandler inputOptionListHandler, boolean detailFlag, - boolean blobFlag, boolean statusFlag) throws I2B2DAOException { - - PatientSet patientSet = new PatientSet(); - I2B2PdoFactory.PatientBuilder patientBuilder = new I2B2PdoFactory().new PatientBuilder( - detailFlag, blobFlag, statusFlag, dataSourceLookup.getServerType()); - PatientFactRelated patientFactRelated = new PatientFactRelated( - buildOutputOptionType(detailFlag, blobFlag, statusFlag)); - patientFactRelated.setMetaDataParamList(metaDataParamList); - - String selectClause = patientFactRelated.getSelectClause(); - String serverType = dataSourceLookup.getServerType(); - String factTempTable = ""; - Connection conn = null; - PreparedStatement query = null; - try { - conn = dataSource.getConnection(); - if (serverType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { - factTempTable = this.getDbSchemaName() - + FactRelatedQueryHandler.TEMP_FACT_PARAM_TABLE; - } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.SQLSERVER) || - serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { - log.debug("creating temp table"); - java.sql.Statement tempStmt = conn.createStatement(); - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) - factTempTable = SQLServerFactRelatedQueryHandler.TEMP_FACT_PARAM_TABLE.substring(1); - else - factTempTable = SQLServerFactRelatedQueryHandler.TEMP_FACT_PARAM_TABLE; - try { - tempStmt.executeUpdate("drop table " + factTempTable); - } catch (SQLException sqlex) { - ; - } - String createTempInputListTable = "create " - + (serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL) ? " temp ": "" ) - + " table " - + factTempTable - + " ( set_index int, char_param1 varchar(500) )"; - tempStmt.executeUpdate(createTempInputListTable); - log.debug("created temp table" + factTempTable); - } - // if the inputlist is enumeration, then upload the enumerated input - // to temp table. - // the uploaded enumerated input will be used in the fact join. - if (inputOptionListHandler.isEnumerationSet()) { - inputOptionListHandler.uploadEnumerationValueToTempTable(conn); - } - String insertSql = ""; - int i = 0; - int sqlParamCount = 0; - ResultSet resultSet = null; - for (String panelSql : panelSqlList) { - insertSql = " insert into " - + factTempTable - + "(char_param1) select distinct obs_patient_num from ( " - + panelSql + ") b"; - - log.debug("Executing SQL [ " + insertSql + "]"); - sqlParamCount = sqlParamCountList.get(i++); - // conn.createStatement().executeUpdate(insertSql); - executeUpdateSql(insertSql, conn, sqlParamCount, - inputOptionListHandler); - - } - - String finalSql = "SELECT " - + selectClause - + " FROM " - + getDbSchemaName() - + "patient_dimension patient where patient_num in (select distinct char_param1 from " - + factTempTable + ") order by patient_num"; - log.debug("Executing SQL [" + finalSql + "]"); - - - query = conn.prepareStatement(finalSql); - - resultSet = query.executeQuery(); - - while (resultSet.next()) { - PatientType patient = patientBuilder.buildPatientSet(resultSet, this.metaDataParamList); - patientSet.getPatient().add(patient); - } - } catch (SQLException sqlEx) { - log.error("", sqlEx); - throw new I2B2DAOException("sql exception", sqlEx); - } catch (IOException ioEx) { - log.error("", ioEx); - throw new I2B2DAOException("IO exception", ioEx); - } finally { - - PdoTempTableUtil tempUtil = new PdoTempTableUtil(); - tempUtil.clearTempTable(dataSourceLookup.getServerType(), conn, factTempTable); - - if (inputOptionListHandler != null - && inputOptionListHandler.isEnumerationSet()) { - try { - inputOptionListHandler.deleteTempTable(conn); - } catch (SQLException e) { - - e.printStackTrace(); - } - } - try { - - JDBCUtil.closeJdbcResource(null, query, conn); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - } - } - return patientSet; - - } - - private void executeUpdateSql(String totalSql, Connection conn, - int sqlParamCount, IInputOptionListHandler inputOptionListHandler) - throws SQLException { - - PreparedStatement stmt = conn.prepareStatement(totalSql); - - log.debug(totalSql + " [ " + sqlParamCount + " ]"); - if (inputOptionListHandler.isCollectionId()) { - for (int i = 1; i <= sqlParamCount; i++) { - stmt.setInt(i, Integer.parseInt(inputOptionListHandler - .getCollectionId())); - } - } - - stmt.executeUpdate(); - - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao.pdo; + +import java.io.IOException; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.List; + +import javax.sql.DataSource; + + + +//import org.jboss.resource.adapter.jdbc.WrappedConnection; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.util.db.JDBCUtil; +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.dao.pdo.input.FactRelatedQueryHandler; +import edu.harvard.i2b2.crc.dao.pdo.input.IInputOptionListHandler; +import edu.harvard.i2b2.crc.dao.pdo.input.PatientListTypeHandler; +import edu.harvard.i2b2.crc.dao.pdo.input.SQLServerFactRelatedQueryHandler; +import edu.harvard.i2b2.crc.dao.pdo.input.VisitListTypeHandler; +import edu.harvard.i2b2.crc.dao.pdo.output.PatientFactRelated; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.pdo.ParamType; +import edu.harvard.i2b2.crc.datavo.pdo.PatientSet; +import edu.harvard.i2b2.crc.datavo.pdo.PatientType; +import edu.harvard.i2b2.crc.datavo.pdo.query.EventListType; +import edu.harvard.i2b2.crc.datavo.pdo.query.PatientListType; + +/** + * Class to build patient section of plain pdo $Id: PdoQueryPatientDao.java,v + * 1.11 2008/03/19 22:42:08 rk903 Exp $ + * + * @author rkuttan + */ +public class PdoQueryPatientDao extends CRCDAO implements IPdoQueryPatientDao { + + private DataSourceLookup dataSourceLookup = null; + private List metaDataParamList = null; + + public PdoQueryPatientDao(DataSourceLookup dataSourceLookup, + DataSource dataSource) { + setDataSource(dataSource); + setDbSchemaName(dataSourceLookup.getFullSchema()); + this.dataSourceLookup = dataSourceLookup; + } + + @Override + public void setMetaDataParamList(List metaDataParamList) { + this.metaDataParamList = metaDataParamList; + } + + /** + * Function to return patient dimension data for given list of patient num + * + * @param patientNumList + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return PatientDataType.PatientDimensionSet + * @throws Exception + */ + @Override + public PatientSet getPatientByPatientNum(List patientNumList, + boolean detailFlag, boolean blobFlag, boolean statusFlag) + throws I2B2DAOException { + + Connection conn = null; + PreparedStatement query = null; + PatientSet patientDimensionSet = new PatientSet(); + + String tempTableName = ""; + try { + // execute fullsql + conn = getDataSource().getConnection(); + PatientFactRelated patientRelated = new PatientFactRelated( + buildOutputOptionType(detailFlag, blobFlag, statusFlag)); + patientRelated.setMetaDataParamList(this.metaDataParamList); + + String selectClause = patientRelated.getSelectClause(); + ResultSet resultSet = null; + /* + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.ORACLE)) { + //oracle.jdbc.driver.OracleConnection conn1 = null;// (oracle.jdbc.driver.OracleConnection) ((WrappedConnection) conn) + //.getUnderlyingConnection(); + String finalSql = "SELECT " + + selectClause + + " FROM " + + getDbSchemaName() + + "patient_dimension patient WHERE patient.patient_num IN (SELECT * FROM TABLE (cast (? as QT_PDO_QRY_STRING_ARRAY))) order by 1"; + log.debug("Executing [" + finalSql + "]"); + query = conn.prepareStatement(finalSql); + + ArrayDescriptor desc = ArrayDescriptor.createDescriptor( + "QT_PDO_QRY_STRING_ARRAY", conn); + + oracle.sql.ARRAY paramArray = new oracle.sql.ARRAY(desc, conn, + patientNumList.toArray(new String[] {})); + query.setArray(1, paramArray); + resultSet = query.executeQuery(); + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER) || + dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) { + */ + // create temp table + // load to temp table + // execute sql + log.debug("creating temp table"); + java.sql.Statement tempStmt = conn.createStatement(); + + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) + tempTableName = SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE.substring(1); + else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER)) + tempTableName = this.getDbSchemaName() + SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE; + else + tempTableName = this.getDbSchemaName() + + FactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE; + + + try { + if (!dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.ORACLE)) + tempStmt.executeUpdate("drop table " + tempTableName); + } catch (SQLException sqlex) { + ; + } + + uploadTempTable(tempStmt, tempTableName, patientNumList, dataSourceLookup.getServerType()); + String finalSql = "SELECT " + + selectClause + + " FROM " + + getDbSchemaName() + + "patient_dimension patient WHERE patient.patient_num IN (select distinct char_param1 FROM " + + tempTableName + ") order by patient_num"; + log.debug("Executing [" + finalSql + "]"); + + query = conn.prepareStatement(finalSql); + resultSet = query.executeQuery(); + //} + + I2B2PdoFactory.PatientBuilder patientBuilder = new I2B2PdoFactory().new PatientBuilder( + detailFlag, blobFlag, statusFlag, dataSourceLookup.getServerType()); + while (resultSet.next()) { + PatientType patientDimensionType = patientBuilder + .buildPatientSet(resultSet, this.metaDataParamList); + patientDimensionSet.getPatient().add(patientDimensionType); + } + + } catch (SQLException ex) { + log.error("", ex); + throw new I2B2DAOException("sql exception", ex); + } catch (IOException ioex) { + log.error("", ioex); + throw new I2B2DAOException("io exception", ioex); + } catch (Throwable t) { + t.printStackTrace(); + } finally { + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER)) { + PdoTempTableUtil tempUtil = new PdoTempTableUtil(); + tempUtil.deleteTempTableSqlServer(conn, tempTableName); + } + try { + JDBCUtil.closeJdbcResource(null, query, conn); + + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + } + + } + return patientDimensionSet; + } + + /** + * Get Patient dimension data based on patientlist present in input option + * list + * + * @param patientListType + * {@link PatientListType} + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return PatientDataType.PatientDimensionSet + * @throws I2B2DAOException + */ + @Override + public PatientSet getPatientFromPatientSet(PatientListType patientListType, + boolean detailFlag, boolean blobFlag, boolean statusFlag) + throws I2B2DAOException { + + PatientListTypeHandler patientListTypeHandler = new PatientListTypeHandler( + dataSourceLookup, patientListType); + String inSqlClause = patientListTypeHandler.generateWhereClauseSql(); + + PatientFactRelated patientRelated = new PatientFactRelated( + buildOutputOptionType(detailFlag, blobFlag, statusFlag)); + patientRelated.setMetaDataParamList(metaDataParamList); + + String selectClause = patientRelated.getSelectClause(); + String mainSqlString = " SELECT " + selectClause + " FROM " + + getDbSchemaName() + + "patient_dimension patient WHERE patient.patient_num IN ( "; + mainSqlString += inSqlClause; + mainSqlString += " ) order by patient_num \n"; + + PatientSet patientDimensionSet = new PatientSet(); + Connection conn = null; + PreparedStatement preparedStmt = null; + try { + // execute fullsql + conn = getDataSource().getConnection(); + + log.debug("Executing sql[" + mainSqlString + "]"); + + if (patientListTypeHandler.isCollectionId()) { + String patientSetCollectionId = patientListTypeHandler + .getCollectionId(); + preparedStmt = conn.prepareStatement(mainSqlString); + preparedStmt.setInt(1, Integer.parseInt(patientSetCollectionId)); + + } else if (patientListTypeHandler.isEnumerationSet()) { + + patientListTypeHandler.uploadEnumerationValueToTempTable(conn); + preparedStmt = conn.prepareStatement(mainSqlString); + + } else { + preparedStmt = conn.prepareStatement(mainSqlString); + } + ResultSet resultSet = preparedStmt.executeQuery(); + I2B2PdoFactory.PatientBuilder patientBuilder = new I2B2PdoFactory().new PatientBuilder( + detailFlag, blobFlag, statusFlag, dataSourceLookup.getServerType()); + while (resultSet.next()) { + PatientType patientDimensionType = patientBuilder + .buildPatientSet(resultSet, this.metaDataParamList); + patientDimensionSet.getPatient().add(patientDimensionType); + } + + } catch (SQLException sqlEx) { + log.error("", sqlEx); + throw new I2B2DAOException("SQLException", sqlEx); + } catch (IOException ioex) { + log.error("", ioex); + throw new I2B2DAOException("io exception", ioex); + } finally { + if (patientListTypeHandler.isEnumerationSet()) { + try { + patientListTypeHandler.deleteTempTable(conn); + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + try { + JDBCUtil.closeJdbcResource(null, preparedStmt, conn); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + } + } + return patientDimensionSet; + } + + /** + * Get Patient dimension data based on visitlist present in input option + * list + * + * @param eventListType + * {@link EventListType} + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return PatientDataType.PatientDimensionSet + * @throws I2B2DAOException + */ + @Override + public PatientSet getPatientFromVisitSet(EventListType visitListType, + boolean detailFlag, boolean blobFlag, boolean statusFlag) + throws I2B2DAOException { + + VisitListTypeHandler visitListTypeHandler = new VisitListTypeHandler( + dataSourceLookup, visitListType); + + String inSqlClause = null; + PatientFactRelated patientRelated = new PatientFactRelated( + buildOutputOptionType(detailFlag, blobFlag, statusFlag)); + patientRelated.setMetaDataParamList(metaDataParamList); + + String selectClause = patientRelated.getSelectClause(); + + String mainSqlString = " select " + selectClause + " from " + + getDbSchemaName() + + "patient_dimension patient where patient.patient_num in "; + + // if visit set id, then take patient num directly from + // qt_patient_enc_collection table, else go thru visit dimension to get + // patient num + if (visitListTypeHandler.isCollectionId()) { + inSqlClause = visitListTypeHandler.generatePatentSql(); + mainSqlString += " ( " + inSqlClause + " ) "; + } else { + inSqlClause = visitListTypeHandler.generateWhereClauseSql(); + mainSqlString += " (select distinct patient_num from " + + getDbSchemaName() + "visit_dimension where " + + " encounter_num in ( " + inSqlClause + " ))"; + } + mainSqlString += " order by patient_num"; + + PatientSet patientDimensionSet = new PatientSet(); + Connection conn = null; + PreparedStatement preparedStmt = null; + + try { + // execute fullsql + conn = getDataSource().getConnection(); + + log.debug("Executing sql [" + mainSqlString + "]"); + + if (visitListTypeHandler.isCollectionId()) { + String encounterSetCollectionId = visitListTypeHandler + .getCollectionId(); + preparedStmt = conn.prepareStatement(mainSqlString); + preparedStmt.setString(1, encounterSetCollectionId); + + } else if (visitListTypeHandler.isEnumerationSet()) { + String serverType = dataSourceLookup.getServerType(); + visitListTypeHandler.uploadEnumerationValueToTempTable(conn); + preparedStmt = conn.prepareStatement(mainSqlString); + + } else { + preparedStmt = conn.prepareStatement(mainSqlString); + } + + ResultSet resultSet = preparedStmt.executeQuery(); + I2B2PdoFactory.PatientBuilder patientBuilder = new I2B2PdoFactory().new PatientBuilder( + detailFlag, blobFlag, statusFlag, dataSourceLookup.getServerType()); + while (resultSet.next()) { + PatientType patientDimensionType = patientBuilder + .buildPatientSet(resultSet,this.metaDataParamList); + patientDimensionSet.getPatient().add(patientDimensionType); + } + + } catch (SQLException sqlEx) { + log.error("", sqlEx); + throw new I2B2DAOException("Sql exception", sqlEx); + } catch (IOException ioEx) { + log.error("", ioEx); + throw new I2B2DAOException("IO exception", ioEx); + } finally { + if (visitListTypeHandler.isEnumerationSet()) { + try { + visitListTypeHandler.deleteTempTable(conn); + } catch (SQLException e) { + + e.printStackTrace(); + } + } + try { + JDBCUtil.closeJdbcResource(null, preparedStmt, conn); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + } + } + + return patientDimensionSet; + + } + + private void uploadTempTable(Statement tempStmt, String tempTableName, + List patientNumList, String dbServer) throws SQLException { + if ( !dbServer.equalsIgnoreCase( + DAOFactoryHelper.ORACLE)) { + String createTempInputListTable = "create " + + (dbServer.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL) ? " temp ": "" ) + + " table " + + tempTableName + + " ( char_param1 varchar(100) )"; + tempStmt.executeUpdate(createTempInputListTable); + log.debug("created temp table" + tempTableName); + } + // load to temp table + // TempInputListInsert inputListInserter = new + // TempInputListInsert(dataSource,TEMP_PDO_INPUTLIST_TABLE); + // inputListInserter.setBatchSize(100); + int i = 0; + for (String singleValue : patientNumList) { + tempStmt.addBatch("insert into " + tempTableName + " values ('" + + singleValue + "' )"); + log.debug("adding batch" + singleValue); + i++; + if (i % 100 == 0) { + log.debug("batch insert"); + tempStmt.executeBatch(); + + } + } + log.debug("batch insert1"); + tempStmt.executeBatch(); + } + + + + @Override + public PatientSet getPatientByFact(List panelSqlList, + List sqlParamCountList, + IInputOptionListHandler inputOptionListHandler, boolean detailFlag, + boolean blobFlag, boolean statusFlag) throws I2B2DAOException { + + PatientSet patientSet = new PatientSet(); + I2B2PdoFactory.PatientBuilder patientBuilder = new I2B2PdoFactory().new PatientBuilder( + detailFlag, blobFlag, statusFlag, dataSourceLookup.getServerType()); + PatientFactRelated patientFactRelated = new PatientFactRelated( + buildOutputOptionType(detailFlag, blobFlag, statusFlag)); + patientFactRelated.setMetaDataParamList(metaDataParamList); + + String selectClause = patientFactRelated.getSelectClause(); + String serverType = dataSourceLookup.getServerType(); + String factTempTable = ""; + Connection conn = null; + PreparedStatement query = null; + try { + conn = dataSource.getConnection(); + if (serverType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { + factTempTable = this.getDbSchemaName() + + FactRelatedQueryHandler.TEMP_FACT_PARAM_TABLE; + } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.SQLSERVER) || + serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { + log.debug("creating temp table"); + java.sql.Statement tempStmt = conn.createStatement(); + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) + factTempTable = SQLServerFactRelatedQueryHandler.TEMP_FACT_PARAM_TABLE.substring(1); + else + factTempTable = SQLServerFactRelatedQueryHandler.TEMP_FACT_PARAM_TABLE; + try { + tempStmt.executeUpdate("drop table " + factTempTable); + } catch (SQLException sqlex) { + ; + } + String createTempInputListTable = "create " + + (serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL) ? " temp ": "" ) + + " table " + + factTempTable + + " ( set_index int, char_param1 varchar(500) )"; + tempStmt.executeUpdate(createTempInputListTable); + log.debug("created temp table" + factTempTable); + } + // if the inputlist is enumeration, then upload the enumerated input + // to temp table. + // the uploaded enumerated input will be used in the fact join. + if (inputOptionListHandler.isEnumerationSet()) { + inputOptionListHandler.uploadEnumerationValueToTempTable(conn); + } + String insertSql = ""; + int i = 0; + int sqlParamCount = 0; + ResultSet resultSet = null; + for (String panelSql : panelSqlList) { + insertSql = " insert into " + + factTempTable + + "(char_param1) select distinct obs_patient_num from ( " + + panelSql + ") b"; + + log.debug("Executing SQL [ " + insertSql + "]"); + sqlParamCount = sqlParamCountList.get(i++); + // conn.createStatement().executeUpdate(insertSql); + executeUpdateSql(insertSql, conn, sqlParamCount, + inputOptionListHandler); + + } + + String finalSql = "SELECT " + + selectClause + + " FROM " + + getDbSchemaName() + + "patient_dimension patient where patient_num in (select distinct char_param1 from " + + factTempTable + ") order by patient_num"; + log.debug("Executing SQL [" + finalSql + "]"); + + + query = conn.prepareStatement(finalSql); + + resultSet = query.executeQuery(); + + while (resultSet.next()) { + PatientType patient = patientBuilder.buildPatientSet(resultSet, this.metaDataParamList); + patientSet.getPatient().add(patient); + } + } catch (SQLException sqlEx) { + log.error("", sqlEx); + throw new I2B2DAOException("sql exception", sqlEx); + } catch (IOException ioEx) { + log.error("", ioEx); + throw new I2B2DAOException("IO exception", ioEx); + } finally { + + PdoTempTableUtil tempUtil = new PdoTempTableUtil(); + tempUtil.clearTempTable(dataSourceLookup.getServerType(), conn, factTempTable); + + if (inputOptionListHandler != null + && inputOptionListHandler.isEnumerationSet()) { + try { + inputOptionListHandler.deleteTempTable(conn); + } catch (SQLException e) { + + e.printStackTrace(); + } + } + try { + + JDBCUtil.closeJdbcResource(null, query, conn); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + } + } + return patientSet; + + } + + private void executeUpdateSql(String totalSql, Connection conn, + int sqlParamCount, IInputOptionListHandler inputOptionListHandler) + throws SQLException { + + PreparedStatement stmt = conn.prepareStatement(totalSql); + + log.debug(totalSql + " [ " + sqlParamCount + " ]"); + if (inputOptionListHandler.isCollectionId()) { + for (int i = 1; i <= sqlParamCount; i++) { + stmt.setInt(i, Integer.parseInt(inputOptionListHandler + .getCollectionId())); + } + } + + stmt.executeUpdate(); + + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/PdoQueryPidDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/PdoQueryPidDao.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/PdoQueryPidDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/PdoQueryPidDao.java index 64d7d36d..730540a8 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/PdoQueryPidDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/PdoQueryPidDao.java @@ -1,682 +1,682 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao.pdo; - -import java.io.IOException; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.List; - -import javax.sql.DataSource; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import oracle.sql.ArrayDescriptor; - -//import org.jboss.resource.adapter.jdbc.WrappedConnection; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.util.db.JDBCUtil; -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.dao.pdo.input.FactRelatedQueryHandler; -import edu.harvard.i2b2.crc.dao.pdo.input.IInputOptionListHandler; -import edu.harvard.i2b2.crc.dao.pdo.input.PatientListTypeHandler; -import edu.harvard.i2b2.crc.dao.pdo.input.SQLServerFactRelatedQueryHandler; -import edu.harvard.i2b2.crc.dao.pdo.output.PidFactRelated; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.pdo.PidSet; -import edu.harvard.i2b2.crc.datavo.pdo.PidType; -import edu.harvard.i2b2.crc.datavo.pdo.PidType.PatientId; -import edu.harvard.i2b2.crc.datavo.pdo.query.PatientListType; -import edu.harvard.i2b2.crc.datavo.pdo.query.PidListType; -import edu.harvard.i2b2.crc.datavo.pdo.query.PidListType.Pid; - -/** - * Class to build patient section of plain pdo $Id: PdoQueryPatientDao.java,v - * 1.11 2008/03/19 22:42:08 rk903 Exp $ - * - * @author rkuttan - */ -public class PdoQueryPidDao extends CRCDAO implements IPdoQueryPidDao { - - private DataSourceLookup dataSourceLookup = null; - protected static Log logesapi = LogFactory.getLog(PdoQueryPidDao.class); - - public PdoQueryPidDao(DataSourceLookup dataSourceLookup, - DataSource dataSource) { - setDataSource(dataSource); - setDbSchemaName(dataSourceLookup.getFullSchema()); - this.dataSourceLookup = dataSourceLookup; - } - - /** - * Function to return patient dimension data for given list of patient num - * - * @param patientNumList - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return PatientDataType.PatientDimensionSet - * @throws Exception - */ - @Override - public PidSet getPidByPatientNum(List patientNumList, - boolean detailFlag, boolean blobFlag, boolean statusFlag) - throws I2B2DAOException { - - Connection conn = null; - PreparedStatement query = null; - PidSet pidSet = new PidSet(); - - try { - // execute fullsql - conn = getDataSource().getConnection(); - PidFactRelated pidRelated = new PidFactRelated( - buildOutputOptionType(detailFlag, blobFlag, statusFlag)); - String selectClause = pidRelated.getSelectClause(); - ResultSet resultSet = null; - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE)) { - - String finalSql = "SELECT " - + selectClause - + " FROM " - + getDbSchemaName() - + "patient_mapping pm WHERE pm.patient_num IN (SELECT * FROM TABLE (cast (? as QT_PDO_QRY_STRING_ARRAY))) order by pm_patient_num"; - log.debug("Executing [" + finalSql + "]"); - - oracle.jdbc.driver.OracleConnection conn1 = null;// (oracle.jdbc.driver.OracleConnection) ((WrappedConnection) conn) - // .getUnderlyingConnection(); - query = conn.prepareStatement(finalSql); - ArrayDescriptor desc = ArrayDescriptor.createDescriptor( - "QT_PDO_QRY_STRING_ARRAY", conn1); - - oracle.sql.ARRAY paramArray = new oracle.sql.ARRAY(desc, conn1, - patientNumList.toArray(new String[] {})); - query.setArray(1, paramArray); - resultSet = query.executeQuery(); - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER)) { - // create temp table - // load to temp table - // execute sql - log.debug("creating temp table"); - java.sql.Statement tempStmt = conn.createStatement(); - - uploadTempTable(tempStmt, patientNumList, dataSourceLookup.getServerType().equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)); - String finalSql = "SELECT " - + selectClause - + " FROM " - + getDbSchemaName() - + "patient_mapping pm WHERE pm.patient_num IN (select distinct char_param1 FROM " - + SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE - + ") order by pm_patient_num"; - log.debug("Executing [" + finalSql + "]"); - - query = conn.prepareStatement(finalSql); - resultSet = query.executeQuery(); - } else if - (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) - { - // create temp table - // load to temp table - // execute sql - log.debug("creating temp table"); - java.sql.Statement tempStmt = conn.createStatement(); - - uploadTempTable(tempStmt, patientNumList,dataSourceLookup.getServerType().equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)); - String finalSql = "SELECT " - + selectClause - + " FROM " - + getDbSchemaName() - + "patient_mapping pm WHERE pm.patient_num IN (select distinct char_param1 FROM " - + SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE.substring(1) - + ") order by pm_patient_num"; - log.debug("Executing [" + finalSql + "]"); - - query = conn.prepareStatement(finalSql); - resultSet = query.executeQuery(); - } - - RPDRPdoFactory.PidBuilder pidBuilder = new RPDRPdoFactory.PidBuilder( - detailFlag, blobFlag, statusFlag); - pidSet = buildPidSetFromResultSet(resultSet, pidBuilder); - - } catch (SQLException ex) { - log.error("", ex); - throw new I2B2DAOException("sql exception", ex); - } catch (IOException ioex) { - log.error("", ioex); - throw new I2B2DAOException("io exception", ioex); - } catch (Throwable t) { - t.printStackTrace(); - } finally { - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER)) { - deleteTempTable( - conn, - SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE); - } - try { - JDBCUtil.closeJdbcResource(null, query, conn); - - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - } - - } - return pidSet; - } - - /** - * Get Patient dimension data based on patientlist present in input option - * list - * - * @param patientListType - * {@link PatientListType} - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return PatientDataType.PatientDimensionSet - * @throws I2B2DAOException - */ - @Override - public PidSet getPidFromPatientSet(PatientListType patientListType, - boolean detailFlag, boolean blobFlag, boolean statusFlag) - throws I2B2DAOException { - - PatientListTypeHandler patientListTypeHandler = new PatientListTypeHandler( - dataSourceLookup, patientListType); - String inSqlClause = patientListTypeHandler.generateWhereClauseSql(); - - PidFactRelated pidRelated = new PidFactRelated(buildOutputOptionType( - detailFlag, blobFlag, statusFlag)); - String selectClause = pidRelated.getSelectClause(); - String mainSqlString = " SELECT " + selectClause + " FROM " - + getDbSchemaName() - + "patient_mapping pm WHERE pm.patient_num IN ( "; - mainSqlString += inSqlClause; - mainSqlString += " ) order by pm_patient_num \n"; - - PidSet pidSet = new PidSet(); - Connection conn = null; - PreparedStatement preparedStmt = null; - try { - // execute fullsql - conn = getDataSource().getConnection(); - - log.debug("Executing sql[" + mainSqlString + "]"); - - if (patientListTypeHandler.isCollectionId()) { - String patientSetCollectionId = patientListTypeHandler - .getCollectionId(); - preparedStmt = conn.prepareStatement(mainSqlString); - preparedStmt.setInt(1, Integer.parseInt(patientSetCollectionId)); - - } else if (patientListTypeHandler.isEnumerationSet()) { - String serverType = dataSourceLookup.getServerType(); - patientListTypeHandler.uploadEnumerationValueToTempTable(conn); - preparedStmt = conn.prepareStatement(mainSqlString); - - } else { - preparedStmt = conn.prepareStatement(mainSqlString); - } - ResultSet resultSet = preparedStmt.executeQuery(); - RPDRPdoFactory.PidBuilder pidBuilder = new RPDRPdoFactory.PidBuilder( - detailFlag, blobFlag, statusFlag); - pidSet = buildPidSetFromResultSet(resultSet, pidBuilder); - - } catch (SQLException sqlEx) { - log.error("", sqlEx); - throw new I2B2DAOException("SQLException", sqlEx); - } catch (IOException ioex) { - log.error("", ioex); - throw new I2B2DAOException("io exception", ioex); - } finally { - if (patientListTypeHandler.isEnumerationSet()) { - try { - patientListTypeHandler.deleteTempTable(conn); - } catch (SQLException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - try { - JDBCUtil.closeJdbcResource(null, preparedStmt, conn); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - } - } - return pidSet; - } - - /** - * Function to return patient dimension data for given list of pid list - * - * @param pidList - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return PatientDataType.PatientDimensionSet - * @throws Exception - */ - @Override - public PidSet getPidByPidList(PidListType pidList, boolean detailFlag, - boolean blobFlag, boolean statusFlag) throws I2B2DAOException { - - Connection conn = null; - PreparedStatement query = null; - PidSet pidSet = new PidSet(); - String tempTableName = this.getDbSchemaName() + FactRelatedQueryHandler.TEMP_PARAM_TABLE; - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER)) { - tempTableName = this.getDbSchemaName() + SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE; - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) { - tempTableName = SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE.substring(1); - } - try { - // execute fullsql - conn = getDataSource().getConnection(); - PidFactRelated pidRelated = new PidFactRelated( - buildOutputOptionType(detailFlag, blobFlag, statusFlag)); - String selectClause = pidRelated.getSelectClause(); - ResultSet resultSet = null; - - - - // create temp table - // load to temp table - // execute sql - log.debug("creating temp table"); - java.sql.Statement tempStmt = conn.createStatement(); - - upLoadPidListToTempTable(conn, tempTableName, pidList); - String finalSql = "SELECT " - + selectClause - + " FROM " - + getDbSchemaName() - + "patient_mapping pm WHERE " - + "patient_num in (select patient_num from " - + getDbSchemaName() - + "patient_mapping where " - + " exists (select char_param2 FROM " - + tempTableName - + " where patient_ide = char_param2 and patient_ide_source = char_param1 )) order by pm_patient_num"; - log.debug("Executing [" + finalSql + "]"); - - query = conn.prepareStatement(finalSql); - resultSet = query.executeQuery(); - - RPDRPdoFactory.PidBuilder pidBuilder = new RPDRPdoFactory.PidBuilder( - detailFlag, blobFlag, statusFlag); - pidSet = buildPidSetFromResultSet(resultSet, pidBuilder); - if (pidSet.getPid()!=null) { - logesapi.debug("pid set size " + pidSet.getPid().size()); - if (pidSet.getPid().size()>0) { - logesapi.debug("pid set size " + pidSet.getPid().get(0).getPatientId().getValue()); - } - } - - } catch (SQLException ex) { - log.error("", ex); - throw new I2B2DAOException("sql exception", ex); - } catch (IOException ioex) { - log.error("", ioex); - throw new I2B2DAOException("io exception", ioex); - } catch (Throwable t) { - t.printStackTrace(); - } finally { - PdoTempTableUtil tempUtil = new PdoTempTableUtil(); - tempUtil.clearTempTable(dataSourceLookup.getServerType(), conn, tempTableName); - - try { - JDBCUtil.closeJdbcResource(null, query, conn); - - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - } - - } - return pidSet; - } - - private PidSet buildPidSetFromResultSet(ResultSet resultSet, - RPDRPdoFactory.PidBuilder pidBuilder) throws SQLException, - IOException { - String prevPatientNum = ""; - PidType pidType = new PidType(); - PidSet pidSet = new PidSet(); - boolean firstFlag = true; - PatientId singlePatientId = new PatientId(); - PidType singlePidType = null; - PidType.PatientMapId pidMapId = null; - String tempSinglePidType = null; - while (resultSet.next()) { - singlePidType = pidBuilder.buildPidSet(resultSet); - pidMapId = singlePidType.getPatientMapId().get(0); - - tempSinglePidType = singlePidType.getPatientId().getValue(); - - if (pidMapId.getSource().equalsIgnoreCase("hive")) { - singlePatientId = new PatientId(); - singlePatientId.setSource(pidMapId.getSource()); - singlePatientId.setValue(pidMapId.getValue()); - singlePatientId.setSourcesystemCd(pidMapId.getSourcesystemCd()); - singlePatientId.setStatus(pidMapId.getStatus()); - singlePatientId.setUploadId(pidMapId.getUploadId()); - singlePatientId.setUpdateDate(pidMapId.getUpdateDate()); - singlePatientId.setImportDate(pidMapId.getImportDate()); - singlePatientId.setDownloadDate(pidMapId.getDownloadDate()); - } - - if (prevPatientNum.equals(tempSinglePidType)) { - if (!pidMapId.getSource().equalsIgnoreCase("hive")) { - pidType.getPatientMapId().add(pidMapId); - } else { - pidType.setPatientId(singlePatientId); - } - - } else { - if (!firstFlag) { - pidSet.getPid().add(pidType); - } else { - firstFlag = false; - } - - pidType = new PidType(); - if (pidMapId.getSource().equalsIgnoreCase("hive")) { - pidType.setPatientId(singlePatientId); - } else { - pidType.getPatientMapId().add(pidMapId); - } - } - prevPatientNum = tempSinglePidType; - - } - if ((pidType.getPatientId() != null && pidType.getPatientId() - .getValue() != null) - || (pidType.getPatientMapId() != null && pidType - .getPatientMapId().size() > 0)) { - // pidType.setPatientId(singlePatientId); - pidSet.getPid().add(pidType); - } - return pidSet; - } - - private void uploadTempTable(Statement tempStmt, List patientNumList, boolean isPostgresql) - throws SQLException { - String temp_pdo = SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE; - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) - temp_pdo = temp_pdo.substring(1); - - String createTempInputListTable = "create " - + (isPostgresql ? " temp ": "" ) - + " table " - + temp_pdo - + " ( char_param1 varchar(100) )"; - - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) - createTempInputListTable = "create temp table " - + temp_pdo - + " ( char_param1 varchar(100) )"; - - - tempStmt.executeUpdate(createTempInputListTable); - log.debug("created temp table" - + temp_pdo); - // load to temp table - // TempInputListInsert inputListInserter = new - // TempInputListInsert(dataSource,TEMP_PDO_INPUTLIST_TABLE); - // inputListInserter.setBatchSize(100); - int i = 0; - for (String singleValue : patientNumList) { - tempStmt.addBatch("insert into " - + temp_pdo - + " values ('" + singleValue + "' )"); - log.debug("adding batch" + singleValue); - i++; - if (i % 100 == 0) { - log.debug("batch insert"); - tempStmt.executeBatch(); - - } - } - log.debug("batch insert1"); - tempStmt.executeBatch(); - } - - private void deleteTempTable(Connection conn, String tempTableName) { - - - Statement deleteStmt = null; - try { - deleteStmt = conn.createStatement(); - //conn.createStatement().executeUpdate("drop table " + tempTableName); - deleteStmt.executeUpdate("drop table " + tempTableName); - } catch (SQLException sqle) { - ; - } finally { - try { - if (deleteStmt != null) - deleteStmt.close(); - } catch (SQLException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - } - - private void upLoadPidListToTempTable(Connection conn, - String tempTableName, PidListType pidListType) throws SQLException { - - // create temp table - java.sql.Statement tempStmt = conn.createStatement(); - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER)) { - String createTempInputListTable = "create table " - + tempTableName - + " (set_index int, char_param1 varchar(200), char_param2 varchar(200) )"; - tempStmt.executeUpdate(createTempInputListTable); - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) { - String createTempInputListTable = "create temp table " - + tempTableName - + " (set_index int, char_param1 varchar(200), char_param2 varchar(200) )"; - tempStmt.executeUpdate(createTempInputListTable); - } - // load to temp table - // TempInputListInsert inputListInserter = new - // TempInputListInsert(dataSource,TEMP_PDO_INPUTLIST_TABLE); - // inputListInserter.setBatchSize(100); - int i = 0, j = 1; - for (Pid pid : pidListType.getPid()) { - tempStmt.addBatch("insert into " + tempTableName - + "(set_index,char_param1,char_param2) values (" - + pid.getIndex() + ",'" + pid.getSource() + "','" - + pid.getValue() + "')"); - i++; - if (i % 100 == 0) { - tempStmt.executeBatch(); - - } - } - tempStmt.executeBatch(); - } - - @Override - public PidSet getPidByFact(List panelSqlList, - List sqlParamCountList, - IInputOptionListHandler inputOptionListHandler, boolean detailFlag, - boolean blobFlag, boolean statusFlag) throws I2B2DAOException { - - PidSet pidSet = new PidSet(); - RPDRPdoFactory.PidBuilder pidBuilder = new RPDRPdoFactory.PidBuilder( - detailFlag, blobFlag, statusFlag); - PidFactRelated pidFactRelated = new PidFactRelated( - buildOutputOptionType(detailFlag, blobFlag, statusFlag)); - String selectClause = pidFactRelated.getSelectClause(); - - String serverType = dataSourceLookup.getServerType(); - String tempTable = ""; - Connection conn = null; - PreparedStatement query = null; - try { - conn = dataSource.getConnection(); - if (serverType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { - tempTable = FactRelatedQueryHandler.TEMP_PARAM_TABLE; - } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.SQLSERVER)) { - log.debug("creating temp table"); - java.sql.Statement tempStmt = conn.createStatement(); - tempTable = SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE; - try { - tempStmt.executeUpdate("drop table " + tempTable); - } catch (SQLException sqlex) { - ; - } - String createTempInputListTable = "create table " + tempTable - + " ( set_index int, char_param1 varchar(500) )"; - tempStmt.executeUpdate(createTempInputListTable); - log.debug("created temp table" + tempTable); - } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { - log.debug("creating temp table"); - java.sql.Statement tempStmt = conn.createStatement(); - tempTable = SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE.substring(1); - try { - tempStmt.executeUpdate("drop table " + tempTable); - } catch (SQLException sqlex) { - ; - } - String createTempInputListTable = "create temp table " + tempTable - + " ( set_index int, char_param1 varchar(500) )"; - tempStmt.executeUpdate(createTempInputListTable); - log.debug("created temp table" + tempTable); - } - // if the inputlist is enumeration, then upload the enumerated input - // to temp table. - // the uploaded enumerated input will be used in the fact join. - if (inputOptionListHandler.isEnumerationSet()) { - inputOptionListHandler.uploadEnumerationValueToTempTable(conn); - } - String insertSql = ""; - int i = 0; - int sqlParamCount = 0; - ResultSet resultSet = null; - for (String panelSql : panelSqlList) { - // if sqlserver and getting a pid than remove order by - if (serverType.equalsIgnoreCase(DAOFactoryHelper.SQLSERVER)) { - panelSql = panelSql.replace("ORDER BY obs_patient_num,obs_start_date,obs_concept_cd,obs_instance_num,obs_modifier_cd,rnum", ""); - - } - insertSql = " insert into " - + tempTable - + "(char_param1) select distinct obs_patient_num from ( " - + panelSql + ") b"; - - log.debug("Executing SQL [ " + insertSql + "]"); - sqlParamCount = sqlParamCountList.get(i++); - // conn.createStatement().executeUpdate(insertSql); - executeUpdateSql(insertSql, conn, sqlParamCount, - inputOptionListHandler); - - } - - String finalSql = "SELECT " - + selectClause - + " FROM " - + getDbSchemaName() - + "patient_mapping pm " - + " where patient_num in (select distinct "; - - if (serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) - finalSql += " CAST(coalesce(char_param1, '0') as integer) "; - else - finalSql += " char_param1 "; - - - finalSql += "from " - + tempTable + ") order by patient_num"; - log.debug("Executing SQL [" + finalSql + "]"); - log.debug("Final Sql " + finalSql); - - query = conn.prepareStatement(finalSql); - - resultSet = query.executeQuery(); - - // while (resultSet.next()) { - // PidType pid = pidBuilder.buildPidSet(resultSet); - // pidSet.getPid().add(pid); - // } - pidSet = buildPidSetFromResultSet(resultSet, pidBuilder); - } catch (SQLException sqlEx) { - log.error("", sqlEx); - throw new I2B2DAOException("sql exception", sqlEx); - } catch (IOException ioEx) { - log.error("", ioEx); - throw new I2B2DAOException("IO exception", ioEx); - } finally { - PdoTempTableUtil tempUtil = new PdoTempTableUtil(); - tempUtil.clearTempTable(dataSourceLookup.getServerType(), conn, tempTable); - - if (inputOptionListHandler != null - && inputOptionListHandler.isEnumerationSet()) { - try { - inputOptionListHandler.deleteTempTable(conn); - } catch (SQLException e) { - - e.printStackTrace(); - } - } - try { - - JDBCUtil.closeJdbcResource(null, query, conn); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - } - } - return pidSet; - - } - - - - private void executeUpdateSql(String totalSql, Connection conn, - int sqlParamCount, IInputOptionListHandler inputOptionListHandler) - throws SQLException { - - PreparedStatement stmt = conn.prepareStatement(totalSql); - - log.debug(totalSql + " [ " + sqlParamCount + " ]"); - if (inputOptionListHandler.isCollectionId()) { - for (int i = 1; i <= sqlParamCount; i++) { - stmt.setInt(i, Integer.parseInt(inputOptionListHandler - .getCollectionId())); - } - } - - stmt.executeUpdate(); - - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao.pdo; + +import java.io.IOException; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.List; + +import javax.sql.DataSource; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import oracle.sql.ArrayDescriptor; + +//import org.jboss.resource.adapter.jdbc.WrappedConnection; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.util.db.JDBCUtil; +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.dao.pdo.input.FactRelatedQueryHandler; +import edu.harvard.i2b2.crc.dao.pdo.input.IInputOptionListHandler; +import edu.harvard.i2b2.crc.dao.pdo.input.PatientListTypeHandler; +import edu.harvard.i2b2.crc.dao.pdo.input.SQLServerFactRelatedQueryHandler; +import edu.harvard.i2b2.crc.dao.pdo.output.PidFactRelated; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.pdo.PidSet; +import edu.harvard.i2b2.crc.datavo.pdo.PidType; +import edu.harvard.i2b2.crc.datavo.pdo.PidType.PatientId; +import edu.harvard.i2b2.crc.datavo.pdo.query.PatientListType; +import edu.harvard.i2b2.crc.datavo.pdo.query.PidListType; +import edu.harvard.i2b2.crc.datavo.pdo.query.PidListType.Pid; + +/** + * Class to build patient section of plain pdo $Id: PdoQueryPatientDao.java,v + * 1.11 2008/03/19 22:42:08 rk903 Exp $ + * + * @author rkuttan + */ +public class PdoQueryPidDao extends CRCDAO implements IPdoQueryPidDao { + + private DataSourceLookup dataSourceLookup = null; + protected static Log logesapi = LogFactory.getLog(PdoQueryPidDao.class); + + public PdoQueryPidDao(DataSourceLookup dataSourceLookup, + DataSource dataSource) { + setDataSource(dataSource); + setDbSchemaName(dataSourceLookup.getFullSchema()); + this.dataSourceLookup = dataSourceLookup; + } + + /** + * Function to return patient dimension data for given list of patient num + * + * @param patientNumList + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return PatientDataType.PatientDimensionSet + * @throws Exception + */ + @Override + public PidSet getPidByPatientNum(List patientNumList, + boolean detailFlag, boolean blobFlag, boolean statusFlag) + throws I2B2DAOException { + + Connection conn = null; + PreparedStatement query = null; + PidSet pidSet = new PidSet(); + + try { + // execute fullsql + conn = getDataSource().getConnection(); + PidFactRelated pidRelated = new PidFactRelated( + buildOutputOptionType(detailFlag, blobFlag, statusFlag)); + String selectClause = pidRelated.getSelectClause(); + ResultSet resultSet = null; + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.ORACLE)) { + + String finalSql = "SELECT " + + selectClause + + " FROM " + + getDbSchemaName() + + "patient_mapping pm WHERE pm.patient_num IN (SELECT * FROM TABLE (cast (? as QT_PDO_QRY_STRING_ARRAY))) order by pm_patient_num"; + log.debug("Executing [" + finalSql + "]"); + + oracle.jdbc.driver.OracleConnection conn1 = null;// (oracle.jdbc.driver.OracleConnection) ((WrappedConnection) conn) + // .getUnderlyingConnection(); + query = conn.prepareStatement(finalSql); + ArrayDescriptor desc = ArrayDescriptor.createDescriptor( + "QT_PDO_QRY_STRING_ARRAY", conn1); + + oracle.sql.ARRAY paramArray = new oracle.sql.ARRAY(desc, conn1, + patientNumList.toArray(new String[] {})); + query.setArray(1, paramArray); + resultSet = query.executeQuery(); + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER)) { + // create temp table + // load to temp table + // execute sql + log.debug("creating temp table"); + java.sql.Statement tempStmt = conn.createStatement(); + + uploadTempTable(tempStmt, patientNumList, dataSourceLookup.getServerType().equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)); + String finalSql = "SELECT " + + selectClause + + " FROM " + + getDbSchemaName() + + "patient_mapping pm WHERE pm.patient_num IN (select distinct char_param1 FROM " + + SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE + + ") order by pm_patient_num"; + log.debug("Executing [" + finalSql + "]"); + + query = conn.prepareStatement(finalSql); + resultSet = query.executeQuery(); + } else if + (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) + { + // create temp table + // load to temp table + // execute sql + log.debug("creating temp table"); + java.sql.Statement tempStmt = conn.createStatement(); + + uploadTempTable(tempStmt, patientNumList,dataSourceLookup.getServerType().equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)); + String finalSql = "SELECT " + + selectClause + + " FROM " + + getDbSchemaName() + + "patient_mapping pm WHERE pm.patient_num IN (select distinct char_param1 FROM " + + SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE.substring(1) + + ") order by pm_patient_num"; + log.debug("Executing [" + finalSql + "]"); + + query = conn.prepareStatement(finalSql); + resultSet = query.executeQuery(); + } + + RPDRPdoFactory.PidBuilder pidBuilder = new RPDRPdoFactory.PidBuilder( + detailFlag, blobFlag, statusFlag); + pidSet = buildPidSetFromResultSet(resultSet, pidBuilder); + + } catch (SQLException ex) { + log.error("", ex); + throw new I2B2DAOException("sql exception", ex); + } catch (IOException ioex) { + log.error("", ioex); + throw new I2B2DAOException("io exception", ioex); + } catch (Throwable t) { + t.printStackTrace(); + } finally { + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER)) { + deleteTempTable( + conn, + SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE); + } + try { + JDBCUtil.closeJdbcResource(null, query, conn); + + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + } + + } + return pidSet; + } + + /** + * Get Patient dimension data based on patientlist present in input option + * list + * + * @param patientListType + * {@link PatientListType} + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return PatientDataType.PatientDimensionSet + * @throws I2B2DAOException + */ + @Override + public PidSet getPidFromPatientSet(PatientListType patientListType, + boolean detailFlag, boolean blobFlag, boolean statusFlag) + throws I2B2DAOException { + + PatientListTypeHandler patientListTypeHandler = new PatientListTypeHandler( + dataSourceLookup, patientListType); + String inSqlClause = patientListTypeHandler.generateWhereClauseSql(); + + PidFactRelated pidRelated = new PidFactRelated(buildOutputOptionType( + detailFlag, blobFlag, statusFlag)); + String selectClause = pidRelated.getSelectClause(); + String mainSqlString = " SELECT " + selectClause + " FROM " + + getDbSchemaName() + + "patient_mapping pm WHERE pm.patient_num IN ( "; + mainSqlString += inSqlClause; + mainSqlString += " ) order by pm_patient_num \n"; + + PidSet pidSet = new PidSet(); + Connection conn = null; + PreparedStatement preparedStmt = null; + try { + // execute fullsql + conn = getDataSource().getConnection(); + + log.debug("Executing sql[" + mainSqlString + "]"); + + if (patientListTypeHandler.isCollectionId()) { + String patientSetCollectionId = patientListTypeHandler + .getCollectionId(); + preparedStmt = conn.prepareStatement(mainSqlString); + preparedStmt.setInt(1, Integer.parseInt(patientSetCollectionId)); + + } else if (patientListTypeHandler.isEnumerationSet()) { + String serverType = dataSourceLookup.getServerType(); + patientListTypeHandler.uploadEnumerationValueToTempTable(conn); + preparedStmt = conn.prepareStatement(mainSqlString); + + } else { + preparedStmt = conn.prepareStatement(mainSqlString); + } + ResultSet resultSet = preparedStmt.executeQuery(); + RPDRPdoFactory.PidBuilder pidBuilder = new RPDRPdoFactory.PidBuilder( + detailFlag, blobFlag, statusFlag); + pidSet = buildPidSetFromResultSet(resultSet, pidBuilder); + + } catch (SQLException sqlEx) { + log.error("", sqlEx); + throw new I2B2DAOException("SQLException", sqlEx); + } catch (IOException ioex) { + log.error("", ioex); + throw new I2B2DAOException("io exception", ioex); + } finally { + if (patientListTypeHandler.isEnumerationSet()) { + try { + patientListTypeHandler.deleteTempTable(conn); + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + try { + JDBCUtil.closeJdbcResource(null, preparedStmt, conn); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + } + } + return pidSet; + } + + /** + * Function to return patient dimension data for given list of pid list + * + * @param pidList + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return PatientDataType.PatientDimensionSet + * @throws Exception + */ + @Override + public PidSet getPidByPidList(PidListType pidList, boolean detailFlag, + boolean blobFlag, boolean statusFlag) throws I2B2DAOException { + + Connection conn = null; + PreparedStatement query = null; + PidSet pidSet = new PidSet(); + String tempTableName = this.getDbSchemaName() + FactRelatedQueryHandler.TEMP_PARAM_TABLE; + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER)) { + tempTableName = this.getDbSchemaName() + SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE; + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) { + tempTableName = SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE.substring(1); + } + try { + // execute fullsql + conn = getDataSource().getConnection(); + PidFactRelated pidRelated = new PidFactRelated( + buildOutputOptionType(detailFlag, blobFlag, statusFlag)); + String selectClause = pidRelated.getSelectClause(); + ResultSet resultSet = null; + + + + // create temp table + // load to temp table + // execute sql + log.debug("creating temp table"); + java.sql.Statement tempStmt = conn.createStatement(); + + upLoadPidListToTempTable(conn, tempTableName, pidList); + String finalSql = "SELECT " + + selectClause + + " FROM " + + getDbSchemaName() + + "patient_mapping pm WHERE " + + "patient_num in (select patient_num from " + + getDbSchemaName() + + "patient_mapping where " + + " exists (select char_param2 FROM " + + tempTableName + + " where patient_ide = char_param2 and patient_ide_source = char_param1 )) order by pm_patient_num"; + log.debug("Executing [" + finalSql + "]"); + + query = conn.prepareStatement(finalSql); + resultSet = query.executeQuery(); + + RPDRPdoFactory.PidBuilder pidBuilder = new RPDRPdoFactory.PidBuilder( + detailFlag, blobFlag, statusFlag); + pidSet = buildPidSetFromResultSet(resultSet, pidBuilder); + if (pidSet.getPid()!=null) { + logesapi.debug("pid set size " + pidSet.getPid().size()); + if (pidSet.getPid().size()>0) { + logesapi.debug("pid set size " + pidSet.getPid().get(0).getPatientId().getValue()); + } + } + + } catch (SQLException ex) { + log.error("", ex); + throw new I2B2DAOException("sql exception", ex); + } catch (IOException ioex) { + log.error("", ioex); + throw new I2B2DAOException("io exception", ioex); + } catch (Throwable t) { + t.printStackTrace(); + } finally { + PdoTempTableUtil tempUtil = new PdoTempTableUtil(); + tempUtil.clearTempTable(dataSourceLookup.getServerType(), conn, tempTableName); + + try { + JDBCUtil.closeJdbcResource(null, query, conn); + + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + } + + } + return pidSet; + } + + private PidSet buildPidSetFromResultSet(ResultSet resultSet, + RPDRPdoFactory.PidBuilder pidBuilder) throws SQLException, + IOException { + String prevPatientNum = ""; + PidType pidType = new PidType(); + PidSet pidSet = new PidSet(); + boolean firstFlag = true; + PatientId singlePatientId = new PatientId(); + PidType singlePidType = null; + PidType.PatientMapId pidMapId = null; + String tempSinglePidType = null; + while (resultSet.next()) { + singlePidType = pidBuilder.buildPidSet(resultSet); + pidMapId = singlePidType.getPatientMapId().get(0); + + tempSinglePidType = singlePidType.getPatientId().getValue(); + + if (pidMapId.getSource().equalsIgnoreCase("hive")) { + singlePatientId = new PatientId(); + singlePatientId.setSource(pidMapId.getSource()); + singlePatientId.setValue(pidMapId.getValue()); + singlePatientId.setSourcesystemCd(pidMapId.getSourcesystemCd()); + singlePatientId.setStatus(pidMapId.getStatus()); + singlePatientId.setUploadId(pidMapId.getUploadId()); + singlePatientId.setUpdateDate(pidMapId.getUpdateDate()); + singlePatientId.setImportDate(pidMapId.getImportDate()); + singlePatientId.setDownloadDate(pidMapId.getDownloadDate()); + } + + if (prevPatientNum.equals(tempSinglePidType)) { + if (!pidMapId.getSource().equalsIgnoreCase("hive")) { + pidType.getPatientMapId().add(pidMapId); + } else { + pidType.setPatientId(singlePatientId); + } + + } else { + if (!firstFlag) { + pidSet.getPid().add(pidType); + } else { + firstFlag = false; + } + + pidType = new PidType(); + if (pidMapId.getSource().equalsIgnoreCase("hive")) { + pidType.setPatientId(singlePatientId); + } else { + pidType.getPatientMapId().add(pidMapId); + } + } + prevPatientNum = tempSinglePidType; + + } + if ((pidType.getPatientId() != null && pidType.getPatientId() + .getValue() != null) + || (pidType.getPatientMapId() != null && pidType + .getPatientMapId().size() > 0)) { + // pidType.setPatientId(singlePatientId); + pidSet.getPid().add(pidType); + } + return pidSet; + } + + private void uploadTempTable(Statement tempStmt, List patientNumList, boolean isPostgresql) + throws SQLException { + String temp_pdo = SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE; + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) + temp_pdo = temp_pdo.substring(1); + + String createTempInputListTable = "create " + + (isPostgresql ? " temp ": "" ) + + " table " + + temp_pdo + + " ( char_param1 varchar(100) )"; + + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) + createTempInputListTable = "create temp table " + + temp_pdo + + " ( char_param1 varchar(100) )"; + + + tempStmt.executeUpdate(createTempInputListTable); + log.debug("created temp table" + + temp_pdo); + // load to temp table + // TempInputListInsert inputListInserter = new + // TempInputListInsert(dataSource,TEMP_PDO_INPUTLIST_TABLE); + // inputListInserter.setBatchSize(100); + int i = 0; + for (String singleValue : patientNumList) { + tempStmt.addBatch("insert into " + + temp_pdo + + " values ('" + singleValue + "' )"); + log.debug("adding batch" + singleValue); + i++; + if (i % 100 == 0) { + log.debug("batch insert"); + tempStmt.executeBatch(); + + } + } + log.debug("batch insert1"); + tempStmt.executeBatch(); + } + + private void deleteTempTable(Connection conn, String tempTableName) { + + + Statement deleteStmt = null; + try { + deleteStmt = conn.createStatement(); + //conn.createStatement().executeUpdate("drop table " + tempTableName); + deleteStmt.executeUpdate("drop table " + tempTableName); + } catch (SQLException sqle) { + ; + } finally { + try { + if (deleteStmt != null) + deleteStmt.close(); + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + } + + private void upLoadPidListToTempTable(Connection conn, + String tempTableName, PidListType pidListType) throws SQLException { + + // create temp table + java.sql.Statement tempStmt = conn.createStatement(); + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER)) { + String createTempInputListTable = "create table " + + tempTableName + + " (set_index int, char_param1 varchar(200), char_param2 varchar(200) )"; + tempStmt.executeUpdate(createTempInputListTable); + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) { + String createTempInputListTable = "create temp table " + + tempTableName + + " (set_index int, char_param1 varchar(200), char_param2 varchar(200) )"; + tempStmt.executeUpdate(createTempInputListTable); + } + // load to temp table + // TempInputListInsert inputListInserter = new + // TempInputListInsert(dataSource,TEMP_PDO_INPUTLIST_TABLE); + // inputListInserter.setBatchSize(100); + int i = 0, j = 1; + for (Pid pid : pidListType.getPid()) { + tempStmt.addBatch("insert into " + tempTableName + + "(set_index,char_param1,char_param2) values (" + + pid.getIndex() + ",'" + pid.getSource() + "','" + + pid.getValue() + "')"); + i++; + if (i % 100 == 0) { + tempStmt.executeBatch(); + + } + } + tempStmt.executeBatch(); + } + + @Override + public PidSet getPidByFact(List panelSqlList, + List sqlParamCountList, + IInputOptionListHandler inputOptionListHandler, boolean detailFlag, + boolean blobFlag, boolean statusFlag) throws I2B2DAOException { + + PidSet pidSet = new PidSet(); + RPDRPdoFactory.PidBuilder pidBuilder = new RPDRPdoFactory.PidBuilder( + detailFlag, blobFlag, statusFlag); + PidFactRelated pidFactRelated = new PidFactRelated( + buildOutputOptionType(detailFlag, blobFlag, statusFlag)); + String selectClause = pidFactRelated.getSelectClause(); + + String serverType = dataSourceLookup.getServerType(); + String tempTable = ""; + Connection conn = null; + PreparedStatement query = null; + try { + conn = dataSource.getConnection(); + if (serverType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { + tempTable = FactRelatedQueryHandler.TEMP_PARAM_TABLE; + } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.SQLSERVER)) { + log.debug("creating temp table"); + java.sql.Statement tempStmt = conn.createStatement(); + tempTable = SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE; + try { + tempStmt.executeUpdate("drop table " + tempTable); + } catch (SQLException sqlex) { + ; + } + String createTempInputListTable = "create table " + tempTable + + " ( set_index int, char_param1 varchar(500) )"; + tempStmt.executeUpdate(createTempInputListTable); + log.debug("created temp table" + tempTable); + } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { + log.debug("creating temp table"); + java.sql.Statement tempStmt = conn.createStatement(); + tempTable = SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE.substring(1); + try { + tempStmt.executeUpdate("drop table " + tempTable); + } catch (SQLException sqlex) { + ; + } + String createTempInputListTable = "create temp table " + tempTable + + " ( set_index int, char_param1 varchar(500) )"; + tempStmt.executeUpdate(createTempInputListTable); + log.debug("created temp table" + tempTable); + } + // if the inputlist is enumeration, then upload the enumerated input + // to temp table. + // the uploaded enumerated input will be used in the fact join. + if (inputOptionListHandler.isEnumerationSet()) { + inputOptionListHandler.uploadEnumerationValueToTempTable(conn); + } + String insertSql = ""; + int i = 0; + int sqlParamCount = 0; + ResultSet resultSet = null; + for (String panelSql : panelSqlList) { + // if sqlserver and getting a pid than remove order by + if (serverType.equalsIgnoreCase(DAOFactoryHelper.SQLSERVER)) { + panelSql = panelSql.replace("ORDER BY obs_patient_num,obs_start_date,obs_concept_cd,obs_instance_num,obs_modifier_cd,rnum", ""); + + } + insertSql = " insert into " + + tempTable + + "(char_param1) select distinct obs_patient_num from ( " + + panelSql + ") b"; + + log.debug("Executing SQL [ " + insertSql + "]"); + sqlParamCount = sqlParamCountList.get(i++); + // conn.createStatement().executeUpdate(insertSql); + executeUpdateSql(insertSql, conn, sqlParamCount, + inputOptionListHandler); + + } + + String finalSql = "SELECT " + + selectClause + + " FROM " + + getDbSchemaName() + + "patient_mapping pm " + + " where patient_num in (select distinct "; + + if (serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) + finalSql += " CAST(coalesce(char_param1, '0') as integer) "; + else + finalSql += " char_param1 "; + + + finalSql += "from " + + tempTable + ") order by patient_num"; + log.debug("Executing SQL [" + finalSql + "]"); + log.debug("Final Sql " + finalSql); + + query = conn.prepareStatement(finalSql); + + resultSet = query.executeQuery(); + + // while (resultSet.next()) { + // PidType pid = pidBuilder.buildPidSet(resultSet); + // pidSet.getPid().add(pid); + // } + pidSet = buildPidSetFromResultSet(resultSet, pidBuilder); + } catch (SQLException sqlEx) { + log.error("", sqlEx); + throw new I2B2DAOException("sql exception", sqlEx); + } catch (IOException ioEx) { + log.error("", ioEx); + throw new I2B2DAOException("IO exception", ioEx); + } finally { + PdoTempTableUtil tempUtil = new PdoTempTableUtil(); + tempUtil.clearTempTable(dataSourceLookup.getServerType(), conn, tempTable); + + if (inputOptionListHandler != null + && inputOptionListHandler.isEnumerationSet()) { + try { + inputOptionListHandler.deleteTempTable(conn); + } catch (SQLException e) { + + e.printStackTrace(); + } + } + try { + + JDBCUtil.closeJdbcResource(null, query, conn); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + } + } + return pidSet; + + } + + + + private void executeUpdateSql(String totalSql, Connection conn, + int sqlParamCount, IInputOptionListHandler inputOptionListHandler) + throws SQLException { + + PreparedStatement stmt = conn.prepareStatement(totalSql); + + log.debug(totalSql + " [ " + sqlParamCount + " ]"); + if (inputOptionListHandler.isCollectionId()) { + for (int i = 1; i <= sqlParamCount; i++) { + stmt.setInt(i, Integer.parseInt(inputOptionListHandler + .getCollectionId())); + } + } + + stmt.executeUpdate(); + + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/PdoQueryProviderDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/PdoQueryProviderDao.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/PdoQueryProviderDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/PdoQueryProviderDao.java index b5714d46..6234acdc --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/PdoQueryProviderDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/PdoQueryProviderDao.java @@ -1,318 +1,318 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao.pdo; - -import java.io.IOException; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.List; - -import javax.sql.DataSource; - -import oracle.sql.ArrayDescriptor; - -//import org.jboss.resource.adapter.jdbc.WrappedConnection; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.util.db.JDBCUtil; -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.dao.pdo.input.FactRelatedQueryHandler; -import edu.harvard.i2b2.crc.dao.pdo.input.IInputOptionListHandler; -import edu.harvard.i2b2.crc.dao.pdo.input.SQLServerFactRelatedQueryHandler; -import edu.harvard.i2b2.crc.dao.pdo.output.ProviderFactRelated; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.pdo.ObserverSet; -import edu.harvard.i2b2.crc.datavo.pdo.ObserverType; - -/** - * Class to support provider section of plain pdo query $Id: - * PdoQueryProviderDao.java,v 1.10 2008/03/19 22:42:08 rk903 Exp $ - * - * @author rkuttan - */ -public class PdoQueryProviderDao extends CRCDAO implements IPdoQueryProviderDao { - private DataSourceLookup dataSourceLookup = null; - - public PdoQueryProviderDao(DataSourceLookup dataSourceLookup, - DataSource dataSource) { - this.dataSourceLookup = dataSourceLookup; - setDbSchemaName(dataSourceLookup.getFullSchema()); - setDataSource(dataSource); - } - - /** - * Function to return provider/observer section of plain pdo for the given - * id list - * - * @param providerIdList - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return PatientDataType.ProviderDimensionSet - * @throws I2B2DAOException - */ - @Override - public ObserverSet getProviderById(List providerIdList, - boolean detailFlag, boolean blobFlag, boolean statusFlag) - throws I2B2DAOException { - ObserverSet providerDimensionSet = new ObserverSet(); - log.debug("provider list size " + providerIdList.size()); - Connection conn = null; - PreparedStatement query = null; - String tempTableName = ""; - try { - conn = getDataSource().getConnection(); - ProviderFactRelated providerRelated = new ProviderFactRelated( - buildOutputOptionType(detailFlag, blobFlag, statusFlag)); - String selectClause = providerRelated.getSelectClause(); - String serverType = dataSourceLookup.getServerType(); - if (serverType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { - oracle.jdbc.driver.OracleConnection conn1 = null;// (oracle.jdbc.driver.OracleConnection) ((WrappedConnection) conn) - // .getUnderlyingConnection(); - String finalSql = "SELECT " - + selectClause - + " FROM " - + getDbSchemaName() - + "provider_dimension provider WHERE provider.provider_id IN (SELECT * FROM TABLE (?))"; - log.debug("Executing sql[" + finalSql + "]"); - query = conn1.prepareStatement(finalSql); - - ArrayDescriptor desc = ArrayDescriptor.createDescriptor( - "QT_PDO_QRY_STRING_ARRAY", conn1); - oracle.sql.ARRAY paramArray = new oracle.sql.ARRAY(desc, conn1, - providerIdList.toArray(new String[] {})); - query.setArray(1, paramArray); - } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.SQLSERVER) || - serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { - log.debug("creating temp table"); - java.sql.Statement tempStmt = conn.createStatement(); - if (serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) - tempTableName = SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE.substring(1); - else - tempTableName = SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE; - try { - tempStmt.executeUpdate("drop table " + tempTableName); - } catch (SQLException sqlex) { - ; - } - - uploadTempTable(tempStmt, tempTableName, providerIdList, dataSourceLookup.getServerType().equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)); - String finalSql = "SELECT " - + selectClause - + " FROM " - + getDbSchemaName() - + "provider_dimension provider WHERE provider.provider_id IN (select distinct char_param1 FROM " - + tempTableName + ") order by provider_id"; - log.debug("Executing [" + finalSql + "]"); - - query = conn.prepareStatement(finalSql); - - } - ResultSet resultSet = query.executeQuery(); - I2B2PdoFactory.ProviderBuilder providerBuilder = new I2B2PdoFactory().new ProviderBuilder( - detailFlag, blobFlag, statusFlag, dataSourceLookup.getServerType()); - while (resultSet.next()) { - ObserverType providerDimensionType = providerBuilder - .buildObserverSet(resultSet); - providerDimensionSet.getObserver().add(providerDimensionType); - } - - } catch (SQLException sqlEx) { - log.error("", sqlEx); - throw new I2B2DAOException("sql exception", sqlEx); - } catch (IOException ioex) { - log.error("", ioex); - throw new I2B2DAOException("io exception", ioex); - } finally { - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER)) { - PdoTempTableUtil tempUtil = new PdoTempTableUtil(); - tempUtil.deleteTempTableSqlServer(conn, tempTableName); - } - try { - JDBCUtil.closeJdbcResource(null, query, conn); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - } - } - return providerDimensionSet; - } - - private void uploadTempTable(Statement tempStmt, String tempTable, - List patientNumList, boolean isPostgresql) throws SQLException { - String createTempInputListTable = "create " - + (isPostgresql ? " temp ": "" ) - + " table " + tempTable - + " ( char_param1 varchar(100) )"; - tempStmt.executeUpdate(createTempInputListTable); - log.debug("created temp table" + tempTable); - // load to temp table - // TempInputListInsert inputListInserter = new - // TempInputListInsert(dataSource,TEMP_PDO_INPUTLIST_TABLE); - // inputListInserter.setBatchSize(100); - int i = 0; - PreparedStatement preparedStmt = tempStmt.getConnection() - .prepareStatement("insert into " + tempTable + " values (?)"); - for (String singleValue : patientNumList) { - preparedStmt.setString(1, singleValue); - preparedStmt.addBatch(); - log.debug("adding batch" + singleValue); - i++; - if (i % 100 == 0) { - log.debug("batch insert"); - preparedStmt.executeBatch(); - - } - } - log.debug("batch insert1"); - preparedStmt.executeBatch(); - } - - - - @Override - public ObserverSet getProviderByFact(List panelSqlList, - List sqlParamCountList, - IInputOptionListHandler inputOptionListHandler, boolean detailFlag, - boolean blobFlag, boolean statusFlag) throws I2B2DAOException { - - ObserverSet observerSet = new ObserverSet(); - I2B2PdoFactory.ProviderBuilder providerBuilder = new I2B2PdoFactory().new ProviderBuilder( - detailFlag, blobFlag, statusFlag, dataSourceLookup.getServerType()); - ProviderFactRelated providerFactRelated = new ProviderFactRelated( - buildOutputOptionType(detailFlag, blobFlag, statusFlag)); - String selectClause = providerFactRelated.getSelectClause(); - String serverType = dataSourceLookup.getServerType(); - String factTempTable = ""; - Connection conn = null; - PreparedStatement query = null; - try { - conn = dataSource.getConnection(); - if (serverType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { - factTempTable = this.getDbSchemaName() - + FactRelatedQueryHandler.TEMP_FACT_PARAM_TABLE; - } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.SQLSERVER) || - serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { - log.debug("creating temp table"); - java.sql.Statement tempStmt = conn.createStatement(); - if (serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) - factTempTable = SQLServerFactRelatedQueryHandler.TEMP_FACT_PARAM_TABLE.substring(1); - else - factTempTable = SQLServerFactRelatedQueryHandler.TEMP_FACT_PARAM_TABLE; - try { - tempStmt.executeUpdate("drop table " + factTempTable); - } catch (SQLException sqlex) { - ; - } - String createTempInputListTable = "create table " - + factTempTable - + " ( set_index int, char_param1 varchar(500) )"; - tempStmt.executeUpdate(createTempInputListTable); - log.debug("created temp table" + factTempTable); - } - // if the inputlist is enumeration, then upload the enumerated input - // to temp table. - // the uploaded enumerated input will be used in the fact join. - if (inputOptionListHandler.isEnumerationSet()) { - inputOptionListHandler.uploadEnumerationValueToTempTable(conn); - } - String insertSql = ""; - int i = 0; - int sqlParamCount = 0; - ResultSet resultSet = null; - for (String panelSql : panelSqlList) { - insertSql = " insert into " - + factTempTable - + "(char_param1) select distinct obs_provider_id from ( " - + panelSql + ") b"; - - log.debug("Executing SQL [ " + insertSql + "]"); - sqlParamCount = sqlParamCountList.get(i++); - // conn.createStatement().executeUpdate(insertSql); - executeUpdateSql(insertSql, conn, sqlParamCount, - inputOptionListHandler); - - } - - String finalSql = "SELECT " - + selectClause - + " FROM " - + getDbSchemaName() - + "provider_dimension provider where provider_id in (select distinct char_param1 from " - + factTempTable + ") order by provider_path"; - log.debug("Executing SQL [" + finalSql + "]"); - log.debug("Final Sql " + finalSql); - - query = conn.prepareStatement(finalSql); - - resultSet = query.executeQuery(); - - while (resultSet.next()) { - ObserverType observer = providerBuilder - .buildObserverSet(resultSet); - observerSet.getObserver().add(observer); - } - } catch (SQLException sqlEx) { - log.error("", sqlEx); - throw new I2B2DAOException("sql exception", sqlEx); - } catch (IOException ioEx) { - log.error("", ioEx); - throw new I2B2DAOException("IO exception", ioEx); - } finally { - PdoTempTableUtil tempUtil = new PdoTempTableUtil(); - tempUtil.clearTempTable(dataSourceLookup.getServerType(),conn, factTempTable); - - if (inputOptionListHandler != null - && inputOptionListHandler.isEnumerationSet()) { - try { - inputOptionListHandler.deleteTempTable(conn); - } catch (SQLException e) { - - e.printStackTrace(); - } - } - try { - - JDBCUtil.closeJdbcResource(null, query, conn); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - } - } - return observerSet; - } - - private void executeUpdateSql(String totalSql, Connection conn, - int sqlParamCount, IInputOptionListHandler inputOptionListHandler) - throws SQLException { - - PreparedStatement stmt = conn.prepareStatement(totalSql); - - log.debug(totalSql + " [ " + sqlParamCount + " ]"); - if (inputOptionListHandler.isCollectionId()) { - for (int i = 1; i <= sqlParamCount; i++) { - stmt.setInt(i, Integer.parseInt(inputOptionListHandler - .getCollectionId())); - } - } - - stmt.executeUpdate(); - - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao.pdo; + +import java.io.IOException; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.List; + +import javax.sql.DataSource; + +import oracle.sql.ArrayDescriptor; + +//import org.jboss.resource.adapter.jdbc.WrappedConnection; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.util.db.JDBCUtil; +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.dao.pdo.input.FactRelatedQueryHandler; +import edu.harvard.i2b2.crc.dao.pdo.input.IInputOptionListHandler; +import edu.harvard.i2b2.crc.dao.pdo.input.SQLServerFactRelatedQueryHandler; +import edu.harvard.i2b2.crc.dao.pdo.output.ProviderFactRelated; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.pdo.ObserverSet; +import edu.harvard.i2b2.crc.datavo.pdo.ObserverType; + +/** + * Class to support provider section of plain pdo query $Id: + * PdoQueryProviderDao.java,v 1.10 2008/03/19 22:42:08 rk903 Exp $ + * + * @author rkuttan + */ +public class PdoQueryProviderDao extends CRCDAO implements IPdoQueryProviderDao { + private DataSourceLookup dataSourceLookup = null; + + public PdoQueryProviderDao(DataSourceLookup dataSourceLookup, + DataSource dataSource) { + this.dataSourceLookup = dataSourceLookup; + setDbSchemaName(dataSourceLookup.getFullSchema()); + setDataSource(dataSource); + } + + /** + * Function to return provider/observer section of plain pdo for the given + * id list + * + * @param providerIdList + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return PatientDataType.ProviderDimensionSet + * @throws I2B2DAOException + */ + @Override + public ObserverSet getProviderById(List providerIdList, + boolean detailFlag, boolean blobFlag, boolean statusFlag) + throws I2B2DAOException { + ObserverSet providerDimensionSet = new ObserverSet(); + log.debug("provider list size " + providerIdList.size()); + Connection conn = null; + PreparedStatement query = null; + String tempTableName = ""; + try { + conn = getDataSource().getConnection(); + ProviderFactRelated providerRelated = new ProviderFactRelated( + buildOutputOptionType(detailFlag, blobFlag, statusFlag)); + String selectClause = providerRelated.getSelectClause(); + String serverType = dataSourceLookup.getServerType(); + if (serverType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { + oracle.jdbc.driver.OracleConnection conn1 = null;// (oracle.jdbc.driver.OracleConnection) ((WrappedConnection) conn) + // .getUnderlyingConnection(); + String finalSql = "SELECT " + + selectClause + + " FROM " + + getDbSchemaName() + + "provider_dimension provider WHERE provider.provider_id IN (SELECT * FROM TABLE (?))"; + log.debug("Executing sql[" + finalSql + "]"); + query = conn1.prepareStatement(finalSql); + + ArrayDescriptor desc = ArrayDescriptor.createDescriptor( + "QT_PDO_QRY_STRING_ARRAY", conn1); + oracle.sql.ARRAY paramArray = new oracle.sql.ARRAY(desc, conn1, + providerIdList.toArray(new String[] {})); + query.setArray(1, paramArray); + } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.SQLSERVER) || + serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { + log.debug("creating temp table"); + java.sql.Statement tempStmt = conn.createStatement(); + if (serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) + tempTableName = SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE.substring(1); + else + tempTableName = SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE; + try { + tempStmt.executeUpdate("drop table " + tempTableName); + } catch (SQLException sqlex) { + ; + } + + uploadTempTable(tempStmt, tempTableName, providerIdList, dataSourceLookup.getServerType().equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)); + String finalSql = "SELECT " + + selectClause + + " FROM " + + getDbSchemaName() + + "provider_dimension provider WHERE provider.provider_id IN (select distinct char_param1 FROM " + + tempTableName + ") order by provider_id"; + log.debug("Executing [" + finalSql + "]"); + + query = conn.prepareStatement(finalSql); + + } + ResultSet resultSet = query.executeQuery(); + I2B2PdoFactory.ProviderBuilder providerBuilder = new I2B2PdoFactory().new ProviderBuilder( + detailFlag, blobFlag, statusFlag, dataSourceLookup.getServerType()); + while (resultSet.next()) { + ObserverType providerDimensionType = providerBuilder + .buildObserverSet(resultSet); + providerDimensionSet.getObserver().add(providerDimensionType); + } + + } catch (SQLException sqlEx) { + log.error("", sqlEx); + throw new I2B2DAOException("sql exception", sqlEx); + } catch (IOException ioex) { + log.error("", ioex); + throw new I2B2DAOException("io exception", ioex); + } finally { + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER)) { + PdoTempTableUtil tempUtil = new PdoTempTableUtil(); + tempUtil.deleteTempTableSqlServer(conn, tempTableName); + } + try { + JDBCUtil.closeJdbcResource(null, query, conn); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + } + } + return providerDimensionSet; + } + + private void uploadTempTable(Statement tempStmt, String tempTable, + List patientNumList, boolean isPostgresql) throws SQLException { + String createTempInputListTable = "create " + + (isPostgresql ? " temp ": "" ) + + " table " + tempTable + + " ( char_param1 varchar(100) )"; + tempStmt.executeUpdate(createTempInputListTable); + log.debug("created temp table" + tempTable); + // load to temp table + // TempInputListInsert inputListInserter = new + // TempInputListInsert(dataSource,TEMP_PDO_INPUTLIST_TABLE); + // inputListInserter.setBatchSize(100); + int i = 0; + PreparedStatement preparedStmt = tempStmt.getConnection() + .prepareStatement("insert into " + tempTable + " values (?)"); + for (String singleValue : patientNumList) { + preparedStmt.setString(1, singleValue); + preparedStmt.addBatch(); + log.debug("adding batch" + singleValue); + i++; + if (i % 100 == 0) { + log.debug("batch insert"); + preparedStmt.executeBatch(); + + } + } + log.debug("batch insert1"); + preparedStmt.executeBatch(); + } + + + + @Override + public ObserverSet getProviderByFact(List panelSqlList, + List sqlParamCountList, + IInputOptionListHandler inputOptionListHandler, boolean detailFlag, + boolean blobFlag, boolean statusFlag) throws I2B2DAOException { + + ObserverSet observerSet = new ObserverSet(); + I2B2PdoFactory.ProviderBuilder providerBuilder = new I2B2PdoFactory().new ProviderBuilder( + detailFlag, blobFlag, statusFlag, dataSourceLookup.getServerType()); + ProviderFactRelated providerFactRelated = new ProviderFactRelated( + buildOutputOptionType(detailFlag, blobFlag, statusFlag)); + String selectClause = providerFactRelated.getSelectClause(); + String serverType = dataSourceLookup.getServerType(); + String factTempTable = ""; + Connection conn = null; + PreparedStatement query = null; + try { + conn = dataSource.getConnection(); + if (serverType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { + factTempTable = this.getDbSchemaName() + + FactRelatedQueryHandler.TEMP_FACT_PARAM_TABLE; + } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.SQLSERVER) || + serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { + log.debug("creating temp table"); + java.sql.Statement tempStmt = conn.createStatement(); + if (serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) + factTempTable = SQLServerFactRelatedQueryHandler.TEMP_FACT_PARAM_TABLE.substring(1); + else + factTempTable = SQLServerFactRelatedQueryHandler.TEMP_FACT_PARAM_TABLE; + try { + tempStmt.executeUpdate("drop table " + factTempTable); + } catch (SQLException sqlex) { + ; + } + String createTempInputListTable = "create table " + + factTempTable + + " ( set_index int, char_param1 varchar(500) )"; + tempStmt.executeUpdate(createTempInputListTable); + log.debug("created temp table" + factTempTable); + } + // if the inputlist is enumeration, then upload the enumerated input + // to temp table. + // the uploaded enumerated input will be used in the fact join. + if (inputOptionListHandler.isEnumerationSet()) { + inputOptionListHandler.uploadEnumerationValueToTempTable(conn); + } + String insertSql = ""; + int i = 0; + int sqlParamCount = 0; + ResultSet resultSet = null; + for (String panelSql : panelSqlList) { + insertSql = " insert into " + + factTempTable + + "(char_param1) select distinct obs_provider_id from ( " + + panelSql + ") b"; + + log.debug("Executing SQL [ " + insertSql + "]"); + sqlParamCount = sqlParamCountList.get(i++); + // conn.createStatement().executeUpdate(insertSql); + executeUpdateSql(insertSql, conn, sqlParamCount, + inputOptionListHandler); + + } + + String finalSql = "SELECT " + + selectClause + + " FROM " + + getDbSchemaName() + + "provider_dimension provider where provider_id in (select distinct char_param1 from " + + factTempTable + ") order by provider_path"; + log.debug("Executing SQL [" + finalSql + "]"); + log.debug("Final Sql " + finalSql); + + query = conn.prepareStatement(finalSql); + + resultSet = query.executeQuery(); + + while (resultSet.next()) { + ObserverType observer = providerBuilder + .buildObserverSet(resultSet); + observerSet.getObserver().add(observer); + } + } catch (SQLException sqlEx) { + log.error("", sqlEx); + throw new I2B2DAOException("sql exception", sqlEx); + } catch (IOException ioEx) { + log.error("", ioEx); + throw new I2B2DAOException("IO exception", ioEx); + } finally { + PdoTempTableUtil tempUtil = new PdoTempTableUtil(); + tempUtil.clearTempTable(dataSourceLookup.getServerType(),conn, factTempTable); + + if (inputOptionListHandler != null + && inputOptionListHandler.isEnumerationSet()) { + try { + inputOptionListHandler.deleteTempTable(conn); + } catch (SQLException e) { + + e.printStackTrace(); + } + } + try { + + JDBCUtil.closeJdbcResource(null, query, conn); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + } + } + return observerSet; + } + + private void executeUpdateSql(String totalSql, Connection conn, + int sqlParamCount, IInputOptionListHandler inputOptionListHandler) + throws SQLException { + + PreparedStatement stmt = conn.prepareStatement(totalSql); + + log.debug(totalSql + " [ " + sqlParamCount + " ]"); + if (inputOptionListHandler.isCollectionId()) { + for (int i = 1; i <= sqlParamCount; i++) { + stmt.setInt(i, Integer.parseInt(inputOptionListHandler + .getCollectionId())); + } + } + + stmt.executeUpdate(); + + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/PdoQueryVisitDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/PdoQueryVisitDao.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/PdoQueryVisitDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/PdoQueryVisitDao.java index 387e4398..a1474a94 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/PdoQueryVisitDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/PdoQueryVisitDao.java @@ -1,501 +1,501 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao.pdo; - -import java.io.IOException; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.List; - -import javax.sql.DataSource; - -import oracle.sql.ArrayDescriptor; - -//import org.jboss.resource.adapter.jdbc.WrappedConnection; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.util.db.JDBCUtil; -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.dao.pdo.input.FactRelatedQueryHandler; -import edu.harvard.i2b2.crc.dao.pdo.input.IInputOptionListHandler; -import edu.harvard.i2b2.crc.dao.pdo.input.PatientListTypeHandler; -import edu.harvard.i2b2.crc.dao.pdo.input.SQLServerFactRelatedQueryHandler; -import edu.harvard.i2b2.crc.dao.pdo.input.VisitListTypeHandler; -import edu.harvard.i2b2.crc.dao.pdo.output.VisitFactRelated; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.pdo.EventSet; -import edu.harvard.i2b2.crc.datavo.pdo.EventType; -import edu.harvard.i2b2.crc.datavo.pdo.ParamType; -import edu.harvard.i2b2.crc.datavo.pdo.query.EventListType; -import edu.harvard.i2b2.crc.datavo.pdo.query.PatientListType; - -/** - * Class to support visit/event section of plain pdo query $Id: - * PdoQueryVisitDao.java,v 1.12 2008/04/08 19:41:30 rk903 Exp $ - * - * @author rkuttan - */ -public class PdoQueryVisitDao extends CRCDAO implements IPdoQueryVisitDao { - - private DataSourceLookup dataSourceLookup = null; - private List metaDataParamList = null; - - public PdoQueryVisitDao(DataSourceLookup dataSourceLookup, - DataSource dataSource) { - setDbSchemaName(dataSourceLookup.getFullSchema()); - setDataSource(dataSource); - this.dataSourceLookup = dataSourceLookup; - } - - @Override - public void setMetaDataParamList(List metaDataParamList) { - this.metaDataParamList = metaDataParamList; - } - - /** - * Function to return list of eventset for given encounter number list - * - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @exception I2B2DAOException - */ - @Override - public EventSet getVisitsByEncounterNum(List encounterNumList, - boolean detailFlag, boolean blobFlag, boolean statusFlag) - throws I2B2DAOException { - EventSet visitDimensionSet = new EventSet(); - log.debug("visit list size " + encounterNumList.size()); - Connection conn = null; - PreparedStatement query = null; - String tempTableName = ""; - try { - conn = getDataSource().getConnection(); - VisitFactRelated visitRelated = new VisitFactRelated( - buildOutputOptionType(detailFlag, blobFlag, statusFlag)); - visitRelated.setMetaDataParamList(this.metaDataParamList); - String selectClause = visitRelated.getSelectClause(); - String serverType = dataSourceLookup.getServerType(); - if (serverType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { - oracle.jdbc.driver.OracleConnection conn1 = null;//(oracle.jdbc.driver.OracleConnection) ((WrappedConnection) conn) - // .getUnderlyingConnection(); - String finalSql = "SELECT " - + selectClause - + " FROM " - + getDbSchemaName() - + "visit_dimension visit WHERE visit.encounter_num IN (SELECT * FROM TABLE (cast (? as QT_PDO_QRY_STRING_ARRAY)))"; - log.debug("Executing sql[" + finalSql + "]"); - query = conn1.prepareStatement(finalSql); - - ArrayDescriptor desc = ArrayDescriptor.createDescriptor( - "QT_PDO_QRY_STRING_ARRAY", conn1); - oracle.sql.ARRAY paramArray = new oracle.sql.ARRAY(desc, conn1, - encounterNumList.toArray(new String[] {})); - query.setArray(1, paramArray); - } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.SQLSERVER) || - serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { - log.debug("creating temp table"); - if (serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) - tempTableName = SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE.substring(1); - else - tempTableName = SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE; - java.sql.Statement tempStmt = conn.createStatement(); - - try { - tempStmt.executeUpdate("drop table " + tempTableName); - } catch (SQLException sqlex) { - ; - } - - uploadTempTable(tempStmt, tempTableName, encounterNumList, dataSourceLookup.getServerType().equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)); - String finalSql = "SELECT " - + selectClause - + " FROM " - + getDbSchemaName() - + "visit_dimension visit WHERE visit.encounter_num IN (select distinct char_param1 FROM " - + tempTableName + ") order by encounter_num"; - log.debug("Executing [" + finalSql + "]"); - - query = conn.prepareStatement(finalSql); - - } - ResultSet resultSet = query.executeQuery(); - I2B2PdoFactory.EventBuilder eventBuilder = new I2B2PdoFactory().new EventBuilder( - detailFlag, blobFlag, statusFlag, dataSourceLookup.getServerType()); - while (resultSet.next()) { - EventType visitDimensionType = eventBuilder - .buildEventSet(resultSet,this.metaDataParamList); - visitDimensionSet.getEvent().add(visitDimensionType); - } - - } catch (SQLException sqlEx) { - log.error("", sqlEx); - throw new I2B2DAOException("sql exception", sqlEx); - } catch (IOException ioex) { - log.error("", ioex); - throw new I2B2DAOException("io exception", ioex); - } finally { - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER)) { - PdoTempTableUtil tempUtil = new PdoTempTableUtil(); - tempUtil.deleteTempTableSqlServer(conn, tempTableName); - } - try { - JDBCUtil.closeJdbcResource(null, query, conn); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - } - } - return visitDimensionSet; - } - - /** - * Get visit dimension data base on visit list - * (InputOptionList.getVisitListType()) - * - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return I2B2DAOException - * @throws Exception - */ - @Override - public EventSet getVisitDimensionSetFromVisitList( - EventListType visitListType, boolean detailFlag, boolean blobFlag, - boolean statusFlag) throws I2B2DAOException { - VisitListTypeHandler visitListTypeHandler = new VisitListTypeHandler( - dataSourceLookup, visitListType); - String inSqlClause = visitListTypeHandler.generateWhereClauseSql(); - VisitFactRelated visitRelated = new VisitFactRelated( - buildOutputOptionType(detailFlag, blobFlag, statusFlag)); - visitRelated.setMetaDataParamList(this.metaDataParamList); - String selectClause = visitRelated.getSelectClause(); - - String mainSqlString = " SELECT " + selectClause + " FROM " - + getDbSchemaName() - + "visit_dimension visit WHERE visit.encounter_num IN ( "; - mainSqlString += inSqlClause; - mainSqlString += " ) order by visit.encounter_num, visit.patient_num \n"; - - EventSet visitDimensionSet = new EventSet(); - Connection conn = null; - PreparedStatement preparedStmt = null; - try { - // execute fullsql - conn = getDataSource().getConnection(); - - log.debug("Executing Sql[" + mainSqlString + "]"); - - if (visitListTypeHandler.isCollectionId()) { - String patientEncCollectionId = visitListTypeHandler - .getCollectionId(); - preparedStmt = conn.prepareStatement(mainSqlString); - preparedStmt.setInt(1,Integer.parseInt(patientEncCollectionId)); - - } else if (visitListTypeHandler.isEnumerationSet()) { - String serverType = dataSourceLookup.getServerType(); - visitListTypeHandler.uploadEnumerationValueToTempTable(conn); - preparedStmt = conn.prepareStatement(mainSqlString); - - } else { - preparedStmt = conn.prepareStatement(mainSqlString); - } - - ResultSet resultSet = preparedStmt.executeQuery(); - I2B2PdoFactory.EventBuilder eventBuilder = new I2B2PdoFactory().new EventBuilder( - detailFlag, blobFlag, statusFlag, dataSourceLookup.getServerType()); - while (resultSet.next()) { - // VisitDimensionType visitDimensionType = - // getVisitDimensionType(resultSet); - EventType visitDimensionType = eventBuilder - .buildEventSet(resultSet, metaDataParamList); - visitDimensionSet.getEvent().add(visitDimensionType); - } - } catch (SQLException sqlEx) { - log.error("", sqlEx); - throw new I2B2DAOException("sql exception", sqlEx); - } catch (IOException ioEx) { - log.error("", ioEx); - throw new I2B2DAOException("io exception", ioEx); - } finally { - if (visitListTypeHandler.isEnumerationSet()) { - try { - visitListTypeHandler.deleteTempTable(conn); - } catch (SQLException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - try { - JDBCUtil.closeJdbcResource(null, preparedStmt, conn); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - } - } - - return visitDimensionSet; - } - - /** - * Get visit dimension from patientlist (InputOptionList.getPatientList()) - * - * @param patientListType - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return PatientDataType.VisitDimensionSet - * @throws I2B2DAOException - */ - @Override - public EventSet getVisitDimensionSetFromPatientList( - PatientListType patientListType, boolean detailFlag, - boolean blobFlag, boolean statusFlag) throws I2B2DAOException { - - VisitFactRelated visitRelated = new VisitFactRelated( - buildOutputOptionType(detailFlag, blobFlag, statusFlag)); - visitRelated.setMetaDataParamList(this.metaDataParamList); - String selectClause = visitRelated.getSelectClause(); - String mainSqlString = " SELECT " + selectClause + " FROM " - + getDbSchemaName() - + "visit_dimension visit WHERE visit.patient_num IN ( "; - PatientListTypeHandler patientListTypeHandler = new PatientListTypeHandler( - dataSourceLookup, patientListType); - String inSqlClause = patientListTypeHandler.generateWhereClauseSql(); - mainSqlString += inSqlClause; - mainSqlString += " ) order by visit.encounter_num, visit.patient_num \n"; - - log.debug("Executing sql[" + mainSqlString + "]"); - EventSet visitDimensionSet = new EventSet(); - Connection conn = null; - PreparedStatement preparedStmt = null; - try { - // execute fullsql - conn = getDataSource().getConnection(); - - if (patientListTypeHandler.isCollectionId()) { - preparedStmt = conn.prepareStatement(mainSqlString); - preparedStmt.setInt(1, Integer.parseInt(patientListTypeHandler - .getCollectionId())); - } else if (patientListTypeHandler.isEnumerationSet()) { - String serverType = dataSourceLookup.getServerType(); - patientListTypeHandler.uploadEnumerationValueToTempTable(conn); - preparedStmt = conn.prepareStatement(mainSqlString); - - } else if (patientListTypeHandler.isEntireSet()) { - // log.debug("No need to pass parameter to sql"); - preparedStmt = conn.prepareStatement(mainSqlString); - } - - ResultSet resultSet = preparedStmt.executeQuery(); - I2B2PdoFactory.EventBuilder eventBuilder = new I2B2PdoFactory().new EventBuilder( - detailFlag, blobFlag, statusFlag, dataSourceLookup.getServerType()); - while (resultSet.next()) { - // VisitDimensionType visitDimensionType = - // getVisitDimensionType(resultSet); - EventType visitDimensionType = eventBuilder - .buildEventSet(resultSet,this.metaDataParamList); - visitDimensionSet.getEvent().add(visitDimensionType); - } - - } catch (SQLException sqlEx) { - log.error("", sqlEx); - throw new I2B2DAOException("sql exception", sqlEx); - } catch (IOException ioEx) { - log.error("", ioEx); - throw new I2B2DAOException("io exception", ioEx); - } finally { - if (patientListTypeHandler.isEnumerationSet()) { - try { - patientListTypeHandler.deleteTempTable(conn); - } catch (SQLException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - try { - JDBCUtil.closeJdbcResource(null, preparedStmt, conn); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - } - } - return visitDimensionSet; - } - - private void uploadTempTable(Statement tempStmt, String tempTableName, - List patientNumList, boolean isPostgresql) throws SQLException { - String createTempInputListTable = "create " - + (isPostgresql ? " temp ": "" ) - + " table " + tempTableName - + " ( char_param1 varchar(100) )"; - tempStmt.executeUpdate(createTempInputListTable); - log.debug("created temp table" + tempTableName); - // load to temp table - // TempInputListInsert inputListInserter = new - // TempInputListInsert(dataSource,TEMP_PDO_INPUTLIST_TABLE); - // inputListInserter.setBatchSize(100); - int i = 0; - for (String singleValue : patientNumList) { - tempStmt.addBatch("insert into " + tempTableName + " values ('" - + singleValue + "' )"); - log.debug("adding batch" + singleValue); - i++; - if (i % 100 == 0) { - log.debug("batch insert"); - tempStmt.executeBatch(); - - } - } - log.debug("batch insert1"); - tempStmt.executeBatch(); - } - - - - @Override - public EventSet getVisitByFact(List panelSqlList, - List sqlParamCountList, - IInputOptionListHandler inputOptionListHandler, boolean detailFlag, - boolean blobFlag, boolean statusFlag) throws I2B2DAOException { - - EventSet eventSet = new EventSet(); - I2B2PdoFactory.EventBuilder eventBuilder = new I2B2PdoFactory().new EventBuilder( - detailFlag, blobFlag, statusFlag, dataSourceLookup.getServerType()); - VisitFactRelated eventFactRelated = new VisitFactRelated( - buildOutputOptionType(detailFlag, blobFlag, statusFlag)); - eventFactRelated.setMetaDataParamList(this.metaDataParamList); - - String selectClause = eventFactRelated.getSelectClause(); - String serverType = dataSourceLookup.getServerType(); - String factTempTable = ""; - Connection conn = null; - PreparedStatement query = null; - try { - conn = dataSource.getConnection(); - if (serverType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { - factTempTable = getDbSchemaName() - + FactRelatedQueryHandler.TEMP_FACT_PARAM_TABLE; - } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.SQLSERVER) || - serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { - log.debug("creating temp table"); - java.sql.Statement tempStmt = conn.createStatement(); - if (serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) - factTempTable = SQLServerFactRelatedQueryHandler.TEMP_FACT_PARAM_TABLE.substring(1); - else - factTempTable = SQLServerFactRelatedQueryHandler.TEMP_FACT_PARAM_TABLE; - try { - tempStmt.executeUpdate("drop table " + factTempTable); - } catch (SQLException sqlex) { - ; - } - String createTempInputListTable = "create table " - + factTempTable - + " ( set_index int, char_param1 varchar(500) )"; - tempStmt.executeUpdate(createTempInputListTable); - log.debug("created temp table" + factTempTable); - } - // if the inputlist is enumeration, then upload the enumerated input - // to temp table. - // the uploaded enumerated input will be used in the fact join. - if (inputOptionListHandler.isEnumerationSet()) { - inputOptionListHandler.uploadEnumerationValueToTempTable(conn); - } - String insertSql = ""; - int i = 0; - int sqlParamCount = 0; - ResultSet resultSet = null; - for (String panelSql : panelSqlList) { - insertSql = " insert into " - + factTempTable - + "(char_param1) select distinct obs_encounter_num from ( " - + panelSql + ") b"; - - log.debug("Executing SQL [ " + insertSql + "]"); - sqlParamCount = sqlParamCountList.get(i++); - // conn.createStatement().executeUpdate(insertSql); - executeUpdateSql(insertSql, conn, sqlParamCount, - inputOptionListHandler); - - } - - String finalSql = "SELECT " - + selectClause - + " FROM " - + getDbSchemaName() - + "visit_dimension visit where encounter_num in (select distinct char_param1 from " - + factTempTable + ") order by encounter_num"; - log.debug("Executing SQL [" + finalSql + "]"); - log.debug("Final Sql " + finalSql); - - query = conn.prepareStatement(finalSql); - - resultSet = query.executeQuery(); - - while (resultSet.next()) { - EventType event = eventBuilder.buildEventSet(resultSet,this.metaDataParamList); - eventSet.getEvent().add(event); - } - } catch (SQLException sqlEx) { - log.error("", sqlEx); - throw new I2B2DAOException("sql exception", sqlEx); - } catch (IOException ioEx) { - log.error("", ioEx); - throw new I2B2DAOException("IO exception", ioEx); - } finally { - PdoTempTableUtil tempUtil = new PdoTempTableUtil(); - tempUtil.clearTempTable(dataSourceLookup.getServerType(), conn, factTempTable); - - if (inputOptionListHandler != null - && inputOptionListHandler.isEnumerationSet()) { - try { - inputOptionListHandler.deleteTempTable(conn); - } catch (SQLException e) { - - e.printStackTrace(); - } - } - try { - - JDBCUtil.closeJdbcResource(null, query, conn); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - } - } - return eventSet; - - } - - private void executeUpdateSql(String totalSql, Connection conn, - int sqlParamCount, IInputOptionListHandler inputOptionListHandler) - throws SQLException { - - PreparedStatement stmt = conn.prepareStatement(totalSql); - - log.debug(totalSql + " [ " + sqlParamCount + " ]"); - if (inputOptionListHandler.isCollectionId()) { - for (int i = 1; i <= sqlParamCount; i++) { - stmt.setInt(i, Integer.parseInt(inputOptionListHandler - .getCollectionId())); - } - } - - stmt.executeUpdate(); - - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao.pdo; + +import java.io.IOException; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.List; + +import javax.sql.DataSource; + +import oracle.sql.ArrayDescriptor; + +//import org.jboss.resource.adapter.jdbc.WrappedConnection; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.util.db.JDBCUtil; +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.dao.pdo.input.FactRelatedQueryHandler; +import edu.harvard.i2b2.crc.dao.pdo.input.IInputOptionListHandler; +import edu.harvard.i2b2.crc.dao.pdo.input.PatientListTypeHandler; +import edu.harvard.i2b2.crc.dao.pdo.input.SQLServerFactRelatedQueryHandler; +import edu.harvard.i2b2.crc.dao.pdo.input.VisitListTypeHandler; +import edu.harvard.i2b2.crc.dao.pdo.output.VisitFactRelated; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.pdo.EventSet; +import edu.harvard.i2b2.crc.datavo.pdo.EventType; +import edu.harvard.i2b2.crc.datavo.pdo.ParamType; +import edu.harvard.i2b2.crc.datavo.pdo.query.EventListType; +import edu.harvard.i2b2.crc.datavo.pdo.query.PatientListType; + +/** + * Class to support visit/event section of plain pdo query $Id: + * PdoQueryVisitDao.java,v 1.12 2008/04/08 19:41:30 rk903 Exp $ + * + * @author rkuttan + */ +public class PdoQueryVisitDao extends CRCDAO implements IPdoQueryVisitDao { + + private DataSourceLookup dataSourceLookup = null; + private List metaDataParamList = null; + + public PdoQueryVisitDao(DataSourceLookup dataSourceLookup, + DataSource dataSource) { + setDbSchemaName(dataSourceLookup.getFullSchema()); + setDataSource(dataSource); + this.dataSourceLookup = dataSourceLookup; + } + + @Override + public void setMetaDataParamList(List metaDataParamList) { + this.metaDataParamList = metaDataParamList; + } + + /** + * Function to return list of eventset for given encounter number list + * + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @exception I2B2DAOException + */ + @Override + public EventSet getVisitsByEncounterNum(List encounterNumList, + boolean detailFlag, boolean blobFlag, boolean statusFlag) + throws I2B2DAOException { + EventSet visitDimensionSet = new EventSet(); + log.debug("visit list size " + encounterNumList.size()); + Connection conn = null; + PreparedStatement query = null; + String tempTableName = ""; + try { + conn = getDataSource().getConnection(); + VisitFactRelated visitRelated = new VisitFactRelated( + buildOutputOptionType(detailFlag, blobFlag, statusFlag)); + visitRelated.setMetaDataParamList(this.metaDataParamList); + String selectClause = visitRelated.getSelectClause(); + String serverType = dataSourceLookup.getServerType(); + if (serverType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { + oracle.jdbc.driver.OracleConnection conn1 = null;//(oracle.jdbc.driver.OracleConnection) ((WrappedConnection) conn) + // .getUnderlyingConnection(); + String finalSql = "SELECT " + + selectClause + + " FROM " + + getDbSchemaName() + + "visit_dimension visit WHERE visit.encounter_num IN (SELECT * FROM TABLE (cast (? as QT_PDO_QRY_STRING_ARRAY)))"; + log.debug("Executing sql[" + finalSql + "]"); + query = conn1.prepareStatement(finalSql); + + ArrayDescriptor desc = ArrayDescriptor.createDescriptor( + "QT_PDO_QRY_STRING_ARRAY", conn1); + oracle.sql.ARRAY paramArray = new oracle.sql.ARRAY(desc, conn1, + encounterNumList.toArray(new String[] {})); + query.setArray(1, paramArray); + } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.SQLSERVER) || + serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { + log.debug("creating temp table"); + if (serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) + tempTableName = SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE.substring(1); + else + tempTableName = SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE; + java.sql.Statement tempStmt = conn.createStatement(); + + try { + tempStmt.executeUpdate("drop table " + tempTableName); + } catch (SQLException sqlex) { + ; + } + + uploadTempTable(tempStmt, tempTableName, encounterNumList, dataSourceLookup.getServerType().equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)); + String finalSql = "SELECT " + + selectClause + + " FROM " + + getDbSchemaName() + + "visit_dimension visit WHERE visit.encounter_num IN (select distinct char_param1 FROM " + + tempTableName + ") order by encounter_num"; + log.debug("Executing [" + finalSql + "]"); + + query = conn.prepareStatement(finalSql); + + } + ResultSet resultSet = query.executeQuery(); + I2B2PdoFactory.EventBuilder eventBuilder = new I2B2PdoFactory().new EventBuilder( + detailFlag, blobFlag, statusFlag, dataSourceLookup.getServerType()); + while (resultSet.next()) { + EventType visitDimensionType = eventBuilder + .buildEventSet(resultSet,this.metaDataParamList); + visitDimensionSet.getEvent().add(visitDimensionType); + } + + } catch (SQLException sqlEx) { + log.error("", sqlEx); + throw new I2B2DAOException("sql exception", sqlEx); + } catch (IOException ioex) { + log.error("", ioex); + throw new I2B2DAOException("io exception", ioex); + } finally { + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER)) { + PdoTempTableUtil tempUtil = new PdoTempTableUtil(); + tempUtil.deleteTempTableSqlServer(conn, tempTableName); + } + try { + JDBCUtil.closeJdbcResource(null, query, conn); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + } + } + return visitDimensionSet; + } + + /** + * Get visit dimension data base on visit list + * (InputOptionList.getVisitListType()) + * + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return I2B2DAOException + * @throws Exception + */ + @Override + public EventSet getVisitDimensionSetFromVisitList( + EventListType visitListType, boolean detailFlag, boolean blobFlag, + boolean statusFlag) throws I2B2DAOException { + VisitListTypeHandler visitListTypeHandler = new VisitListTypeHandler( + dataSourceLookup, visitListType); + String inSqlClause = visitListTypeHandler.generateWhereClauseSql(); + VisitFactRelated visitRelated = new VisitFactRelated( + buildOutputOptionType(detailFlag, blobFlag, statusFlag)); + visitRelated.setMetaDataParamList(this.metaDataParamList); + String selectClause = visitRelated.getSelectClause(); + + String mainSqlString = " SELECT " + selectClause + " FROM " + + getDbSchemaName() + + "visit_dimension visit WHERE visit.encounter_num IN ( "; + mainSqlString += inSqlClause; + mainSqlString += " ) order by visit.encounter_num, visit.patient_num \n"; + + EventSet visitDimensionSet = new EventSet(); + Connection conn = null; + PreparedStatement preparedStmt = null; + try { + // execute fullsql + conn = getDataSource().getConnection(); + + log.debug("Executing Sql[" + mainSqlString + "]"); + + if (visitListTypeHandler.isCollectionId()) { + String patientEncCollectionId = visitListTypeHandler + .getCollectionId(); + preparedStmt = conn.prepareStatement(mainSqlString); + preparedStmt.setInt(1,Integer.parseInt(patientEncCollectionId)); + + } else if (visitListTypeHandler.isEnumerationSet()) { + String serverType = dataSourceLookup.getServerType(); + visitListTypeHandler.uploadEnumerationValueToTempTable(conn); + preparedStmt = conn.prepareStatement(mainSqlString); + + } else { + preparedStmt = conn.prepareStatement(mainSqlString); + } + + ResultSet resultSet = preparedStmt.executeQuery(); + I2B2PdoFactory.EventBuilder eventBuilder = new I2B2PdoFactory().new EventBuilder( + detailFlag, blobFlag, statusFlag, dataSourceLookup.getServerType()); + while (resultSet.next()) { + // VisitDimensionType visitDimensionType = + // getVisitDimensionType(resultSet); + EventType visitDimensionType = eventBuilder + .buildEventSet(resultSet, metaDataParamList); + visitDimensionSet.getEvent().add(visitDimensionType); + } + } catch (SQLException sqlEx) { + log.error("", sqlEx); + throw new I2B2DAOException("sql exception", sqlEx); + } catch (IOException ioEx) { + log.error("", ioEx); + throw new I2B2DAOException("io exception", ioEx); + } finally { + if (visitListTypeHandler.isEnumerationSet()) { + try { + visitListTypeHandler.deleteTempTable(conn); + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + try { + JDBCUtil.closeJdbcResource(null, preparedStmt, conn); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + } + } + + return visitDimensionSet; + } + + /** + * Get visit dimension from patientlist (InputOptionList.getPatientList()) + * + * @param patientListType + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return PatientDataType.VisitDimensionSet + * @throws I2B2DAOException + */ + @Override + public EventSet getVisitDimensionSetFromPatientList( + PatientListType patientListType, boolean detailFlag, + boolean blobFlag, boolean statusFlag) throws I2B2DAOException { + + VisitFactRelated visitRelated = new VisitFactRelated( + buildOutputOptionType(detailFlag, blobFlag, statusFlag)); + visitRelated.setMetaDataParamList(this.metaDataParamList); + String selectClause = visitRelated.getSelectClause(); + String mainSqlString = " SELECT " + selectClause + " FROM " + + getDbSchemaName() + + "visit_dimension visit WHERE visit.patient_num IN ( "; + PatientListTypeHandler patientListTypeHandler = new PatientListTypeHandler( + dataSourceLookup, patientListType); + String inSqlClause = patientListTypeHandler.generateWhereClauseSql(); + mainSqlString += inSqlClause; + mainSqlString += " ) order by visit.encounter_num, visit.patient_num \n"; + + log.debug("Executing sql[" + mainSqlString + "]"); + EventSet visitDimensionSet = new EventSet(); + Connection conn = null; + PreparedStatement preparedStmt = null; + try { + // execute fullsql + conn = getDataSource().getConnection(); + + if (patientListTypeHandler.isCollectionId()) { + preparedStmt = conn.prepareStatement(mainSqlString); + preparedStmt.setInt(1, Integer.parseInt(patientListTypeHandler + .getCollectionId())); + } else if (patientListTypeHandler.isEnumerationSet()) { + String serverType = dataSourceLookup.getServerType(); + patientListTypeHandler.uploadEnumerationValueToTempTable(conn); + preparedStmt = conn.prepareStatement(mainSqlString); + + } else if (patientListTypeHandler.isEntireSet()) { + // log.debug("No need to pass parameter to sql"); + preparedStmt = conn.prepareStatement(mainSqlString); + } + + ResultSet resultSet = preparedStmt.executeQuery(); + I2B2PdoFactory.EventBuilder eventBuilder = new I2B2PdoFactory().new EventBuilder( + detailFlag, blobFlag, statusFlag, dataSourceLookup.getServerType()); + while (resultSet.next()) { + // VisitDimensionType visitDimensionType = + // getVisitDimensionType(resultSet); + EventType visitDimensionType = eventBuilder + .buildEventSet(resultSet,this.metaDataParamList); + visitDimensionSet.getEvent().add(visitDimensionType); + } + + } catch (SQLException sqlEx) { + log.error("", sqlEx); + throw new I2B2DAOException("sql exception", sqlEx); + } catch (IOException ioEx) { + log.error("", ioEx); + throw new I2B2DAOException("io exception", ioEx); + } finally { + if (patientListTypeHandler.isEnumerationSet()) { + try { + patientListTypeHandler.deleteTempTable(conn); + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + try { + JDBCUtil.closeJdbcResource(null, preparedStmt, conn); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + } + } + return visitDimensionSet; + } + + private void uploadTempTable(Statement tempStmt, String tempTableName, + List patientNumList, boolean isPostgresql) throws SQLException { + String createTempInputListTable = "create " + + (isPostgresql ? " temp ": "" ) + + " table " + tempTableName + + " ( char_param1 varchar(100) )"; + tempStmt.executeUpdate(createTempInputListTable); + log.debug("created temp table" + tempTableName); + // load to temp table + // TempInputListInsert inputListInserter = new + // TempInputListInsert(dataSource,TEMP_PDO_INPUTLIST_TABLE); + // inputListInserter.setBatchSize(100); + int i = 0; + for (String singleValue : patientNumList) { + tempStmt.addBatch("insert into " + tempTableName + " values ('" + + singleValue + "' )"); + log.debug("adding batch" + singleValue); + i++; + if (i % 100 == 0) { + log.debug("batch insert"); + tempStmt.executeBatch(); + + } + } + log.debug("batch insert1"); + tempStmt.executeBatch(); + } + + + + @Override + public EventSet getVisitByFact(List panelSqlList, + List sqlParamCountList, + IInputOptionListHandler inputOptionListHandler, boolean detailFlag, + boolean blobFlag, boolean statusFlag) throws I2B2DAOException { + + EventSet eventSet = new EventSet(); + I2B2PdoFactory.EventBuilder eventBuilder = new I2B2PdoFactory().new EventBuilder( + detailFlag, blobFlag, statusFlag, dataSourceLookup.getServerType()); + VisitFactRelated eventFactRelated = new VisitFactRelated( + buildOutputOptionType(detailFlag, blobFlag, statusFlag)); + eventFactRelated.setMetaDataParamList(this.metaDataParamList); + + String selectClause = eventFactRelated.getSelectClause(); + String serverType = dataSourceLookup.getServerType(); + String factTempTable = ""; + Connection conn = null; + PreparedStatement query = null; + try { + conn = dataSource.getConnection(); + if (serverType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { + factTempTable = getDbSchemaName() + + FactRelatedQueryHandler.TEMP_FACT_PARAM_TABLE; + } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.SQLSERVER) || + serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { + log.debug("creating temp table"); + java.sql.Statement tempStmt = conn.createStatement(); + if (serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) + factTempTable = SQLServerFactRelatedQueryHandler.TEMP_FACT_PARAM_TABLE.substring(1); + else + factTempTable = SQLServerFactRelatedQueryHandler.TEMP_FACT_PARAM_TABLE; + try { + tempStmt.executeUpdate("drop table " + factTempTable); + } catch (SQLException sqlex) { + ; + } + String createTempInputListTable = "create table " + + factTempTable + + " ( set_index int, char_param1 varchar(500) )"; + tempStmt.executeUpdate(createTempInputListTable); + log.debug("created temp table" + factTempTable); + } + // if the inputlist is enumeration, then upload the enumerated input + // to temp table. + // the uploaded enumerated input will be used in the fact join. + if (inputOptionListHandler.isEnumerationSet()) { + inputOptionListHandler.uploadEnumerationValueToTempTable(conn); + } + String insertSql = ""; + int i = 0; + int sqlParamCount = 0; + ResultSet resultSet = null; + for (String panelSql : panelSqlList) { + insertSql = " insert into " + + factTempTable + + "(char_param1) select distinct obs_encounter_num from ( " + + panelSql + ") b"; + + log.debug("Executing SQL [ " + insertSql + "]"); + sqlParamCount = sqlParamCountList.get(i++); + // conn.createStatement().executeUpdate(insertSql); + executeUpdateSql(insertSql, conn, sqlParamCount, + inputOptionListHandler); + + } + + String finalSql = "SELECT " + + selectClause + + " FROM " + + getDbSchemaName() + + "visit_dimension visit where encounter_num in (select distinct char_param1 from " + + factTempTable + ") order by encounter_num"; + log.debug("Executing SQL [" + finalSql + "]"); + log.debug("Final Sql " + finalSql); + + query = conn.prepareStatement(finalSql); + + resultSet = query.executeQuery(); + + while (resultSet.next()) { + EventType event = eventBuilder.buildEventSet(resultSet,this.metaDataParamList); + eventSet.getEvent().add(event); + } + } catch (SQLException sqlEx) { + log.error("", sqlEx); + throw new I2B2DAOException("sql exception", sqlEx); + } catch (IOException ioEx) { + log.error("", ioEx); + throw new I2B2DAOException("IO exception", ioEx); + } finally { + PdoTempTableUtil tempUtil = new PdoTempTableUtil(); + tempUtil.clearTempTable(dataSourceLookup.getServerType(), conn, factTempTable); + + if (inputOptionListHandler != null + && inputOptionListHandler.isEnumerationSet()) { + try { + inputOptionListHandler.deleteTempTable(conn); + } catch (SQLException e) { + + e.printStackTrace(); + } + } + try { + + JDBCUtil.closeJdbcResource(null, query, conn); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + } + } + return eventSet; + + } + + private void executeUpdateSql(String totalSql, Connection conn, + int sqlParamCount, IInputOptionListHandler inputOptionListHandler) + throws SQLException { + + PreparedStatement stmt = conn.prepareStatement(totalSql); + + log.debug(totalSql + " [ " + sqlParamCount + " ]"); + if (inputOptionListHandler.isCollectionId()) { + for (int i = 1; i <= sqlParamCount; i++) { + stmt.setInt(i, Integer.parseInt(inputOptionListHandler + .getCollectionId())); + } + } + + stmt.executeUpdate(); + + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/PdoTempTableUtil.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/PdoTempTableUtil.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/PdoTempTableUtil.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/PdoTempTableUtil.java index 016df7d2..8a46bb1d --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/PdoTempTableUtil.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/PdoTempTableUtil.java @@ -1,73 +1,73 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.pdo; - -import java.sql.Connection; -import java.sql.SQLException; -import java.sql.Statement; - -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; - -public class PdoTempTableUtil { - - public void clearTempTable(String serverType, Connection conn, String tableName) { - if (serverType.equalsIgnoreCase(DAOFactoryHelper.SQLSERVER) || - serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { - this.deleteTempTableSqlServer(conn, tableName); - } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { - this.deleteTempTableOracle(conn, tableName); - } - } - - public void deleteTempTableSqlServer(Connection conn, String tableName) { - - Statement deleteStmt = null; - try { - deleteStmt = conn.createStatement(); - conn.createStatement().executeUpdate("drop table " + tableName); - deleteStmt.executeUpdate("drop table " + tableName); - - } catch (SQLException sqle) { - ; - } finally { - try { - if(deleteStmt != null) - deleteStmt.close(); - } catch (SQLException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - } - - public void deleteTempTableOracle(Connection conn, String tableName) { - - - Statement clearTempStmt = null; - try { - clearTempStmt = conn.createStatement(); - clearTempStmt.executeUpdate("delete from " + tableName); - - } catch (SQLException dEx) { - ; - } finally { - try { - if(clearTempStmt != null) - clearTempStmt.close(); - } catch (SQLException e) { - - e.printStackTrace(); - } - } - } - - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.pdo; + +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.Statement; + +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; + +public class PdoTempTableUtil { + + public void clearTempTable(String serverType, Connection conn, String tableName) { + if (serverType.equalsIgnoreCase(DAOFactoryHelper.SQLSERVER) || + serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { + this.deleteTempTableSqlServer(conn, tableName); + } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { + this.deleteTempTableOracle(conn, tableName); + } + } + + public void deleteTempTableSqlServer(Connection conn, String tableName) { + + Statement deleteStmt = null; + try { + deleteStmt = conn.createStatement(); + conn.createStatement().executeUpdate("drop table " + tableName); + deleteStmt.executeUpdate("drop table " + tableName); + + } catch (SQLException sqle) { + ; + } finally { + try { + if(deleteStmt != null) + deleteStmt.close(); + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + } + + public void deleteTempTableOracle(Connection conn, String tableName) { + + + Statement clearTempStmt = null; + try { + clearTempStmt = conn.createStatement(); + clearTempStmt.executeUpdate("delete from " + tableName); + + } catch (SQLException dEx) { + ; + } finally { + try { + if(clearTempStmt != null) + clearTempStmt.close(); + } catch (SQLException e) { + + e.printStackTrace(); + } + } + } + + + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/RPDRPdoFactory.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/RPDRPdoFactory.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/RPDRPdoFactory.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/RPDRPdoFactory.java index ada1769e..df0f6193 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/RPDRPdoFactory.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/RPDRPdoFactory.java @@ -1,787 +1,787 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao.pdo; - -import java.io.IOException; -import java.sql.Clob; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.Date; -import java.util.Iterator; -import java.util.List; - -import edu.harvard.i2b2.common.util.db.JDBCUtil; -import edu.harvard.i2b2.common.util.jaxb.DTOFactory; -import edu.harvard.i2b2.crc.datavo.pdo.BlobType; -import edu.harvard.i2b2.crc.datavo.pdo.ConceptType; -import edu.harvard.i2b2.crc.datavo.pdo.EidType; -import edu.harvard.i2b2.crc.datavo.pdo.EventType; -import edu.harvard.i2b2.crc.datavo.pdo.ModifierType; -import edu.harvard.i2b2.crc.datavo.pdo.ObservationType; -import edu.harvard.i2b2.crc.datavo.pdo.ObserverType; -import edu.harvard.i2b2.crc.datavo.pdo.ParamType; -import edu.harvard.i2b2.crc.datavo.pdo.PatientIdType; -import edu.harvard.i2b2.crc.datavo.pdo.PatientType; -import edu.harvard.i2b2.crc.datavo.pdo.PidType; -import edu.harvard.i2b2.crc.datavo.pdo.PidType.PatientId; - -/** - * Class to build individual sections of table pdo xml like - * patient,concept,observationfact from the given {@link java.sql.ResultSet} - * $Id: RPDRPdoFactory.java,v 1.20 2009/11/14 16:41:26 rk903 Exp $ - * - * @author rkuttan - */ -public class RPDRPdoFactory { - private static DTOFactory dtoFactory = new DTOFactory(); - - /** - * Inner class to build observation fact in table PDO format - */ - public static class ObservationFactBuilder { - boolean obsFactDetailFlag = false; - boolean obsFactBlobFlag = false; - boolean obsFactStatusFlag = false; - - public ObservationFactBuilder(boolean detailFlag, boolean blobFlag, - boolean statusFlag) { - this.obsFactDetailFlag = detailFlag; - this.obsFactBlobFlag = blobFlag; - this.obsFactStatusFlag = statusFlag; - } - - /** - * Read one record from resultset and build observation fact - * - * @param rowSet - * @param source - * @return ObservationSet.Observation - * @throws SQLException - * @throws IOException - */ - public ObservationType buildObservationSet(ResultSet rowSet, - String source) throws SQLException, IOException { - - ObservationType observation = new ObservationType(); - PatientIdType pId = new PatientIdType(); - pId.setValue(rowSet.getString("obs_patient_num")); - pId.setSource(source); - observation.setPatientId(pId); - - ObservationType.EventId eventId = new ObservationType.EventId(); - eventId.setValue(rowSet.getString("obs_encounter_num")); - eventId.setSource(source); - observation.setEventId(eventId); - - ObservationType.ConceptCd conceptCd = new ObservationType.ConceptCd(); - conceptCd.setValue(rowSet.getString("obs_concept_cd")); - conceptCd.setName(rowSet.getString("concept_name")); - observation.setConceptCd(conceptCd); - - ObservationType.ModifierCd modifierCd = new ObservationType.ModifierCd(); - modifierCd.setValue(rowSet.getString("obs_modifier_cd")); - modifierCd.setName(rowSet.getString("modifier_name")); - observation.setModifierCd(modifierCd); - - ObservationType.InstanceNum instanceNum = new ObservationType.InstanceNum(); - instanceNum.setValue(rowSet.getString("obs_instance_num")); - observation.setInstanceNum(instanceNum); - - Date startDate = rowSet.getTimestamp("obs_start_date"); - - if (startDate != null) { - observation.setStartDate(dtoFactory - .getXMLGregorianCalendar(startDate.getTime())); - } - - ObservationType.ObserverCd observerCd = new ObservationType.ObserverCd(); - observerCd.setValue(rowSet.getString("obs_provider_id")); - String providerName = rowSet.getString("provider_name"); - observerCd.setName((providerName != null) ? providerName : ""); - observation.setObserverCd(observerCd); - if (obsFactDetailFlag) { - Date endDate = rowSet.getTimestamp("obs_end_date"); - - if (endDate != null) { - observation.setEndDate(dtoFactory - .getXMLGregorianCalendar(endDate.getTime())); - } - - observation.setValuetypeCd(rowSet.getString("obs_valtype_cd")); - observation.setTvalChar(rowSet.getString("obs_tval_char")); - - ObservationType.NvalNum nvalNum = new ObservationType.NvalNum(); - nvalNum.setValue(rowSet.getBigDecimal("obs_nval_num")); - observation.setNvalNum(nvalNum); - - ObservationType.ValueflagCd valueFlagCd = new ObservationType.ValueflagCd(); - valueFlagCd.setValue(rowSet.getString("obs_valueflag_cd")); - observation.setValueflagCd(valueFlagCd); - - observation.setQuantityNum(rowSet - .getBigDecimal("obs_quantity_num")); - - observation.setUnitsCd(rowSet.getString("obs_units_cd")); - - if (rowSet.getString("obs_location_cd") != null) { - ObservationType.LocationCd locationCd = new ObservationType.LocationCd(); - locationCd.setValue(rowSet.getString("obs_location_cd")); - String locationName = rowSet.getString("location_name"); - locationCd.setName((locationName != null) ? locationName - : ""); - observation.setLocationCd(locationCd); - } - - observation.setConfidenceNum(rowSet - .getBigDecimal("obs_confidence_num")); - - } - - if (obsFactBlobFlag) { - Clob observationClob = rowSet.getClob("obs_observation_blob"); - if (observationClob != null) { - try { - BlobType blobType = new BlobType(); - blobType.getContent().add( - JDBCUtil.getClobStringWithLinebreak(observationClob)); - observation.setObservationBlob(blobType); - } catch (IOException ioEx) { - ioEx.printStackTrace(); - throw ioEx; - } - } - } - - if (obsFactStatusFlag) { - if (rowSet.getTimestamp("obs_update_date") != null) { - observation.setUpdateDate(dtoFactory - .getXMLGregorianCalendar(rowSet.getTimestamp( - "obs_update_date").getTime())); - } - - if (rowSet.getDate("obs_download_date") != null) { - observation.setDownloadDate(dtoFactory - .getXMLGregorianCalendar(rowSet.getTimestamp( - "obs_download_date").getTime())); - } - - if (rowSet.getDate("obs_import_date") != null) { - observation.setImportDate(dtoFactory - .getXMLGregorianCalendar(rowSet.getTimestamp( - "obs_import_date").getTime())); - } - - observation.setSourcesystemCd(rowSet - .getString("obs_sourcesystem_cd")); - observation.setUploadId(rowSet.getString("obs_upload_id")); - } - - return observation; - } - } - - /* - * Inner class to build patient in table PDO format - */ - public static class PatientBuilder { - boolean patientDetailFlag = false; - boolean patientBlobFlag = false; - boolean patientStatusFlag = false; - - public PatientBuilder(boolean detailFlag, boolean blobFlag, - boolean statusFlag) { - this.patientDetailFlag = detailFlag; - this.patientBlobFlag = blobFlag; - this.patientStatusFlag = statusFlag; - } - - /** - * Read one record from resultset and build patient set - * - * @param rowSet - * @param source - * @return PatientSet.Patient - * @throws SQLException - * @throws IOException - */ - public PatientType buildPatientSet(ResultSet rowSet, String source,List metaDataParamList) - throws SQLException, IOException { - PatientType patientDimensionType = new PatientType(); - PatientIdType patientIdType = new PatientIdType(); - patientIdType.setSource(source); - patientIdType.setValue(rowSet.getString("patient_patient_num")); - patientDimensionType.setPatientId(patientIdType); - - if (patientDetailFlag) { - - - - - - ParamTypeValueBuilder paramValBuilder = new ParamTypeValueBuilder(); - for (Iterator metaParamIterator = metaDataParamList.iterator(); metaParamIterator.hasNext();) { - ParamType metaParamType = metaParamIterator.next(); - if (metaParamType.getType().equalsIgnoreCase("string")) { - patientDimensionType.getParam().add(paramValBuilder.buildParamType(metaParamType,"patient_","_name",rowSet)); - } else { - patientDimensionType.getParam().add(paramValBuilder.buildParamType(metaParamType,"patient_",null,rowSet)); - } - - - } - } - - if (patientBlobFlag) { - if (rowSet.getClob("patient_patient_blob") != null) { - BlobType blobType = new BlobType(); - blobType.getContent().add( - JDBCUtil.getClobStringWithLinebreak(rowSet - .getClob("patient_patient_blob"))); - } - } - - if (patientStatusFlag) { - if (rowSet.getTimestamp("patient_update_date") != null) { - patientDimensionType.setUpdateDate(dtoFactory - .getXMLGregorianCalendar(rowSet.getTimestamp( - "patient_update_date").getTime())); - } - - if (rowSet.getTimestamp("patient_download_date") != null) { - patientDimensionType.setDownloadDate(dtoFactory - .getXMLGregorianCalendar(rowSet.getTimestamp( - "patient_download_date").getTime())); - } - - if (rowSet.getTimestamp("patient_import_date") != null) { - patientDimensionType.setImportDate(dtoFactory - .getXMLGregorianCalendar(rowSet.getTimestamp( - "patient_import_date").getTime())); - } - - patientDimensionType.setSourcesystemCd(rowSet - .getString("patient_sourcesystem_cd")); - patientDimensionType.setUploadId(rowSet - .getString("patient_upload_id")); - } - - return patientDimensionType; - } - } - - /* - * Inner class to build observer section in table PDO format - */ - public static class ProviderBuilder { - boolean providerDetailFlag = false; - boolean providerBlobFlag = false; - boolean providerStatusFlag = false; - - public ProviderBuilder(boolean detailFlag, boolean blobFlag, - boolean statusFlag) { - this.providerDetailFlag = detailFlag; - this.providerBlobFlag = blobFlag; - this.providerStatusFlag = statusFlag; - } - - /** - * Read one record from resultset and build observer set - * - * @param rowSet - * @param source - * @return ObserverSet.Observer - * @throws SQLException - * @throws IOException - */ - public ObserverType buildObserverSet(ResultSet rowSet) - throws IOException, SQLException { - ObserverType providerDimensionType = new ObserverType(); - providerDimensionType.setObserverCd(rowSet - .getString("provider_provider_id")); - providerDimensionType.setObserverPath(rowSet - .getString("provider_provider_path")); - - if (providerDetailFlag) { - providerDimensionType.setNameChar(rowSet - .getString("provider_name_char")); - } - - if (providerBlobFlag) { - Clob providerClob = rowSet.getClob("provider_provider_blob"); - - if (providerClob != null) { - BlobType blobType = new BlobType(); - blobType.getContent().add( - JDBCUtil.getClobStringWithLinebreak(providerClob)); - providerDimensionType.setObserverBlob(blobType); - } - } - - if (providerStatusFlag) { - if (rowSet.getTimestamp("provider_update_date") != null) { - providerDimensionType.setUpdateDate(dtoFactory - .getXMLGregorianCalendar(rowSet.getTimestamp( - "provider_update_date").getTime())); - } - - if (rowSet.getTimestamp("provider_download_date") != null) { - providerDimensionType.setDownloadDate(dtoFactory - .getXMLGregorianCalendar(rowSet.getTimestamp( - "provider_download_date").getTime())); - } - - if (rowSet.getTimestamp("provider_import_date") != null) { - providerDimensionType.setImportDate(dtoFactory - .getXMLGregorianCalendar(rowSet.getTimestamp( - "provider_import_date").getTime())); - } - - providerDimensionType.setSourcesystemCd(rowSet - .getString("provider_sourcesystem_cd")); - providerDimensionType.setUploadId(rowSet - .getString("provider_upload_id")); - - } - - return providerDimensionType; - } - } - - /* - * Inner class to build concept section in table PDO format - */ - public static class ConceptBuilder { - boolean conceptDetailFlag = false; - boolean conceptBlobFlag = false; - boolean conceptStatusFlag = false; - - public ConceptBuilder(boolean detailFlag, boolean blobFlag, - boolean statusFlag) { - this.conceptDetailFlag = detailFlag; - this.conceptBlobFlag = blobFlag; - this.conceptStatusFlag = statusFlag; - } - - /** - * Read one record from resultset and build concept set - * - * @param rowSet - * @param source - * @return ConceptSet.Concept - * @throws SQLException - * @throws IOException - */ - public ConceptType buildConceptSet(ResultSet rowSet) - throws SQLException, IOException { - ConceptType conceptDimensionType = new ConceptType(); - - conceptDimensionType.setConceptCd(rowSet - .getString("concept_concept_cd")); - - if (conceptDetailFlag) { - conceptDimensionType.setConceptPath(rowSet - .getString("concept_concept_path")); - conceptDimensionType.setNameChar(rowSet - .getString("concept_name_char")); - } - - if (conceptBlobFlag) { - Clob conceptClob = rowSet.getClob("concept_concept_blob"); - - if (conceptClob != null) { - BlobType blobType = new BlobType(); - blobType.getContent().add( - JDBCUtil.getClobStringWithLinebreak(conceptClob)); - conceptDimensionType.setConceptBlob(blobType); - } - } - - if (conceptStatusFlag) { - if (rowSet.getTimestamp("concept_update_date") != null) { - conceptDimensionType.setUpdateDate(dtoFactory - .getXMLGregorianCalendar(rowSet.getTimestamp( - "concept_update_date").getTime())); - } - - if (rowSet.getTimestamp("concept_download_date") != null) { - conceptDimensionType.setDownloadDate(dtoFactory - .getXMLGregorianCalendar(rowSet.getTimestamp( - "concept_download_date").getTime())); - } - - if (rowSet.getTimestamp("concept_import_date") != null) { - conceptDimensionType.setImportDate(dtoFactory - .getXMLGregorianCalendar(rowSet.getTimestamp( - "concept_import_date").getTime())); - } - - conceptDimensionType.setSourcesystemCd(rowSet - .getString("concept_sourcesystem_cd")); - - conceptDimensionType.setUploadId(rowSet - .getString("concept_upload_id")); - } - - return conceptDimensionType; - } - } - - /* - * Inner class to build concept section in table PDO format - */ - public static class ModifierBuilder { - boolean modifierDetailFlag = false; - boolean modifierBlobFlag = false; - boolean modifierStatusFlag = false; - - public ModifierBuilder(boolean detailFlag, boolean blobFlag, - boolean statusFlag) { - this.modifierDetailFlag = detailFlag; - this.modifierBlobFlag = blobFlag; - this.modifierStatusFlag = statusFlag; - } - - /** - * Read one record from resultset and build concept set - * - * @param rowSet - * @param source - * @return ConceptSet.Concept - * @throws SQLException - * @throws IOException - */ - public ModifierType buildModifierSet(ResultSet rowSet) - throws SQLException, IOException { - ModifierType modifierDimensionType = new ModifierType(); - - modifierDimensionType.setModifierCd(rowSet - .getString("modifier_modifier_cd")); - - if (modifierDetailFlag) { - modifierDimensionType.setModifierPath(rowSet - .getString("modifier_modifier_path")); - modifierDimensionType.setNameChar(rowSet - .getString("modifier_name_char")); - } - - if (modifierBlobFlag) { - Clob modifierClob = rowSet.getClob("modifier_modifier_blob"); - - if (modifierClob != null) { - BlobType blobType = new BlobType(); - blobType.getContent().add( - JDBCUtil.getClobStringWithLinebreak(modifierClob)); - modifierDimensionType.setModifierBlob(blobType); - } - } - - if (modifierStatusFlag) { - if (rowSet.getTimestamp("modifier_update_date") != null) { - modifierDimensionType.setUpdateDate(dtoFactory - .getXMLGregorianCalendar(rowSet.getTimestamp( - "modifier_update_date").getTime())); - } - - if (rowSet.getTimestamp("modifier_download_date") != null) { - modifierDimensionType.setDownloadDate(dtoFactory - .getXMLGregorianCalendar(rowSet.getTimestamp( - "modifier_download_date").getTime())); - } - - if (rowSet.getTimestamp("modifier_import_date") != null) { - modifierDimensionType.setImportDate(dtoFactory - .getXMLGregorianCalendar(rowSet.getTimestamp( - "modifier_import_date").getTime())); - } - - modifierDimensionType.setSourcesystemCd(rowSet - .getString("modifier_sourcesystem_cd")); - - modifierDimensionType.setUploadId(rowSet - .getString("modifier_upload_id")); - } - - return modifierDimensionType; - } - } - /* - * Inner class to build event section in table PDO format - */ - public static class EventBuilder { - boolean eventDetailFlag = false; - boolean eventBlobFlag = false; - boolean eventStatusFlag = false; - - public EventBuilder(boolean detailFlag, boolean blobFlag, - boolean statusFlag) { - this.eventDetailFlag = detailFlag; - this.eventBlobFlag = blobFlag; - this.eventStatusFlag = statusFlag; - } - - /** - * Read one record from resultset and build event set - * - * @param rowSet - * @param source - * @return EventSet.Event - * @throws SQLException - * @throws IOException - */ - public EventType buildEventSet(ResultSet rowSet, String source,List metaDataParamList) - throws SQLException, IOException { - EventType visitDimensionType = new EventType(); - - PatientIdType patientIdType = new PatientIdType(); - patientIdType.setValue(rowSet.getString("visit_patient_num")); - patientIdType.setSource(source); - visitDimensionType.setPatientId(patientIdType); - - EventType.EventId eventId = new EventType.EventId(); - eventId.setValue(rowSet.getString("visit_encounter_num")); - eventId.setSource(source); - visitDimensionType.setEventId(eventId); - ParamTypeValueBuilder paramValBuilder = new ParamTypeValueBuilder(); - - if (eventDetailFlag) { - for (Iterator metaParamIterator = metaDataParamList.iterator(); metaParamIterator.hasNext();) { - ParamType metaParamType = metaParamIterator.next(); - - if (metaParamType.getType().equalsIgnoreCase("string")) { - visitDimensionType.getParam().add(paramValBuilder.buildParamType(metaParamType,"visit_","_name",rowSet)); - } else { - visitDimensionType.getParam().add(paramValBuilder.buildParamType(metaParamType,"visit_",null,rowSet)); - } - } - - Date startDate = rowSet.getTimestamp("visit_start_date"); - - if (startDate != null) { - visitDimensionType.setStartDate(dtoFactory - .getXMLGregorianCalendar(startDate.getTime())); - } - - Date endDate = rowSet.getTimestamp("visit_end_date"); - - if (endDate != null) { - visitDimensionType.setEndDate(dtoFactory - .getXMLGregorianCalendar(endDate.getTime())); - } - } - - if (eventBlobFlag) { - Clob visitClob = rowSet.getClob("visit_visit_blob"); - - if (visitClob != null) { - BlobType blobType = new BlobType(); - blobType.getContent() - .add(JDBCUtil.getClobStringWithLinebreak(visitClob)); - visitDimensionType.setEventBlob(blobType); - } - } - - if (eventStatusFlag) { - if (rowSet.getTimestamp("visit_update_date") != null) { - visitDimensionType.setUpdateDate(dtoFactory - .getXMLGregorianCalendar(rowSet.getTimestamp( - "visit_update_date").getTime())); - } - - if (rowSet.getTimestamp("visit_download_date") != null) { - visitDimensionType.setDownloadDate(dtoFactory - .getXMLGregorianCalendar(rowSet.getTimestamp( - "visit_download_date").getTime())); - } - - if (rowSet.getTimestamp("visit_import_date") != null) { - visitDimensionType.setImportDate(dtoFactory - .getXMLGregorianCalendar(rowSet.getTimestamp( - "visit_import_date").getTime())); - } - - visitDimensionType.setSourcesystemCd(rowSet - .getString("visit_sourcesystem_cd")); - - visitDimensionType.setUploadId(rowSet - .getString("visit_upload_id")); - } - - return visitDimensionType; - } - } - - /* - * Inner class to build pid section in table PDO format - */ - public static class PidBuilder { - boolean pmDetailFlag = false; - boolean pmBlobFlag = false; - boolean pmStatusFlag = false; - - public PidBuilder(boolean detailFlag, boolean blobFlag, - boolean statusFlag) { - this.pmDetailFlag = detailFlag; - this.pmBlobFlag = blobFlag; - this.pmStatusFlag = statusFlag; - } - - /** - * Read one record from resultset and build concept set - * - * @param rowSet - * @param source - * @return ConceptSet.Concept - * @throws SQLException - * @throws IOException - */ - public PidType buildPidSet(ResultSet rowSet) throws SQLException, - IOException { - PidType.PatientMapId patientMapType = new PidType.PatientMapId(); - patientMapType.setValue(rowSet.getString("pm_patient_ide")); - patientMapType.setSource(rowSet.getString("pm_patient_ide_source")); - - PatientId patientId = new PatientId(); - patientId.setValue(rowSet.getString("pm_patient_num")); - - PidType pidType = new PidType(); - pidType.setPatientId(patientId); - pidType.getPatientMapId().add(patientMapType); - // patientMapType.setValue(rowSet.getString("pm_patient_num")); - - if (pmDetailFlag) { - patientMapType.setStatus(rowSet - .getString("pm_patient_ide_status")); - } - - if (pmBlobFlag) { - ; // no blob field in the mapping table - } - - if (pmStatusFlag) { - if (rowSet.getTimestamp("pm_update_date") != null) { - patientMapType.setUpdateDate(dtoFactory - .getXMLGregorianCalendar(rowSet.getTimestamp( - "pm_update_date").getTime())); - } - - if (rowSet.getTimestamp("pm_download_date") != null) { - patientMapType.setDownloadDate(dtoFactory - .getXMLGregorianCalendar(rowSet.getTimestamp( - "pm_download_date").getTime())); - } - - if (rowSet.getTimestamp("pm_import_date") != null) { - patientMapType.setImportDate(dtoFactory - .getXMLGregorianCalendar(rowSet.getTimestamp( - "pm_import_date").getTime())); - } - - patientMapType.setSourcesystemCd(rowSet - .getString("pm_sourcesystem_cd")); - patientMapType.setUploadId(rowSet.getString("pm_upload_id")); - - } - - return pidType; - } - } - - /* - * Inner class to build pid section in table PDO format - */ - public static class EidBuilder { - boolean pmDetailFlag = false; - boolean pmBlobFlag = false; - boolean pmStatusFlag = false; - - public EidBuilder(boolean detailFlag, boolean blobFlag, - boolean statusFlag) { - this.pmDetailFlag = detailFlag; - this.pmBlobFlag = blobFlag; - this.pmStatusFlag = statusFlag; - } - - /** - * Read one record from resultset and build concept set - * - * @param rowSet - * @param source - * @return ConceptSet.Concept - * @throws SQLException - * @throws IOException - */ - public EidType buildEidSet(ResultSet rowSet) throws SQLException, - IOException { - EidType.EventMapId eventMapType = new EidType.EventMapId(); - eventMapType.setValue(rowSet.getString("em_encounter_ide")); - eventMapType.setSource(rowSet.getString("em_encounter_ide_source")); - eventMapType.setPatientId(rowSet.getString("em_patient_ide")); - eventMapType.setPatientIdSource(rowSet - .getString("em_patient_ide_source")); - - EidType.EventId eventId = new EidType.EventId(); - eventId.setValue(rowSet.getString("em_encounter_num")); - - EidType eidType = new EidType(); - eidType.setEventId(eventId); - eidType.getEventMapId().add(eventMapType); - // patientMapType.setValue(rowSet.getString("pm_patient_num")); - - if (pmDetailFlag) { - eventMapType.setStatus(rowSet - .getString("em_encounter_ide_status")); - eventId.setStatus(eventMapType.getStatus()); - } - - if (pmBlobFlag) { - ; // no blob field in the mapping table - } - - if (pmStatusFlag) { - if (rowSet.getTimestamp("em_update_date") != null) { - eventMapType.setUpdateDate(dtoFactory - .getXMLGregorianCalendar(rowSet.getTimestamp( - "em_update_date").getTime())); - eventId.setUpdateDate(eventMapType.getUpdateDate()); - } - - if (rowSet.getTimestamp("em_download_date") != null) { - eventMapType.setDownloadDate(dtoFactory - .getXMLGregorianCalendar(rowSet.getTimestamp( - "em_download_date").getTime())); - eventId.setDownloadDate(eventMapType.getDownloadDate()); - } - - if (rowSet.getTimestamp("em_import_date") != null) { - eventMapType.setImportDate(dtoFactory - .getXMLGregorianCalendar(rowSet.getTimestamp( - "em_import_date").getTime())); - eventId.setImportDate(eventMapType.getImportDate()); - } - - eventMapType.setSourcesystemCd(rowSet - .getString("em_sourcesystem_cd")); - eventId.setSourcesystemCd(eventMapType.getSourcesystemCd()); - - eventMapType.setUploadId(rowSet.getString("em_upload_id")); - eventId.setUploadId(eventMapType.getUploadId()); - } - - // - - return eidType; - } - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao.pdo; + +import java.io.IOException; +import java.sql.Clob; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Date; +import java.util.Iterator; +import java.util.List; + +import edu.harvard.i2b2.common.util.db.JDBCUtil; +import edu.harvard.i2b2.common.util.jaxb.DTOFactory; +import edu.harvard.i2b2.crc.datavo.pdo.BlobType; +import edu.harvard.i2b2.crc.datavo.pdo.ConceptType; +import edu.harvard.i2b2.crc.datavo.pdo.EidType; +import edu.harvard.i2b2.crc.datavo.pdo.EventType; +import edu.harvard.i2b2.crc.datavo.pdo.ModifierType; +import edu.harvard.i2b2.crc.datavo.pdo.ObservationType; +import edu.harvard.i2b2.crc.datavo.pdo.ObserverType; +import edu.harvard.i2b2.crc.datavo.pdo.ParamType; +import edu.harvard.i2b2.crc.datavo.pdo.PatientIdType; +import edu.harvard.i2b2.crc.datavo.pdo.PatientType; +import edu.harvard.i2b2.crc.datavo.pdo.PidType; +import edu.harvard.i2b2.crc.datavo.pdo.PidType.PatientId; + +/** + * Class to build individual sections of table pdo xml like + * patient,concept,observationfact from the given {@link java.sql.ResultSet} + * $Id: RPDRPdoFactory.java,v 1.20 2009/11/14 16:41:26 rk903 Exp $ + * + * @author rkuttan + */ +public class RPDRPdoFactory { + private static DTOFactory dtoFactory = new DTOFactory(); + + /** + * Inner class to build observation fact in table PDO format + */ + public static class ObservationFactBuilder { + boolean obsFactDetailFlag = false; + boolean obsFactBlobFlag = false; + boolean obsFactStatusFlag = false; + + public ObservationFactBuilder(boolean detailFlag, boolean blobFlag, + boolean statusFlag) { + this.obsFactDetailFlag = detailFlag; + this.obsFactBlobFlag = blobFlag; + this.obsFactStatusFlag = statusFlag; + } + + /** + * Read one record from resultset and build observation fact + * + * @param rowSet + * @param source + * @return ObservationSet.Observation + * @throws SQLException + * @throws IOException + */ + public ObservationType buildObservationSet(ResultSet rowSet, + String source) throws SQLException, IOException { + + ObservationType observation = new ObservationType(); + PatientIdType pId = new PatientIdType(); + pId.setValue(rowSet.getString("obs_patient_num")); + pId.setSource(source); + observation.setPatientId(pId); + + ObservationType.EventId eventId = new ObservationType.EventId(); + eventId.setValue(rowSet.getString("obs_encounter_num")); + eventId.setSource(source); + observation.setEventId(eventId); + + ObservationType.ConceptCd conceptCd = new ObservationType.ConceptCd(); + conceptCd.setValue(rowSet.getString("obs_concept_cd")); + conceptCd.setName(rowSet.getString("concept_name")); + observation.setConceptCd(conceptCd); + + ObservationType.ModifierCd modifierCd = new ObservationType.ModifierCd(); + modifierCd.setValue(rowSet.getString("obs_modifier_cd")); + modifierCd.setName(rowSet.getString("modifier_name")); + observation.setModifierCd(modifierCd); + + ObservationType.InstanceNum instanceNum = new ObservationType.InstanceNum(); + instanceNum.setValue(rowSet.getString("obs_instance_num")); + observation.setInstanceNum(instanceNum); + + Date startDate = rowSet.getTimestamp("obs_start_date"); + + if (startDate != null) { + observation.setStartDate(dtoFactory + .getXMLGregorianCalendar(startDate.getTime())); + } + + ObservationType.ObserverCd observerCd = new ObservationType.ObserverCd(); + observerCd.setValue(rowSet.getString("obs_provider_id")); + String providerName = rowSet.getString("provider_name"); + observerCd.setName((providerName != null) ? providerName : ""); + observation.setObserverCd(observerCd); + if (obsFactDetailFlag) { + Date endDate = rowSet.getTimestamp("obs_end_date"); + + if (endDate != null) { + observation.setEndDate(dtoFactory + .getXMLGregorianCalendar(endDate.getTime())); + } + + observation.setValuetypeCd(rowSet.getString("obs_valtype_cd")); + observation.setTvalChar(rowSet.getString("obs_tval_char")); + + ObservationType.NvalNum nvalNum = new ObservationType.NvalNum(); + nvalNum.setValue(rowSet.getBigDecimal("obs_nval_num")); + observation.setNvalNum(nvalNum); + + ObservationType.ValueflagCd valueFlagCd = new ObservationType.ValueflagCd(); + valueFlagCd.setValue(rowSet.getString("obs_valueflag_cd")); + observation.setValueflagCd(valueFlagCd); + + observation.setQuantityNum(rowSet + .getBigDecimal("obs_quantity_num")); + + observation.setUnitsCd(rowSet.getString("obs_units_cd")); + + if (rowSet.getString("obs_location_cd") != null) { + ObservationType.LocationCd locationCd = new ObservationType.LocationCd(); + locationCd.setValue(rowSet.getString("obs_location_cd")); + String locationName = rowSet.getString("location_name"); + locationCd.setName((locationName != null) ? locationName + : ""); + observation.setLocationCd(locationCd); + } + + observation.setConfidenceNum(rowSet + .getBigDecimal("obs_confidence_num")); + + } + + if (obsFactBlobFlag) { + Clob observationClob = rowSet.getClob("obs_observation_blob"); + if (observationClob != null) { + try { + BlobType blobType = new BlobType(); + blobType.getContent().add( + JDBCUtil.getClobStringWithLinebreak(observationClob)); + observation.setObservationBlob(blobType); + } catch (IOException ioEx) { + ioEx.printStackTrace(); + throw ioEx; + } + } + } + + if (obsFactStatusFlag) { + if (rowSet.getTimestamp("obs_update_date") != null) { + observation.setUpdateDate(dtoFactory + .getXMLGregorianCalendar(rowSet.getTimestamp( + "obs_update_date").getTime())); + } + + if (rowSet.getDate("obs_download_date") != null) { + observation.setDownloadDate(dtoFactory + .getXMLGregorianCalendar(rowSet.getTimestamp( + "obs_download_date").getTime())); + } + + if (rowSet.getDate("obs_import_date") != null) { + observation.setImportDate(dtoFactory + .getXMLGregorianCalendar(rowSet.getTimestamp( + "obs_import_date").getTime())); + } + + observation.setSourcesystemCd(rowSet + .getString("obs_sourcesystem_cd")); + observation.setUploadId(rowSet.getString("obs_upload_id")); + } + + return observation; + } + } + + /* + * Inner class to build patient in table PDO format + */ + public static class PatientBuilder { + boolean patientDetailFlag = false; + boolean patientBlobFlag = false; + boolean patientStatusFlag = false; + + public PatientBuilder(boolean detailFlag, boolean blobFlag, + boolean statusFlag) { + this.patientDetailFlag = detailFlag; + this.patientBlobFlag = blobFlag; + this.patientStatusFlag = statusFlag; + } + + /** + * Read one record from resultset and build patient set + * + * @param rowSet + * @param source + * @return PatientSet.Patient + * @throws SQLException + * @throws IOException + */ + public PatientType buildPatientSet(ResultSet rowSet, String source,List metaDataParamList) + throws SQLException, IOException { + PatientType patientDimensionType = new PatientType(); + PatientIdType patientIdType = new PatientIdType(); + patientIdType.setSource(source); + patientIdType.setValue(rowSet.getString("patient_patient_num")); + patientDimensionType.setPatientId(patientIdType); + + if (patientDetailFlag) { + + + + + + ParamTypeValueBuilder paramValBuilder = new ParamTypeValueBuilder(); + for (Iterator metaParamIterator = metaDataParamList.iterator(); metaParamIterator.hasNext();) { + ParamType metaParamType = metaParamIterator.next(); + if (metaParamType.getType().equalsIgnoreCase("string")) { + patientDimensionType.getParam().add(paramValBuilder.buildParamType(metaParamType,"patient_","_name",rowSet)); + } else { + patientDimensionType.getParam().add(paramValBuilder.buildParamType(metaParamType,"patient_",null,rowSet)); + } + + + } + } + + if (patientBlobFlag) { + if (rowSet.getClob("patient_patient_blob") != null) { + BlobType blobType = new BlobType(); + blobType.getContent().add( + JDBCUtil.getClobStringWithLinebreak(rowSet + .getClob("patient_patient_blob"))); + } + } + + if (patientStatusFlag) { + if (rowSet.getTimestamp("patient_update_date") != null) { + patientDimensionType.setUpdateDate(dtoFactory + .getXMLGregorianCalendar(rowSet.getTimestamp( + "patient_update_date").getTime())); + } + + if (rowSet.getTimestamp("patient_download_date") != null) { + patientDimensionType.setDownloadDate(dtoFactory + .getXMLGregorianCalendar(rowSet.getTimestamp( + "patient_download_date").getTime())); + } + + if (rowSet.getTimestamp("patient_import_date") != null) { + patientDimensionType.setImportDate(dtoFactory + .getXMLGregorianCalendar(rowSet.getTimestamp( + "patient_import_date").getTime())); + } + + patientDimensionType.setSourcesystemCd(rowSet + .getString("patient_sourcesystem_cd")); + patientDimensionType.setUploadId(rowSet + .getString("patient_upload_id")); + } + + return patientDimensionType; + } + } + + /* + * Inner class to build observer section in table PDO format + */ + public static class ProviderBuilder { + boolean providerDetailFlag = false; + boolean providerBlobFlag = false; + boolean providerStatusFlag = false; + + public ProviderBuilder(boolean detailFlag, boolean blobFlag, + boolean statusFlag) { + this.providerDetailFlag = detailFlag; + this.providerBlobFlag = blobFlag; + this.providerStatusFlag = statusFlag; + } + + /** + * Read one record from resultset and build observer set + * + * @param rowSet + * @param source + * @return ObserverSet.Observer + * @throws SQLException + * @throws IOException + */ + public ObserverType buildObserverSet(ResultSet rowSet) + throws IOException, SQLException { + ObserverType providerDimensionType = new ObserverType(); + providerDimensionType.setObserverCd(rowSet + .getString("provider_provider_id")); + providerDimensionType.setObserverPath(rowSet + .getString("provider_provider_path")); + + if (providerDetailFlag) { + providerDimensionType.setNameChar(rowSet + .getString("provider_name_char")); + } + + if (providerBlobFlag) { + Clob providerClob = rowSet.getClob("provider_provider_blob"); + + if (providerClob != null) { + BlobType blobType = new BlobType(); + blobType.getContent().add( + JDBCUtil.getClobStringWithLinebreak(providerClob)); + providerDimensionType.setObserverBlob(blobType); + } + } + + if (providerStatusFlag) { + if (rowSet.getTimestamp("provider_update_date") != null) { + providerDimensionType.setUpdateDate(dtoFactory + .getXMLGregorianCalendar(rowSet.getTimestamp( + "provider_update_date").getTime())); + } + + if (rowSet.getTimestamp("provider_download_date") != null) { + providerDimensionType.setDownloadDate(dtoFactory + .getXMLGregorianCalendar(rowSet.getTimestamp( + "provider_download_date").getTime())); + } + + if (rowSet.getTimestamp("provider_import_date") != null) { + providerDimensionType.setImportDate(dtoFactory + .getXMLGregorianCalendar(rowSet.getTimestamp( + "provider_import_date").getTime())); + } + + providerDimensionType.setSourcesystemCd(rowSet + .getString("provider_sourcesystem_cd")); + providerDimensionType.setUploadId(rowSet + .getString("provider_upload_id")); + + } + + return providerDimensionType; + } + } + + /* + * Inner class to build concept section in table PDO format + */ + public static class ConceptBuilder { + boolean conceptDetailFlag = false; + boolean conceptBlobFlag = false; + boolean conceptStatusFlag = false; + + public ConceptBuilder(boolean detailFlag, boolean blobFlag, + boolean statusFlag) { + this.conceptDetailFlag = detailFlag; + this.conceptBlobFlag = blobFlag; + this.conceptStatusFlag = statusFlag; + } + + /** + * Read one record from resultset and build concept set + * + * @param rowSet + * @param source + * @return ConceptSet.Concept + * @throws SQLException + * @throws IOException + */ + public ConceptType buildConceptSet(ResultSet rowSet) + throws SQLException, IOException { + ConceptType conceptDimensionType = new ConceptType(); + + conceptDimensionType.setConceptCd(rowSet + .getString("concept_concept_cd")); + + if (conceptDetailFlag) { + conceptDimensionType.setConceptPath(rowSet + .getString("concept_concept_path")); + conceptDimensionType.setNameChar(rowSet + .getString("concept_name_char")); + } + + if (conceptBlobFlag) { + Clob conceptClob = rowSet.getClob("concept_concept_blob"); + + if (conceptClob != null) { + BlobType blobType = new BlobType(); + blobType.getContent().add( + JDBCUtil.getClobStringWithLinebreak(conceptClob)); + conceptDimensionType.setConceptBlob(blobType); + } + } + + if (conceptStatusFlag) { + if (rowSet.getTimestamp("concept_update_date") != null) { + conceptDimensionType.setUpdateDate(dtoFactory + .getXMLGregorianCalendar(rowSet.getTimestamp( + "concept_update_date").getTime())); + } + + if (rowSet.getTimestamp("concept_download_date") != null) { + conceptDimensionType.setDownloadDate(dtoFactory + .getXMLGregorianCalendar(rowSet.getTimestamp( + "concept_download_date").getTime())); + } + + if (rowSet.getTimestamp("concept_import_date") != null) { + conceptDimensionType.setImportDate(dtoFactory + .getXMLGregorianCalendar(rowSet.getTimestamp( + "concept_import_date").getTime())); + } + + conceptDimensionType.setSourcesystemCd(rowSet + .getString("concept_sourcesystem_cd")); + + conceptDimensionType.setUploadId(rowSet + .getString("concept_upload_id")); + } + + return conceptDimensionType; + } + } + + /* + * Inner class to build concept section in table PDO format + */ + public static class ModifierBuilder { + boolean modifierDetailFlag = false; + boolean modifierBlobFlag = false; + boolean modifierStatusFlag = false; + + public ModifierBuilder(boolean detailFlag, boolean blobFlag, + boolean statusFlag) { + this.modifierDetailFlag = detailFlag; + this.modifierBlobFlag = blobFlag; + this.modifierStatusFlag = statusFlag; + } + + /** + * Read one record from resultset and build concept set + * + * @param rowSet + * @param source + * @return ConceptSet.Concept + * @throws SQLException + * @throws IOException + */ + public ModifierType buildModifierSet(ResultSet rowSet) + throws SQLException, IOException { + ModifierType modifierDimensionType = new ModifierType(); + + modifierDimensionType.setModifierCd(rowSet + .getString("modifier_modifier_cd")); + + if (modifierDetailFlag) { + modifierDimensionType.setModifierPath(rowSet + .getString("modifier_modifier_path")); + modifierDimensionType.setNameChar(rowSet + .getString("modifier_name_char")); + } + + if (modifierBlobFlag) { + Clob modifierClob = rowSet.getClob("modifier_modifier_blob"); + + if (modifierClob != null) { + BlobType blobType = new BlobType(); + blobType.getContent().add( + JDBCUtil.getClobStringWithLinebreak(modifierClob)); + modifierDimensionType.setModifierBlob(blobType); + } + } + + if (modifierStatusFlag) { + if (rowSet.getTimestamp("modifier_update_date") != null) { + modifierDimensionType.setUpdateDate(dtoFactory + .getXMLGregorianCalendar(rowSet.getTimestamp( + "modifier_update_date").getTime())); + } + + if (rowSet.getTimestamp("modifier_download_date") != null) { + modifierDimensionType.setDownloadDate(dtoFactory + .getXMLGregorianCalendar(rowSet.getTimestamp( + "modifier_download_date").getTime())); + } + + if (rowSet.getTimestamp("modifier_import_date") != null) { + modifierDimensionType.setImportDate(dtoFactory + .getXMLGregorianCalendar(rowSet.getTimestamp( + "modifier_import_date").getTime())); + } + + modifierDimensionType.setSourcesystemCd(rowSet + .getString("modifier_sourcesystem_cd")); + + modifierDimensionType.setUploadId(rowSet + .getString("modifier_upload_id")); + } + + return modifierDimensionType; + } + } + /* + * Inner class to build event section in table PDO format + */ + public static class EventBuilder { + boolean eventDetailFlag = false; + boolean eventBlobFlag = false; + boolean eventStatusFlag = false; + + public EventBuilder(boolean detailFlag, boolean blobFlag, + boolean statusFlag) { + this.eventDetailFlag = detailFlag; + this.eventBlobFlag = blobFlag; + this.eventStatusFlag = statusFlag; + } + + /** + * Read one record from resultset and build event set + * + * @param rowSet + * @param source + * @return EventSet.Event + * @throws SQLException + * @throws IOException + */ + public EventType buildEventSet(ResultSet rowSet, String source,List metaDataParamList) + throws SQLException, IOException { + EventType visitDimensionType = new EventType(); + + PatientIdType patientIdType = new PatientIdType(); + patientIdType.setValue(rowSet.getString("visit_patient_num")); + patientIdType.setSource(source); + visitDimensionType.setPatientId(patientIdType); + + EventType.EventId eventId = new EventType.EventId(); + eventId.setValue(rowSet.getString("visit_encounter_num")); + eventId.setSource(source); + visitDimensionType.setEventId(eventId); + ParamTypeValueBuilder paramValBuilder = new ParamTypeValueBuilder(); + + if (eventDetailFlag) { + for (Iterator metaParamIterator = metaDataParamList.iterator(); metaParamIterator.hasNext();) { + ParamType metaParamType = metaParamIterator.next(); + + if (metaParamType.getType().equalsIgnoreCase("string")) { + visitDimensionType.getParam().add(paramValBuilder.buildParamType(metaParamType,"visit_","_name",rowSet)); + } else { + visitDimensionType.getParam().add(paramValBuilder.buildParamType(metaParamType,"visit_",null,rowSet)); + } + } + + Date startDate = rowSet.getTimestamp("visit_start_date"); + + if (startDate != null) { + visitDimensionType.setStartDate(dtoFactory + .getXMLGregorianCalendar(startDate.getTime())); + } + + Date endDate = rowSet.getTimestamp("visit_end_date"); + + if (endDate != null) { + visitDimensionType.setEndDate(dtoFactory + .getXMLGregorianCalendar(endDate.getTime())); + } + } + + if (eventBlobFlag) { + Clob visitClob = rowSet.getClob("visit_visit_blob"); + + if (visitClob != null) { + BlobType blobType = new BlobType(); + blobType.getContent() + .add(JDBCUtil.getClobStringWithLinebreak(visitClob)); + visitDimensionType.setEventBlob(blobType); + } + } + + if (eventStatusFlag) { + if (rowSet.getTimestamp("visit_update_date") != null) { + visitDimensionType.setUpdateDate(dtoFactory + .getXMLGregorianCalendar(rowSet.getTimestamp( + "visit_update_date").getTime())); + } + + if (rowSet.getTimestamp("visit_download_date") != null) { + visitDimensionType.setDownloadDate(dtoFactory + .getXMLGregorianCalendar(rowSet.getTimestamp( + "visit_download_date").getTime())); + } + + if (rowSet.getTimestamp("visit_import_date") != null) { + visitDimensionType.setImportDate(dtoFactory + .getXMLGregorianCalendar(rowSet.getTimestamp( + "visit_import_date").getTime())); + } + + visitDimensionType.setSourcesystemCd(rowSet + .getString("visit_sourcesystem_cd")); + + visitDimensionType.setUploadId(rowSet + .getString("visit_upload_id")); + } + + return visitDimensionType; + } + } + + /* + * Inner class to build pid section in table PDO format + */ + public static class PidBuilder { + boolean pmDetailFlag = false; + boolean pmBlobFlag = false; + boolean pmStatusFlag = false; + + public PidBuilder(boolean detailFlag, boolean blobFlag, + boolean statusFlag) { + this.pmDetailFlag = detailFlag; + this.pmBlobFlag = blobFlag; + this.pmStatusFlag = statusFlag; + } + + /** + * Read one record from resultset and build concept set + * + * @param rowSet + * @param source + * @return ConceptSet.Concept + * @throws SQLException + * @throws IOException + */ + public PidType buildPidSet(ResultSet rowSet) throws SQLException, + IOException { + PidType.PatientMapId patientMapType = new PidType.PatientMapId(); + patientMapType.setValue(rowSet.getString("pm_patient_ide")); + patientMapType.setSource(rowSet.getString("pm_patient_ide_source")); + + PatientId patientId = new PatientId(); + patientId.setValue(rowSet.getString("pm_patient_num")); + + PidType pidType = new PidType(); + pidType.setPatientId(patientId); + pidType.getPatientMapId().add(patientMapType); + // patientMapType.setValue(rowSet.getString("pm_patient_num")); + + if (pmDetailFlag) { + patientMapType.setStatus(rowSet + .getString("pm_patient_ide_status")); + } + + if (pmBlobFlag) { + ; // no blob field in the mapping table + } + + if (pmStatusFlag) { + if (rowSet.getTimestamp("pm_update_date") != null) { + patientMapType.setUpdateDate(dtoFactory + .getXMLGregorianCalendar(rowSet.getTimestamp( + "pm_update_date").getTime())); + } + + if (rowSet.getTimestamp("pm_download_date") != null) { + patientMapType.setDownloadDate(dtoFactory + .getXMLGregorianCalendar(rowSet.getTimestamp( + "pm_download_date").getTime())); + } + + if (rowSet.getTimestamp("pm_import_date") != null) { + patientMapType.setImportDate(dtoFactory + .getXMLGregorianCalendar(rowSet.getTimestamp( + "pm_import_date").getTime())); + } + + patientMapType.setSourcesystemCd(rowSet + .getString("pm_sourcesystem_cd")); + patientMapType.setUploadId(rowSet.getString("pm_upload_id")); + + } + + return pidType; + } + } + + /* + * Inner class to build pid section in table PDO format + */ + public static class EidBuilder { + boolean pmDetailFlag = false; + boolean pmBlobFlag = false; + boolean pmStatusFlag = false; + + public EidBuilder(boolean detailFlag, boolean blobFlag, + boolean statusFlag) { + this.pmDetailFlag = detailFlag; + this.pmBlobFlag = blobFlag; + this.pmStatusFlag = statusFlag; + } + + /** + * Read one record from resultset and build concept set + * + * @param rowSet + * @param source + * @return ConceptSet.Concept + * @throws SQLException + * @throws IOException + */ + public EidType buildEidSet(ResultSet rowSet) throws SQLException, + IOException { + EidType.EventMapId eventMapType = new EidType.EventMapId(); + eventMapType.setValue(rowSet.getString("em_encounter_ide")); + eventMapType.setSource(rowSet.getString("em_encounter_ide_source")); + eventMapType.setPatientId(rowSet.getString("em_patient_ide")); + eventMapType.setPatientIdSource(rowSet + .getString("em_patient_ide_source")); + + EidType.EventId eventId = new EidType.EventId(); + eventId.setValue(rowSet.getString("em_encounter_num")); + + EidType eidType = new EidType(); + eidType.setEventId(eventId); + eidType.getEventMapId().add(eventMapType); + // patientMapType.setValue(rowSet.getString("pm_patient_num")); + + if (pmDetailFlag) { + eventMapType.setStatus(rowSet + .getString("em_encounter_ide_status")); + eventId.setStatus(eventMapType.getStatus()); + } + + if (pmBlobFlag) { + ; // no blob field in the mapping table + } + + if (pmStatusFlag) { + if (rowSet.getTimestamp("em_update_date") != null) { + eventMapType.setUpdateDate(dtoFactory + .getXMLGregorianCalendar(rowSet.getTimestamp( + "em_update_date").getTime())); + eventId.setUpdateDate(eventMapType.getUpdateDate()); + } + + if (rowSet.getTimestamp("em_download_date") != null) { + eventMapType.setDownloadDate(dtoFactory + .getXMLGregorianCalendar(rowSet.getTimestamp( + "em_download_date").getTime())); + eventId.setDownloadDate(eventMapType.getDownloadDate()); + } + + if (rowSet.getTimestamp("em_import_date") != null) { + eventMapType.setImportDate(dtoFactory + .getXMLGregorianCalendar(rowSet.getTimestamp( + "em_import_date").getTime())); + eventId.setImportDate(eventMapType.getImportDate()); + } + + eventMapType.setSourcesystemCd(rowSet + .getString("em_sourcesystem_cd")); + eventId.setSourcesystemCd(eventMapType.getSourcesystemCd()); + + eventMapType.setUploadId(rowSet.getString("em_upload_id")); + eventId.setUploadId(eventMapType.getUploadId()); + } + + // + + return eidType; + } + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/RpdoTable.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/RpdoTable.java similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/RpdoTable.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/RpdoTable.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/TablePdoQueryConceptDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/TablePdoQueryConceptDao.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/TablePdoQueryConceptDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/TablePdoQueryConceptDao.java index a0862af8..a56c02f4 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/TablePdoQueryConceptDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/TablePdoQueryConceptDao.java @@ -1,311 +1,311 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao.pdo; - -import java.io.IOException; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.List; - -import javax.sql.DataSource; - -import oracle.sql.ArrayDescriptor; - -//import org.jboss.resource.adapter.jdbc.WrappedConnection; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.util.db.JDBCUtil; -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.dao.pdo.input.FactRelatedQueryHandler; -import edu.harvard.i2b2.crc.dao.pdo.input.IInputOptionListHandler; -import edu.harvard.i2b2.crc.dao.pdo.input.SQLServerFactRelatedQueryHandler; -import edu.harvard.i2b2.crc.dao.pdo.output.ConceptFactRelated; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.pdo.ConceptSet; -import edu.harvard.i2b2.crc.datavo.pdo.ConceptType; - -/** - * Class to support concept section of table pdo query $Id: - * TablePdoQueryConceptDao.java,v 1.13 2008/07/21 19:53:40 rk903 Exp $ - * - * @author rkuttan - */ -public class TablePdoQueryConceptDao extends CRCDAO implements - ITablePdoQueryConceptDao { - - private DataSourceLookup dataSourceLookup = null; - private String schemaName = null; - - public TablePdoQueryConceptDao(DataSourceLookup dataSourceLookup, - DataSource dataSource) { - this.dataSourceLookup = dataSourceLookup; - this.setDbSchemaName(dataSourceLookup.getFullSchema()); - setDataSource(dataSource); - } - - @Override - public ConceptSet getConceptByFact(List panelSqlList, - List sqlParamCountList, - IInputOptionListHandler inputOptionListHandler, boolean detailFlag, - boolean blobFlag, boolean statusFlag) throws I2B2DAOException { - ConceptSet conceptSet = new ConceptSet(); - RPDRPdoFactory.ConceptBuilder conceptBuilder = new RPDRPdoFactory.ConceptBuilder( - detailFlag, blobFlag, statusFlag); - ConceptFactRelated conceptFactRelated = new ConceptFactRelated( - buildOutputOptionType(detailFlag, blobFlag, statusFlag)); - String selectClause = conceptFactRelated.getSelectClause(); - String serverType = dataSourceLookup.getServerType(); - String factTempTable = ""; - Connection conn = null; - PreparedStatement query = null; - try { - conn = dataSource.getConnection(); - if (serverType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { - factTempTable = this.getDbSchemaName() - + FactRelatedQueryHandler.TEMP_FACT_PARAM_TABLE; - } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.SQLSERVER) || serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL )) { - log.debug("creating temp table"); - java.sql.Statement tempStmt = conn.createStatement(); - factTempTable = this.getDbSchemaName() - + SQLServerFactRelatedQueryHandler.TEMP_FACT_PARAM_TABLE; - try { - tempStmt.executeUpdate("drop table " + factTempTable); - } catch (SQLException sqlex) { - ; - } - String createTempInputListTable = "create table " - + factTempTable - + " ( set_index int, char_param1 varchar(500) )"; - tempStmt.executeUpdate(createTempInputListTable); - log.debug("created temp table" + factTempTable); - } - // if the inputlist is enumeration, then upload the enumerated input - // to temp table. - // the uploaded enumerated input will be used in the fact join. - if (inputOptionListHandler.isEnumerationSet()) { - inputOptionListHandler.uploadEnumerationValueToTempTable(conn); - } - String insertSql = ""; - int i = 0; - int sqlParamCount = 0; - ResultSet resultSet = null; - for (String panelSql : panelSqlList) { - insertSql = " insert into " - + factTempTable; - - if (serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) - insertSql = " CAST(coalesce(char_param1, '0') as integer) "; - //else - // insertSql += " (char_param1) "; - insertSql += "(char_param1) select distinct obs_concept_cd from ( " - + panelSql + ") b"; - - log.debug("Executing SQL [ " + insertSql + "]"); - sqlParamCount = sqlParamCountList.get(i++); - // conn.createStatement().executeUpdate(insertSql); - executeTotalSql(insertSql, conn, sqlParamCount, - inputOptionListHandler); - - } - - String finalSql = "SELECT " - + selectClause - + " FROM " - + getDbSchemaName() - + "concept_dimension concept where concept_cd in (select distinct char_param1 from " - + factTempTable + ") order by concept_path"; - log.debug("Executing SQL [" + finalSql + "]"); - - - query = conn.prepareStatement(finalSql); - - resultSet = query.executeQuery(); - - while (resultSet.next()) { - ConceptType concept = conceptBuilder.buildConceptSet(resultSet); - conceptSet.getConcept().add(concept); - } - } catch (SQLException sqlEx) { - log.error("", sqlEx); - throw new I2B2DAOException("sql exception", sqlEx); - } catch (IOException ioEx) { - log.error("", ioEx); - throw new I2B2DAOException("IO exception", ioEx); - } finally { - PdoTempTableUtil tempTableUtil = new PdoTempTableUtil(); - tempTableUtil.clearTempTable(serverType, conn, factTempTable); - - if (inputOptionListHandler != null - && inputOptionListHandler.isEnumerationSet()) { - try { - inputOptionListHandler.deleteTempTable(conn); - } catch (SQLException e) { - - e.printStackTrace(); - } - } - try { - JDBCUtil.closeJdbcResource(null, query, conn); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - } - } - return conceptSet; - } - - private void executeTotalSql(String totalSql, Connection conn, - int sqlParamCount, IInputOptionListHandler inputOptionListHandler) - throws SQLException { - - PreparedStatement stmt = conn.prepareStatement(totalSql); - - log.debug(totalSql + " [ " + sqlParamCount + " ]"); - if (inputOptionListHandler.isCollectionId()) { - for (int i = 1; i <= sqlParamCount; i++) { - stmt.setInt(i, Integer.parseInt(inputOptionListHandler - .getCollectionId())); - } - } - - stmt.executeUpdate(); - - } - - /** - * Function returns concepts based on list of concept codes - * - * @param conceptCdList - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return ConceptSet - * @throws I2B2DAOException - */ - @Override - public ConceptSet getConceptByConceptCd(List conceptCdList, - boolean detailFlag, boolean blobFlag, boolean statusFlag) - throws I2B2DAOException { - ConceptSet conceptSet = new ConceptSet(); - RPDRPdoFactory.ConceptBuilder conceptBuilder = new RPDRPdoFactory.ConceptBuilder( - detailFlag, blobFlag, statusFlag); - log.debug("input concept cd list size " + conceptCdList.size()); - Connection conn = null; - PreparedStatement query = null; - String tempTableName = ""; - try { - conn = getDataSource().getConnection(); - ConceptFactRelated conceptFactRelated = new ConceptFactRelated( - buildOutputOptionType(detailFlag, blobFlag, statusFlag)); - String selectClause = conceptFactRelated.getSelectClause(); - String serverType = dataSourceLookup.getServerType(); - if (serverType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { - oracle.jdbc.driver.OracleConnection conn1 = null;// (oracle.jdbc.driver.OracleConnection) ((WrappedConnection) conn) - // .getUnderlyingConnection(); - String finalSql = "SELECT " - + selectClause - + " FROM " - + getDbSchemaName() - + "concept_dimension concept WHERE concept.concept_cd IN (SELECT * FROM TABLE (?))"; - log.debug("Executing sql[" + finalSql + "]"); - query = conn1.prepareStatement(finalSql); - - ArrayDescriptor desc = ArrayDescriptor.createDescriptor( - "QT_PDO_QRY_STRING_ARRAY", conn1); - - oracle.sql.ARRAY paramArray = new oracle.sql.ARRAY(desc, conn1, - conceptCdList.toArray(new String[] {})); - query.setArray(1, paramArray); - } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.SQLSERVER) || - serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { - log.debug("creating temp table"); - java.sql.Statement tempStmt = conn.createStatement(); - tempTableName = this.getDbSchemaName() - + SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE; - try { - tempStmt.executeUpdate("drop table " + tempTableName); - } catch (SQLException sqlex) { - ; - } - - uploadTempTable(tempStmt, tempTableName, conceptCdList); - String finalSql = "SELECT " - + selectClause - + " FROM " - + getDbSchemaName() - + "concept_dimension concept WHERE concept.concept_cd IN (select distinct char_param1 FROM " - + tempTableName + ") order by concept_path"; - log.debug("Executing [" + finalSql + "]"); - - query = conn.prepareStatement(finalSql); - - } - ResultSet resultSet = query.executeQuery(); - - while (resultSet.next()) { - ConceptType concept = conceptBuilder.buildConceptSet(resultSet); - conceptSet.getConcept().add(concept); - } - - } catch (SQLException sqlEx) { - log.error("", sqlEx); - throw new I2B2DAOException("sql exception", sqlEx); - } catch (IOException ioEx) { - log.error("", ioEx); - throw new I2B2DAOException("IO exception", ioEx); - } finally { - PdoTempTableUtil tempTableUtil = new PdoTempTableUtil(); - tempTableUtil.deleteTempTableSqlServer(conn, tempTableName); - - try { - JDBCUtil.closeJdbcResource(null, query, conn); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - } - } - return conceptSet; - } - - private void uploadTempTable(Statement tempStmt, String tempTableName, - List patientNumList) throws SQLException { - String createTempInputListTable = "create table " + tempTableName - + " ( char_param1 varchar(100) )"; - tempStmt.executeUpdate(createTempInputListTable); - log.debug("created temp table" + tempTableName); - // load to temp table - // TempInputListInsert inputListInserter = new - // TempInputListInsert(dataSource,TEMP_PDO_INPUTLIST_TABLE); - // inputListInserter.setBatchSize(100); - int i = 0; - for (String singleValue : patientNumList) { - tempStmt.addBatch("insert into " + tempTableName + " values ('" - + singleValue + "' )"); - log.debug("adding batch" + singleValue); - i++; - if (i % 100 == 0) { - log.debug("batch insert"); - tempStmt.executeBatch(); - - } - } - log.debug("batch insert1"); - tempStmt.executeBatch(); - } - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao.pdo; + +import java.io.IOException; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.List; + +import javax.sql.DataSource; + +import oracle.sql.ArrayDescriptor; + +//import org.jboss.resource.adapter.jdbc.WrappedConnection; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.util.db.JDBCUtil; +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.dao.pdo.input.FactRelatedQueryHandler; +import edu.harvard.i2b2.crc.dao.pdo.input.IInputOptionListHandler; +import edu.harvard.i2b2.crc.dao.pdo.input.SQLServerFactRelatedQueryHandler; +import edu.harvard.i2b2.crc.dao.pdo.output.ConceptFactRelated; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.pdo.ConceptSet; +import edu.harvard.i2b2.crc.datavo.pdo.ConceptType; + +/** + * Class to support concept section of table pdo query $Id: + * TablePdoQueryConceptDao.java,v 1.13 2008/07/21 19:53:40 rk903 Exp $ + * + * @author rkuttan + */ +public class TablePdoQueryConceptDao extends CRCDAO implements + ITablePdoQueryConceptDao { + + private DataSourceLookup dataSourceLookup = null; + private String schemaName = null; + + public TablePdoQueryConceptDao(DataSourceLookup dataSourceLookup, + DataSource dataSource) { + this.dataSourceLookup = dataSourceLookup; + this.setDbSchemaName(dataSourceLookup.getFullSchema()); + setDataSource(dataSource); + } + + @Override + public ConceptSet getConceptByFact(List panelSqlList, + List sqlParamCountList, + IInputOptionListHandler inputOptionListHandler, boolean detailFlag, + boolean blobFlag, boolean statusFlag) throws I2B2DAOException { + ConceptSet conceptSet = new ConceptSet(); + RPDRPdoFactory.ConceptBuilder conceptBuilder = new RPDRPdoFactory.ConceptBuilder( + detailFlag, blobFlag, statusFlag); + ConceptFactRelated conceptFactRelated = new ConceptFactRelated( + buildOutputOptionType(detailFlag, blobFlag, statusFlag)); + String selectClause = conceptFactRelated.getSelectClause(); + String serverType = dataSourceLookup.getServerType(); + String factTempTable = ""; + Connection conn = null; + PreparedStatement query = null; + try { + conn = dataSource.getConnection(); + if (serverType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { + factTempTable = this.getDbSchemaName() + + FactRelatedQueryHandler.TEMP_FACT_PARAM_TABLE; + } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.SQLSERVER) || serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL )) { + log.debug("creating temp table"); + java.sql.Statement tempStmt = conn.createStatement(); + factTempTable = this.getDbSchemaName() + + SQLServerFactRelatedQueryHandler.TEMP_FACT_PARAM_TABLE; + try { + tempStmt.executeUpdate("drop table " + factTempTable); + } catch (SQLException sqlex) { + ; + } + String createTempInputListTable = "create table " + + factTempTable + + " ( set_index int, char_param1 varchar(500) )"; + tempStmt.executeUpdate(createTempInputListTable); + log.debug("created temp table" + factTempTable); + } + // if the inputlist is enumeration, then upload the enumerated input + // to temp table. + // the uploaded enumerated input will be used in the fact join. + if (inputOptionListHandler.isEnumerationSet()) { + inputOptionListHandler.uploadEnumerationValueToTempTable(conn); + } + String insertSql = ""; + int i = 0; + int sqlParamCount = 0; + ResultSet resultSet = null; + for (String panelSql : panelSqlList) { + insertSql = " insert into " + + factTempTable; + + if (serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) + insertSql = " CAST(coalesce(char_param1, '0') as integer) "; + //else + // insertSql += " (char_param1) "; + insertSql += "(char_param1) select distinct obs_concept_cd from ( " + + panelSql + ") b"; + + log.debug("Executing SQL [ " + insertSql + "]"); + sqlParamCount = sqlParamCountList.get(i++); + // conn.createStatement().executeUpdate(insertSql); + executeTotalSql(insertSql, conn, sqlParamCount, + inputOptionListHandler); + + } + + String finalSql = "SELECT " + + selectClause + + " FROM " + + getDbSchemaName() + + "concept_dimension concept where concept_cd in (select distinct char_param1 from " + + factTempTable + ") order by concept_path"; + log.debug("Executing SQL [" + finalSql + "]"); + + + query = conn.prepareStatement(finalSql); + + resultSet = query.executeQuery(); + + while (resultSet.next()) { + ConceptType concept = conceptBuilder.buildConceptSet(resultSet); + conceptSet.getConcept().add(concept); + } + } catch (SQLException sqlEx) { + log.error("", sqlEx); + throw new I2B2DAOException("sql exception", sqlEx); + } catch (IOException ioEx) { + log.error("", ioEx); + throw new I2B2DAOException("IO exception", ioEx); + } finally { + PdoTempTableUtil tempTableUtil = new PdoTempTableUtil(); + tempTableUtil.clearTempTable(serverType, conn, factTempTable); + + if (inputOptionListHandler != null + && inputOptionListHandler.isEnumerationSet()) { + try { + inputOptionListHandler.deleteTempTable(conn); + } catch (SQLException e) { + + e.printStackTrace(); + } + } + try { + JDBCUtil.closeJdbcResource(null, query, conn); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + } + } + return conceptSet; + } + + private void executeTotalSql(String totalSql, Connection conn, + int sqlParamCount, IInputOptionListHandler inputOptionListHandler) + throws SQLException { + + PreparedStatement stmt = conn.prepareStatement(totalSql); + + log.debug(totalSql + " [ " + sqlParamCount + " ]"); + if (inputOptionListHandler.isCollectionId()) { + for (int i = 1; i <= sqlParamCount; i++) { + stmt.setInt(i, Integer.parseInt(inputOptionListHandler + .getCollectionId())); + } + } + + stmt.executeUpdate(); + + } + + /** + * Function returns concepts based on list of concept codes + * + * @param conceptCdList + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return ConceptSet + * @throws I2B2DAOException + */ + @Override + public ConceptSet getConceptByConceptCd(List conceptCdList, + boolean detailFlag, boolean blobFlag, boolean statusFlag) + throws I2B2DAOException { + ConceptSet conceptSet = new ConceptSet(); + RPDRPdoFactory.ConceptBuilder conceptBuilder = new RPDRPdoFactory.ConceptBuilder( + detailFlag, blobFlag, statusFlag); + log.debug("input concept cd list size " + conceptCdList.size()); + Connection conn = null; + PreparedStatement query = null; + String tempTableName = ""; + try { + conn = getDataSource().getConnection(); + ConceptFactRelated conceptFactRelated = new ConceptFactRelated( + buildOutputOptionType(detailFlag, blobFlag, statusFlag)); + String selectClause = conceptFactRelated.getSelectClause(); + String serverType = dataSourceLookup.getServerType(); + if (serverType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { + oracle.jdbc.driver.OracleConnection conn1 = null;// (oracle.jdbc.driver.OracleConnection) ((WrappedConnection) conn) + // .getUnderlyingConnection(); + String finalSql = "SELECT " + + selectClause + + " FROM " + + getDbSchemaName() + + "concept_dimension concept WHERE concept.concept_cd IN (SELECT * FROM TABLE (?))"; + log.debug("Executing sql[" + finalSql + "]"); + query = conn1.prepareStatement(finalSql); + + ArrayDescriptor desc = ArrayDescriptor.createDescriptor( + "QT_PDO_QRY_STRING_ARRAY", conn1); + + oracle.sql.ARRAY paramArray = new oracle.sql.ARRAY(desc, conn1, + conceptCdList.toArray(new String[] {})); + query.setArray(1, paramArray); + } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.SQLSERVER) || + serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { + log.debug("creating temp table"); + java.sql.Statement tempStmt = conn.createStatement(); + tempTableName = this.getDbSchemaName() + + SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE; + try { + tempStmt.executeUpdate("drop table " + tempTableName); + } catch (SQLException sqlex) { + ; + } + + uploadTempTable(tempStmt, tempTableName, conceptCdList); + String finalSql = "SELECT " + + selectClause + + " FROM " + + getDbSchemaName() + + "concept_dimension concept WHERE concept.concept_cd IN (select distinct char_param1 FROM " + + tempTableName + ") order by concept_path"; + log.debug("Executing [" + finalSql + "]"); + + query = conn.prepareStatement(finalSql); + + } + ResultSet resultSet = query.executeQuery(); + + while (resultSet.next()) { + ConceptType concept = conceptBuilder.buildConceptSet(resultSet); + conceptSet.getConcept().add(concept); + } + + } catch (SQLException sqlEx) { + log.error("", sqlEx); + throw new I2B2DAOException("sql exception", sqlEx); + } catch (IOException ioEx) { + log.error("", ioEx); + throw new I2B2DAOException("IO exception", ioEx); + } finally { + PdoTempTableUtil tempTableUtil = new PdoTempTableUtil(); + tempTableUtil.deleteTempTableSqlServer(conn, tempTableName); + + try { + JDBCUtil.closeJdbcResource(null, query, conn); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + } + } + return conceptSet; + } + + private void uploadTempTable(Statement tempStmt, String tempTableName, + List patientNumList) throws SQLException { + String createTempInputListTable = "create table " + tempTableName + + " ( char_param1 varchar(100) )"; + tempStmt.executeUpdate(createTempInputListTable); + log.debug("created temp table" + tempTableName); + // load to temp table + // TempInputListInsert inputListInserter = new + // TempInputListInsert(dataSource,TEMP_PDO_INPUTLIST_TABLE); + // inputListInserter.setBatchSize(100); + int i = 0; + for (String singleValue : patientNumList) { + tempStmt.addBatch("insert into " + tempTableName + " values ('" + + singleValue + "' )"); + log.debug("adding batch" + singleValue); + i++; + if (i % 100 == 0) { + log.debug("batch insert"); + tempStmt.executeBatch(); + + } + } + log.debug("batch insert1"); + tempStmt.executeBatch(); + } + + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/TablePdoQueryModifierDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/TablePdoQueryModifierDao.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/TablePdoQueryModifierDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/TablePdoQueryModifierDao.java index a8c0cdc2..5a3bd932 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/TablePdoQueryModifierDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/TablePdoQueryModifierDao.java @@ -1,307 +1,307 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao.pdo; - -import java.io.IOException; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.List; - -import javax.sql.DataSource; - -import oracle.sql.ArrayDescriptor; - -//import org.jboss.resource.adapter.jdbc.WrappedConnection; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.util.db.JDBCUtil; -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.dao.pdo.input.FactRelatedQueryHandler; -import edu.harvard.i2b2.crc.dao.pdo.input.IInputOptionListHandler; -import edu.harvard.i2b2.crc.dao.pdo.input.SQLServerFactRelatedQueryHandler; -import edu.harvard.i2b2.crc.dao.pdo.output.ModifierFactRelated; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.pdo.ModifierSet; -import edu.harvard.i2b2.crc.datavo.pdo.ModifierType; - -/** - * Class to support concept section of table pdo query $Id: - * TablePdoQueryConceptDao.java,v 1.13 2008/07/21 19:53:40 rk903 Exp $ - * - * @author rkuttan - */ -public class TablePdoQueryModifierDao extends CRCDAO implements - ITablePdoQueryModifierDao { - - private DataSourceLookup dataSourceLookup = null; - private String schemaName = null; - - public TablePdoQueryModifierDao(DataSourceLookup dataSourceLookup, - DataSource dataSource) { - this.dataSourceLookup = dataSourceLookup; - this.setDbSchemaName(dataSourceLookup.getFullSchema()); - setDataSource(dataSource); - } - - @Override - public ModifierSet getModifierByFact(List panelSqlList, - List sqlParamCountList, - IInputOptionListHandler inputOptionListHandler, boolean detailFlag, - boolean blobFlag, boolean statusFlag) throws I2B2DAOException { - ModifierSet modifierSet = new ModifierSet(); - RPDRPdoFactory.ModifierBuilder modifierBuilder = new RPDRPdoFactory.ModifierBuilder( - detailFlag, blobFlag, statusFlag); - ModifierFactRelated modifierFactRelated = new ModifierFactRelated( - buildOutputOptionType(detailFlag, blobFlag, statusFlag)); - String selectClause = modifierFactRelated.getSelectClause(); - String serverType = dataSourceLookup.getServerType(); - String factTempTable = ""; - Connection conn = null; - PreparedStatement query = null; - try { - conn = dataSource.getConnection(); - if (serverType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { - factTempTable = this.getDbSchemaName() - + FactRelatedQueryHandler.TEMP_FACT_PARAM_TABLE; - } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.SQLSERVER) || - serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { - log.debug("creating temp table"); - java.sql.Statement tempStmt = conn.createStatement(); - factTempTable = this.getDbSchemaName() - + SQLServerFactRelatedQueryHandler.TEMP_FACT_PARAM_TABLE; - try { - tempStmt.executeUpdate("drop table " + factTempTable); - } catch (SQLException sqlex) { - ; - } - String createTempInputListTable = "create table " - + factTempTable - + " ( set_index int, char_param1 varchar(500) )"; - tempStmt.executeUpdate(createTempInputListTable); - log.debug("created temp table" + factTempTable); - } - // if the inputlist is enumeration, then upload the enumerated input - // to temp table. - // the uploaded enumerated input will be used in the fact join. - if (inputOptionListHandler.isEnumerationSet()) { - inputOptionListHandler.uploadEnumerationValueToTempTable(conn); - } - String insertSql = ""; - int i = 0; - int sqlParamCount = 0; - ResultSet resultSet = null; - for (String panelSql : panelSqlList) { - insertSql = " insert into " - + factTempTable - + "(char_param1) select distinct obs_modifier_cd from ( " - + panelSql + ") b"; - - log.debug("Executing SQL [ " + insertSql + "]"); - sqlParamCount = sqlParamCountList.get(i++); - // conn.createStatement().executeUpdate(insertSql); - executeTotalSql(insertSql, conn, sqlParamCount, - inputOptionListHandler); - - } - - String finalSql = "SELECT " - + selectClause - + " FROM " - + getDbSchemaName() - + "modifier_dimension modifier where modifier_cd in (select distinct char_param1 from " - + factTempTable + ") order by modifier_path"; - log.debug("Executing SQL [" + finalSql + "]"); - - - query = conn.prepareStatement(finalSql); - - resultSet = query.executeQuery(); - - while (resultSet.next()) { - ModifierType modifier = modifierBuilder.buildModifierSet(resultSet); - modifierSet.getModifier().add(modifier); - } - } catch (SQLException sqlEx) { - log.error("", sqlEx); - throw new I2B2DAOException("sql exception", sqlEx); - } catch (IOException ioEx) { - log.error("", ioEx); - throw new I2B2DAOException("IO exception", ioEx); - } finally { - PdoTempTableUtil tempTableUtil = new PdoTempTableUtil(); - tempTableUtil.clearTempTable(serverType, conn, factTempTable); - - if (inputOptionListHandler != null - && inputOptionListHandler.isEnumerationSet()) { - try { - inputOptionListHandler.deleteTempTable(conn); - } catch (SQLException e) { - - e.printStackTrace(); - } - } - try { - JDBCUtil.closeJdbcResource(null, query, conn); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - } - } - return modifierSet; - } - - private void executeTotalSql(String totalSql, Connection conn, - int sqlParamCount, IInputOptionListHandler inputOptionListHandler) - throws SQLException { - - PreparedStatement stmt = conn.prepareStatement(totalSql); - - log.debug(totalSql + " [ " + sqlParamCount + " ]"); - if (inputOptionListHandler.isCollectionId()) { - for (int i = 1; i <= sqlParamCount; i++) { - stmt.setInt(i, Integer.parseInt(inputOptionListHandler - .getCollectionId())); - } - } - - stmt.executeUpdate(); - - } - - /** - * Function returns concepts based on list of concept codes - * - * @param conceptCdList - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return ConceptSet - * @throws I2B2DAOException - */ - @Override - public ModifierSet getModifierByModifierCd(List modifierCdList, - boolean detailFlag, boolean blobFlag, boolean statusFlag) - throws I2B2DAOException { - ModifierSet modifierSet = new ModifierSet(); - RPDRPdoFactory.ModifierBuilder modifierBuilder = new RPDRPdoFactory.ModifierBuilder( - detailFlag, blobFlag, statusFlag); - log.debug("input concept cd list size " + modifierCdList.size()); - Connection conn = null; - PreparedStatement query = null; - String tempTableName = ""; - try { - conn = getDataSource().getConnection(); - ModifierFactRelated modifierFactRelated = new ModifierFactRelated( - buildOutputOptionType(detailFlag, blobFlag, statusFlag)); - String selectClause = modifierFactRelated.getSelectClause(); - String serverType = dataSourceLookup.getServerType(); - if (serverType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { - oracle.jdbc.driver.OracleConnection conn1 = null;// (oracle.jdbc.driver.OracleConnection) ((WrappedConnection) conn) - // .getUnderlyingConnection(); - String finalSql = "SELECT " - + selectClause - + " FROM " - + getDbSchemaName() - + "modifier_dimension modifier WHERE modifier.modifier_cd IN (SELECT * FROM TABLE (?))"; - log.debug("Executing sql[" + finalSql + "]"); - query = conn1.prepareStatement(finalSql); - - ArrayDescriptor desc = ArrayDescriptor.createDescriptor( - "QT_PDO_QRY_STRING_ARRAY", conn1); - - oracle.sql.ARRAY paramArray = new oracle.sql.ARRAY(desc, conn1, - modifierCdList.toArray(new String[] {})); - query.setArray(1, paramArray); - } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.SQLSERVER) || - serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { - log.debug("creating temp table"); - java.sql.Statement tempStmt = conn.createStatement(); - tempTableName = this.getDbSchemaName() - + SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE; - try { - tempStmt.executeUpdate("drop table " + tempTableName); - } catch (SQLException sqlex) { - ; - } - - uploadTempTable(tempStmt, tempTableName, modifierCdList); - String finalSql = "SELECT " - + selectClause - + " FROM " - + getDbSchemaName() - + "modifier_dimension modifier WHERE modifier.modifier_cd IN (select distinct char_param1 FROM " - + tempTableName + ") order by modifier_path"; - log.debug("Executing [" + finalSql + "]"); - - query = conn.prepareStatement(finalSql); - - } - ResultSet resultSet = query.executeQuery(); - - while (resultSet.next()) { - ModifierType modifier = modifierBuilder.buildModifierSet(resultSet); - modifierSet.getModifier().add(modifier); - } - - } catch (SQLException sqlEx) { - log.error("", sqlEx); - throw new I2B2DAOException("sql exception", sqlEx); - } catch (IOException ioEx) { - log.error("", ioEx); - throw new I2B2DAOException("IO exception", ioEx); - } finally { - PdoTempTableUtil tempTableUtil = new PdoTempTableUtil(); - tempTableUtil.deleteTempTableSqlServer(conn, tempTableName); - - try { - JDBCUtil.closeJdbcResource(null, query, conn); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - } - } - return modifierSet; - } - - private void uploadTempTable(Statement tempStmt, String tempTableName, - List patientNumList) throws SQLException { - String createTempInputListTable = "create table " + tempTableName - + " ( char_param1 varchar(100) )"; - tempStmt.executeUpdate(createTempInputListTable); - log.debug("created temp table" + tempTableName); - // load to temp table - // TempInputListInsert inputListInserter = new - // TempInputListInsert(dataSource,TEMP_PDO_INPUTLIST_TABLE); - // inputListInserter.setBatchSize(100); - int i = 0; - for (String singleValue : patientNumList) { - tempStmt.addBatch("insert into " + tempTableName + " values ('" - + singleValue + "' )"); - log.debug("adding batch" + singleValue); - i++; - if (i % 100 == 0) { - log.debug("batch insert"); - tempStmt.executeBatch(); - - } - } - log.debug("batch insert1"); - tempStmt.executeBatch(); - } - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao.pdo; + +import java.io.IOException; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.List; + +import javax.sql.DataSource; + +import oracle.sql.ArrayDescriptor; + +//import org.jboss.resource.adapter.jdbc.WrappedConnection; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.util.db.JDBCUtil; +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.dao.pdo.input.FactRelatedQueryHandler; +import edu.harvard.i2b2.crc.dao.pdo.input.IInputOptionListHandler; +import edu.harvard.i2b2.crc.dao.pdo.input.SQLServerFactRelatedQueryHandler; +import edu.harvard.i2b2.crc.dao.pdo.output.ModifierFactRelated; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.pdo.ModifierSet; +import edu.harvard.i2b2.crc.datavo.pdo.ModifierType; + +/** + * Class to support concept section of table pdo query $Id: + * TablePdoQueryConceptDao.java,v 1.13 2008/07/21 19:53:40 rk903 Exp $ + * + * @author rkuttan + */ +public class TablePdoQueryModifierDao extends CRCDAO implements + ITablePdoQueryModifierDao { + + private DataSourceLookup dataSourceLookup = null; + private String schemaName = null; + + public TablePdoQueryModifierDao(DataSourceLookup dataSourceLookup, + DataSource dataSource) { + this.dataSourceLookup = dataSourceLookup; + this.setDbSchemaName(dataSourceLookup.getFullSchema()); + setDataSource(dataSource); + } + + @Override + public ModifierSet getModifierByFact(List panelSqlList, + List sqlParamCountList, + IInputOptionListHandler inputOptionListHandler, boolean detailFlag, + boolean blobFlag, boolean statusFlag) throws I2B2DAOException { + ModifierSet modifierSet = new ModifierSet(); + RPDRPdoFactory.ModifierBuilder modifierBuilder = new RPDRPdoFactory.ModifierBuilder( + detailFlag, blobFlag, statusFlag); + ModifierFactRelated modifierFactRelated = new ModifierFactRelated( + buildOutputOptionType(detailFlag, blobFlag, statusFlag)); + String selectClause = modifierFactRelated.getSelectClause(); + String serverType = dataSourceLookup.getServerType(); + String factTempTable = ""; + Connection conn = null; + PreparedStatement query = null; + try { + conn = dataSource.getConnection(); + if (serverType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { + factTempTable = this.getDbSchemaName() + + FactRelatedQueryHandler.TEMP_FACT_PARAM_TABLE; + } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.SQLSERVER) || + serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { + log.debug("creating temp table"); + java.sql.Statement tempStmt = conn.createStatement(); + factTempTable = this.getDbSchemaName() + + SQLServerFactRelatedQueryHandler.TEMP_FACT_PARAM_TABLE; + try { + tempStmt.executeUpdate("drop table " + factTempTable); + } catch (SQLException sqlex) { + ; + } + String createTempInputListTable = "create table " + + factTempTable + + " ( set_index int, char_param1 varchar(500) )"; + tempStmt.executeUpdate(createTempInputListTable); + log.debug("created temp table" + factTempTable); + } + // if the inputlist is enumeration, then upload the enumerated input + // to temp table. + // the uploaded enumerated input will be used in the fact join. + if (inputOptionListHandler.isEnumerationSet()) { + inputOptionListHandler.uploadEnumerationValueToTempTable(conn); + } + String insertSql = ""; + int i = 0; + int sqlParamCount = 0; + ResultSet resultSet = null; + for (String panelSql : panelSqlList) { + insertSql = " insert into " + + factTempTable + + "(char_param1) select distinct obs_modifier_cd from ( " + + panelSql + ") b"; + + log.debug("Executing SQL [ " + insertSql + "]"); + sqlParamCount = sqlParamCountList.get(i++); + // conn.createStatement().executeUpdate(insertSql); + executeTotalSql(insertSql, conn, sqlParamCount, + inputOptionListHandler); + + } + + String finalSql = "SELECT " + + selectClause + + " FROM " + + getDbSchemaName() + + "modifier_dimension modifier where modifier_cd in (select distinct char_param1 from " + + factTempTable + ") order by modifier_path"; + log.debug("Executing SQL [" + finalSql + "]"); + + + query = conn.prepareStatement(finalSql); + + resultSet = query.executeQuery(); + + while (resultSet.next()) { + ModifierType modifier = modifierBuilder.buildModifierSet(resultSet); + modifierSet.getModifier().add(modifier); + } + } catch (SQLException sqlEx) { + log.error("", sqlEx); + throw new I2B2DAOException("sql exception", sqlEx); + } catch (IOException ioEx) { + log.error("", ioEx); + throw new I2B2DAOException("IO exception", ioEx); + } finally { + PdoTempTableUtil tempTableUtil = new PdoTempTableUtil(); + tempTableUtil.clearTempTable(serverType, conn, factTempTable); + + if (inputOptionListHandler != null + && inputOptionListHandler.isEnumerationSet()) { + try { + inputOptionListHandler.deleteTempTable(conn); + } catch (SQLException e) { + + e.printStackTrace(); + } + } + try { + JDBCUtil.closeJdbcResource(null, query, conn); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + } + } + return modifierSet; + } + + private void executeTotalSql(String totalSql, Connection conn, + int sqlParamCount, IInputOptionListHandler inputOptionListHandler) + throws SQLException { + + PreparedStatement stmt = conn.prepareStatement(totalSql); + + log.debug(totalSql + " [ " + sqlParamCount + " ]"); + if (inputOptionListHandler.isCollectionId()) { + for (int i = 1; i <= sqlParamCount; i++) { + stmt.setInt(i, Integer.parseInt(inputOptionListHandler + .getCollectionId())); + } + } + + stmt.executeUpdate(); + + } + + /** + * Function returns concepts based on list of concept codes + * + * @param conceptCdList + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return ConceptSet + * @throws I2B2DAOException + */ + @Override + public ModifierSet getModifierByModifierCd(List modifierCdList, + boolean detailFlag, boolean blobFlag, boolean statusFlag) + throws I2B2DAOException { + ModifierSet modifierSet = new ModifierSet(); + RPDRPdoFactory.ModifierBuilder modifierBuilder = new RPDRPdoFactory.ModifierBuilder( + detailFlag, blobFlag, statusFlag); + log.debug("input concept cd list size " + modifierCdList.size()); + Connection conn = null; + PreparedStatement query = null; + String tempTableName = ""; + try { + conn = getDataSource().getConnection(); + ModifierFactRelated modifierFactRelated = new ModifierFactRelated( + buildOutputOptionType(detailFlag, blobFlag, statusFlag)); + String selectClause = modifierFactRelated.getSelectClause(); + String serverType = dataSourceLookup.getServerType(); + if (serverType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { + oracle.jdbc.driver.OracleConnection conn1 = null;// (oracle.jdbc.driver.OracleConnection) ((WrappedConnection) conn) + // .getUnderlyingConnection(); + String finalSql = "SELECT " + + selectClause + + " FROM " + + getDbSchemaName() + + "modifier_dimension modifier WHERE modifier.modifier_cd IN (SELECT * FROM TABLE (?))"; + log.debug("Executing sql[" + finalSql + "]"); + query = conn1.prepareStatement(finalSql); + + ArrayDescriptor desc = ArrayDescriptor.createDescriptor( + "QT_PDO_QRY_STRING_ARRAY", conn1); + + oracle.sql.ARRAY paramArray = new oracle.sql.ARRAY(desc, conn1, + modifierCdList.toArray(new String[] {})); + query.setArray(1, paramArray); + } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.SQLSERVER) || + serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { + log.debug("creating temp table"); + java.sql.Statement tempStmt = conn.createStatement(); + tempTableName = this.getDbSchemaName() + + SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE; + try { + tempStmt.executeUpdate("drop table " + tempTableName); + } catch (SQLException sqlex) { + ; + } + + uploadTempTable(tempStmt, tempTableName, modifierCdList); + String finalSql = "SELECT " + + selectClause + + " FROM " + + getDbSchemaName() + + "modifier_dimension modifier WHERE modifier.modifier_cd IN (select distinct char_param1 FROM " + + tempTableName + ") order by modifier_path"; + log.debug("Executing [" + finalSql + "]"); + + query = conn.prepareStatement(finalSql); + + } + ResultSet resultSet = query.executeQuery(); + + while (resultSet.next()) { + ModifierType modifier = modifierBuilder.buildModifierSet(resultSet); + modifierSet.getModifier().add(modifier); + } + + } catch (SQLException sqlEx) { + log.error("", sqlEx); + throw new I2B2DAOException("sql exception", sqlEx); + } catch (IOException ioEx) { + log.error("", ioEx); + throw new I2B2DAOException("IO exception", ioEx); + } finally { + PdoTempTableUtil tempTableUtil = new PdoTempTableUtil(); + tempTableUtil.deleteTempTableSqlServer(conn, tempTableName); + + try { + JDBCUtil.closeJdbcResource(null, query, conn); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + } + } + return modifierSet; + } + + private void uploadTempTable(Statement tempStmt, String tempTableName, + List patientNumList) throws SQLException { + String createTempInputListTable = "create table " + tempTableName + + " ( char_param1 varchar(100) )"; + tempStmt.executeUpdate(createTempInputListTable); + log.debug("created temp table" + tempTableName); + // load to temp table + // TempInputListInsert inputListInserter = new + // TempInputListInsert(dataSource,TEMP_PDO_INPUTLIST_TABLE); + // inputListInserter.setBatchSize(100); + int i = 0; + for (String singleValue : patientNumList) { + tempStmt.addBatch("insert into " + tempTableName + " values ('" + + singleValue + "' )"); + log.debug("adding batch" + singleValue); + i++; + if (i % 100 == 0) { + log.debug("batch insert"); + tempStmt.executeBatch(); + + } + } + log.debug("batch insert1"); + tempStmt.executeBatch(); + } + + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/TablePdoQueryPatientDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/TablePdoQueryPatientDao.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/TablePdoQueryPatientDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/TablePdoQueryPatientDao.java index 2b9902cf..043adcb8 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/TablePdoQueryPatientDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/TablePdoQueryPatientDao.java @@ -1,661 +1,661 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao.pdo; - -import java.io.IOException; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.Iterator; -import java.util.List; - -import javax.sql.DataSource; - -import oracle.sql.ArrayDescriptor; - -//import org.jboss.resource.adapter.jdbc.WrappedConnection; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.util.db.JDBCUtil; -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.dao.pdo.input.FactRelatedQueryHandler; -import edu.harvard.i2b2.crc.dao.pdo.input.IInputOptionListHandler; -import edu.harvard.i2b2.crc.dao.pdo.input.PatientListTypeHandler; -import edu.harvard.i2b2.crc.dao.pdo.input.SQLServerFactRelatedQueryHandler; -import edu.harvard.i2b2.crc.dao.pdo.input.VisitListTypeHandler; -import edu.harvard.i2b2.crc.dao.pdo.output.PatientFactRelated; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.pdo.ParamType; -import edu.harvard.i2b2.crc.datavo.pdo.PatientSet; -import edu.harvard.i2b2.crc.datavo.pdo.PatientType; -import edu.harvard.i2b2.crc.datavo.pdo.query.EventListType; -import edu.harvard.i2b2.crc.datavo.pdo.query.PatientListType; - -/** - * Class to support Patient section of table pdo query $Id: - * TablePdoQueryPatientDao.java,v 1.11 2008/03/19 22:42:08 rk903 Exp $ - * - * @author rkuttan - */ -public class TablePdoQueryPatientDao extends CRCDAO implements - ITablePdoQueryPatientDao { - - private DataSourceLookup dataSourceLookup = null; - private String schemaName = null; - private List metaDataParamList = null; - - - public TablePdoQueryPatientDao(DataSourceLookup dataSourceLookup, - DataSource dataSource) { - setDataSource(dataSource); - setDbSchemaName(dataSourceLookup.getFullSchema()); - this.dataSourceLookup = dataSourceLookup; - - } - - @Override - public void setMetaDataParamList(List metaDataParamList) { - this.metaDataParamList = metaDataParamList; - } - - /** - * Function returns Patient information for given list of patient number in - * TablePDO format - * - * @param patientNumList - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return - * @throws I2B2DAOException - */ - @Override - public PatientSet getPatientByPatientNum(List patientNumList, - boolean detailFlag, boolean blobFlag, boolean statusFlag) - throws I2B2DAOException { - - Connection conn = null; - - PatientSet patientSet = new PatientSet(); - RPDRPdoFactory.PatientBuilder patientBuilder = new RPDRPdoFactory.PatientBuilder( - detailFlag, blobFlag, statusFlag); - PreparedStatement query = null; - String tempTableName = ""; - try { - // execute fullsql - conn = getDataSource().getConnection(); - String serverType = dataSourceLookup.getServerType(); - - String selectClause = getSelectClause(detailFlag, blobFlag, - statusFlag); - String joinClause = getLookupJoinClause(detailFlag, blobFlag, - statusFlag); - if (serverType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { - oracle.jdbc.driver.OracleConnection conn1 = null;//(oracle.jdbc.driver.OracleConnection) ((WrappedConnection) conn) - // .getUnderlyingConnection(); - String finalSql = "SELECT " - + selectClause - + " FROM " - + getDbSchemaName() - + "patient_dimension patient " - + joinClause - + " WHERE patient.patient_num IN (SELECT * FROM TABLE (cast (? as QT_PDO_QRY_STRING_ARRAY)))"; - log.debug("Executing sql[" + finalSql + "]"); - query = conn1.prepareStatement(finalSql); - - ArrayDescriptor desc = ArrayDescriptor.createDescriptor( - "QT_PDO_QRY_STRING_ARRAY", conn1); - - oracle.sql.ARRAY paramArray = new oracle.sql.ARRAY(desc, conn1, - patientNumList.toArray(new String[] {})); - query.setArray(1, paramArray); - - } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.SQLSERVER) || - serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { - // create temp table - // load to temp table - // execute sql - log.debug("creating temp table"); - tempTableName = this.getDbSchemaName() - + SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE; - java.sql.Statement tempStmt = conn.createStatement(); - - try { - tempStmt.executeUpdate("drop table " + tempTableName); - } catch (SQLException sqlex) { - ; - } - - uploadTempTable(tempStmt, tempTableName, patientNumList); - String finalSql = "SELECT " - + selectClause - + " FROM " - + getDbSchemaName() - + "patient_dimension patient " - + joinClause - + " WHERE patient.patient_num IN (select distinct char_param1 FROM " - + tempTableName + ") order by patient_num"; - log.debug("Executing [" + finalSql + "]"); - - query = conn.prepareStatement(finalSql); - - } - long startTimeSql = System.currentTimeMillis(); - ResultSet resultSet = query.executeQuery(); - long endTimeSql = System.currentTimeMillis(); - long totalTimeSql = endTimeSql - startTimeSql; - log.debug("********* Total time for visit sql ****" - + totalTimeSql); - long startTime = System.currentTimeMillis(); - // JdbcRowSet rowSet = new JdbcRowSetImpl(resultSet); - while (resultSet.next()) { - PatientType patient = patientBuilder.buildPatientSet(resultSet, - "i2b2",metaDataParamList); - patientSet.getPatient().add(patient); - - } - long endTime = System.currentTimeMillis(); - long totalTime = endTimeSql - startTimeSql; - log.debug("********* Total time for visit objects ****" - + totalTime); - - } catch (SQLException sqlEx) { - log.error("", sqlEx); - throw new I2B2DAOException("sql exception", sqlEx); - } catch (IOException ioEx) { - log.error("", ioEx); - throw new I2B2DAOException("IO exception", ioEx); - } finally { - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER)) { - PdoTempTableUtil tempUtil = new PdoTempTableUtil(); - tempUtil.deleteTempTableSqlServer(conn, tempTableName); - } - - try { - JDBCUtil.closeJdbcResource(null, query, conn); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - } - } - return patientSet; - } - - /** - * - * @param patientListType - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return - * @throws I2B2DAOException - */ - @Override - public PatientSet getPatientFromPatientSet(PatientListType patientListType, - boolean detailFlag, boolean blobFlag, boolean statusFlag) - throws I2B2DAOException { - PatientListTypeHandler patientListTypeHandler = new PatientListTypeHandler( - dataSourceLookup, patientListType); - String inSqlClause = patientListTypeHandler.generateWhereClauseSql(); - String selectClause = getSelectClause(detailFlag, blobFlag, statusFlag); - String joinClause = getLookupJoinClause(detailFlag, blobFlag, - statusFlag); - String mainSqlString = " SELECT " + selectClause + " FROM " - + getDbSchemaName() + "patient_dimension patient " + joinClause - + " WHERE patient.patient_num IN ( "; - mainSqlString += inSqlClause; - mainSqlString += " ) order by patient.patient_num \n"; - - PatientSet patientSet = new PatientSet(); - RPDRPdoFactory.PatientBuilder patientBuilder = new RPDRPdoFactory.PatientBuilder( - detailFlag, blobFlag, statusFlag); - Connection conn = null; - PreparedStatement preparedStmt = null; - try { - // execute fullsql - conn = getDataSource().getConnection(); - - log.debug("Executing sql[" + mainSqlString + "]"); - - if (patientListTypeHandler.isCollectionId()) { - String patientSetCollectionId = patientListTypeHandler - .getCollectionId(); - preparedStmt = conn.prepareStatement(mainSqlString); - preparedStmt - .setInt(1, Integer.parseInt(patientSetCollectionId)); - - } else if (patientListTypeHandler.isEnumerationSet()) { - - patientListTypeHandler.uploadEnumerationValueToTempTable(conn); - preparedStmt = conn.prepareStatement(mainSqlString); - - } else { - preparedStmt = conn.prepareStatement(mainSqlString); - } - long startTimeSql = System.currentTimeMillis(); - ResultSet resultSet = preparedStmt.executeQuery(); - long endTimeSql = System.currentTimeMillis(); - long totalTimeSql = endTimeSql - startTimeSql; - log.debug("********* Total time for patient sql ****" - + totalTimeSql); - long startTime = System.currentTimeMillis(); - // JdbcRowSet rowSet = new JdbcRowSetImpl(resultSet); - while (resultSet.next()) { - PatientType patient = patientBuilder.buildPatientSet(resultSet, - "i2b2",metaDataParamList); - patientSet.getPatient().add(patient); - } - long endTime = System.currentTimeMillis(); - long totalTime = endTimeSql - startTimeSql; - log.debug("********* Total time for patient objects ****" - + totalTime); - - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - } catch (IOException ioEx) { - log.error("", ioEx); - throw new I2B2DAOException("IO exception", ioEx); - } finally { - if (patientListTypeHandler.isEnumerationSet()) { - try { - patientListTypeHandler.deleteTempTable(conn); - } catch (SQLException e) { - - e.printStackTrace(); - } - } - try { - JDBCUtil.closeJdbcResource(null, preparedStmt, conn); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - } - - } - return patientSet; - } - - /** - * Function returns patient information for given list of encounters - * - * @param visitListType - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return PatientSet - * @throws I2B2DAOException - */ - @Override - public PatientSet getPatientFromVisitSet(EventListType visitListType, - boolean detailFlag, boolean blobFlag, boolean statusFlag) - throws I2B2DAOException { - VisitListTypeHandler visitListTypeHandler = new VisitListTypeHandler( - dataSourceLookup, visitListType); - - String inSqlClause = null; - String selectClause = getSelectClause(detailFlag, blobFlag, statusFlag); - String joinClause = getLookupJoinClause(detailFlag, blobFlag, - statusFlag); - String mainSqlString = " select " + selectClause + " from " - + getDbSchemaName() + "patient_dimension patient " + joinClause - + " where patient.patient_num in "; - - // if visit set id, then take patient num directly from - // qt_patient_enc_collection table, else go thru visit dimension to get - // patient num - if (visitListTypeHandler.isCollectionId()) { - inSqlClause = visitListTypeHandler.generatePatentSql(); - mainSqlString += " ( " + inSqlClause + " ) "; - } else { - inSqlClause = visitListTypeHandler.generateWhereClauseSql(); - mainSqlString += " (select distinct patient_num from " - + getDbSchemaName() + "visit_dimension where " - + " encounter_num in ( " + inSqlClause + " )) order by patient.patient_num "; - } - - PatientSet patientSet = new PatientSet(); - RPDRPdoFactory.PatientBuilder patientBuilder = new RPDRPdoFactory.PatientBuilder( - detailFlag, blobFlag, statusFlag); - Connection conn = null; - PreparedStatement preparedStmt = null; - try { - // execute fullsql - conn = getDataSource().getConnection(); - log.debug("Executing sql[" + mainSqlString + "]"); - - if (visitListTypeHandler.isCollectionId()) { - String encounterSetCollectionId = visitListTypeHandler - .getCollectionId(); - preparedStmt = conn.prepareStatement(mainSqlString); - preparedStmt.setInt(1, Integer - .parseInt(encounterSetCollectionId)); - - } else if (visitListTypeHandler.isEnumerationSet()) { - - visitListTypeHandler.uploadEnumerationValueToTempTable(conn); - preparedStmt = conn.prepareStatement(mainSqlString); - - } else { - preparedStmt = conn.prepareStatement(mainSqlString); - } - ResultSet resultSet = preparedStmt.executeQuery(); - // JdbcRowSet rowSet = new JdbcRowSetImpl(resultSet); - while (resultSet.next()) { - PatientType patient = patientBuilder.buildPatientSet(resultSet, - "i2b2",metaDataParamList); - patientSet.getPatient().add(patient); - preparedStmt = conn.prepareStatement(mainSqlString); - } - - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - } catch (IOException ioEx) { - log.error("", ioEx); - throw new I2B2DAOException("IO exception", ioEx); - } finally { - if (visitListTypeHandler.isEnumerationSet()) { - try { - visitListTypeHandler.deleteTempTable(conn); - } catch (SQLException e) { - e.printStackTrace(); - } - } - try { - JDBCUtil.closeJdbcResource(null, preparedStmt, conn); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - } - - } - return patientSet; - - } - - private String buildCustomSelectClause(String prefix) { - String detailSelectClause = " "; - for (Iterator iterator = this.metaDataParamList.iterator();iterator.hasNext();) { - ParamType paramType = iterator.next(); - detailSelectClause += prefix + "." + paramType.getColumn() + " " + prefix + "_" + paramType.getColumn(); - if (iterator.hasNext()) { - detailSelectClause += " , "; - } - } - return detailSelectClause; - } - - private String buildCustomLookupSelectClause() { - String detailSelectClause = " "; - for (Iterator iterator = this.metaDataParamList.iterator();iterator.hasNext();) { - ParamType paramType = iterator.next(); - if (paramType.getType().equalsIgnoreCase("string")) { - detailSelectClause += " , " + paramType.getColumn() + "_lookup" + ".name_char" + " " + paramType.getColumn() + "_name"; - } - } - detailSelectClause += " , vital_status_cd_lookup.name_char vital_status_cd_name"; - return detailSelectClause; - } - - - - /** - * Function to generate select clause based on input flags - * - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return - */ - private String getSelectClause(boolean detailFlag, boolean blobFlag, - boolean statusFlag) { - String selectClause = ""; - selectClause = " patient.patient_num patient_patient_num"; - - if (detailFlag) { - selectClause += " ,patient.vital_status_cd patient_vital_status_cd, vital_Status_cd_lookup.name_char vital_status_cd_name, patient.birth_date patient_birth_date " ; - selectClause += " ," + buildCustomSelectClause("patient"); - selectClause += buildCustomLookupSelectClause() ; - //status_lookup.name_char vital_status_name, sex_lookup.name_char sex_name, language_lookup.name_char language_name, race_lookup.name_char race_name, religion_lookup.name_char religion_name, marital_status_lookup.name_char marital_status_name "; - } - if (blobFlag) { - selectClause += ", patient.patient_blob patient_patient_blob "; - } - if (statusFlag) { - selectClause += " , patient.update_date patient_update_date, patient.download_date patient_download_date, patient.import_date patient_import_date, patient.sourcesystem_cd patient_sourcesystem_cd, patient.upload_id patient_upload_id "; - } - - return selectClause; - } - - /** - * Function returns sql join clause, which joins lookup tables - * - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return String joinclause required for table pdo lookup - */ - private String getLookupJoinClause(boolean detailFlag, boolean blobFlag, - boolean statusFlag) { - String joinClause = " "; - - if (detailFlag) { - for (Iterator iterator = this.metaDataParamList.iterator();iterator.hasNext();) { - ParamType paramType = iterator.next(); - if (paramType.getType().equalsIgnoreCase("string")) { - String columnName = paramType.getColumn(); - joinClause += " left JOIN " - + this.getDbSchemaName() - + "code_lookup " + columnName + "_lookup \n" - + " ON (patient." + columnName + " = " + columnName + "_lookup.code_Cd AND upper(" + columnName +"_lookup.column_cd) = '" + columnName.toUpperCase() + "') \n"; - } - } - - - - /* - joinClause = " left JOIN " - + this.getDbSchemaName() - + "code_lookup vital_status_lookup \n" - + " ON (patient.vital_status_Cd = vital_status_lookup.code_Cd AND vital_status_lookup.column_cd = 'VITAL_STATUS_CD') \n" - + " left JOIN " - + this.getDbSchemaName() - + "code_lookup sex_lookup \n" - + " ON (patient.sex_Cd = sex_lookup.code_Cd AND sex_lookup.column_cd = 'SEX_CD') \n" - + " left JOIN " - + this.getDbSchemaName() - + "code_lookup language_lookup \n" - + " ON (patient.language_Cd = language_lookup.code_Cd AND language_lookup.column_cd = 'LANGUAGE_CD') \n" - + " left JOIN " - + this.getDbSchemaName() - + "code_lookup race_lookup \n" - + " ON (patient.race_Cd = race_lookup.code_Cd AND race_lookup.column_cd = 'RACE_CD') \n" - + " left JOIN " - + this.getDbSchemaName() - + "code_lookup marital_status_lookup \n" - + " ON (patient.marital_status_cd = marital_status_lookup.code_Cd AND marital_status_lookup.column_cd = 'MARITAL_STATUS_CD') \n" - + " left JOIN " - + this.getDbSchemaName() - + "code_lookup religion_lookup \n" - + " ON (patient.religion_Cd = religion_lookup.code_Cd AND religion_lookup.column_cd = 'RELIGION_CD') \n"; - */ - - } - return joinClause; - } - - private void uploadTempTable(Statement tempStmt, String tempTableName, - List patientNumList) throws SQLException { - String createTempInputListTable = "create table " + tempTableName - + " ( char_param1 varchar(100) )"; - tempStmt.executeUpdate(createTempInputListTable); - log.debug("created temp table" + tempTableName); - // load to temp table - // TempInputListInsert inputListInserter = new - // TempInputListInsert(dataSource,TEMP_PDO_INPUTLIST_TABLE); - // inputListInserter.setBatchSize(100); - int i = 0; - for (String singleValue : patientNumList) { - tempStmt.addBatch("insert into " + tempTableName + " values ('" - + singleValue + "' )"); - log.debug("adding batch" + singleValue); - i++; - if (i % 100 == 0) { - log.debug("batch insert"); - tempStmt.executeBatch(); - - } - } - log.debug("batch insert1"); - tempStmt.executeBatch(); - } - - - - @Override - public PatientSet getPatientByFact(List panelSqlList, - List sqlParamCountList, - IInputOptionListHandler inputOptionListHandler, boolean detailFlag, - boolean blobFlag, boolean statusFlag) throws I2B2DAOException { - - PatientSet patientSet = new PatientSet(); - RPDRPdoFactory.PatientBuilder patientBuilder = new RPDRPdoFactory.PatientBuilder( - detailFlag, blobFlag, statusFlag); - PatientFactRelated patientFactRelated = new PatientFactRelated( - buildOutputOptionType(detailFlag, blobFlag, statusFlag)); - - String selectClause = getSelectClause(detailFlag, blobFlag, statusFlag); - String joinClause = getLookupJoinClause(detailFlag, blobFlag, - statusFlag); - String serverType = dataSourceLookup.getServerType(); - String factTempTable = ""; - Connection conn = null; - PreparedStatement query = null; - try { - conn = dataSource.getConnection(); - if (serverType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { - factTempTable = this.getDbSchemaName() - + FactRelatedQueryHandler.TEMP_FACT_PARAM_TABLE; - } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.SQLSERVER) || - serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { - log.debug("creating temp table"); - java.sql.Statement tempStmt = conn.createStatement(); - factTempTable = this.getDbSchemaName() - + SQLServerFactRelatedQueryHandler.TEMP_FACT_PARAM_TABLE; - try { - tempStmt.executeUpdate("drop table " + factTempTable); - } catch (SQLException sqlex) { - ; - } - String createTempInputListTable = "create table " - + factTempTable - + " ( set_index int, char_param1 varchar(500) )"; - tempStmt.executeUpdate(createTempInputListTable); - log.debug("created temp table" + factTempTable); - } - // if the inputlist is enumeration, then upload the enumerated input - // to temp table. - // the uploaded enumerated input will be used in the fact join. - if (inputOptionListHandler.isEnumerationSet()) { - inputOptionListHandler.uploadEnumerationValueToTempTable(conn); - } - String insertSql = ""; - int i = 0; - int sqlParamCount = 0; - ResultSet resultSet = null; - for (String panelSql : panelSqlList) { - insertSql = " insert into " - + factTempTable - + "(char_param1) select distinct obs_patient_num from ( " - + panelSql + ") b"; - - log.debug("Executing SQL [ " + insertSql + "]"); - sqlParamCount = sqlParamCountList.get(i++); - // conn.createStatement().executeUpdate(insertSql); - executeUpdateSql(insertSql, conn, sqlParamCount, - inputOptionListHandler); - - } - - String finalSql = "SELECT " - + selectClause - + " FROM " - + getDbSchemaName() - + "patient_dimension patient " - + joinClause - + " where patient_num in (select distinct char_param1 from " - + factTempTable + ") order by patient_num"; - log.debug("Executing SQL [" + finalSql + "]"); - - - query = conn.prepareStatement(finalSql); - - resultSet = query.executeQuery(); - - while (resultSet.next()) { - PatientType patient = patientBuilder.buildPatientSet(resultSet, - "i2b2",metaDataParamList); - patientSet.getPatient().add(patient); - } - } catch (SQLException sqlEx) { - log.error("", sqlEx); - throw new I2B2DAOException("sql exception", sqlEx); - } catch (IOException ioEx) { - log.error("", ioEx); - throw new I2B2DAOException("IO exception", ioEx); - } finally { - PdoTempTableUtil tempTableUtil = new PdoTempTableUtil(); - tempTableUtil.clearTempTable(serverType, conn, factTempTable); - - if (inputOptionListHandler != null - && inputOptionListHandler.isEnumerationSet()) { - try { - inputOptionListHandler.deleteTempTable(conn); - } catch (SQLException e) { - - e.printStackTrace(); - } - } - try { - - JDBCUtil.closeJdbcResource(null, query, conn); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - } - } - return patientSet; - - } - - private void executeUpdateSql(String totalSql, Connection conn, - int sqlParamCount, IInputOptionListHandler inputOptionListHandler) - throws SQLException { - - PreparedStatement stmt = conn.prepareStatement(totalSql); - - log.debug(totalSql + " [ " + sqlParamCount + " ]"); - if (inputOptionListHandler.isCollectionId()) { - for (int i = 1; i <= sqlParamCount; i++) { - stmt.setInt(i, Integer.parseInt(inputOptionListHandler - .getCollectionId())); - } - } - - stmt.executeUpdate(); - - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao.pdo; + +import java.io.IOException; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Iterator; +import java.util.List; + +import javax.sql.DataSource; + +import oracle.sql.ArrayDescriptor; + +//import org.jboss.resource.adapter.jdbc.WrappedConnection; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.util.db.JDBCUtil; +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.dao.pdo.input.FactRelatedQueryHandler; +import edu.harvard.i2b2.crc.dao.pdo.input.IInputOptionListHandler; +import edu.harvard.i2b2.crc.dao.pdo.input.PatientListTypeHandler; +import edu.harvard.i2b2.crc.dao.pdo.input.SQLServerFactRelatedQueryHandler; +import edu.harvard.i2b2.crc.dao.pdo.input.VisitListTypeHandler; +import edu.harvard.i2b2.crc.dao.pdo.output.PatientFactRelated; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.pdo.ParamType; +import edu.harvard.i2b2.crc.datavo.pdo.PatientSet; +import edu.harvard.i2b2.crc.datavo.pdo.PatientType; +import edu.harvard.i2b2.crc.datavo.pdo.query.EventListType; +import edu.harvard.i2b2.crc.datavo.pdo.query.PatientListType; + +/** + * Class to support Patient section of table pdo query $Id: + * TablePdoQueryPatientDao.java,v 1.11 2008/03/19 22:42:08 rk903 Exp $ + * + * @author rkuttan + */ +public class TablePdoQueryPatientDao extends CRCDAO implements + ITablePdoQueryPatientDao { + + private DataSourceLookup dataSourceLookup = null; + private String schemaName = null; + private List metaDataParamList = null; + + + public TablePdoQueryPatientDao(DataSourceLookup dataSourceLookup, + DataSource dataSource) { + setDataSource(dataSource); + setDbSchemaName(dataSourceLookup.getFullSchema()); + this.dataSourceLookup = dataSourceLookup; + + } + + @Override + public void setMetaDataParamList(List metaDataParamList) { + this.metaDataParamList = metaDataParamList; + } + + /** + * Function returns Patient information for given list of patient number in + * TablePDO format + * + * @param patientNumList + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return + * @throws I2B2DAOException + */ + @Override + public PatientSet getPatientByPatientNum(List patientNumList, + boolean detailFlag, boolean blobFlag, boolean statusFlag) + throws I2B2DAOException { + + Connection conn = null; + + PatientSet patientSet = new PatientSet(); + RPDRPdoFactory.PatientBuilder patientBuilder = new RPDRPdoFactory.PatientBuilder( + detailFlag, blobFlag, statusFlag); + PreparedStatement query = null; + String tempTableName = ""; + try { + // execute fullsql + conn = getDataSource().getConnection(); + String serverType = dataSourceLookup.getServerType(); + + String selectClause = getSelectClause(detailFlag, blobFlag, + statusFlag); + String joinClause = getLookupJoinClause(detailFlag, blobFlag, + statusFlag); + if (serverType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { + oracle.jdbc.driver.OracleConnection conn1 = null;//(oracle.jdbc.driver.OracleConnection) ((WrappedConnection) conn) + // .getUnderlyingConnection(); + String finalSql = "SELECT " + + selectClause + + " FROM " + + getDbSchemaName() + + "patient_dimension patient " + + joinClause + + " WHERE patient.patient_num IN (SELECT * FROM TABLE (cast (? as QT_PDO_QRY_STRING_ARRAY)))"; + log.debug("Executing sql[" + finalSql + "]"); + query = conn1.prepareStatement(finalSql); + + ArrayDescriptor desc = ArrayDescriptor.createDescriptor( + "QT_PDO_QRY_STRING_ARRAY", conn1); + + oracle.sql.ARRAY paramArray = new oracle.sql.ARRAY(desc, conn1, + patientNumList.toArray(new String[] {})); + query.setArray(1, paramArray); + + } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.SQLSERVER) || + serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { + // create temp table + // load to temp table + // execute sql + log.debug("creating temp table"); + tempTableName = this.getDbSchemaName() + + SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE; + java.sql.Statement tempStmt = conn.createStatement(); + + try { + tempStmt.executeUpdate("drop table " + tempTableName); + } catch (SQLException sqlex) { + ; + } + + uploadTempTable(tempStmt, tempTableName, patientNumList); + String finalSql = "SELECT " + + selectClause + + " FROM " + + getDbSchemaName() + + "patient_dimension patient " + + joinClause + + " WHERE patient.patient_num IN (select distinct char_param1 FROM " + + tempTableName + ") order by patient_num"; + log.debug("Executing [" + finalSql + "]"); + + query = conn.prepareStatement(finalSql); + + } + long startTimeSql = System.currentTimeMillis(); + ResultSet resultSet = query.executeQuery(); + long endTimeSql = System.currentTimeMillis(); + long totalTimeSql = endTimeSql - startTimeSql; + log.debug("********* Total time for visit sql ****" + + totalTimeSql); + long startTime = System.currentTimeMillis(); + // JdbcRowSet rowSet = new JdbcRowSetImpl(resultSet); + while (resultSet.next()) { + PatientType patient = patientBuilder.buildPatientSet(resultSet, + "i2b2",metaDataParamList); + patientSet.getPatient().add(patient); + + } + long endTime = System.currentTimeMillis(); + long totalTime = endTimeSql - startTimeSql; + log.debug("********* Total time for visit objects ****" + + totalTime); + + } catch (SQLException sqlEx) { + log.error("", sqlEx); + throw new I2B2DAOException("sql exception", sqlEx); + } catch (IOException ioEx) { + log.error("", ioEx); + throw new I2B2DAOException("IO exception", ioEx); + } finally { + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER)) { + PdoTempTableUtil tempUtil = new PdoTempTableUtil(); + tempUtil.deleteTempTableSqlServer(conn, tempTableName); + } + + try { + JDBCUtil.closeJdbcResource(null, query, conn); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + } + } + return patientSet; + } + + /** + * + * @param patientListType + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return + * @throws I2B2DAOException + */ + @Override + public PatientSet getPatientFromPatientSet(PatientListType patientListType, + boolean detailFlag, boolean blobFlag, boolean statusFlag) + throws I2B2DAOException { + PatientListTypeHandler patientListTypeHandler = new PatientListTypeHandler( + dataSourceLookup, patientListType); + String inSqlClause = patientListTypeHandler.generateWhereClauseSql(); + String selectClause = getSelectClause(detailFlag, blobFlag, statusFlag); + String joinClause = getLookupJoinClause(detailFlag, blobFlag, + statusFlag); + String mainSqlString = " SELECT " + selectClause + " FROM " + + getDbSchemaName() + "patient_dimension patient " + joinClause + + " WHERE patient.patient_num IN ( "; + mainSqlString += inSqlClause; + mainSqlString += " ) order by patient.patient_num \n"; + + PatientSet patientSet = new PatientSet(); + RPDRPdoFactory.PatientBuilder patientBuilder = new RPDRPdoFactory.PatientBuilder( + detailFlag, blobFlag, statusFlag); + Connection conn = null; + PreparedStatement preparedStmt = null; + try { + // execute fullsql + conn = getDataSource().getConnection(); + + log.debug("Executing sql[" + mainSqlString + "]"); + + if (patientListTypeHandler.isCollectionId()) { + String patientSetCollectionId = patientListTypeHandler + .getCollectionId(); + preparedStmt = conn.prepareStatement(mainSqlString); + preparedStmt + .setInt(1, Integer.parseInt(patientSetCollectionId)); + + } else if (patientListTypeHandler.isEnumerationSet()) { + + patientListTypeHandler.uploadEnumerationValueToTempTable(conn); + preparedStmt = conn.prepareStatement(mainSqlString); + + } else { + preparedStmt = conn.prepareStatement(mainSqlString); + } + long startTimeSql = System.currentTimeMillis(); + ResultSet resultSet = preparedStmt.executeQuery(); + long endTimeSql = System.currentTimeMillis(); + long totalTimeSql = endTimeSql - startTimeSql; + log.debug("********* Total time for patient sql ****" + + totalTimeSql); + long startTime = System.currentTimeMillis(); + // JdbcRowSet rowSet = new JdbcRowSetImpl(resultSet); + while (resultSet.next()) { + PatientType patient = patientBuilder.buildPatientSet(resultSet, + "i2b2",metaDataParamList); + patientSet.getPatient().add(patient); + } + long endTime = System.currentTimeMillis(); + long totalTime = endTimeSql - startTimeSql; + log.debug("********* Total time for patient objects ****" + + totalTime); + + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + } catch (IOException ioEx) { + log.error("", ioEx); + throw new I2B2DAOException("IO exception", ioEx); + } finally { + if (patientListTypeHandler.isEnumerationSet()) { + try { + patientListTypeHandler.deleteTempTable(conn); + } catch (SQLException e) { + + e.printStackTrace(); + } + } + try { + JDBCUtil.closeJdbcResource(null, preparedStmt, conn); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + } + + } + return patientSet; + } + + /** + * Function returns patient information for given list of encounters + * + * @param visitListType + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return PatientSet + * @throws I2B2DAOException + */ + @Override + public PatientSet getPatientFromVisitSet(EventListType visitListType, + boolean detailFlag, boolean blobFlag, boolean statusFlag) + throws I2B2DAOException { + VisitListTypeHandler visitListTypeHandler = new VisitListTypeHandler( + dataSourceLookup, visitListType); + + String inSqlClause = null; + String selectClause = getSelectClause(detailFlag, blobFlag, statusFlag); + String joinClause = getLookupJoinClause(detailFlag, blobFlag, + statusFlag); + String mainSqlString = " select " + selectClause + " from " + + getDbSchemaName() + "patient_dimension patient " + joinClause + + " where patient.patient_num in "; + + // if visit set id, then take patient num directly from + // qt_patient_enc_collection table, else go thru visit dimension to get + // patient num + if (visitListTypeHandler.isCollectionId()) { + inSqlClause = visitListTypeHandler.generatePatentSql(); + mainSqlString += " ( " + inSqlClause + " ) "; + } else { + inSqlClause = visitListTypeHandler.generateWhereClauseSql(); + mainSqlString += " (select distinct patient_num from " + + getDbSchemaName() + "visit_dimension where " + + " encounter_num in ( " + inSqlClause + " )) order by patient.patient_num "; + } + + PatientSet patientSet = new PatientSet(); + RPDRPdoFactory.PatientBuilder patientBuilder = new RPDRPdoFactory.PatientBuilder( + detailFlag, blobFlag, statusFlag); + Connection conn = null; + PreparedStatement preparedStmt = null; + try { + // execute fullsql + conn = getDataSource().getConnection(); + log.debug("Executing sql[" + mainSqlString + "]"); + + if (visitListTypeHandler.isCollectionId()) { + String encounterSetCollectionId = visitListTypeHandler + .getCollectionId(); + preparedStmt = conn.prepareStatement(mainSqlString); + preparedStmt.setInt(1, Integer + .parseInt(encounterSetCollectionId)); + + } else if (visitListTypeHandler.isEnumerationSet()) { + + visitListTypeHandler.uploadEnumerationValueToTempTable(conn); + preparedStmt = conn.prepareStatement(mainSqlString); + + } else { + preparedStmt = conn.prepareStatement(mainSqlString); + } + ResultSet resultSet = preparedStmt.executeQuery(); + // JdbcRowSet rowSet = new JdbcRowSetImpl(resultSet); + while (resultSet.next()) { + PatientType patient = patientBuilder.buildPatientSet(resultSet, + "i2b2",metaDataParamList); + patientSet.getPatient().add(patient); + preparedStmt = conn.prepareStatement(mainSqlString); + } + + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + } catch (IOException ioEx) { + log.error("", ioEx); + throw new I2B2DAOException("IO exception", ioEx); + } finally { + if (visitListTypeHandler.isEnumerationSet()) { + try { + visitListTypeHandler.deleteTempTable(conn); + } catch (SQLException e) { + e.printStackTrace(); + } + } + try { + JDBCUtil.closeJdbcResource(null, preparedStmt, conn); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + } + + } + return patientSet; + + } + + private String buildCustomSelectClause(String prefix) { + String detailSelectClause = " "; + for (Iterator iterator = this.metaDataParamList.iterator();iterator.hasNext();) { + ParamType paramType = iterator.next(); + detailSelectClause += prefix + "." + paramType.getColumn() + " " + prefix + "_" + paramType.getColumn(); + if (iterator.hasNext()) { + detailSelectClause += " , "; + } + } + return detailSelectClause; + } + + private String buildCustomLookupSelectClause() { + String detailSelectClause = " "; + for (Iterator iterator = this.metaDataParamList.iterator();iterator.hasNext();) { + ParamType paramType = iterator.next(); + if (paramType.getType().equalsIgnoreCase("string")) { + detailSelectClause += " , " + paramType.getColumn() + "_lookup" + ".name_char" + " " + paramType.getColumn() + "_name"; + } + } + detailSelectClause += " , vital_status_cd_lookup.name_char vital_status_cd_name"; + return detailSelectClause; + } + + + + /** + * Function to generate select clause based on input flags + * + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return + */ + private String getSelectClause(boolean detailFlag, boolean blobFlag, + boolean statusFlag) { + String selectClause = ""; + selectClause = " patient.patient_num patient_patient_num"; + + if (detailFlag) { + selectClause += " ,patient.vital_status_cd patient_vital_status_cd, vital_Status_cd_lookup.name_char vital_status_cd_name, patient.birth_date patient_birth_date " ; + selectClause += " ," + buildCustomSelectClause("patient"); + selectClause += buildCustomLookupSelectClause() ; + //status_lookup.name_char vital_status_name, sex_lookup.name_char sex_name, language_lookup.name_char language_name, race_lookup.name_char race_name, religion_lookup.name_char religion_name, marital_status_lookup.name_char marital_status_name "; + } + if (blobFlag) { + selectClause += ", patient.patient_blob patient_patient_blob "; + } + if (statusFlag) { + selectClause += " , patient.update_date patient_update_date, patient.download_date patient_download_date, patient.import_date patient_import_date, patient.sourcesystem_cd patient_sourcesystem_cd, patient.upload_id patient_upload_id "; + } + + return selectClause; + } + + /** + * Function returns sql join clause, which joins lookup tables + * + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return String joinclause required for table pdo lookup + */ + private String getLookupJoinClause(boolean detailFlag, boolean blobFlag, + boolean statusFlag) { + String joinClause = " "; + + if (detailFlag) { + for (Iterator iterator = this.metaDataParamList.iterator();iterator.hasNext();) { + ParamType paramType = iterator.next(); + if (paramType.getType().equalsIgnoreCase("string")) { + String columnName = paramType.getColumn(); + joinClause += " left JOIN " + + this.getDbSchemaName() + + "code_lookup " + columnName + "_lookup \n" + + " ON (patient." + columnName + " = " + columnName + "_lookup.code_Cd AND upper(" + columnName +"_lookup.column_cd) = '" + columnName.toUpperCase() + "') \n"; + } + } + + + + /* + joinClause = " left JOIN " + + this.getDbSchemaName() + + "code_lookup vital_status_lookup \n" + + " ON (patient.vital_status_Cd = vital_status_lookup.code_Cd AND vital_status_lookup.column_cd = 'VITAL_STATUS_CD') \n" + + " left JOIN " + + this.getDbSchemaName() + + "code_lookup sex_lookup \n" + + " ON (patient.sex_Cd = sex_lookup.code_Cd AND sex_lookup.column_cd = 'SEX_CD') \n" + + " left JOIN " + + this.getDbSchemaName() + + "code_lookup language_lookup \n" + + " ON (patient.language_Cd = language_lookup.code_Cd AND language_lookup.column_cd = 'LANGUAGE_CD') \n" + + " left JOIN " + + this.getDbSchemaName() + + "code_lookup race_lookup \n" + + " ON (patient.race_Cd = race_lookup.code_Cd AND race_lookup.column_cd = 'RACE_CD') \n" + + " left JOIN " + + this.getDbSchemaName() + + "code_lookup marital_status_lookup \n" + + " ON (patient.marital_status_cd = marital_status_lookup.code_Cd AND marital_status_lookup.column_cd = 'MARITAL_STATUS_CD') \n" + + " left JOIN " + + this.getDbSchemaName() + + "code_lookup religion_lookup \n" + + " ON (patient.religion_Cd = religion_lookup.code_Cd AND religion_lookup.column_cd = 'RELIGION_CD') \n"; + */ + + } + return joinClause; + } + + private void uploadTempTable(Statement tempStmt, String tempTableName, + List patientNumList) throws SQLException { + String createTempInputListTable = "create table " + tempTableName + + " ( char_param1 varchar(100) )"; + tempStmt.executeUpdate(createTempInputListTable); + log.debug("created temp table" + tempTableName); + // load to temp table + // TempInputListInsert inputListInserter = new + // TempInputListInsert(dataSource,TEMP_PDO_INPUTLIST_TABLE); + // inputListInserter.setBatchSize(100); + int i = 0; + for (String singleValue : patientNumList) { + tempStmt.addBatch("insert into " + tempTableName + " values ('" + + singleValue + "' )"); + log.debug("adding batch" + singleValue); + i++; + if (i % 100 == 0) { + log.debug("batch insert"); + tempStmt.executeBatch(); + + } + } + log.debug("batch insert1"); + tempStmt.executeBatch(); + } + + + + @Override + public PatientSet getPatientByFact(List panelSqlList, + List sqlParamCountList, + IInputOptionListHandler inputOptionListHandler, boolean detailFlag, + boolean blobFlag, boolean statusFlag) throws I2B2DAOException { + + PatientSet patientSet = new PatientSet(); + RPDRPdoFactory.PatientBuilder patientBuilder = new RPDRPdoFactory.PatientBuilder( + detailFlag, blobFlag, statusFlag); + PatientFactRelated patientFactRelated = new PatientFactRelated( + buildOutputOptionType(detailFlag, blobFlag, statusFlag)); + + String selectClause = getSelectClause(detailFlag, blobFlag, statusFlag); + String joinClause = getLookupJoinClause(detailFlag, blobFlag, + statusFlag); + String serverType = dataSourceLookup.getServerType(); + String factTempTable = ""; + Connection conn = null; + PreparedStatement query = null; + try { + conn = dataSource.getConnection(); + if (serverType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { + factTempTable = this.getDbSchemaName() + + FactRelatedQueryHandler.TEMP_FACT_PARAM_TABLE; + } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.SQLSERVER) || + serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { + log.debug("creating temp table"); + java.sql.Statement tempStmt = conn.createStatement(); + factTempTable = this.getDbSchemaName() + + SQLServerFactRelatedQueryHandler.TEMP_FACT_PARAM_TABLE; + try { + tempStmt.executeUpdate("drop table " + factTempTable); + } catch (SQLException sqlex) { + ; + } + String createTempInputListTable = "create table " + + factTempTable + + " ( set_index int, char_param1 varchar(500) )"; + tempStmt.executeUpdate(createTempInputListTable); + log.debug("created temp table" + factTempTable); + } + // if the inputlist is enumeration, then upload the enumerated input + // to temp table. + // the uploaded enumerated input will be used in the fact join. + if (inputOptionListHandler.isEnumerationSet()) { + inputOptionListHandler.uploadEnumerationValueToTempTable(conn); + } + String insertSql = ""; + int i = 0; + int sqlParamCount = 0; + ResultSet resultSet = null; + for (String panelSql : panelSqlList) { + insertSql = " insert into " + + factTempTable + + "(char_param1) select distinct obs_patient_num from ( " + + panelSql + ") b"; + + log.debug("Executing SQL [ " + insertSql + "]"); + sqlParamCount = sqlParamCountList.get(i++); + // conn.createStatement().executeUpdate(insertSql); + executeUpdateSql(insertSql, conn, sqlParamCount, + inputOptionListHandler); + + } + + String finalSql = "SELECT " + + selectClause + + " FROM " + + getDbSchemaName() + + "patient_dimension patient " + + joinClause + + " where patient_num in (select distinct char_param1 from " + + factTempTable + ") order by patient_num"; + log.debug("Executing SQL [" + finalSql + "]"); + + + query = conn.prepareStatement(finalSql); + + resultSet = query.executeQuery(); + + while (resultSet.next()) { + PatientType patient = patientBuilder.buildPatientSet(resultSet, + "i2b2",metaDataParamList); + patientSet.getPatient().add(patient); + } + } catch (SQLException sqlEx) { + log.error("", sqlEx); + throw new I2B2DAOException("sql exception", sqlEx); + } catch (IOException ioEx) { + log.error("", ioEx); + throw new I2B2DAOException("IO exception", ioEx); + } finally { + PdoTempTableUtil tempTableUtil = new PdoTempTableUtil(); + tempTableUtil.clearTempTable(serverType, conn, factTempTable); + + if (inputOptionListHandler != null + && inputOptionListHandler.isEnumerationSet()) { + try { + inputOptionListHandler.deleteTempTable(conn); + } catch (SQLException e) { + + e.printStackTrace(); + } + } + try { + + JDBCUtil.closeJdbcResource(null, query, conn); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + } + } + return patientSet; + + } + + private void executeUpdateSql(String totalSql, Connection conn, + int sqlParamCount, IInputOptionListHandler inputOptionListHandler) + throws SQLException { + + PreparedStatement stmt = conn.prepareStatement(totalSql); + + log.debug(totalSql + " [ " + sqlParamCount + " ]"); + if (inputOptionListHandler.isCollectionId()) { + for (int i = 1; i <= sqlParamCount; i++) { + stmt.setInt(i, Integer.parseInt(inputOptionListHandler + .getCollectionId())); + } + } + + stmt.executeUpdate(); + + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/TablePdoQueryProviderDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/TablePdoQueryProviderDao.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/TablePdoQueryProviderDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/TablePdoQueryProviderDao.java index bcabb15d..94b434fc --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/TablePdoQueryProviderDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/TablePdoQueryProviderDao.java @@ -1,341 +1,341 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao.pdo; - -import java.io.IOException; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.List; - -import javax.sql.DataSource; - -import oracle.sql.ArrayDescriptor; - -//import org.jboss.resource.adapter.jdbc.WrappedConnection; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.util.db.JDBCUtil; -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.dao.pdo.input.FactRelatedQueryHandler; -import edu.harvard.i2b2.crc.dao.pdo.input.IInputOptionListHandler; -import edu.harvard.i2b2.crc.dao.pdo.input.SQLServerFactRelatedQueryHandler; -import edu.harvard.i2b2.crc.dao.pdo.output.ProviderFactRelated; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.pdo.ObserverSet; -import edu.harvard.i2b2.crc.datavo.pdo.ObserverType; - -/** - * Class to support observer section of table pdo query $Id: - * TablePdoQueryProviderDao.java,v 1.10 2008/03/19 22:42:08 rk903 Exp $ - * - * @author rkuttan - */ -public class TablePdoQueryProviderDao extends CRCDAO implements - ITablePdoQueryProviderDao { - private DataSourceLookup dataSourceLookup = null; - private String schemaName = null; - - public TablePdoQueryProviderDao(DataSourceLookup dataSourceLookup, - DataSource dataSource) { - this.dataSourceLookup = dataSourceLookup; - setDbSchemaName(dataSourceLookup.getFullSchema()); - setDataSource(dataSource); - } - - @Override - public ObserverSet getProviderByFact(List panelSqlList, - List sqlParamCountList, - IInputOptionListHandler inputOptionListHandler, boolean detailFlag, - boolean blobFlag, boolean statusFlag) throws I2B2DAOException { - ObserverSet observerSet = new ObserverSet(); - RPDRPdoFactory.ProviderBuilder observerBuilder = new RPDRPdoFactory.ProviderBuilder( - detailFlag, blobFlag, statusFlag); - ProviderFactRelated providerFactRelated = new ProviderFactRelated( - buildOutputOptionType(detailFlag, blobFlag, statusFlag)); - String selectClause = providerFactRelated.getSelectClause(); - String serverType = dataSourceLookup.getServerType(); - String factTempTable = ""; - Connection conn = null; - PreparedStatement query = null; - try { - conn = dataSource.getConnection(); - if (serverType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { - factTempTable = this.getDbSchemaName() - + FactRelatedQueryHandler.TEMP_FACT_PARAM_TABLE; - } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.SQLSERVER) || - serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { - log.debug("creating temp table"); - java.sql.Statement tempStmt = conn.createStatement(); - factTempTable = this.getDbSchemaName() - + SQLServerFactRelatedQueryHandler.TEMP_FACT_PARAM_TABLE; - try { - tempStmt.executeUpdate("drop table " + factTempTable); - } catch (SQLException sqlex) { - ; - } - String createTempInputListTable = "create table " - + factTempTable - + " ( set_index int, char_param1 varchar(500) )"; - tempStmt.executeUpdate(createTempInputListTable); - log.debug("created temp table" + factTempTable); - } - // if the inputlist is enumeration, then upload the enumerated input - // to temp table. - // the uploaded enumerated input will be used in the fact join. - if (inputOptionListHandler.isEnumerationSet()) { - inputOptionListHandler.uploadEnumerationValueToTempTable(conn); - } - String insertSql = ""; - int i = 0; - int sqlParamCount = 0; - ResultSet resultSet = null; - for (String panelSql : panelSqlList) { - insertSql = " insert into " - + factTempTable - + "(char_param1) select distinct obs_provider_id from ( " - + panelSql + ") b"; - - log.debug("Executing SQL [ " + insertSql + "]"); - sqlParamCount = sqlParamCountList.get(i++); - // conn.createStatement().executeUpdate(insertSql); - executeUpdateSql(insertSql, conn, sqlParamCount, - inputOptionListHandler); - - } - - String finalSql = "SELECT " - + selectClause - + " FROM " - + getDbSchemaName() - + "provider_dimension provider where provider_id in (select distinct char_param1 from " - + factTempTable + ") order by provider_path"; - log.debug("Executing SQL [" + finalSql + "]"); - - - query = conn.prepareStatement(finalSql); - - resultSet = query.executeQuery(); - - while (resultSet.next()) { - ObserverType observer = observerBuilder - .buildObserverSet(resultSet); - observerSet.getObserver().add(observer); - } - } catch (SQLException sqlEx) { - log.error("", sqlEx); - throw new I2B2DAOException("sql exception", sqlEx); - } catch (IOException ioEx) { - log.error("", ioEx); - throw new I2B2DAOException("IO exception", ioEx); - } finally { - PdoTempTableUtil tempUtil = new PdoTempTableUtil(); - tempUtil.clearTempTable(dataSourceLookup.getServerType(), conn, factTempTable); - - if (inputOptionListHandler != null - && inputOptionListHandler.isEnumerationSet()) { - try { - inputOptionListHandler.deleteTempTable(conn); - } catch (SQLException e) { - - e.printStackTrace(); - } - } - try { - JDBCUtil.closeJdbcResource(null, query, conn); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - } - } - return observerSet; - } - - private void executeUpdateSql(String totalSql, Connection conn, - int sqlParamCount, IInputOptionListHandler inputOptionListHandler) - throws SQLException { - - PreparedStatement stmt = conn.prepareStatement(totalSql); - - log.debug(totalSql + " [ " + sqlParamCount + " ]"); - if (inputOptionListHandler.isCollectionId()) { - for (int i = 1; i <= sqlParamCount; i++) { - stmt.setInt(i, Integer.parseInt(inputOptionListHandler - .getCollectionId())); - } - } - - stmt.executeUpdate(); - - } - - /** - * Returns observerset for the given list of provider id - * - * @param providerIdList - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return ObserverSet - * @throws I2B2DAOException - */ - @Override - public ObserverSet getProviderById(List providerIdList, - boolean detailFlag, boolean blobFlag, boolean statusFlag) - throws I2B2DAOException { - log.debug("input encounter list size " + providerIdList.size()); - - ObserverSet observerSet = new ObserverSet(); - RPDRPdoFactory.ProviderBuilder providerBuilder = new RPDRPdoFactory.ProviderBuilder( - detailFlag, blobFlag, statusFlag); - Connection conn = null; - PreparedStatement query = null; - String tempTable = ""; - try { - conn = getDataSource().getConnection(); - - String selectClause = getSelectClause(detailFlag, blobFlag, - statusFlag); - String serverType = dataSourceLookup.getServerType(); - if (serverType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { - oracle.jdbc.driver.OracleConnection conn1 = null;//(oracle.jdbc.driver.OracleConnection) ((WrappedConnection) conn) - // .getUnderlyingConnection(); - query = conn1 - .prepareStatement("SELECT " - + selectClause - + " FROM " - + getDbSchemaName() - + "provider_dimension provider WHERE provider.provider_id IN (SELECT * FROM TABLE (?))"); - - ArrayDescriptor desc = ArrayDescriptor.createDescriptor( - "QT_PDO_QRY_STRING_ARRAY", conn1); - - oracle.sql.ARRAY paramArray = new oracle.sql.ARRAY(desc, conn1, - providerIdList.toArray(new String[] {})); - query.setArray(1, paramArray); - } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.SQLSERVER) || - serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { - log.debug("creating temp table"); - java.sql.Statement tempStmt = conn.createStatement(); - tempTable = this.getDbSchemaName() - + SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE; - try { - tempStmt.executeUpdate("drop table " + tempTable); - } catch (SQLException sqlex) { - ; - } - - uploadTempTable(tempStmt, tempTable, providerIdList); - String finalSql = "SELECT " - + selectClause - + " FROM " - + getDbSchemaName() - + "provider_dimension provider WHERE provider.provider_id IN (select distinct char_param1 FROM " - + tempTable + ") order by provider_path"; - log.debug("Executing [" + finalSql + "]"); - - query = conn.prepareStatement(finalSql); - - } - - ResultSet resultSet = query.executeQuery(); - - // JdbcRowSet rowSet = new JdbcRowSetImpl(resultSet); - while (resultSet.next()) { - ObserverType observer = providerBuilder - .buildObserverSet(resultSet); - observerSet.getObserver().add(observer); - } - } catch (SQLException sqlEx) { - log.error("", sqlEx); - throw new I2B2DAOException("sql exception", sqlEx); - } catch (IOException ioEx) { - log.error("", ioEx); - throw new I2B2DAOException("IO exception", ioEx); - } finally { - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER)) { - PdoTempTableUtil tempTableUtil = new PdoTempTableUtil(); - tempTableUtil.deleteTempTableSqlServer(conn, tempTable); - } - try { - JDBCUtil.closeJdbcResource(null, query, conn); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - } - } - - return observerSet; - } - - /** - * Function returns select clause based on given flag - * - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return - */ - private String getSelectClause(boolean detailFlag, boolean blobFlag, - boolean statusFlag) { - String selectClause = ""; - - selectClause = " provider.provider_id provider_provider_id, provider.provider_path provider_provider_path "; - - if (detailFlag) { - selectClause += ", provider.name_char provider_name_char "; - } - - if (blobFlag) { - selectClause += ", provider.provider_blob provider_provider_blob "; - } - - if (statusFlag) { - selectClause += " , provider.update_date provider_update_date, provider.download_date provider_download_date, provider.import_date provider_import_date, provider.sourcesystem_cd provider_sourcesystem_cd, provider.upload_id provider_upload_id "; - } - - return selectClause; - } - - private void uploadTempTable(Statement tempStmt, String tempTable, - List patientNumList) throws SQLException { - String createTempInputListTable = "create table " + tempTable - + " ( char_param1 varchar(100) )"; - tempStmt.executeUpdate(createTempInputListTable); - log.debug("created temp table" + tempTable); - // load to temp table - // TempInputListInsert inputListInserter = new - // TempInputListInsert(dataSource,TEMP_PDO_INPUTLIST_TABLE); - // inputListInserter.setBatchSize(100); - int i = 0; - for (String singleValue : patientNumList) { - tempStmt.addBatch("insert into " + tempTable + " values ('" - + singleValue + "' )"); - log.debug("adding batch" + singleValue); - i++; - if (i % 100 == 0) { - log.debug("batch insert"); - tempStmt.executeBatch(); - - } - } - log.debug("batch insert1"); - tempStmt.executeBatch(); - } - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao.pdo; + +import java.io.IOException; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.List; + +import javax.sql.DataSource; + +import oracle.sql.ArrayDescriptor; + +//import org.jboss.resource.adapter.jdbc.WrappedConnection; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.util.db.JDBCUtil; +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.dao.pdo.input.FactRelatedQueryHandler; +import edu.harvard.i2b2.crc.dao.pdo.input.IInputOptionListHandler; +import edu.harvard.i2b2.crc.dao.pdo.input.SQLServerFactRelatedQueryHandler; +import edu.harvard.i2b2.crc.dao.pdo.output.ProviderFactRelated; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.pdo.ObserverSet; +import edu.harvard.i2b2.crc.datavo.pdo.ObserverType; + +/** + * Class to support observer section of table pdo query $Id: + * TablePdoQueryProviderDao.java,v 1.10 2008/03/19 22:42:08 rk903 Exp $ + * + * @author rkuttan + */ +public class TablePdoQueryProviderDao extends CRCDAO implements + ITablePdoQueryProviderDao { + private DataSourceLookup dataSourceLookup = null; + private String schemaName = null; + + public TablePdoQueryProviderDao(DataSourceLookup dataSourceLookup, + DataSource dataSource) { + this.dataSourceLookup = dataSourceLookup; + setDbSchemaName(dataSourceLookup.getFullSchema()); + setDataSource(dataSource); + } + + @Override + public ObserverSet getProviderByFact(List panelSqlList, + List sqlParamCountList, + IInputOptionListHandler inputOptionListHandler, boolean detailFlag, + boolean blobFlag, boolean statusFlag) throws I2B2DAOException { + ObserverSet observerSet = new ObserverSet(); + RPDRPdoFactory.ProviderBuilder observerBuilder = new RPDRPdoFactory.ProviderBuilder( + detailFlag, blobFlag, statusFlag); + ProviderFactRelated providerFactRelated = new ProviderFactRelated( + buildOutputOptionType(detailFlag, blobFlag, statusFlag)); + String selectClause = providerFactRelated.getSelectClause(); + String serverType = dataSourceLookup.getServerType(); + String factTempTable = ""; + Connection conn = null; + PreparedStatement query = null; + try { + conn = dataSource.getConnection(); + if (serverType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { + factTempTable = this.getDbSchemaName() + + FactRelatedQueryHandler.TEMP_FACT_PARAM_TABLE; + } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.SQLSERVER) || + serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { + log.debug("creating temp table"); + java.sql.Statement tempStmt = conn.createStatement(); + factTempTable = this.getDbSchemaName() + + SQLServerFactRelatedQueryHandler.TEMP_FACT_PARAM_TABLE; + try { + tempStmt.executeUpdate("drop table " + factTempTable); + } catch (SQLException sqlex) { + ; + } + String createTempInputListTable = "create table " + + factTempTable + + " ( set_index int, char_param1 varchar(500) )"; + tempStmt.executeUpdate(createTempInputListTable); + log.debug("created temp table" + factTempTable); + } + // if the inputlist is enumeration, then upload the enumerated input + // to temp table. + // the uploaded enumerated input will be used in the fact join. + if (inputOptionListHandler.isEnumerationSet()) { + inputOptionListHandler.uploadEnumerationValueToTempTable(conn); + } + String insertSql = ""; + int i = 0; + int sqlParamCount = 0; + ResultSet resultSet = null; + for (String panelSql : panelSqlList) { + insertSql = " insert into " + + factTempTable + + "(char_param1) select distinct obs_provider_id from ( " + + panelSql + ") b"; + + log.debug("Executing SQL [ " + insertSql + "]"); + sqlParamCount = sqlParamCountList.get(i++); + // conn.createStatement().executeUpdate(insertSql); + executeUpdateSql(insertSql, conn, sqlParamCount, + inputOptionListHandler); + + } + + String finalSql = "SELECT " + + selectClause + + " FROM " + + getDbSchemaName() + + "provider_dimension provider where provider_id in (select distinct char_param1 from " + + factTempTable + ") order by provider_path"; + log.debug("Executing SQL [" + finalSql + "]"); + + + query = conn.prepareStatement(finalSql); + + resultSet = query.executeQuery(); + + while (resultSet.next()) { + ObserverType observer = observerBuilder + .buildObserverSet(resultSet); + observerSet.getObserver().add(observer); + } + } catch (SQLException sqlEx) { + log.error("", sqlEx); + throw new I2B2DAOException("sql exception", sqlEx); + } catch (IOException ioEx) { + log.error("", ioEx); + throw new I2B2DAOException("IO exception", ioEx); + } finally { + PdoTempTableUtil tempUtil = new PdoTempTableUtil(); + tempUtil.clearTempTable(dataSourceLookup.getServerType(), conn, factTempTable); + + if (inputOptionListHandler != null + && inputOptionListHandler.isEnumerationSet()) { + try { + inputOptionListHandler.deleteTempTable(conn); + } catch (SQLException e) { + + e.printStackTrace(); + } + } + try { + JDBCUtil.closeJdbcResource(null, query, conn); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + } + } + return observerSet; + } + + private void executeUpdateSql(String totalSql, Connection conn, + int sqlParamCount, IInputOptionListHandler inputOptionListHandler) + throws SQLException { + + PreparedStatement stmt = conn.prepareStatement(totalSql); + + log.debug(totalSql + " [ " + sqlParamCount + " ]"); + if (inputOptionListHandler.isCollectionId()) { + for (int i = 1; i <= sqlParamCount; i++) { + stmt.setInt(i, Integer.parseInt(inputOptionListHandler + .getCollectionId())); + } + } + + stmt.executeUpdate(); + + } + + /** + * Returns observerset for the given list of provider id + * + * @param providerIdList + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return ObserverSet + * @throws I2B2DAOException + */ + @Override + public ObserverSet getProviderById(List providerIdList, + boolean detailFlag, boolean blobFlag, boolean statusFlag) + throws I2B2DAOException { + log.debug("input encounter list size " + providerIdList.size()); + + ObserverSet observerSet = new ObserverSet(); + RPDRPdoFactory.ProviderBuilder providerBuilder = new RPDRPdoFactory.ProviderBuilder( + detailFlag, blobFlag, statusFlag); + Connection conn = null; + PreparedStatement query = null; + String tempTable = ""; + try { + conn = getDataSource().getConnection(); + + String selectClause = getSelectClause(detailFlag, blobFlag, + statusFlag); + String serverType = dataSourceLookup.getServerType(); + if (serverType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { + oracle.jdbc.driver.OracleConnection conn1 = null;//(oracle.jdbc.driver.OracleConnection) ((WrappedConnection) conn) + // .getUnderlyingConnection(); + query = conn1 + .prepareStatement("SELECT " + + selectClause + + " FROM " + + getDbSchemaName() + + "provider_dimension provider WHERE provider.provider_id IN (SELECT * FROM TABLE (?))"); + + ArrayDescriptor desc = ArrayDescriptor.createDescriptor( + "QT_PDO_QRY_STRING_ARRAY", conn1); + + oracle.sql.ARRAY paramArray = new oracle.sql.ARRAY(desc, conn1, + providerIdList.toArray(new String[] {})); + query.setArray(1, paramArray); + } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.SQLSERVER) || + serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { + log.debug("creating temp table"); + java.sql.Statement tempStmt = conn.createStatement(); + tempTable = this.getDbSchemaName() + + SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE; + try { + tempStmt.executeUpdate("drop table " + tempTable); + } catch (SQLException sqlex) { + ; + } + + uploadTempTable(tempStmt, tempTable, providerIdList); + String finalSql = "SELECT " + + selectClause + + " FROM " + + getDbSchemaName() + + "provider_dimension provider WHERE provider.provider_id IN (select distinct char_param1 FROM " + + tempTable + ") order by provider_path"; + log.debug("Executing [" + finalSql + "]"); + + query = conn.prepareStatement(finalSql); + + } + + ResultSet resultSet = query.executeQuery(); + + // JdbcRowSet rowSet = new JdbcRowSetImpl(resultSet); + while (resultSet.next()) { + ObserverType observer = providerBuilder + .buildObserverSet(resultSet); + observerSet.getObserver().add(observer); + } + } catch (SQLException sqlEx) { + log.error("", sqlEx); + throw new I2B2DAOException("sql exception", sqlEx); + } catch (IOException ioEx) { + log.error("", ioEx); + throw new I2B2DAOException("IO exception", ioEx); + } finally { + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER)) { + PdoTempTableUtil tempTableUtil = new PdoTempTableUtil(); + tempTableUtil.deleteTempTableSqlServer(conn, tempTable); + } + try { + JDBCUtil.closeJdbcResource(null, query, conn); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + } + } + + return observerSet; + } + + /** + * Function returns select clause based on given flag + * + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return + */ + private String getSelectClause(boolean detailFlag, boolean blobFlag, + boolean statusFlag) { + String selectClause = ""; + + selectClause = " provider.provider_id provider_provider_id, provider.provider_path provider_provider_path "; + + if (detailFlag) { + selectClause += ", provider.name_char provider_name_char "; + } + + if (blobFlag) { + selectClause += ", provider.provider_blob provider_provider_blob "; + } + + if (statusFlag) { + selectClause += " , provider.update_date provider_update_date, provider.download_date provider_download_date, provider.import_date provider_import_date, provider.sourcesystem_cd provider_sourcesystem_cd, provider.upload_id provider_upload_id "; + } + + return selectClause; + } + + private void uploadTempTable(Statement tempStmt, String tempTable, + List patientNumList) throws SQLException { + String createTempInputListTable = "create table " + tempTable + + " ( char_param1 varchar(100) )"; + tempStmt.executeUpdate(createTempInputListTable); + log.debug("created temp table" + tempTable); + // load to temp table + // TempInputListInsert inputListInserter = new + // TempInputListInsert(dataSource,TEMP_PDO_INPUTLIST_TABLE); + // inputListInserter.setBatchSize(100); + int i = 0; + for (String singleValue : patientNumList) { + tempStmt.addBatch("insert into " + tempTable + " values ('" + + singleValue + "' )"); + log.debug("adding batch" + singleValue); + i++; + if (i % 100 == 0) { + log.debug("batch insert"); + tempStmt.executeBatch(); + + } + } + log.debug("batch insert1"); + tempStmt.executeBatch(); + } + + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/TablePdoQueryVisitDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/TablePdoQueryVisitDao.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/TablePdoQueryVisitDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/TablePdoQueryVisitDao.java index 96b22543..4eff33b7 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/TablePdoQueryVisitDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/TablePdoQueryVisitDao.java @@ -1,592 +1,592 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao.pdo; - -import java.io.IOException; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.Iterator; -import java.util.List; - -import javax.sql.DataSource; - -import oracle.sql.ArrayDescriptor; - -//import org.jboss.resource.adapter.jdbc.WrappedConnection; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.util.db.JDBCUtil; -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.dao.pdo.input.FactRelatedQueryHandler; -import edu.harvard.i2b2.crc.dao.pdo.input.IInputOptionListHandler; -import edu.harvard.i2b2.crc.dao.pdo.input.PatientListTypeHandler; -import edu.harvard.i2b2.crc.dao.pdo.input.SQLServerFactRelatedQueryHandler; -import edu.harvard.i2b2.crc.dao.pdo.input.VisitListTypeHandler; -import edu.harvard.i2b2.crc.dao.pdo.output.VisitFactRelated; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.pdo.EventSet; -import edu.harvard.i2b2.crc.datavo.pdo.EventType; -import edu.harvard.i2b2.crc.datavo.pdo.ParamType; -import edu.harvard.i2b2.crc.datavo.pdo.query.EventListType; -import edu.harvard.i2b2.crc.datavo.pdo.query.PatientListType; - -/** - * Class to support event section of table pdo query $Id: - * TablePdoQueryVisitDao.java,v 1.11 2008/03/19 22:42:08 rk903 Exp $ - * - * @author rkuttan - */ -public class TablePdoQueryVisitDao extends CRCDAO implements - ITablePdoQueryVisitDao { - - private DataSourceLookup dataSourceLookup = null; - private String schemaName = null; - private List metaDataParamList = null; - - - public TablePdoQueryVisitDao(DataSourceLookup dataSourceLookup, - DataSource dataSource) { - this.dataSourceLookup = dataSourceLookup; - setDataSource(dataSource); - this.setDbSchemaName(dataSourceLookup.getFullSchema()); - } - - @Override - public void setMetaDataParamList(List metaDataParamList) { - this.metaDataParamList = metaDataParamList; - } - - /** - * Function to return EventSet from visit information - * - * @param encounterNumList - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return EventSet - * @throws I2B2DAOException - */ - @Override - public EventSet getVisitsByEncounterNum(List encounterNumList, - boolean detailFlag, boolean blobFlag, boolean statusFlag) - throws I2B2DAOException { - EventSet eventSet = new EventSet(); - - RPDRPdoFactory.EventBuilder eventBuilder = new RPDRPdoFactory.EventBuilder( - detailFlag, blobFlag, statusFlag); - log.debug("input encounter list size " - + encounterNumList.size()); - - Connection conn = null; - PreparedStatement query = null; - String tempTableName = ""; - try { - conn = getDataSource().getConnection(); - - // create type StudentIdArrayType as varray(1000) of integer; - String selectClause = getSelectClause(detailFlag, blobFlag, - statusFlag); - String joinClause = getLookupJoinClause(detailFlag, blobFlag, - statusFlag); - String serverType = dataSourceLookup.getServerType(); - - if (serverType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { - oracle.jdbc.driver.OracleConnection conn1 = null;//(oracle.jdbc.driver.OracleConnection) ((WrappedConnection) conn) - // .getUnderlyingConnection(); - String finalSql = "SELECT " - + selectClause - + " FROM " - + getDbSchemaName() - + "visit_dimension visit \n" - + joinClause - + " WHERE visit.encounter_num IN (SELECT * FROM TABLE (cast (? as QT_PDO_QRY_STRING_ARRAY)))"; - log.debug("Executing sql[" + finalSql + "]"); - query = conn1.prepareStatement(finalSql); - - ArrayDescriptor desc = ArrayDescriptor.createDescriptor( - "QT_PDO_QRY_STRING_ARRAY", conn1); - oracle.sql.ARRAY paramArray = new oracle.sql.ARRAY(desc, conn1, - encounterNumList.toArray(new String[] {})); - query.setArray(1, paramArray); - } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.SQLSERVER) || - serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { - log.debug("creating temp table"); - java.sql.Statement tempStmt = conn.createStatement(); - tempTableName = getDbSchemaName() - + SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE; - try { - tempStmt.executeUpdate("drop table " + tempTableName); - } catch (SQLException sqlex) { - ; - } - - uploadTempTable(tempStmt, tempTableName, encounterNumList); - String finalSql = "SELECT " - + selectClause - + " FROM " - + getDbSchemaName() - + "visit_dimension visit \n" - + joinClause - + " WHERE visit.encounter_num IN (select distinct CAST(coalesce(char_param1, '0') as integer) FROM " - + tempTableName + " ) order by encounter_num,patient_num "; - log.debug("Executing [" + finalSql + "]"); - - query = conn.prepareStatement(finalSql); - - } - long startTimeSql = System.currentTimeMillis(); - ResultSet resultSet = query.executeQuery(); - long endTimeSql = System.currentTimeMillis(); - long totalTimeSql = endTimeSql - startTimeSql; - log.debug("********* Total time for visit sql ****" - + totalTimeSql); - long startTime = System.currentTimeMillis(); - while (resultSet.next()) { - EventType event = eventBuilder.buildEventSet(resultSet, "i2b2",this.metaDataParamList); - eventSet.getEvent().add(event); - } - long endTime = System.currentTimeMillis(); - long totalTime = endTimeSql - startTimeSql; - log.debug("********* Total time for visit objects ****" - + totalTime); - } catch (SQLException sqlEx) { - log.error("", sqlEx); - throw new I2B2DAOException("sql exception", sqlEx); - } catch (IOException ioEx) { - log.error("", ioEx); - throw new I2B2DAOException("IO exception", ioEx); - } finally { - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER)) { - PdoTempTableUtil tempUtil = new PdoTempTableUtil(); - tempUtil.deleteTempTableSqlServer(conn, tempTableName); - } - try { - JDBCUtil.closeJdbcResource(null, query, conn); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - } - } - - return eventSet; - } - - /** - * Function to return EventSet from visit information - * - * @param visitListType - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return EventSet - * @throws I2B2DAOException - */ - @Override - public EventSet getVisitDimensionSetFromVisitList( - EventListType visitListType, boolean detailFlag, boolean blobFlag, - boolean statusFlag) throws I2B2DAOException { - VisitListTypeHandler visitListTypeHandler = new VisitListTypeHandler( - dataSourceLookup, visitListType); - String inSqlClause = visitListTypeHandler.generateWhereClauseSql(); - String selectClause = getSelectClause(detailFlag, blobFlag, statusFlag); - String joinClause = getLookupJoinClause(detailFlag, blobFlag, - statusFlag); - String mainSqlString = " SELECT " + selectClause + " FROM " - + getDbSchemaName() + "visit_dimension visit " + joinClause - + " WHERE visit.encounter_num IN ( "; - mainSqlString += inSqlClause; - mainSqlString += " ) order by visit.encounter_num,visit.patient_num \n"; - - EventSet eventSet = new EventSet(); - RPDRPdoFactory.EventBuilder eventBuilder = new RPDRPdoFactory.EventBuilder( - detailFlag, blobFlag, statusFlag); - Connection conn = null; - PreparedStatement preparedStmt = null; - - try { - // execute fullsql - conn = getDataSource().getConnection(); - - log.debug("Executing sql[" + mainSqlString + "]"); - - if (visitListTypeHandler.isCollectionId()) { - String patientEncCollectionId = visitListTypeHandler - .getCollectionId(); - preparedStmt = conn.prepareStatement(mainSqlString); - preparedStmt - .setInt(1, Integer.parseInt(patientEncCollectionId)); - } else if (visitListTypeHandler.isEnumerationSet()) { - String serverType = dataSourceLookup.getServerType(); - visitListTypeHandler.uploadEnumerationValueToTempTable(conn); - preparedStmt = conn.prepareStatement(mainSqlString); - - } else { - preparedStmt = conn.prepareStatement(mainSqlString); - } - - ResultSet resultSet = preparedStmt.executeQuery(); - - while (resultSet.next()) { - // VisitDimensionType visitDimensionType = - // getVisitDimensionType(resultSet); - EventType event = eventBuilder.buildEventSet(resultSet, "i2b2",this.metaDataParamList); - eventSet.getEvent().add(event); - } - } catch (SQLException sqlEx) { - log.error("", sqlEx); - throw new I2B2DAOException("sql exception", sqlEx); - } catch (IOException ioEx) { - log.error("", ioEx); - throw new I2B2DAOException("IO exception", ioEx); - } finally { - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER)) { - try { - visitListTypeHandler.deleteTempTable(conn); - } catch (SQLException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - try { - JDBCUtil.closeJdbcResource(null, preparedStmt, conn); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - } - } - - return eventSet; - } - - /** - * Function to return EventSet for given patient set - * - * @param patientListType - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return - * @throws I2B2DAOException - */ - @Override - public EventSet getVisitDimensionSetFromPatientList( - PatientListType patientListType, boolean detailFlag, - boolean blobFlag, boolean statusFlag) throws I2B2DAOException { - String selectClause = getSelectClause(detailFlag, blobFlag, statusFlag); - String joinClause = getLookupJoinClause(detailFlag, blobFlag, - statusFlag); - - String mainSqlString = " SELECT " + selectClause + " FROM " - + getDbSchemaName() + "visit_dimension visit " + joinClause - + " WHERE visit.patient_num IN ( "; - PatientListTypeHandler patientListTypeHandler = new PatientListTypeHandler( - dataSourceLookup, patientListType); - String inSqlClause = patientListTypeHandler.generateWhereClauseSql(); - - mainSqlString += inSqlClause; - mainSqlString += " ) order by visit.encounter_num,visit.patient_num \n"; - - log.debug("Visit dimension sql " + mainSqlString); - - EventSet eventSet = new EventSet(); - RPDRPdoFactory.EventBuilder eventBuilder = new RPDRPdoFactory.EventBuilder( - detailFlag, blobFlag, statusFlag); - - Connection conn = null; - PreparedStatement preparedStmt = null; - - try { - // execute fullsql - conn = getDataSource().getConnection(); - log.debug("Executing sql[" + mainSqlString + "]"); - - if (patientListTypeHandler.isCollectionId()) { - preparedStmt = conn.prepareStatement(mainSqlString); - preparedStmt.setInt(1, Integer.parseInt(patientListTypeHandler - .getCollectionId())); - } else if (patientListTypeHandler.isEnumerationSet()) { - String serverType = dataSourceLookup.getServerType(); - patientListTypeHandler.uploadEnumerationValueToTempTable(conn); - preparedStmt = conn.prepareStatement(mainSqlString); - - } else if (patientListTypeHandler.isEntireSet()) { - // log.debug("No need to pass parameter to sql"); - preparedStmt = conn.prepareStatement(mainSqlString); - } - - ResultSet resultSet = preparedStmt.executeQuery(); - - while (resultSet.next()) { - EventType event = eventBuilder.buildEventSet(resultSet, "i2b2",this.metaDataParamList); - eventSet.getEvent().add(event); - } - } catch (SQLException sqlEx) { - log.error("", sqlEx); - throw new I2B2DAOException("sql exception", sqlEx); - } catch (IOException ioEx) { - log.error("", ioEx); - throw new I2B2DAOException("IO exception", ioEx); - } finally { - if (patientListTypeHandler.isEnumerationSet()) { - try { - patientListTypeHandler.deleteTempTable(conn); - } catch (SQLException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - try { - JDBCUtil.closeJdbcResource(null, preparedStmt, conn); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - } - } - - return eventSet; - } - - private String buildCustomSelectClause(String prefix) { - String detailSelectClause = " "; - for (Iterator iterator = this.metaDataParamList.iterator();iterator.hasNext();) { - ParamType paramType = iterator.next(); - - detailSelectClause += prefix + "." + paramType.getColumn() + " " + prefix + "_" + paramType.getColumn(); - if (iterator.hasNext()) { - detailSelectClause += " , "; - } - - } - return detailSelectClause; - } - - private String buildCustomLookupSelectClause() { - String detailSelectClause = " "; - for (Iterator iterator = this.metaDataParamList.iterator();iterator.hasNext();) { - ParamType paramType = iterator.next(); - if (paramType.getType().equalsIgnoreCase("string")) { - detailSelectClause += " , " + paramType.getColumn() + "_lookup" + ".name_char" + " " + paramType.getColumn() + "_name"; - } - } - return detailSelectClause; - } - - private String getSelectClause(boolean detailFlag, boolean blobFlag, - boolean statusFlag) { - String selectClause = ""; - selectClause = " visit.encounter_num visit_encounter_num, visit.patient_num visit_patient_num "; - - if (detailFlag) { - selectClause += " ," + buildCustomSelectClause("visit"); - selectClause += buildCustomLookupSelectClause() ; - selectClause += ", visit.start_date visit_start_date,visit.end_date visit_end_date "; - //selectClause += ", inout_lookup.name_char inout_name,location_lookup.name_char location_name, active_status_lookup.name_char active_status_name"; - } - - if (blobFlag) { - selectClause += ", visit.visit_blob visit_visit_blob "; - } - - if (statusFlag) { - selectClause += " , visit.update_date visit_update_date, visit.download_date visit_download_date, visit.import_date visit_import_date, visit.sourcesystem_cd visit_sourcesystem_cd, visit.upload_id visit_upload_id "; - } - - return selectClause; - } - - private String getLookupJoinClause(boolean detailFlag, boolean blobFlag, - boolean statusFlag) { - String joinClause = " "; - - if (detailFlag) { - for (Iterator iterator = this.metaDataParamList.iterator();iterator.hasNext();) { - ParamType paramType = iterator.next(); - if (paramType.getType().equalsIgnoreCase("string")) { - String columnName = paramType.getColumn(); - joinClause += " left JOIN " - + this.getDbSchemaName() - + "code_lookup " + columnName + "_lookup \n" - + " ON (visit." + columnName + " = " + columnName + "_lookup.code_Cd AND upper(" + columnName +"_lookup.column_cd) = '" + columnName.toUpperCase() + "') \n"; - } - } - - } - - return joinClause; - } - - private void uploadTempTable(Statement tempStmt, String tempTableName, - List patientNumList) throws SQLException { - String createTempInputListTable = "create table " + tempTableName - + " ( char_param1 varchar(100) )"; - tempStmt.executeUpdate(createTempInputListTable); - log.debug("created temp table" + tempTableName); - // load to temp table - // TempInputListInsert inputListInserter = new - // TempInputListInsert(dataSource,TEMP_PDO_INPUTLIST_TABLE); - // inputListInserter.setBatchSize(100); - int i = 0; - for (String singleValue : patientNumList) { - tempStmt.addBatch("insert into " + tempTableName + " values ('" - + singleValue + "' )"); - log.debug("adding batch" + singleValue); - i++; - if (i % 100 == 0) { - log.debug("batch insert"); - tempStmt.executeBatch(); - - } - } - log.debug("batch insert1"); - tempStmt.executeBatch(); - } - - - - @Override - public EventSet getVisitByFact(List panelSqlList, - List sqlParamCountList, - IInputOptionListHandler inputOptionListHandler, boolean detailFlag, - boolean blobFlag, boolean statusFlag) throws I2B2DAOException { - - EventSet eventSet = new EventSet(); - RPDRPdoFactory.EventBuilder eventBuilder = new RPDRPdoFactory.EventBuilder( - detailFlag, blobFlag, statusFlag); - VisitFactRelated eventFactRelated = new VisitFactRelated( - buildOutputOptionType(detailFlag, blobFlag, statusFlag)); - String selectClause = getSelectClause(detailFlag, blobFlag, statusFlag); - String joinClause = getLookupJoinClause(detailFlag, blobFlag, - statusFlag); - - String serverType = dataSourceLookup.getServerType(); - String factTempTable = ""; - Connection conn = null; - PreparedStatement query = null; - try { - conn = dataSource.getConnection(); - if (serverType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { - factTempTable = getDbSchemaName() - + FactRelatedQueryHandler.TEMP_FACT_PARAM_TABLE; - } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.SQLSERVER) || - serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { - log.debug("creating temp table"); - java.sql.Statement tempStmt = conn.createStatement(); - factTempTable = getDbSchemaName() - + SQLServerFactRelatedQueryHandler.TEMP_FACT_PARAM_TABLE; - try { - tempStmt.executeUpdate("drop table " + factTempTable); - } catch (SQLException sqlex) { - ; - } - String createTempInputListTable = "create table " - + factTempTable - + " ( set_index int, char_param1 varchar(500) )"; - tempStmt.executeUpdate(createTempInputListTable); - log.debug("created temp table" + factTempTable); - } - // if the inputlist is enumeration, then upload the enumerated input - // to temp table. - // the uploaded enumerated input will be used in the fact join. - if (inputOptionListHandler.isEnumerationSet()) { - inputOptionListHandler.uploadEnumerationValueToTempTable(conn); - } - String insertSql = ""; - int i = 0; - int sqlParamCount = 0; - ResultSet resultSet = null; - for (String panelSql : panelSqlList) { - insertSql = " insert into " - + factTempTable - + "(char_param1) select distinct obs_encounter_num from ( " - + panelSql + ") b"; - - log.debug("Executing SQL [ " + insertSql + "]"); - sqlParamCount = sqlParamCountList.get(i++); - // conn.createStatement().executeUpdate(insertSql); - executeUpdateSql(insertSql, conn, sqlParamCount, - inputOptionListHandler); - - } - - String finalSql = "SELECT " - + selectClause - + " FROM " - + getDbSchemaName() - + "visit_dimension visit " - + joinClause - + " where encounter_num in (select distinct CAST(coalesce(char_param1, '0') as integer) from " - + factTempTable + ") order by encounter_num"; - log.debug("Executing SQL [" + finalSql + "]"); - - - query = conn.prepareStatement(finalSql); - - resultSet = query.executeQuery(); - - while (resultSet.next()) { - EventType event = eventBuilder.buildEventSet(resultSet, "i2b2",this.metaDataParamList); - eventSet.getEvent().add(event); - } - } catch (SQLException sqlEx) { - log.error("", sqlEx); - throw new I2B2DAOException("sql exception", sqlEx); - } catch (IOException ioEx) { - log.error("", ioEx); - throw new I2B2DAOException("IO exception", ioEx); - } finally { - - PdoTempTableUtil tempUtil = new PdoTempTableUtil(); - tempUtil.clearTempTable(dataSourceLookup.getServerType(), conn, factTempTable); - if (inputOptionListHandler != null - && inputOptionListHandler.isEnumerationSet()) { - try { - inputOptionListHandler.deleteTempTable(conn); - } catch (SQLException e) { - - e.printStackTrace(); - } - } - try { - - JDBCUtil.closeJdbcResource(null, query, conn); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - } - } - return eventSet; - - } - - private void executeUpdateSql(String totalSql, Connection conn, - int sqlParamCount, IInputOptionListHandler inputOptionListHandler) - throws SQLException { - - PreparedStatement stmt = conn.prepareStatement(totalSql); - - log.debug(totalSql + " [ " + sqlParamCount + " ]"); - if (inputOptionListHandler.isCollectionId()) { - for (int i = 1; i <= sqlParamCount; i++) { - stmt.setInt(i, Integer.parseInt(inputOptionListHandler - .getCollectionId())); - } - } - - stmt.executeUpdate(); - - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao.pdo; + +import java.io.IOException; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Iterator; +import java.util.List; + +import javax.sql.DataSource; + +import oracle.sql.ArrayDescriptor; + +//import org.jboss.resource.adapter.jdbc.WrappedConnection; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.util.db.JDBCUtil; +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.dao.pdo.input.FactRelatedQueryHandler; +import edu.harvard.i2b2.crc.dao.pdo.input.IInputOptionListHandler; +import edu.harvard.i2b2.crc.dao.pdo.input.PatientListTypeHandler; +import edu.harvard.i2b2.crc.dao.pdo.input.SQLServerFactRelatedQueryHandler; +import edu.harvard.i2b2.crc.dao.pdo.input.VisitListTypeHandler; +import edu.harvard.i2b2.crc.dao.pdo.output.VisitFactRelated; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.pdo.EventSet; +import edu.harvard.i2b2.crc.datavo.pdo.EventType; +import edu.harvard.i2b2.crc.datavo.pdo.ParamType; +import edu.harvard.i2b2.crc.datavo.pdo.query.EventListType; +import edu.harvard.i2b2.crc.datavo.pdo.query.PatientListType; + +/** + * Class to support event section of table pdo query $Id: + * TablePdoQueryVisitDao.java,v 1.11 2008/03/19 22:42:08 rk903 Exp $ + * + * @author rkuttan + */ +public class TablePdoQueryVisitDao extends CRCDAO implements + ITablePdoQueryVisitDao { + + private DataSourceLookup dataSourceLookup = null; + private String schemaName = null; + private List metaDataParamList = null; + + + public TablePdoQueryVisitDao(DataSourceLookup dataSourceLookup, + DataSource dataSource) { + this.dataSourceLookup = dataSourceLookup; + setDataSource(dataSource); + this.setDbSchemaName(dataSourceLookup.getFullSchema()); + } + + @Override + public void setMetaDataParamList(List metaDataParamList) { + this.metaDataParamList = metaDataParamList; + } + + /** + * Function to return EventSet from visit information + * + * @param encounterNumList + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return EventSet + * @throws I2B2DAOException + */ + @Override + public EventSet getVisitsByEncounterNum(List encounterNumList, + boolean detailFlag, boolean blobFlag, boolean statusFlag) + throws I2B2DAOException { + EventSet eventSet = new EventSet(); + + RPDRPdoFactory.EventBuilder eventBuilder = new RPDRPdoFactory.EventBuilder( + detailFlag, blobFlag, statusFlag); + log.debug("input encounter list size " + + encounterNumList.size()); + + Connection conn = null; + PreparedStatement query = null; + String tempTableName = ""; + try { + conn = getDataSource().getConnection(); + + // create type StudentIdArrayType as varray(1000) of integer; + String selectClause = getSelectClause(detailFlag, blobFlag, + statusFlag); + String joinClause = getLookupJoinClause(detailFlag, blobFlag, + statusFlag); + String serverType = dataSourceLookup.getServerType(); + + if (serverType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { + oracle.jdbc.driver.OracleConnection conn1 = null;//(oracle.jdbc.driver.OracleConnection) ((WrappedConnection) conn) + // .getUnderlyingConnection(); + String finalSql = "SELECT " + + selectClause + + " FROM " + + getDbSchemaName() + + "visit_dimension visit \n" + + joinClause + + " WHERE visit.encounter_num IN (SELECT * FROM TABLE (cast (? as QT_PDO_QRY_STRING_ARRAY)))"; + log.debug("Executing sql[" + finalSql + "]"); + query = conn1.prepareStatement(finalSql); + + ArrayDescriptor desc = ArrayDescriptor.createDescriptor( + "QT_PDO_QRY_STRING_ARRAY", conn1); + oracle.sql.ARRAY paramArray = new oracle.sql.ARRAY(desc, conn1, + encounterNumList.toArray(new String[] {})); + query.setArray(1, paramArray); + } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.SQLSERVER) || + serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { + log.debug("creating temp table"); + java.sql.Statement tempStmt = conn.createStatement(); + tempTableName = getDbSchemaName() + + SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE; + try { + tempStmt.executeUpdate("drop table " + tempTableName); + } catch (SQLException sqlex) { + ; + } + + uploadTempTable(tempStmt, tempTableName, encounterNumList); + String finalSql = "SELECT " + + selectClause + + " FROM " + + getDbSchemaName() + + "visit_dimension visit \n" + + joinClause + + " WHERE visit.encounter_num IN (select distinct CAST(coalesce(char_param1, '0') as integer) FROM " + + tempTableName + " ) order by encounter_num,patient_num "; + log.debug("Executing [" + finalSql + "]"); + + query = conn.prepareStatement(finalSql); + + } + long startTimeSql = System.currentTimeMillis(); + ResultSet resultSet = query.executeQuery(); + long endTimeSql = System.currentTimeMillis(); + long totalTimeSql = endTimeSql - startTimeSql; + log.debug("********* Total time for visit sql ****" + + totalTimeSql); + long startTime = System.currentTimeMillis(); + while (resultSet.next()) { + EventType event = eventBuilder.buildEventSet(resultSet, "i2b2",this.metaDataParamList); + eventSet.getEvent().add(event); + } + long endTime = System.currentTimeMillis(); + long totalTime = endTimeSql - startTimeSql; + log.debug("********* Total time for visit objects ****" + + totalTime); + } catch (SQLException sqlEx) { + log.error("", sqlEx); + throw new I2B2DAOException("sql exception", sqlEx); + } catch (IOException ioEx) { + log.error("", ioEx); + throw new I2B2DAOException("IO exception", ioEx); + } finally { + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER)) { + PdoTempTableUtil tempUtil = new PdoTempTableUtil(); + tempUtil.deleteTempTableSqlServer(conn, tempTableName); + } + try { + JDBCUtil.closeJdbcResource(null, query, conn); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + } + } + + return eventSet; + } + + /** + * Function to return EventSet from visit information + * + * @param visitListType + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return EventSet + * @throws I2B2DAOException + */ + @Override + public EventSet getVisitDimensionSetFromVisitList( + EventListType visitListType, boolean detailFlag, boolean blobFlag, + boolean statusFlag) throws I2B2DAOException { + VisitListTypeHandler visitListTypeHandler = new VisitListTypeHandler( + dataSourceLookup, visitListType); + String inSqlClause = visitListTypeHandler.generateWhereClauseSql(); + String selectClause = getSelectClause(detailFlag, blobFlag, statusFlag); + String joinClause = getLookupJoinClause(detailFlag, blobFlag, + statusFlag); + String mainSqlString = " SELECT " + selectClause + " FROM " + + getDbSchemaName() + "visit_dimension visit " + joinClause + + " WHERE visit.encounter_num IN ( "; + mainSqlString += inSqlClause; + mainSqlString += " ) order by visit.encounter_num,visit.patient_num \n"; + + EventSet eventSet = new EventSet(); + RPDRPdoFactory.EventBuilder eventBuilder = new RPDRPdoFactory.EventBuilder( + detailFlag, blobFlag, statusFlag); + Connection conn = null; + PreparedStatement preparedStmt = null; + + try { + // execute fullsql + conn = getDataSource().getConnection(); + + log.debug("Executing sql[" + mainSqlString + "]"); + + if (visitListTypeHandler.isCollectionId()) { + String patientEncCollectionId = visitListTypeHandler + .getCollectionId(); + preparedStmt = conn.prepareStatement(mainSqlString); + preparedStmt + .setInt(1, Integer.parseInt(patientEncCollectionId)); + } else if (visitListTypeHandler.isEnumerationSet()) { + String serverType = dataSourceLookup.getServerType(); + visitListTypeHandler.uploadEnumerationValueToTempTable(conn); + preparedStmt = conn.prepareStatement(mainSqlString); + + } else { + preparedStmt = conn.prepareStatement(mainSqlString); + } + + ResultSet resultSet = preparedStmt.executeQuery(); + + while (resultSet.next()) { + // VisitDimensionType visitDimensionType = + // getVisitDimensionType(resultSet); + EventType event = eventBuilder.buildEventSet(resultSet, "i2b2",this.metaDataParamList); + eventSet.getEvent().add(event); + } + } catch (SQLException sqlEx) { + log.error("", sqlEx); + throw new I2B2DAOException("sql exception", sqlEx); + } catch (IOException ioEx) { + log.error("", ioEx); + throw new I2B2DAOException("IO exception", ioEx); + } finally { + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER)) { + try { + visitListTypeHandler.deleteTempTable(conn); + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + try { + JDBCUtil.closeJdbcResource(null, preparedStmt, conn); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + } + } + + return eventSet; + } + + /** + * Function to return EventSet for given patient set + * + * @param patientListType + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return + * @throws I2B2DAOException + */ + @Override + public EventSet getVisitDimensionSetFromPatientList( + PatientListType patientListType, boolean detailFlag, + boolean blobFlag, boolean statusFlag) throws I2B2DAOException { + String selectClause = getSelectClause(detailFlag, blobFlag, statusFlag); + String joinClause = getLookupJoinClause(detailFlag, blobFlag, + statusFlag); + + String mainSqlString = " SELECT " + selectClause + " FROM " + + getDbSchemaName() + "visit_dimension visit " + joinClause + + " WHERE visit.patient_num IN ( "; + PatientListTypeHandler patientListTypeHandler = new PatientListTypeHandler( + dataSourceLookup, patientListType); + String inSqlClause = patientListTypeHandler.generateWhereClauseSql(); + + mainSqlString += inSqlClause; + mainSqlString += " ) order by visit.encounter_num,visit.patient_num \n"; + + log.debug("Visit dimension sql " + mainSqlString); + + EventSet eventSet = new EventSet(); + RPDRPdoFactory.EventBuilder eventBuilder = new RPDRPdoFactory.EventBuilder( + detailFlag, blobFlag, statusFlag); + + Connection conn = null; + PreparedStatement preparedStmt = null; + + try { + // execute fullsql + conn = getDataSource().getConnection(); + log.debug("Executing sql[" + mainSqlString + "]"); + + if (patientListTypeHandler.isCollectionId()) { + preparedStmt = conn.prepareStatement(mainSqlString); + preparedStmt.setInt(1, Integer.parseInt(patientListTypeHandler + .getCollectionId())); + } else if (patientListTypeHandler.isEnumerationSet()) { + String serverType = dataSourceLookup.getServerType(); + patientListTypeHandler.uploadEnumerationValueToTempTable(conn); + preparedStmt = conn.prepareStatement(mainSqlString); + + } else if (patientListTypeHandler.isEntireSet()) { + // log.debug("No need to pass parameter to sql"); + preparedStmt = conn.prepareStatement(mainSqlString); + } + + ResultSet resultSet = preparedStmt.executeQuery(); + + while (resultSet.next()) { + EventType event = eventBuilder.buildEventSet(resultSet, "i2b2",this.metaDataParamList); + eventSet.getEvent().add(event); + } + } catch (SQLException sqlEx) { + log.error("", sqlEx); + throw new I2B2DAOException("sql exception", sqlEx); + } catch (IOException ioEx) { + log.error("", ioEx); + throw new I2B2DAOException("IO exception", ioEx); + } finally { + if (patientListTypeHandler.isEnumerationSet()) { + try { + patientListTypeHandler.deleteTempTable(conn); + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + try { + JDBCUtil.closeJdbcResource(null, preparedStmt, conn); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + } + } + + return eventSet; + } + + private String buildCustomSelectClause(String prefix) { + String detailSelectClause = " "; + for (Iterator iterator = this.metaDataParamList.iterator();iterator.hasNext();) { + ParamType paramType = iterator.next(); + + detailSelectClause += prefix + "." + paramType.getColumn() + " " + prefix + "_" + paramType.getColumn(); + if (iterator.hasNext()) { + detailSelectClause += " , "; + } + + } + return detailSelectClause; + } + + private String buildCustomLookupSelectClause() { + String detailSelectClause = " "; + for (Iterator iterator = this.metaDataParamList.iterator();iterator.hasNext();) { + ParamType paramType = iterator.next(); + if (paramType.getType().equalsIgnoreCase("string")) { + detailSelectClause += " , " + paramType.getColumn() + "_lookup" + ".name_char" + " " + paramType.getColumn() + "_name"; + } + } + return detailSelectClause; + } + + private String getSelectClause(boolean detailFlag, boolean blobFlag, + boolean statusFlag) { + String selectClause = ""; + selectClause = " visit.encounter_num visit_encounter_num, visit.patient_num visit_patient_num "; + + if (detailFlag) { + selectClause += " ," + buildCustomSelectClause("visit"); + selectClause += buildCustomLookupSelectClause() ; + selectClause += ", visit.start_date visit_start_date,visit.end_date visit_end_date "; + //selectClause += ", inout_lookup.name_char inout_name,location_lookup.name_char location_name, active_status_lookup.name_char active_status_name"; + } + + if (blobFlag) { + selectClause += ", visit.visit_blob visit_visit_blob "; + } + + if (statusFlag) { + selectClause += " , visit.update_date visit_update_date, visit.download_date visit_download_date, visit.import_date visit_import_date, visit.sourcesystem_cd visit_sourcesystem_cd, visit.upload_id visit_upload_id "; + } + + return selectClause; + } + + private String getLookupJoinClause(boolean detailFlag, boolean blobFlag, + boolean statusFlag) { + String joinClause = " "; + + if (detailFlag) { + for (Iterator iterator = this.metaDataParamList.iterator();iterator.hasNext();) { + ParamType paramType = iterator.next(); + if (paramType.getType().equalsIgnoreCase("string")) { + String columnName = paramType.getColumn(); + joinClause += " left JOIN " + + this.getDbSchemaName() + + "code_lookup " + columnName + "_lookup \n" + + " ON (visit." + columnName + " = " + columnName + "_lookup.code_Cd AND upper(" + columnName +"_lookup.column_cd) = '" + columnName.toUpperCase() + "') \n"; + } + } + + } + + return joinClause; + } + + private void uploadTempTable(Statement tempStmt, String tempTableName, + List patientNumList) throws SQLException { + String createTempInputListTable = "create table " + tempTableName + + " ( char_param1 varchar(100) )"; + tempStmt.executeUpdate(createTempInputListTable); + log.debug("created temp table" + tempTableName); + // load to temp table + // TempInputListInsert inputListInserter = new + // TempInputListInsert(dataSource,TEMP_PDO_INPUTLIST_TABLE); + // inputListInserter.setBatchSize(100); + int i = 0; + for (String singleValue : patientNumList) { + tempStmt.addBatch("insert into " + tempTableName + " values ('" + + singleValue + "' )"); + log.debug("adding batch" + singleValue); + i++; + if (i % 100 == 0) { + log.debug("batch insert"); + tempStmt.executeBatch(); + + } + } + log.debug("batch insert1"); + tempStmt.executeBatch(); + } + + + + @Override + public EventSet getVisitByFact(List panelSqlList, + List sqlParamCountList, + IInputOptionListHandler inputOptionListHandler, boolean detailFlag, + boolean blobFlag, boolean statusFlag) throws I2B2DAOException { + + EventSet eventSet = new EventSet(); + RPDRPdoFactory.EventBuilder eventBuilder = new RPDRPdoFactory.EventBuilder( + detailFlag, blobFlag, statusFlag); + VisitFactRelated eventFactRelated = new VisitFactRelated( + buildOutputOptionType(detailFlag, blobFlag, statusFlag)); + String selectClause = getSelectClause(detailFlag, blobFlag, statusFlag); + String joinClause = getLookupJoinClause(detailFlag, blobFlag, + statusFlag); + + String serverType = dataSourceLookup.getServerType(); + String factTempTable = ""; + Connection conn = null; + PreparedStatement query = null; + try { + conn = dataSource.getConnection(); + if (serverType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { + factTempTable = getDbSchemaName() + + FactRelatedQueryHandler.TEMP_FACT_PARAM_TABLE; + } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.SQLSERVER) || + serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { + log.debug("creating temp table"); + java.sql.Statement tempStmt = conn.createStatement(); + factTempTable = getDbSchemaName() + + SQLServerFactRelatedQueryHandler.TEMP_FACT_PARAM_TABLE; + try { + tempStmt.executeUpdate("drop table " + factTempTable); + } catch (SQLException sqlex) { + ; + } + String createTempInputListTable = "create table " + + factTempTable + + " ( set_index int, char_param1 varchar(500) )"; + tempStmt.executeUpdate(createTempInputListTable); + log.debug("created temp table" + factTempTable); + } + // if the inputlist is enumeration, then upload the enumerated input + // to temp table. + // the uploaded enumerated input will be used in the fact join. + if (inputOptionListHandler.isEnumerationSet()) { + inputOptionListHandler.uploadEnumerationValueToTempTable(conn); + } + String insertSql = ""; + int i = 0; + int sqlParamCount = 0; + ResultSet resultSet = null; + for (String panelSql : panelSqlList) { + insertSql = " insert into " + + factTempTable + + "(char_param1) select distinct obs_encounter_num from ( " + + panelSql + ") b"; + + log.debug("Executing SQL [ " + insertSql + "]"); + sqlParamCount = sqlParamCountList.get(i++); + // conn.createStatement().executeUpdate(insertSql); + executeUpdateSql(insertSql, conn, sqlParamCount, + inputOptionListHandler); + + } + + String finalSql = "SELECT " + + selectClause + + " FROM " + + getDbSchemaName() + + "visit_dimension visit " + + joinClause + + " where encounter_num in (select distinct CAST(coalesce(char_param1, '0') as integer) from " + + factTempTable + ") order by encounter_num"; + log.debug("Executing SQL [" + finalSql + "]"); + + + query = conn.prepareStatement(finalSql); + + resultSet = query.executeQuery(); + + while (resultSet.next()) { + EventType event = eventBuilder.buildEventSet(resultSet, "i2b2",this.metaDataParamList); + eventSet.getEvent().add(event); + } + } catch (SQLException sqlEx) { + log.error("", sqlEx); + throw new I2B2DAOException("sql exception", sqlEx); + } catch (IOException ioEx) { + log.error("", ioEx); + throw new I2B2DAOException("IO exception", ioEx); + } finally { + + PdoTempTableUtil tempUtil = new PdoTempTableUtil(); + tempUtil.clearTempTable(dataSourceLookup.getServerType(), conn, factTempTable); + if (inputOptionListHandler != null + && inputOptionListHandler.isEnumerationSet()) { + try { + inputOptionListHandler.deleteTempTable(conn); + } catch (SQLException e) { + + e.printStackTrace(); + } + } + try { + + JDBCUtil.closeJdbcResource(null, query, conn); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + } + } + return eventSet; + + } + + private void executeUpdateSql(String totalSql, Connection conn, + int sqlParamCount, IInputOptionListHandler inputOptionListHandler) + throws SQLException { + + PreparedStatement stmt = conn.prepareStatement(totalSql); + + log.debug(totalSql + " [ " + sqlParamCount + " ]"); + if (inputOptionListHandler.isCollectionId()) { + for (int i = 1; i <= sqlParamCount; i++) { + stmt.setInt(i, Integer.parseInt(inputOptionListHandler + .getCollectionId())); + } + } + + stmt.executeUpdate(); + + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/filter/DimensionFilter.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/filter/DimensionFilter.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/filter/DimensionFilter.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/filter/DimensionFilter.java index 17d46a48..9d7dba40 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/filter/DimensionFilter.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/filter/DimensionFilter.java @@ -1,134 +1,134 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao.pdo.filter; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.db.JDBCUtil; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.pdo.query.ItemType; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; -import edu.harvard.i2b2.crc.util.SqlClauseUtil; - -/** - * Class builds "from" and "where" clause of pdo query based on given provider - * filter $Id: DimensionFilter.java,v 1.3 2009/01/08 19:38:57 rk903 Exp $ - * - * @author rkuttan - */ -public class DimensionFilter { - private ItemType item = null; - private String dimensionColumnName = null; - private String factTableColumn = null; - private String schemaName = null; - private DataSourceLookup dataSourceLookup = null; - private boolean derivedFactTable = QueryProcessorUtil.getInstance().getDerivedFactTable(); - - /** - * Parameter constructor - * - * @param filterListType - */ - public DimensionFilter(ItemType item, String schemaName, DataSourceLookup dataSourceLookup) { - this.item = item; - this.schemaName = schemaName; - this.dataSourceLookup = dataSourceLookup; - } - - /** - * Function generates "from" clause of PDO query, by iterating filter list - * - * @return sql string - */ - public String getFromSqlString() throws I2B2Exception { - String conceptFromString = ""; - - if (item != null) { - conceptFromString = " ( "; - - int i = 0; - - String conceptPathValue = null; - String conceptPathFilterName = null; - - String dimCode = item.getDimDimcode(); - String dimColumnDataType = item.getDimColumndatatype(); - String dimOperator = item.getDimOperator(); - - if (dimOperator.equalsIgnoreCase("LIKE") - && dimCode.trim().length() > 0) { - if (!SqlClauseUtil.isEnclosedinSingleQuote(dimCode)) { - - // check if the dim code ends with "\" other wise add it, - // so that it matches concept_dimension's concept_path or - // provider_dimension's provider_path - if (dimCode.lastIndexOf('\\') == dimCode.length() - 1) { - dimCode = dimCode + "%"; - } else { - dimCode = dimCode + "\\%"; - } - if (dataSourceLookup.getServerType().equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) - dimCode = dimCode.replaceAll("\\\\", "\\\\\\\\"); - - } - } - - if (dimOperator.equalsIgnoreCase("IN")) { - if (dimColumnDataType.equalsIgnoreCase("T")) { - dimCode = SqlClauseUtil.buildINClause(dimCode, true); - } else if (dimColumnDataType.equalsIgnoreCase("N")) { - dimCode = SqlClauseUtil.buildINClause(dimCode, false); - } - dimCode = "(" + dimCode + ")"; - } else { - if (dimColumnDataType.equalsIgnoreCase("T")) { - if (!SqlClauseUtil.isEnclosedinSingleQuote(dimCode)) { - dimCode = JDBCUtil.escapeSingleQuote(dimCode); - dimCode = "'" + dimCode + "'"; - } - } - } - - String facttablecolumn = item.getFacttablecolumn(); - if(derivedFactTable == true){ - if(item.getFacttablecolumn().contains(".")){ - - int lastIndex = facttablecolumn.lastIndexOf("."); - - facttablecolumn = (facttablecolumn.substring(lastIndex+1)); - } - } - //OMOP: WAS item.getFacttablecolumn(); - /* conceptFromString += ("SELECT " + item.getFacttablecolumn() - + " FROM " + this.schemaName + item.getDimTablename() - + " WHERE " + item.getDimColumnname() + " " + dimOperator - + " " + dimCode + "\n"); - */ - - conceptFromString += ("SELECT " + facttablecolumn - + " FROM " + this.schemaName + item.getDimTablename() - + " WHERE " + item.getDimColumnname() + " " + dimOperator - + " " + dimCode + "\n"); - // check if it is exactly one concept, then add group by clause, - // other wise union will take care of - // removing duplicate concept_cd - //OMOP WAS item.getFacttablecolumn(); - conceptFromString += " group by " + facttablecolumn; - conceptFromString += " ) dimension \n"; - } - - return conceptFromString; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao.pdo.filter; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.db.JDBCUtil; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.pdo.query.ItemType; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; +import edu.harvard.i2b2.crc.util.SqlClauseUtil; + +/** + * Class builds "from" and "where" clause of pdo query based on given provider + * filter $Id: DimensionFilter.java,v 1.3 2009/01/08 19:38:57 rk903 Exp $ + * + * @author rkuttan + */ +public class DimensionFilter { + private ItemType item = null; + private String dimensionColumnName = null; + private String factTableColumn = null; + private String schemaName = null; + private DataSourceLookup dataSourceLookup = null; + private boolean derivedFactTable = QueryProcessorUtil.getInstance().getDerivedFactTable(); + + /** + * Parameter constructor + * + * @param filterListType + */ + public DimensionFilter(ItemType item, String schemaName, DataSourceLookup dataSourceLookup) { + this.item = item; + this.schemaName = schemaName; + this.dataSourceLookup = dataSourceLookup; + } + + /** + * Function generates "from" clause of PDO query, by iterating filter list + * + * @return sql string + */ + public String getFromSqlString() throws I2B2Exception { + String conceptFromString = ""; + + if (item != null) { + conceptFromString = " ( "; + + int i = 0; + + String conceptPathValue = null; + String conceptPathFilterName = null; + + String dimCode = item.getDimDimcode(); + String dimColumnDataType = item.getDimColumndatatype(); + String dimOperator = item.getDimOperator(); + + if (dimOperator.equalsIgnoreCase("LIKE") + && dimCode.trim().length() > 0) { + if (!SqlClauseUtil.isEnclosedinSingleQuote(dimCode)) { + + // check if the dim code ends with "\" other wise add it, + // so that it matches concept_dimension's concept_path or + // provider_dimension's provider_path + if (dimCode.lastIndexOf('\\') == dimCode.length() - 1) { + dimCode = dimCode + "%"; + } else { + dimCode = dimCode + "\\%"; + } + if (dataSourceLookup.getServerType().equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) + dimCode = dimCode.replaceAll("\\\\", "\\\\\\\\"); + + } + } + + if (dimOperator.equalsIgnoreCase("IN")) { + if (dimColumnDataType.equalsIgnoreCase("T")) { + dimCode = SqlClauseUtil.buildINClause(dimCode, true); + } else if (dimColumnDataType.equalsIgnoreCase("N")) { + dimCode = SqlClauseUtil.buildINClause(dimCode, false); + } + dimCode = "(" + dimCode + ")"; + } else { + if (dimColumnDataType.equalsIgnoreCase("T")) { + if (!SqlClauseUtil.isEnclosedinSingleQuote(dimCode)) { + dimCode = JDBCUtil.escapeSingleQuote(dimCode); + dimCode = "'" + dimCode + "'"; + } + } + } + + String facttablecolumn = item.getFacttablecolumn(); + if(derivedFactTable == true){ + if(item.getFacttablecolumn().contains(".")){ + + int lastIndex = facttablecolumn.lastIndexOf("."); + + facttablecolumn = (facttablecolumn.substring(lastIndex+1)); + } + } + //OMOP: WAS item.getFacttablecolumn(); + /* conceptFromString += ("SELECT " + item.getFacttablecolumn() + + " FROM " + this.schemaName + item.getDimTablename() + + " WHERE " + item.getDimColumnname() + " " + dimOperator + + " " + dimCode + "\n"); + */ + + conceptFromString += ("SELECT " + facttablecolumn + + " FROM " + this.schemaName + item.getDimTablename() + + " WHERE " + item.getDimColumnname() + " " + dimOperator + + " " + dimCode + "\n"); + // check if it is exactly one concept, then add group by clause, + // other wise union will take care of + // removing duplicate concept_cd + //OMOP WAS item.getFacttablecolumn(); + conceptFromString += " group by " + facttablecolumn; + conceptFromString += " ) dimension \n"; + } + + return conceptFromString; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/input/AverageObservationPageMethod.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/input/AverageObservationPageMethod.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/input/AverageObservationPageMethod.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/input/AverageObservationPageMethod.java index 90062c2e..118c7ea6 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/input/AverageObservationPageMethod.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/input/AverageObservationPageMethod.java @@ -1,44 +1,44 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.pdo.input; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -public class AverageObservationPageMethod implements PageMethod { - - /** log * */ - protected final Log log = LogFactory - .getLog(AverageObservationPageMethod.class); - - public AverageObservationPageMethod() { - } - - @Override - public int calculateListSize(int maxInputList, long totalObservations, - long pageSize) { - - // calculateObservationPerPatient - long observationsPerPatient = calculateObservationPerPatient( - totalObservations, maxInputList); - log.debug("Total observation per patient is [" + observationsPerPatient - + "]"); - if (observationsPerPatient == 0) { - return 0; - } - maxInputList = (int) ((pageSize *0.9) / observationsPerPatient); - return maxInputList; - } - - private long calculateObservationPerPatient(long totalObservations, - int inputListLength) { - long observationPerPatient = totalObservations / inputListLength; - return observationPerPatient; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.pdo.input; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +public class AverageObservationPageMethod implements PageMethod { + + /** log * */ + protected final Log log = LogFactory + .getLog(AverageObservationPageMethod.class); + + public AverageObservationPageMethod() { + } + + @Override + public int calculateListSize(int maxInputList, long totalObservations, + long pageSize) { + + // calculateObservationPerPatient + long observationsPerPatient = calculateObservationPerPatient( + totalObservations, maxInputList); + log.debug("Total observation per patient is [" + observationsPerPatient + + "]"); + if (observationsPerPatient == 0) { + return 0; + } + maxInputList = (int) ((pageSize *0.9) / observationsPerPatient); + return maxInputList; + } + + private long calculateObservationPerPatient(long totalObservations, + int inputListLength) { + long observationPerPatient = totalObservations / inputListLength; + return observationPerPatient; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/input/DateConstrainHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/input/DateConstrainHandler.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/input/DateConstrainHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/input/DateConstrainHandler.java index c79585d2..6ca97c0d --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/input/DateConstrainHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/input/DateConstrainHandler.java @@ -1,121 +1,121 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao.pdo.input; - -import java.text.SimpleDateFormat; - -import javax.xml.datatype.XMLGregorianCalendar; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.pdo.query.InclusiveType; - -/** - * Class to generate date constrains sqls clause. $Id: - * DateConstrainHandler.java,v 1.4 2008/06/26 03:58:56 rk903 Exp $ - * - * @author rkuttan - */ -public class DateConstrainHandler { - /** log **/ - protected final Log log = LogFactory.getLog(getClass()); - private SimpleDateFormat dateFormat = new SimpleDateFormat( - "dd-MMM-yyyy HH:mm:ss"); - private DataSourceLookup dataSourceLookup = null; - - public DateConstrainHandler(DataSourceLookup dataSourceLookup) { - this.dataSourceLookup = dataSourceLookup; - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE)) { - dateFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss"); - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER) ||dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) { - // ISO 8601 - dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); - } - } - - public String constructDateConstrainClause(String fromDateField, - String toDateField, InclusiveType fromInclusiveType, - InclusiveType toInclusiveType, XMLGregorianCalendar fromDate, - XMLGregorianCalendar toDate) throws I2B2Exception { - String dateConstrainSql = null; - String sqlOperator = null; - - if (fromDate != null) { - String fromDateString = dateFormat.format(fromDate - .toGregorianCalendar().getTime()); - - if (fromInclusiveType != null - && fromInclusiveType.name().equals(InclusiveType.NO.name())) { - sqlOperator = " > "; - } else { - sqlOperator = " >= "; - } - - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE)) { - dateConstrainSql = fromDateField + sqlOperator + "to_date('" - + fromDateString + "','DD-MON-YYYY HH24:MI:SS')"; - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER) || dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) { - // {ts '2005-06-27 00:00:00'} - dateConstrainSql = fromDateField + sqlOperator + " '" - + fromDateString + "'"; - } - } - - if (toDate != null) { - sqlOperator = null; - - String toDateString = dateFormat.format(toDate - .toGregorianCalendar().getTime()); - - if (toInclusiveType != null - && toInclusiveType.name().equals(InclusiveType.NO.name())) { - sqlOperator = " < "; - } else { - sqlOperator = " <= "; - } - - if (dateConstrainSql != null) { - dateConstrainSql += " AND "; - } - - if (dateConstrainSql == null) { - dateConstrainSql = " "; - } - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE)) { - dateConstrainSql += (toDateField + sqlOperator + "to_date('" - + toDateString + "','DD-MON-YYYY HH24:MI:SS')"); - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER) || dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) { - dateConstrainSql += (toDateField + sqlOperator + " '" - + toDateString + "'"); - } - } - - return dateConstrainSql; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao.pdo.input; + +import java.text.SimpleDateFormat; + +import javax.xml.datatype.XMLGregorianCalendar; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.pdo.query.InclusiveType; + +/** + * Class to generate date constrains sqls clause. $Id: + * DateConstrainHandler.java,v 1.4 2008/06/26 03:58:56 rk903 Exp $ + * + * @author rkuttan + */ +public class DateConstrainHandler { + /** log **/ + protected final Log log = LogFactory.getLog(getClass()); + private SimpleDateFormat dateFormat = new SimpleDateFormat( + "dd-MMM-yyyy HH:mm:ss"); + private DataSourceLookup dataSourceLookup = null; + + public DateConstrainHandler(DataSourceLookup dataSourceLookup) { + this.dataSourceLookup = dataSourceLookup; + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.ORACLE)) { + dateFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss"); + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER) ||dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) { + // ISO 8601 + dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); + } + } + + public String constructDateConstrainClause(String fromDateField, + String toDateField, InclusiveType fromInclusiveType, + InclusiveType toInclusiveType, XMLGregorianCalendar fromDate, + XMLGregorianCalendar toDate) throws I2B2Exception { + String dateConstrainSql = null; + String sqlOperator = null; + + if (fromDate != null) { + String fromDateString = dateFormat.format(fromDate + .toGregorianCalendar().getTime()); + + if (fromInclusiveType != null + && fromInclusiveType.name().equals(InclusiveType.NO.name())) { + sqlOperator = " > "; + } else { + sqlOperator = " >= "; + } + + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.ORACLE)) { + dateConstrainSql = fromDateField + sqlOperator + "to_date('" + + fromDateString + "','DD-MON-YYYY HH24:MI:SS')"; + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER) || dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) { + // {ts '2005-06-27 00:00:00'} + dateConstrainSql = fromDateField + sqlOperator + " '" + + fromDateString + "'"; + } + } + + if (toDate != null) { + sqlOperator = null; + + String toDateString = dateFormat.format(toDate + .toGregorianCalendar().getTime()); + + if (toInclusiveType != null + && toInclusiveType.name().equals(InclusiveType.NO.name())) { + sqlOperator = " < "; + } else { + sqlOperator = " <= "; + } + + if (dateConstrainSql != null) { + dateConstrainSql += " AND "; + } + + if (dateConstrainSql == null) { + dateConstrainSql = " "; + } + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.ORACLE)) { + dateConstrainSql += (toDateField + sqlOperator + "to_date('" + + toDateString + "','DD-MON-YYYY HH24:MI:SS')"); + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER) || dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) { + dateConstrainSql += (toDateField + sqlOperator + " '" + + toDateString + "'"); + } + } + + return dateConstrainSql; + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/input/EidListTypeHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/input/EidListTypeHandler.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/input/EidListTypeHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/input/EidListTypeHandler.java index 22cc338f..527acd4b --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/input/EidListTypeHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/input/EidListTypeHandler.java @@ -1,278 +1,278 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao.pdo.input; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.List; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.pdo.query.EidListType; -import edu.harvard.i2b2.crc.datavo.pdo.query.EventListType; -import edu.harvard.i2b2.crc.datavo.pdo.query.EidListType.Eid; - -/** - * Handler class for pid list type to generate "where" clause for pdo request - * $Id: EidListTypeHandler.java,v 1.3 2009/10/23 19:54:02 rk903 Exp $ - * - * @author rkuttan - */ -public class EidListTypeHandler extends CRCDAO implements - IInputOptionListHandler { - private EidListType eidListType = null; - private int minIndex = 0; - private int maxIndex = 0; - private String encounterSetCollId = ""; - private List encounterNumList = null; - private DataSourceLookup dataSourceLookup = null; - private boolean deleteTempFlag = false; - - /** - * Constructor accepts {@link EventListType} - * - * @param visitListType - * @throws I2B2DAOException - */ - public EidListTypeHandler(DataSourceLookup dataSourceLookup, - EidListType eidListType) throws I2B2DAOException { - if (eidListType == null) { - throw new I2B2DAOException("Eid List Type is null"); - } - - this.dataSourceLookup = dataSourceLookup; - setDbSchemaName(dataSourceLookup.getFullSchema()); - this.eidListType = eidListType; - - if (eidListType.getMin() != null) { - minIndex = eidListType.getMin(); - } - - if (eidListType.getMax() != null) { - maxIndex = eidListType.getMax(); - } - } - - @Override - public int getMinIndex() { - return minIndex; - } - - @Override - public int getMaxIndex() { - return maxIndex; - } - - @Override - public boolean isCollectionId() { - return false; - } - - @Override - public boolean isEnumerationSet() { - if ((eidListType.getEid() != null) && (eidListType.getEid().size() > 0)) { - return true; - } else { - return false; - } - } - - @Override - public boolean isEntireSet() { - return false; - } - - /** - * Function to generate "where" clause for visit/event list - */ - @Override - public String generateWhereClauseSql() { - - String tempTableName = getTempTableName(); - - String sqlString = "SELECT " - + " em.encounter_num " - + " FROM " - + getDbSchemaName() - + "encounter_mapping em WHERE exists (select 1 FROM " - + tempTableName - + " where char_param1 = em.encounter_ide and char_param2 = em.encounter_ide_source) "; - return sqlString; - } - - public String generatePatentSql() { - String sqlString = null; - - return sqlString; - } - - @Override - public List getEnumerationList() { - ArrayList encounterNumArrayList = new ArrayList(); - return this.encounterNumList; - } - - @Override - public void uploadEnumerationValueToTempTable(Connection conn) - throws SQLException { - - String tempTableName = this.getTempTableName(); - - // create temp table - java.sql.Statement tempStmt = conn.createStatement(); - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER)) { - String createTempInputListTable = "create table " - + getTempTableName() - + " (set_index int, char_param1 varchar(100), char_param2 varchar(100) )"; - deleteTempFlag = true; - tempStmt.executeUpdate(createTempInputListTable); - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) - { - String createTempInputListTable = "create temp table " - + getTempTableName() - + " (set_index int, char_param1 varchar(100), char_param2 varchar(100) )"; - deleteTempFlag = true; - tempStmt.executeUpdate(createTempInputListTable); - - } - int i = 0, j = 1; - - List eidList = eidListType.getEid(); - List finalEidList = new ArrayList(); - if (maxIndex > eidListType.getEid().size()) { - // log.warn("max size is more than list size"); - maxIndex = eidListType.getEid().size(); - } - if (minIndex < maxIndex) { - finalEidList = eidList.subList(minIndex, maxIndex); - } else if (minIndex == maxIndex && minIndex > 0) { - // check if maxIndex is equal to last index - if (maxIndex == eidListType.getEid().size() - 1) { - finalEidList.add(eidList.get(maxIndex)); - } else { - finalEidList = eidList.subList(minIndex, maxIndex); - } - - } else { - maxIndex = eidList.size(); - finalEidList = eidList.subList(minIndex, maxIndex); - } - - PreparedStatement preparedStmt = conn.prepareStatement("insert into " - + tempTableName - + "(set_index,char_param1,char_param2) values (?,?,?)"); - for (Eid eid : finalEidList) { - preparedStmt.setInt(1, j++); - preparedStmt.setString(2, eid.getValue()); - preparedStmt.setString(3, eid.getSource()); - preparedStmt.addBatch(); - i++; - if (i % 100 == 0) { - preparedStmt.executeBatch(); - - } - log.debug("loading " + eid.getValue() + " " + eid.getSource()); - } - preparedStmt.executeBatch(); - } - - @Override - public void deleteTempTable(Connection conn) throws SQLException { - Statement deleteStmt = null; - if (!deleteTempFlag) { - return; - } - try { - deleteStmt = conn.createStatement(); - - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER) || dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) { - // conn.createStatement().executeUpdate( - // "drop table " + getTempTableName()); - deleteStmt.executeUpdate( - "drop table " + getTempTableName()); - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE)) { - // conn.createStatement().executeUpdate( - // "delete " + getTempTableName()); - deleteStmt.executeUpdate( - "delete " + getTempTableName()); - } - } catch (SQLException sqle) { - throw sqle; - } finally { - try { - if(deleteStmt != null) - deleteStmt.close(); - } catch (SQLException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } - - @Override - public String getCollectionId() { - return ""; - } - - @Override - public String generateMinIndexSql(String panelSql) { - // TODO Auto-generated method stub - return null; - } - - /** - * Returns input list's size. if the list is collection id, then collection - * set size, if the list is entire set, then total rows in dimension table - * if the list is enumeration, then size of enumeration set - * - * @return - * @throws I2B2DAOException - */ - @Override - public int getInputSize() throws I2B2DAOException { - - return 0; - - } - - @Override - public void setMaxIndex(int maxIndex) { - eidListType.setMax(maxIndex); - - } - - public String getTempTableName() { - String tempTableName = ""; - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE)) { - tempTableName = this.getDbSchemaName() - + FactRelatedQueryHandler.TEMP_PARAM_TABLE; - } else { - tempTableName = this.getDbSchemaName() - + SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE; - } - return tempTableName; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao.pdo.input; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.pdo.query.EidListType; +import edu.harvard.i2b2.crc.datavo.pdo.query.EventListType; +import edu.harvard.i2b2.crc.datavo.pdo.query.EidListType.Eid; + +/** + * Handler class for pid list type to generate "where" clause for pdo request + * $Id: EidListTypeHandler.java,v 1.3 2009/10/23 19:54:02 rk903 Exp $ + * + * @author rkuttan + */ +public class EidListTypeHandler extends CRCDAO implements + IInputOptionListHandler { + private EidListType eidListType = null; + private int minIndex = 0; + private int maxIndex = 0; + private String encounterSetCollId = ""; + private List encounterNumList = null; + private DataSourceLookup dataSourceLookup = null; + private boolean deleteTempFlag = false; + + /** + * Constructor accepts {@link EventListType} + * + * @param visitListType + * @throws I2B2DAOException + */ + public EidListTypeHandler(DataSourceLookup dataSourceLookup, + EidListType eidListType) throws I2B2DAOException { + if (eidListType == null) { + throw new I2B2DAOException("Eid List Type is null"); + } + + this.dataSourceLookup = dataSourceLookup; + setDbSchemaName(dataSourceLookup.getFullSchema()); + this.eidListType = eidListType; + + if (eidListType.getMin() != null) { + minIndex = eidListType.getMin(); + } + + if (eidListType.getMax() != null) { + maxIndex = eidListType.getMax(); + } + } + + @Override + public int getMinIndex() { + return minIndex; + } + + @Override + public int getMaxIndex() { + return maxIndex; + } + + @Override + public boolean isCollectionId() { + return false; + } + + @Override + public boolean isEnumerationSet() { + if ((eidListType.getEid() != null) && (eidListType.getEid().size() > 0)) { + return true; + } else { + return false; + } + } + + @Override + public boolean isEntireSet() { + return false; + } + + /** + * Function to generate "where" clause for visit/event list + */ + @Override + public String generateWhereClauseSql() { + + String tempTableName = getTempTableName(); + + String sqlString = "SELECT " + + " em.encounter_num " + + " FROM " + + getDbSchemaName() + + "encounter_mapping em WHERE exists (select 1 FROM " + + tempTableName + + " where char_param1 = em.encounter_ide and char_param2 = em.encounter_ide_source) "; + return sqlString; + } + + public String generatePatentSql() { + String sqlString = null; + + return sqlString; + } + + @Override + public List getEnumerationList() { + ArrayList encounterNumArrayList = new ArrayList(); + return this.encounterNumList; + } + + @Override + public void uploadEnumerationValueToTempTable(Connection conn) + throws SQLException { + + String tempTableName = this.getTempTableName(); + + // create temp table + java.sql.Statement tempStmt = conn.createStatement(); + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER)) { + String createTempInputListTable = "create table " + + getTempTableName() + + " (set_index int, char_param1 varchar(100), char_param2 varchar(100) )"; + deleteTempFlag = true; + tempStmt.executeUpdate(createTempInputListTable); + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) + { + String createTempInputListTable = "create temp table " + + getTempTableName() + + " (set_index int, char_param1 varchar(100), char_param2 varchar(100) )"; + deleteTempFlag = true; + tempStmt.executeUpdate(createTempInputListTable); + + } + int i = 0, j = 1; + + List eidList = eidListType.getEid(); + List finalEidList = new ArrayList(); + if (maxIndex > eidListType.getEid().size()) { + // log.warn("max size is more than list size"); + maxIndex = eidListType.getEid().size(); + } + if (minIndex < maxIndex) { + finalEidList = eidList.subList(minIndex, maxIndex); + } else if (minIndex == maxIndex && minIndex > 0) { + // check if maxIndex is equal to last index + if (maxIndex == eidListType.getEid().size() - 1) { + finalEidList.add(eidList.get(maxIndex)); + } else { + finalEidList = eidList.subList(minIndex, maxIndex); + } + + } else { + maxIndex = eidList.size(); + finalEidList = eidList.subList(minIndex, maxIndex); + } + + PreparedStatement preparedStmt = conn.prepareStatement("insert into " + + tempTableName + + "(set_index,char_param1,char_param2) values (?,?,?)"); + for (Eid eid : finalEidList) { + preparedStmt.setInt(1, j++); + preparedStmt.setString(2, eid.getValue()); + preparedStmt.setString(3, eid.getSource()); + preparedStmt.addBatch(); + i++; + if (i % 100 == 0) { + preparedStmt.executeBatch(); + + } + log.debug("loading " + eid.getValue() + " " + eid.getSource()); + } + preparedStmt.executeBatch(); + } + + @Override + public void deleteTempTable(Connection conn) throws SQLException { + Statement deleteStmt = null; + if (!deleteTempFlag) { + return; + } + try { + deleteStmt = conn.createStatement(); + + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER) || dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) { + // conn.createStatement().executeUpdate( + // "drop table " + getTempTableName()); + deleteStmt.executeUpdate( + "drop table " + getTempTableName()); + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.ORACLE)) { + // conn.createStatement().executeUpdate( + // "delete " + getTempTableName()); + deleteStmt.executeUpdate( + "delete " + getTempTableName()); + } + } catch (SQLException sqle) { + throw sqle; + } finally { + try { + if(deleteStmt != null) + deleteStmt.close(); + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + + @Override + public String getCollectionId() { + return ""; + } + + @Override + public String generateMinIndexSql(String panelSql) { + // TODO Auto-generated method stub + return null; + } + + /** + * Returns input list's size. if the list is collection id, then collection + * set size, if the list is entire set, then total rows in dimension table + * if the list is enumeration, then size of enumeration set + * + * @return + * @throws I2B2DAOException + */ + @Override + public int getInputSize() throws I2B2DAOException { + + return 0; + + } + + @Override + public void setMaxIndex(int maxIndex) { + eidListType.setMax(maxIndex); + + } + + public String getTempTableName() { + String tempTableName = ""; + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.ORACLE)) { + tempTableName = this.getDbSchemaName() + + FactRelatedQueryHandler.TEMP_PARAM_TABLE; + } else { + tempTableName = this.getDbSchemaName() + + SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE; + } + return tempTableName; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/input/FactRelatedQueryHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/input/FactRelatedQueryHandler.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/input/FactRelatedQueryHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/input/FactRelatedQueryHandler.java index 29c7fbe9..fd7de56e --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/input/FactRelatedQueryHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/input/FactRelatedQueryHandler.java @@ -1,1493 +1,1493 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ - -package edu.harvard.i2b2.crc.dao.pdo.input; - -import java.io.IOException; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Vector; - -import javax.xml.datatype.XMLGregorianCalendar; -import javax.xml.stream.XMLStreamException; - -import org.apache.axis2.AxisFault; -import org.w3c.dom.Element; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.exception.StackTraceUtil; -import edu.harvard.i2b2.common.util.db.JDBCUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.common.util.xml.XMLOperatorLookup; -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.dao.pdo.I2B2PdoFactory; -import edu.harvard.i2b2.crc.dao.pdo.PdoQueryHandler; -import edu.harvard.i2b2.crc.dao.pdo.RPDRPdoFactory; -import edu.harvard.i2b2.crc.dao.pdo.filter.DimensionFilter; -import edu.harvard.i2b2.crc.dao.pdo.output.ConceptFactRelated; -import edu.harvard.i2b2.crc.dao.pdo.output.EidFactRelated; -import edu.harvard.i2b2.crc.dao.pdo.output.ModifierFactRelated; -import edu.harvard.i2b2.crc.dao.pdo.output.ObservationFactFactRelated; -import edu.harvard.i2b2.crc.dao.pdo.output.PatientFactRelated; -import edu.harvard.i2b2.crc.dao.pdo.output.PidFactRelated; -import edu.harvard.i2b2.crc.dao.pdo.output.ProviderFactRelated; -import edu.harvard.i2b2.crc.dao.pdo.output.VisitFactRelated; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.ConceptNotFoundException; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.OntologyException; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.UnitConverstionUtil; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; -import edu.harvard.i2b2.crc.datavo.ontology.DerivedFactColumnsType; -import edu.harvard.i2b2.crc.datavo.ontology.XmlValueType; -import edu.harvard.i2b2.crc.datavo.pdo.ObservationSet; -import edu.harvard.i2b2.crc.datavo.pdo.ObservationType; -import edu.harvard.i2b2.crc.datavo.pdo.query.ConstrainDateTimeType; -import edu.harvard.i2b2.crc.datavo.pdo.query.ConstrainDateType; -import edu.harvard.i2b2.crc.datavo.pdo.query.FilterListType; -import edu.harvard.i2b2.crc.datavo.pdo.query.InclusiveType; -import edu.harvard.i2b2.crc.datavo.pdo.query.InputOptionListType; -import edu.harvard.i2b2.crc.datavo.pdo.query.ItemType; -import edu.harvard.i2b2.crc.datavo.pdo.query.OutputOptionListType; -import edu.harvard.i2b2.crc.datavo.pdo.query.PanelType; -import edu.harvard.i2b2.crc.datavo.pdo.query.ItemType.ConstrainByDate; -import edu.harvard.i2b2.crc.datavo.pdo.query.PanelType.TotalItemOccurrences; -import edu.harvard.i2b2.crc.delegate.ontology.CallOntologyUtil; -import edu.harvard.i2b2.crc.util.ItemKeyUtil; -import edu.harvard.i2b2.crc.util.PMServiceAccountUtil; -import edu.harvard.i2b2.crc.util.ParamUtil; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - -/** - * Observation fact handler class for pdo request. This class uses given pdo - * request to generate pdo sql and build observation fact, unique list of fact's - * patient,concept code, visit and provider list - *

    - * This class handles fact related queries for both plain and table pdo $Id: - * FactRelatedQueryHandler.java,v 1.23 2008/06/10 14:59:04 rk903 Exp $ - * - * @author rkuttan - * @see VisitFactRelated - * @see ProviderFactRelated - * @see PatientFactRelated - * @see ObservationFactRelated - */ -public class FactRelatedQueryHandler extends CRCDAO implements -IFactRelatedQueryHandler { - /** Input option list from pdo request* */ - private InputOptionListType inputList = null; - - /** filter list from pdo request * */ - private FilterListType filterList = null; - - private OutputOptionListType outputOptionList = null; - - /** helper class for visit/event in pdo * */ - private VisitFactRelated visitFactRelated = null; - - /** helper class for observer/provider in pdo * */ - private ProviderFactRelated providerFactRelated = null; - - /** helper class for patient in pdo * */ - private PatientFactRelated patientFactRelated = null; - - /** helper class for concepts in pdo * */ - private ConceptFactRelated conceptFactRelated = null; - /** helper class for modifiers in pdo * */ - private ModifierFactRelated modifierFactRelated = null; - - private PidFactRelated pidFactRelated = null; - private EidFactRelated eidFactRelated = null; - - /** helper class for observation fact in pdo * */ - private ObservationFactFactRelated obsFactFactRelated = null; - /** to store unique patient number list present in fact* */ - List patientFactList = new Vector(); - /** to store unique concept code list present in fact* */ - List conceptFactList = new Vector(); - /** to store unique modifier code list present in fact* */ - List modifierFactList = new Vector(); - /** to store unique encounter number present in fact * */ - List visitFactList = new Vector(); - /** to store unique provider/observer id present in fact * */ - List providerFactList = new Vector(); - - /** Handler interface for input list, i.e Patient list or visit list * */ - private IInputOptionListHandler inputOptionListHandler = null; - - /** - * flag to see if concept filter is set, used in observation fact set - * element * - */ - private boolean checkFilter = false; - - /** - * field to keep track number of prepared statment parameters in the - * genereated pdo query* - */ - private int queryParameterCount = 0; - - private DataSourceLookup dataSourceLookup = null; - - // public static final String TEMP_PDO_OBSFACT_TABLE = "TEMP_PDO_OBSFACT"; - // public static final String TEMP_PDO_INPUTLIST_TABLE = - // "TEMP_PDO_INPUTLIST"; - public static final String TEMP_PARAM_TABLE = "GLOBAL_TEMP_PARAM_TABLE"; - public static final String TEMP_FACT_PARAM_TABLE = "GLOBAL_TEMP_FACT_PARAM_TABLE"; - - public static String TEMP_PDO_INPUTLIST_TABLE = "TEMP_PDO_INPUTLIST"; - - private List panelSqlList = new ArrayList(); - - private Map projectParamMap = null; - private Map modifierMetadataXmlMap = null; - private String requestVersion = ""; - - private String factTable = "observation_FACT"; - private boolean derivedFactTable = QueryProcessorUtil.getInstance().getDerivedFactTable(); - - private SecurityType security = null; - private String project = null; - - /** - * Constructor with parameter - * - * @param inputList - * @param filterList - * @param outputOptionList - */ - public FactRelatedQueryHandler(DataSourceLookup dataSourceLookup, - InputOptionListType inputList, FilterListType filterList, - OutputOptionListType outputOptionList) { - this.dataSourceLookup = dataSourceLookup; - setDbSchemaName(dataSourceLookup.getFullSchema()); - this.inputList = inputList; - this.filterList = filterList; - this.outputOptionList = outputOptionList; - - visitFactRelated = new VisitFactRelated(outputOptionList.getEventSet()); - providerFactRelated = new ProviderFactRelated(outputOptionList - .getObserverSetUsingFilterList()); - patientFactRelated = new PatientFactRelated(outputOptionList - .getPatientSet()); - conceptFactRelated = new ConceptFactRelated(outputOptionList - .getConceptSetUsingFilterList()); - modifierFactRelated = new ModifierFactRelated(outputOptionList - .getModifierSetUsingFilterList()); - obsFactFactRelated = new ObservationFactFactRelated(outputOptionList - .getObservationSet()); - pidFactRelated = new PidFactRelated(outputOptionList.getPidSet()); - eidFactRelated = new EidFactRelated(outputOptionList.getEidSet()); - - // check if concept filter present - if ((filterList != null) && (filterList.getPanel() != null) - && (filterList.getPanel().size() > 0)) { - checkFilter = true; - } - } - - @Override - public void setProjectParamMap(Map projectParamMap) { - this.projectParamMap = projectParamMap; - } - - @Override - public void setModifierMetadataXmlMap(Map modifierMetadataXmlMap) { - this.modifierMetadataXmlMap = modifierMetadataXmlMap; - } - - @Override - public void setRequestVersion(String requestVersion) { - this.requestVersion = requestVersion; - } - - - @Override - public List getPanelSqlList() { - return this.panelSqlList; - } - - - public void setSecurity(SecurityType security){ - this.security = security; - } - public void setProject(String project){ - this.project = project; - } - - public String getProject(){ - return this.project; - } - - public SecurityType getSecurity(){ - return this.security; - } - - - /** - * Function to build and execute pdo sql and build plain pdo's observation - * fact - * - * @return - * @throws Exception - */ - @Override - public List getPdoObservationFact() throws I2B2DAOException { - ResultSet resultSet = null; - Connection conn = null; - List observationFactSetList = new ArrayList(); - - try { - conn = this.getApplicationDataSource( - dataSourceLookup.getDataSource()).getConnection(); - - int sqlParamCount = 1; - boolean createTempTable = true; - if(checkFilter == false) { -//WAS if (filterList.getPanel().size() == 0) { - - if(derivedFactTable == true){ - - String sql= "select * from pg_tables where lower(tablename) = 'observation_fact'"; - sql += " and schemaname = '" + dataSourceLookup.getFullSchema() + "'"; - if(dataSourceLookup.getServerType().equals("ORACLE")){ - sql= "SELECT * FROM ALL_OBJECTS WHERE OBJECT_TYPE = 'TABLE' AND lower(OBJECT_NAME) = 'observation_fact'"; - sql += " and OWNER = '" + dataSourceLookup.getFullSchema() + "'"; - } - //log.info("no Filter sql: " + dataSourceLookup.getServerType() + " " + sql); - - PreparedStatement stmt1 = conn.prepareStatement(sql); - ResultSet resultSet1 = stmt1.executeQuery(); - - if(!(resultSet1.next())){ - resultSet1.close(); - createTempTable = false; - try { - JDBCUtil.closeJdbcResource(null, stmt1, conn); - } catch (SQLException e) { - log.error("Error trying to close connection:"+ e.getMessage()); - } - - return observationFactSetList; - } - - - } - // generate sql - String querySql = buildQuery(null, - PdoQueryHandler.PLAIN_PDO_TYPE); - log.debug("Executing sql PLAIN PDO[" + querySql + "]"); - panelSqlList.add(querySql); - if (createTempTable) { - if (inputOptionListHandler.isEnumerationSet()) { - inputOptionListHandler - .uploadEnumerationValueToTempTable(conn); - } - } - // execute fullsql - resultSet = executeQuery(conn, querySql, sqlParamCount); - // build facts - observationFactSetList.add(buildPDOFact(resultSet, "")); - } else { - for (PanelType panel : filterList.getPanel()) { - // generate sql - String querySql = buildQuery(panel, - PdoQueryHandler.PLAIN_PDO_TYPE); - if (querySql.trim().length() == 0 ) { - continue; - } - String defaultTableName = this.getDbSchemaName() + "observation_FACT" ; - // OMOP addition for multi domains - if(panel != null){ - if(derivedFactTable == true){ - if(panel.getItem().get(0).getFacttablecolumn().contains(".")){ - - String baseItemFactColumn = panel.getItem().get(0).getFacttablecolumn(); - int lastIndex = baseItemFactColumn.lastIndexOf("."); - String factTable = this.getDbSchemaName() + (baseItemFactColumn.substring(0, lastIndex)); - - DerivedFactColumnsType columns = getFactColumnsFromOntologyCell(panel.getItem().get(0).getItemKey()); - if(columns != null){ - if(columns.getDerivedFactTableColumn().size() > 1) { - // parse through solumns and build up replace string. - - Iterator it = columns.getDerivedFactTableColumn().iterator(); - String column = it.next(); - - lastIndex = column.lastIndexOf("."); - String table = this.getDbSchemaName() + (column.substring(0, lastIndex)); - - - factTable = "( select * from " + table; - while(it.hasNext()){ - column = it.next(); - - lastIndex = column.lastIndexOf("."); - table = this.getDbSchemaName() + (column.substring(0, lastIndex)); - - factTable += "\n UNION ALL \n" - + " select * from " + table; - } - factTable += " )"; - - } - } - log.debug("Parse columns " + factTable); - querySql=querySql.replaceAll(defaultTableName, factTable) ; - } - } - } - log.debug("Executing sql PLAIN PDO [" + querySql + "]"); - panelSqlList.add(querySql); - // execute fullsql - sqlParamCount = panel.getItem().size(); - if (panel.getInvert() == 1) { - sqlParamCount++; - } - if (createTempTable) { - if (inputOptionListHandler.isEnumerationSet()) { - inputOptionListHandler - .uploadEnumerationValueToTempTable(conn); - } - } - resultSet = executeQuery(conn, querySql, sqlParamCount); - - // build facts - observationFactSetList.add(buildPDOFact(resultSet, panel - .getName())); - createTempTable = false; - } - } - } catch (SQLException sqlEx) { - throw new I2B2DAOException("", sqlEx); - } catch (IOException ioEx) { - throw new I2B2DAOException("", ioEx); - } finally { - // IInputOptionListHandler inputOptionListHandler = PDOFactory - // .buildInputListHandler(inputList, dataSourceLookup); - try { - if(inputOptionListHandler != null && conn != null) - inputOptionListHandler.deleteTempTable(conn); - } catch (SQLException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - // close connection - try { - JDBCUtil.closeJdbcResource(null, null, conn); - } catch (SQLException e) { - log.error("Error trying to close connection", e); - } - } - - return observationFactSetList; - } - - /** - * Function to build and execute pdo sql and build table pdo's observation - * fact - * - * @return ObservationSet list - * @throws I2B2DAOException - */ - @Override - public List getTablePdoObservationFact() - throws I2B2DAOException { - Connection conn = null; - List observationSetList = new ArrayList(); - ResultSet resultSet = null; - - try { - conn = this.getApplicationDataSource( - dataSourceLookup.getDataSource()).getConnection(); - - int sqlParamCount = 1; - boolean createTempTable = true; - if(checkFilter == false) { -//WAS if (filterList.getPanel().size() == 0) { - - if(derivedFactTable == true){ - - String sql= "select * from pg_tables where lower(tablename) = 'observation_fact'"; - sql += " and schemaname = '" + dataSourceLookup.getFullSchema() + "'"; - if(dataSourceLookup.getServerType().equals("ORACLE")){ - sql= "SELECT * FROM ALL_OBJECTS WHERE OBJECT_TYPE = 'TABLE' AND lower(OBJECT_NAME) = 'observation_fact'"; - sql += " and OWNER = '" + dataSourceLookup.getFullSchema() + "'"; - } - //log.info("no Filter sql: " + dataSourceLookup.getServerType() + " " + sql); - PreparedStatement stmt1 = conn.prepareStatement(sql); - ResultSet resultSet1 = stmt1.executeQuery(); - - if(!(resultSet1.next())){ - resultSet1.close(); - createTempTable = false; - try { - JDBCUtil.closeJdbcResource(null, stmt1, conn); - } catch (SQLException e) { - log.error("Error trying to close connection:"+ e.getMessage()); - } - - return observationSetList; - } - - } - - // generate sql - String querySql = buildQuery(null, - PdoQueryHandler.PLAIN_PDO_TYPE); - - log.debug("Executing sql PLAIN PDO [" + querySql + "]"); - panelSqlList.add(querySql); - if (createTempTable) { - if (inputOptionListHandler.isEnumerationSet()) { - inputOptionListHandler - .uploadEnumerationValueToTempTable(conn); - } - } - // execute fullsql - resultSet = executeQuery(conn, querySql, sqlParamCount); - // build facts - observationSetList.add(buildPDOFact(resultSet, "")); - } else { - for (PanelType panel : filterList.getPanel()) { - - // generate sql - String querySql = buildQuery(panel, - PdoQueryHandler.TABLE_PDO_TYPE); - if (querySql.trim().length() == 0 ) { - continue; - } - log.debug("Executing sql[" + querySql + "]"); - // panelSqlList.add(querySql); - sqlParamCount = panel.getItem().size(); - if (panel.getInvert() == 1) { - sqlParamCount++; - } - if (createTempTable) { - if (inputOptionListHandler.isEnumerationSet()) { - inputOptionListHandler - .uploadEnumerationValueToTempTable(conn); - } - } - - String defaultTableName = this.getDbSchemaName() + "observation_FACT" ; - // OMOP addition for multi domains - if(panel != null){ - if(derivedFactTable == true){ - if(panel.getItem().get(0).getFacttablecolumn().contains(".")){ - - String baseItemFactColumn = panel.getItem().get(0).getFacttablecolumn(); - int lastIndex = baseItemFactColumn.lastIndexOf("."); - String factTable = this.getDbSchemaName() + (baseItemFactColumn.substring(0, lastIndex)); - - DerivedFactColumnsType columns = getFactColumnsFromOntologyCell(panel.getItem().get(0).getItemKey()); - if(columns != null){ - if(columns.getDerivedFactTableColumn().size() > 1) { - // parse through solumns and build up replace string. - - Iterator it = columns.getDerivedFactTableColumn().iterator(); - String column = it.next(); - - lastIndex = column.lastIndexOf("."); - String table = this.getDbSchemaName() + (column.substring(0, lastIndex)); - - - factTable = "( select * from " + table; - while(it.hasNext()){ - column = it.next(); - - lastIndex = column.lastIndexOf("."); - table = this.getDbSchemaName() + (column.substring(0, lastIndex)); - - factTable += "\n UNION ALL \n" - + " select * from " + table; - } - factTable += " )"; - - } - } - log.debug("Parse columns " + factTable); - querySql=querySql.replaceAll(defaultTableName, factTable) ; - } - } - } - - panelSqlList.add(querySql); - log.debug("TABLE PDO Executing sql [" + querySql + "]"); - // execute fullsql - resultSet = executeQuery(conn, querySql, sqlParamCount); - // build facts - observationSetList.add(buildTablePDOFact(resultSet, panel - .getName())); - // reset loading the temp table after first iteration - createTempTable = false; - } - } - } catch (SQLException sqlEx) { - log.error(sqlEx.getMessage()); - throw new I2B2DAOException("", sqlEx); - } catch (IOException ioEx) { - throw new I2B2DAOException("", ioEx); - } finally { - // IInputOptionListHandler inputOptionListHandler = PDOFactory - // .buildInputListHandler(inputList, dataSourceLookup); - try { - if(inputOptionListHandler != null && conn != null) - inputOptionListHandler.deleteTempTable(conn); - } catch (SQLException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - // close connection - try { - JDBCUtil.closeJdbcResource(null, null, conn); - } catch (SQLException e) { - log.error("Error trying to close connection", e); - } - } - - return observationSetList; - } - - /** - * Returns provider id, belong to the facts - * - * @return list of provider/observer id - */ - @Override - public List getProviderFactList() { - return providerFactList; - } - - /** - * Returns concept code belong to the facts - * - * @return - */ - @Override - public List getConceptFactList() { - return conceptFactList; - } - - /** - * Returns modifier code belong to the facts - * - * @return - */ - @Override - public List getModifierFactList() { - return modifierFactList; - } - - /** - * Returns patient number belong to the facts - * - * @return - */ - @Override - public List getPatientFactList() { - return patientFactList; - } - - /** - * Returns encounter number belong to the facts - * - * @return list of encounter number - */ - @Override - public List getVisitFactList() { - return visitFactList; - } - - @Override - public String buildTotalQuery(PanelType panel, String pdoType) - throws I2B2DAOException { - // TODO Auto-generated method stub - return buildQuery(panel, pdoType); - } - - /** - * This is the main function to build query for plain and table pdo request - * - * @param pdoType - * @return String - * @throws I2B2DAOException - */ - @Override - public String buildQuery(PanelType panel, String pdoType) - throws I2B2DAOException { - String obsFactSelectClause = null; -/* - * Original OMOP addition, superceded by mult domain solution. - if(panel != null){ - if(derivedFactTable == true){ - if(panel.getItem().get(0).getFacttablecolumn().contains(".")){ - - String factColumnName = panel.getItem().get(0).getFacttablecolumn(); - - int lastIndex = factColumnName.lastIndexOf("."); - setFactTable(factColumnName.substring(0, lastIndex)); - - - // if ((lastIndex+1) 1) { - int totOcurranceValue = totOccurance.getValue(); - String totOccuranceOperator = ">="; - if (totOccurance.getOperator() != null) { - String totOccuranceOperatorValue = totOccurance.getOperator() - .value(); - totOccuranceOperator = XMLOperatorLookup - .getComparisonOperatorFromAcronum(totOccuranceOperatorValue); - if (totOccuranceOperator == null) { - totOccuranceOperator = ">="; - } - } - - mainQuerySql += " AND seqNumber " + totOccuranceOperator - + totOcurranceValue; - } - - //check for version 1.5, if so return the fact without the duplicates in modifier_cd and instance num - //TODO Removed because not working in 1.6.05 - /* - if (this.requestVersion.startsWith("1.5")) { - mainQuerySql = " select * from (select *, rank() over(partition by obs_encounter_num, obs_patient_num,obs_concept_cd,obs_start_date,obs_provider_id order by obs_modifier_cd,obs_instance_num ) ordernum " + - " from ( " + mainQuerySql + ") ordersql ) ordersql1 where ordernum = 1 "; - } - */ - } - - if (this.outputOptionList.getObservationSet().getSelectionfilter()!= null) - { - //mainQuerySql = "with f as (" + mainQuerySql + ") select * from f where f.NVAL_NUM in (select min(nval_num) from OBSERVATION_FACT f2 where f2.PATIENT_NUM = f.PATIENT_NUM)"; - mainQuerySql = "with main_query as (" + mainQuerySql + ") select * from (select f1.*, " + - " rank() over(partition by obs_patient_num, obs_concept_cd order by "; - if (this.outputOptionList.getObservationSet().getSelectionfilter().value().equalsIgnoreCase("min_value")) - mainQuerySql += " obs_nval_num "; - else if (this.outputOptionList.getObservationSet().getSelectionfilter().value().equalsIgnoreCase("max_value")) - mainQuerySql += " obs_nval_num desc "; - else if (this.outputOptionList.getObservationSet().getSelectionfilter().value().equalsIgnoreCase("first_value")) - mainQuerySql += " obs_start_date "; - else if (this.outputOptionList.getObservationSet().getSelectionfilter().value().equalsIgnoreCase("last_value")) - mainQuerySql += " obs_start_date desc "; - else if (this.outputOptionList.getObservationSet().getSelectionfilter().value().equalsIgnoreCase("single_observation")) - mainQuerySql += " case when obs_modifier_cd = '@' then 1 else 0 end, obs_modifier_cd "; - else - mainQuerySql += " obs_start_date desc "; - - mainQuerySql += " ) rank " + - " from main_query f1 " ; - - if ((this.outputOptionList.getObservationSet().getSelectionfilter().value().equalsIgnoreCase("min_value")) || - (this.outputOptionList.getObservationSet().getSelectionfilter().value().equalsIgnoreCase("max_value")) ) - mainQuerySql += " where obs_nval_num is not null "; - - - if (this.outputOptionList.getObservationSet().getSelectionfilter().value().equalsIgnoreCase("last_n_values")) - { - mainQuerySql += ") f where f.rank < " + this.outputOptionList.getObservationSet().getValue(); - } else { - mainQuerySql += ") f where f.rank = 1 "; - } - - } - - return mainQuerySql; - } - - // ----------------------------------------- - // private helper functions start from here - // ----------------------------------------- - - /** - * Function to uses given select, join and where clause to build core pdo - * query, related to provider filter - * - * @param obsFactSelectClause - * @param tableLookupJoinClause - * @param fullWhereClause - * @return - */ - private String factQueryWithDimensionFilter(String obsFactSelectClause, - String tableLookupJoinClause, String fullWhereClause, - PanelType panel) throws I2B2Exception { - String factByProviderSql = ""; - int i = 0; - String panelName = null; - DateConstrainHandler dateConstrainHandler = new DateConstrainHandler( - dataSourceLookup); - - - - if (panel.getName() != null) { - panelName = JDBCUtil.escapeSingleQuote(panel.getName()); - } - - obsFactSelectClause += (", '" + panelName + "' panel_name "); - int totalItemOccurance = 0; - if (panel.getTotalItemOccurrences() != null) { - totalItemOccurance = panel.getTotalItemOccurrences().getValue(); - } - - int panelAccuracyScale = panel.getPanelAccuracyScale(); - //ignore panel accuracy scale value bcos the function is reverted - panelAccuracyScale = 0; - - String panelDateConstrain = null; - // generate panel date constrain - if (panel.getPanelDateFrom() != null || panel.getPanelDateTo() != null) { - panelDateConstrain = generatePanelDateConstrain( - dateConstrainHandler, panel.getPanelDateFrom(), panel - .getPanelDateTo()); - } - - for (ItemType item : panel.getItem()) { - - if (item.getFacttablecolumn() != null - || item.getDimColumnname() != null || item.getItemKey().toLowerCase().startsWith(ItemKeyUtil.ITEM_KEY_MASTERID)) { - - if (item.getDimTablename() != null) { - if (item.getDimTablename().equalsIgnoreCase("patient_dimension") || - item.getDimTablename().equalsIgnoreCase("visit_dimension")) { - continue; - } - } - - // read the first item - // ItemType item = panel.getItem().get(0); - - if (i == 0) { - i = 1; - } else { - if (totalItemOccurance > 1) { - factByProviderSql += "UNION ALL \n"; - } else { - factByProviderSql += "UNION \n"; - } - } - - factByProviderSql += (" SELECT " - + obsFactSelectClause + " FROM \n"); - - // check if the item key has "patient_set_coll_id:XXXX" as - // prefix - String itemKey = item.getItemKey(); - - if (itemKey.toLowerCase().startsWith(ItemKeyUtil.ITEM_KEY_PATIENT_SET)) { - String[] itemKeyParam = itemKey.split(":"); - factByProviderSql += (" select patient_num from " - + this.getDbSchemaName() - + "qt_patient_set_collection where patient_set_coll_id = " - + itemKeyParam[1] + " \n"); - item.setFacttablecolumn("patient_num"); - - } else if (itemKey.toLowerCase().startsWith(ItemKeyUtil.ITEM_KEY_PATIENT_ENCOUNTER_SET)) { // check - // if - // the - // item - // key - // has - // "patient_enc_coll_id:XXXX" - // as - // prefix - String[] itemKeyParam = itemKey.split(":"); - factByProviderSql += (" select encounter_num from " - + this.getDbSchemaName() - + "qt_patient_enc_collection where patient_enc_coll_id = " - + itemKeyParam[1] + " \n"); - item.setFacttablecolumn("encount_num"); - } else { - DimensionFilter providerFilter = new DimensionFilter(item, - this.getDbSchemaName(), dataSourceLookup); - factByProviderSql += (" " - + providerFilter.getFromSqlString() + " \n"); - - } - - String facttablecolumn = item.getFacttablecolumn(); - if(derivedFactTable == true){ - - if(item.getFacttablecolumn().contains(".")){ - String factColumnName = item.getFacttablecolumn(); - - int lastIndex = factColumnName.lastIndexOf("."); - facttablecolumn = (factColumnName.substring(lastIndex+1)); - - } - } - // OMOP WAS... - // factByProviderSql += ", " + this.getDbSchemaName() - // + "observation_FACT obs \n"; - factByProviderSql += ", " + this.getDbSchemaName() - + factTable + " obs \n"; - - String tempSqlClause = "",containsJoinSql = ""; - - String fullWhereClause1 = fullWhereClause - + (" AND obs." + facttablecolumn - + " = dimension." + facttablecolumn); - - //factByProviderSql += tableLookupJoinClause; - tempSqlClause += tableLookupJoinClause; - - //factByProviderSql += (" WHERE \n" + fullWhereClause1 + "\n"); - tempSqlClause += (" WHERE \n" + fullWhereClause1 + "\n"); - - //if output option has modifier option false, then select modifier_cd = '@' - if (outputOptionList.getObservationSet() != null && outputOptionList.getObservationSet().isWithmodifiers() == false) { - //factByProviderSql += (" AND obs.modifier_cd = '@' \n"); - tempSqlClause += (" AND obs.modifier_cd = '@' \n"); - } - - boolean itemConstrainValueFlag = false, modifierConstrainValueFlag = false; - //if modifier constrain is present in the request, then generate modifier constrain sql - ItemType.ConstrainByModifier modifierConstrain = item.getConstrainByModifier(); - if (modifierConstrain != null) { - // generate sql for item date constrain - ModifierConstrainsHandler modifierConstrainUtil = new ModifierConstrainsHandler(this.getDbSchemaName()); - String itemModifierConstrainSql = modifierConstrainUtil.constructModifierConstainClause(modifierConstrain); - if ((itemModifierConstrainSql != null) - && (itemModifierConstrainSql.length() > 0)) { - // factByProviderSql += (" AND (" + itemModifierConstrainSql + ")\n"); - tempSqlClause += (" AND (" + itemModifierConstrainSql + ")\n"); - } - if (modifierConstrain.getConstrainByValue() != null && - modifierConstrain.getConstrainByValue().size()>0) { - modifierConstrainValueFlag = true; - } - } - if (item.getConstrainByValue() != null - && item.getConstrainByValue().size() > 0) { - itemConstrainValueFlag = true; - } - - String unitCdSwitchClause = "", unitCdInClause = ""; - String modifierUnitCdSwitchClause = "", modifierUnitCdInClause = ""; - // if value constrain is given, generate value constrain sql - if (itemConstrainValueFlag || modifierConstrainValueFlag ) { - - //generate sql for unit_cd conversion - - if ( projectParamMap != null && projectParamMap.get(ParamUtil.CRC_ENABLE_UNITCD_CONVERSION) != null) { - String unitCdConversionFlag = (String)projectParamMap.get(ParamUtil.CRC_ENABLE_UNITCD_CONVERSION); - if (unitCdConversionFlag != null && unitCdConversionFlag.equalsIgnoreCase("ON")) { - if (item.getMetadataxml() != null && item.getMetadataxml().getContent().get(0) != null) { - Element valueMetadataElement = (Element)item.getMetadataxml().getContent().get(0); - UnitConverstionUtil unitConverstionUtil = new UnitConverstionUtil(); - unitCdSwitchClause = unitConverstionUtil.buildUnitCdSwitchClause(valueMetadataElement,false,"obs."); - unitCdInClause = unitConverstionUtil.buildUnitCdInClause(valueMetadataElement,""); - } - if (modifierConstrainValueFlag) { - XmlValueType xmlValueType = this.modifierMetadataXmlMap.get(item.getConstrainByModifier().getModifierKey()+item.getConstrainByModifier().getAppliedPath()); - if (xmlValueType != null && xmlValueType.getAny().get(0) != null) { - Element valueMetadataElement = xmlValueType.getAny().get(0); - UnitConverstionUtil unitConverstionUtil = new UnitConverstionUtil(); - modifierUnitCdSwitchClause = unitConverstionUtil.buildUnitCdSwitchClause(valueMetadataElement,false,"obs."); - modifierUnitCdInClause = unitConverstionUtil.buildUnitCdInClause(valueMetadataElement,""); - } else { - log.debug("No metadata xml for modifier key = " +item.getConstrainByModifier().getModifierKey() + " applied path " + item.getConstrainByModifier().getAppliedPath()); - } - } - } - } - } - - ValueConstrainsHandler vh = new ValueConstrainsHandler(); - - if (unitCdSwitchClause.length()>0) { - vh.setUnitCdConversionFlag(true, unitCdInClause, unitCdSwitchClause); - } - String[] valueConstrainSql = new String[] {"",""} ; - if (itemConstrainValueFlag) { - valueConstrainSql = vh - .constructValueConstainClause(item.getConstrainByValue(),this.dataSourceLookup.getServerType(),this.getDbSchemaName(),panelAccuracyScale); - if (panelAccuracyScale>0) { - containsJoinSql = valueConstrainSql[1]; - } - } - String[] modifierConstrainValueSql = new String[]{"",""}; - if (modifierConstrainValueFlag) { - if (modifierUnitCdInClause.length()>0) { - vh.setUnitCdConversionFlag(true, modifierUnitCdInClause, modifierUnitCdSwitchClause); - } - modifierConstrainValueSql = vh.constructValueConstainClause(buildItemValueConstrain(modifierConstrain.getConstrainByValue()),this.dataSourceLookup.getServerType(),this.getDbSchemaName(),panelAccuracyScale); - if (panelAccuracyScale>0) { - containsJoinSql += modifierConstrainValueSql[1]; - } - } - - if ((valueConstrainSql[0] != null - && valueConstrainSql[0].length() > 0) || (modifierConstrainValueSql[0] != null - && modifierConstrainValueSql[0].length() > 0)) { - // factByProviderSql += (" AND (" + valueConstrainSql + modifierConstrainValueSql + ")\n"); - tempSqlClause += (" AND (" + valueConstrainSql[0] + modifierConstrainValueSql[0] + ")\n"); - } - - factByProviderSql += containsJoinSql; - - factByProviderSql += tempSqlClause; - - // add start and end date constrains - - List constrainByDateList = item - .getConstrainByDate(); - for (ConstrainByDate constrainByDate : constrainByDateList) { - ConstrainDateType dateFrom = constrainByDate.getDateFrom(); - ConstrainDateType dateTo = constrainByDate.getDateTo(); - - String dateFromColumn = null, dateToColumn = null; - InclusiveType dateFromInclusive = null, dateToInclusive = null; - XMLGregorianCalendar dateFromValue = null, dateToValue = null; - String dateConstrainSql = null; - - if (dateFrom != null || dateTo != null) { - - if (dateFrom != null) { - dateFromInclusive = dateFrom.getInclusive(); - dateFromValue = dateFrom.getValue(); - dateFrom.getTime(); - if (dateFrom.getTime() != null - && dateFrom.getTime().name() != null - && dateFrom.getTime().name() - .equalsIgnoreCase( - ConstrainDateTimeType.END_DATE - .name())) { - dateFromColumn = "obs.end_date"; - } else { - dateFromColumn = "obs.start_date"; - } - - } - - if (dateTo != null) { - dateToInclusive = dateTo.getInclusive(); - dateToValue = dateTo.getValue(); - dateTo.getTime(); - if (dateTo.getTime() != null - && dateTo.getTime().name() != null - && dateTo.getTime().name() - .equalsIgnoreCase( - ConstrainDateTimeType.END_DATE - .name())) { - dateToColumn = "obs.end_date"; - } else { - dateToColumn = "obs.start_date"; - } - } - - dateConstrainSql = dateConstrainHandler - .constructDateConstrainClause(dateFromColumn, - dateToColumn, dateFromInclusive, - dateToInclusive, dateFromValue, - dateToValue); - if (dateConstrainSql != null) { - factByProviderSql += (" AND " + dateConstrainSql + "\n"); - } - - // item.getConstrainByModifier().get(0).getModifierName() - } - } - // generate panel date constrain - if (panelDateConstrain != null) { - factByProviderSql += (" AND (" + panelDateConstrain + ")\n"); - } - // item.getConstrainByModifier().get(0).getModifierName() - } - } - - if (factByProviderSql.trim().length()<10) { - return ""; - } - - int invert = panel.getInvert(); - - if (invert == 1) { - String invertSql = ("( SELECT " + obsFactSelectClause + " FROM \n"); - invertSql += " " + this.getDbSchemaName() - + getFactTable() + " obs \n"; - invertSql += tableLookupJoinClause; - invertSql += (" WHERE \n" + fullWhereClause + ")\n"); - factByProviderSql = invertSql + " MINUS \n " + "(" - + factByProviderSql + ")"; - } - - if (totalItemOccurance > 1) { - factByProviderSql = "SELECT a.*, rank() OVER (partition by obs_encounter_num,obs_patient_num,obs_start_date,obs_concept_cd order by rownum ) as seqNumber FROM (\n" - + factByProviderSql; - } else { - factByProviderSql = "SELECT a.* FROM (\n" + factByProviderSql; - } - - // factByProviderSql += " ORDER BY - // obs.patient_num,obs.start_date,obs.concept_cd,obs.rowid) a \n"; - if (this.requestVersion.startsWith("1.5")) { - factByProviderSql += " ) a \n"; - } else { - factByProviderSql += " ORDER BY 2,5,3,7,6) a \n"; - } - - return factByProviderSql; - } - - /** - * Function to uses given select, join and where clause to build core pdo - * query, without any filter (concept and provider) - * - * @param obsFactSelectClause - * @param tableLookupJoinClause - * @param fullWhereClause - * @return - */ - private String factQueryWithoutFilter(String obsFactSelectClause, - String tableLookupJoinClause, String fullWhereClause) { - String factSql = "SELECT b.*, ROWNUM rnum FROM (\n"; - // OMOP WAS - // factSql += (" SELECT " - // + obsFactSelectClause + " FROM " + this.getDbSchemaName() + "observation_FACT obs\n"); - - factSql += (" SELECT " - + obsFactSelectClause + " FROM " + this.getDbSchemaName() + getFactTable() + " obs\n"); - - factSql += tableLookupJoinClause; - - factSql += (" WHERE \n" + fullWhereClause + "\n"); - if (this.outputOptionList.getObservationSet().isWithmodifiers() == false) { - factSql += " AND obs.modifier_cd = '@' "; - } - factSql += " ORDER BY obs.patient_num,obs.start_date,obs.concept_cd,obs.instance_num,obs.modifier_cd,obs.rowid) b \n"; - - return factSql; - } - - /** - * Function to uses given select, join and where clause to build core pdo - * query, without any filter (concept and provider) - * - * @param obsFactSelectClause - * @param tableLookupJoinClause - * @param fullWhereClause - * @return - */ - private String postgresFactQueryWithoutFilter(String obsFactSelectClause, - String tableLookupJoinClause, String fullWhereClause) { - String factSql = "SELECT b.*, ROW_NUMBER() OVER (order by obs_patient_num) rnum FROM (\n"; - factSql += (" SELECT " - + obsFactSelectClause + " FROM " + this.getDbSchemaName() + getFactTable() + " obs\n"); - - factSql += tableLookupJoinClause; - - factSql += (" WHERE \n" + fullWhereClause + "\n"); - if (this.outputOptionList.getObservationSet().isWithmodifiers() == false) { - factSql += " AND obs.modifier_cd = '@' "; - } - - return factSql; - } - - /** - * Generate fact's join clause for table pdo - * - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return - */ - private String getLookupJoinClause(boolean detailFlag, boolean blobFlag, - boolean statusFlag) { - String joinClause = " "; - - if (detailFlag) { - joinClause = " left JOIN " - + this.getDbSchemaName() - + "code_lookup modifier_lookup \n" - + " ON (obs.modifier_cd = modifier_lookup.code_Cd AND modifier_lookup.column_cd = 'MODIFIER_CD') \n" - + " left JOIN " - + "(select name_char, concept_cd from " - + this.getDbSchemaName() - + "concept_dimension group by name_char, concept_cd) concept_lookup " - + "ON (obs.concept_cd = concept_lookup.concept_Cd) \n" - + " left JOIN " - + this.getDbSchemaName() - + "provider_dimension provider_lookup \n" - + " ON (obs.provider_id = provider_lookup.provider_id) \n" - + " left JOIN " - + this.getDbSchemaName() - + "code_lookup location_lookup \n" - + " ON (obs.location_Cd = location_lookup.code_Cd AND location_lookup.column_cd = 'LOCATION_CD') \n"; - } - - return joinClause; - } - - /** - * Helper function to build unique visit, patient, concept list from - * observation fact - * - * @param encounterNum - * @param patientNum - * @param providerId - * @param conceptCd - */ - private void addToDistinctList(String encounterNum, String patientNum, - String providerId, String conceptCd,String modifierCd) { - if (visitFactRelated.isSelected() || eidFactRelated.isSelected()) { - if (!visitFactList.contains(encounterNum)) { - visitFactList.add(encounterNum); - } - } - - if (patientFactRelated.isSelected() || pidFactRelated.isSelected()) { - if (!patientFactList.contains(patientNum)) { - patientFactList.add(patientNum); - } - } - - if (providerFactRelated.isSelected()) { - if (!providerFactList.contains(providerId)) { - providerFactList.add(providerId); - } - } - - if (conceptFactRelated.isSelected()) { - if (!conceptFactList.contains(conceptCd)) { - conceptFactList.add(conceptCd); - } - } - - if (modifierFactRelated.isSelected()) { - if (!modifierFactList.contains(modifierCd)) { - modifierFactList.add(modifierCd); - } - } - } - - /** - * Executive the given query - * - * @param conn - * @param querySql - * @return - * @throws SQLException - */ - private ResultSet executeQuery(Connection conn, String querySql, - int sqlParamCount) throws SQLException { - PreparedStatement stmt = conn.prepareStatement(querySql); - - if (inputOptionListHandler.isCollectionId()) { - for (int i = 1; i <= sqlParamCount; i++) { - stmt.setInt(i, Integer.parseInt(inputOptionListHandler - .getCollectionId())); - } - } - - ResultSet resultSet = stmt.executeQuery(); - - return resultSet; - - // JdbcRowSet rowSet = new JdbcRowSetImpl(resultSet); - // return rowSet; - } - - /** - * Build plain pdo's observation fact - * - * @param rowSet - * @return - * @throws SQLException - * @throws IOException - */ - private ObservationSet buildPDOFact(ResultSet rowSet, String panelName) - throws SQLException, IOException { - ObservationSet currentObsFactSetType = new ObservationSet(); - currentObsFactSetType.setPanelName(panelName); - - I2B2PdoFactory.ObservationFactBuilder observationFactBuilder = new I2B2PdoFactory().new ObservationFactBuilder( - obsFactFactRelated.isSelectDetail(), obsFactFactRelated - .isSelectBlob(), obsFactFactRelated.isSelectStatus(), dataSourceLookup.getServerType()); - - while (rowSet.next()) { - ObservationType obsFactType = null; - - obsFactType = observationFactBuilder.buildObservationSet(rowSet); - - if (obsFactFactRelated.isSelected()) { - currentObsFactSetType.getObservation().add(obsFactType); - } - - addToDistinctList(obsFactType.getEventId().getValue(), obsFactType - .getPatientId().getValue(), obsFactType.getObserverCd() - .getValue(), obsFactType.getConceptCd().getValue(),obsFactType.getModifierCd().getValue()); - } - - return currentObsFactSetType; - } - - /** - * Build table pdo observaton fact - * - * @param rowSet - * @return - * @throws SQLException - * @throws IOException - */ - private ObservationSet buildTablePDOFact(ResultSet rowSet, String panelName) - throws SQLException, IOException { - // obsFactSetTypeList = new - // Vector(); - boolean detailFlag = obsFactFactRelated.isSelectDetail(); - boolean booleanFlag = obsFactFactRelated.isSelectBlob(); - boolean statusFlag = obsFactFactRelated.isSelectStatus(); - ObservationSet currentObservationSet = new ObservationSet(); - currentObservationSet.setPanelName(panelName); - - RPDRPdoFactory.ObservationFactBuilder observationFactBuilder = new RPDRPdoFactory.ObservationFactBuilder( - detailFlag, booleanFlag, statusFlag); - - while (rowSet.next()) { - ObservationType observation = null; - observation = observationFactBuilder.buildObservationSet(rowSet, - "HIVE"); - - if (obsFactFactRelated.isSelected()) { - currentObservationSet.getObservation().add(observation); - } - - addToDistinctList(observation.getEventId().getValue(), observation.getPatientId().getValue(), - observation.getObserverCd().getValue(), observation.getConceptCd().getValue(),observation.getModifierCd().getValue()); - } - - return currentObservationSet; - } - - private List buildItemValueConstrain(List modifierConstrainList) { - List itemValueConstrainList = new ArrayList(); - for (ItemType.ConstrainByModifier.ConstrainByValue modifierValueConstrain : modifierConstrainList) { - ItemType.ConstrainByValue constrainByValue = new ItemType.ConstrainByValue(); - constrainByValue.setValueConstraint(modifierValueConstrain.getValueConstraint()); - constrainByValue.setValueOperator(modifierValueConstrain.getValueOperator()) ; - constrainByValue.setValueType(modifierValueConstrain.getValueType()); - constrainByValue.setValueUnitOfMeasure(modifierValueConstrain.getValueUnitOfMeasure()) ; - itemValueConstrainList.add(constrainByValue); - } - return itemValueConstrainList; - } - - private String generatePanelDateConstrain( - DateConstrainHandler dateConstrainHandler, - ConstrainDateType dateFrom, ConstrainDateType dateTo) - throws I2B2Exception { - - String dateFromColumn = null, dateToColumn = null; - InclusiveType dateFromInclusive = null, dateToInclusive = null; - XMLGregorianCalendar dateFromValue = null, dateToValue = null; - String dateConstrainSql = null; - - if (dateFrom != null || dateTo != null) { - - if (dateFrom != null) { - dateFromInclusive = dateFrom.getInclusive(); - dateFromValue = dateFrom.getValue(); - dateFrom.getTime(); - if (dateFrom.getTime() != null - && dateFrom.getTime().name() != null - && dateFrom.getTime().name().equalsIgnoreCase( - ConstrainDateTimeType.END_DATE.name())) { - dateFromColumn = "obs.end_date"; - } else { - dateFromColumn = "obs.start_date"; - } - - } - - if (dateTo != null) { - dateToInclusive = dateTo.getInclusive(); - dateToValue = dateTo.getValue(); - dateTo.getTime(); - if (dateTo.getTime() != null - && dateTo.getTime().name() != null - && dateTo.getTime().name().equalsIgnoreCase( - ConstrainDateTimeType.END_DATE.name())) { - dateToColumn = "obs.end_date"; - } else { - dateToColumn = "obs.start_date"; - } - } - - dateConstrainSql = dateConstrainHandler - .constructDateConstrainClause(dateFromColumn, dateToColumn, - dateFromInclusive, dateToInclusive, dateFromValue, - dateToValue); - } - return dateConstrainSql; - } - - public String getFactTable(){ - return this.factTable; - } - - public void setFactTable(String table){ - this.factTable = table; - } - - - protected DerivedFactColumnsType getFactColumnsFromOntologyCell(String itemKey) - throws ConceptNotFoundException, OntologyException { - DerivedFactColumnsType factColumns = new DerivedFactColumnsType(); - try { - - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - String ontologyUrl = qpUtil - .getCRCPropertyValue(QueryProcessorUtil.ONTOLOGYCELL_ROOT_WS_URL_PROPERTIES); - - SecurityType securityType = PMServiceAccountUtil - .getServiceSecurityType(dataSourceLookup.getDomainId()); - - factColumns = CallOntologyUtil.callGetFactColumns(itemKey, - securityType, dataSourceLookup.getProjectPath(), - ontologyUrl +"/getDerivedFactColumns"); - } catch (JAXBUtilException e) { - - log.error("Error while fetching metadata [" + itemKey - + "] from ontology ", e); - throw new OntologyException("Error while fetching metadata [" - + itemKey + "] from ontology " - + StackTraceUtil.getStackTrace(e)); - } catch (I2B2Exception e) { - log.error("Error while fetching metadata from ontology ", e); - throw new OntologyException("Error while fetching metadata [" - + itemKey + "] from ontology " - + StackTraceUtil.getStackTrace(e)); - } catch (AxisFault e) { - log.error("Error while fetching metadata from ontology ", e); - throw new OntologyException("Error while fetching metadata [" - + itemKey + "] from ontology " - + StackTraceUtil.getStackTrace(e)); - } catch (XMLStreamException e) { - log.error("Error while fetching metadata from ontology ", e); - throw new OntologyException("Error while fetching metadata [" - + itemKey + "] from ontology " - + StackTraceUtil.getStackTrace(e)); - } - - return factColumns; - } - - - +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ + +package edu.harvard.i2b2.crc.dao.pdo.input; + +import java.io.IOException; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Vector; + +import javax.xml.datatype.XMLGregorianCalendar; +import javax.xml.stream.XMLStreamException; + +import org.apache.axis2.AxisFault; +import org.w3c.dom.Element; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.exception.StackTraceUtil; +import edu.harvard.i2b2.common.util.db.JDBCUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.common.util.xml.XMLOperatorLookup; +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.dao.pdo.I2B2PdoFactory; +import edu.harvard.i2b2.crc.dao.pdo.PdoQueryHandler; +import edu.harvard.i2b2.crc.dao.pdo.RPDRPdoFactory; +import edu.harvard.i2b2.crc.dao.pdo.filter.DimensionFilter; +import edu.harvard.i2b2.crc.dao.pdo.output.ConceptFactRelated; +import edu.harvard.i2b2.crc.dao.pdo.output.EidFactRelated; +import edu.harvard.i2b2.crc.dao.pdo.output.ModifierFactRelated; +import edu.harvard.i2b2.crc.dao.pdo.output.ObservationFactFactRelated; +import edu.harvard.i2b2.crc.dao.pdo.output.PatientFactRelated; +import edu.harvard.i2b2.crc.dao.pdo.output.PidFactRelated; +import edu.harvard.i2b2.crc.dao.pdo.output.ProviderFactRelated; +import edu.harvard.i2b2.crc.dao.pdo.output.VisitFactRelated; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.ConceptNotFoundException; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.OntologyException; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.UnitConverstionUtil; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; +import edu.harvard.i2b2.crc.datavo.ontology.DerivedFactColumnsType; +import edu.harvard.i2b2.crc.datavo.ontology.XmlValueType; +import edu.harvard.i2b2.crc.datavo.pdo.ObservationSet; +import edu.harvard.i2b2.crc.datavo.pdo.ObservationType; +import edu.harvard.i2b2.crc.datavo.pdo.query.ConstrainDateTimeType; +import edu.harvard.i2b2.crc.datavo.pdo.query.ConstrainDateType; +import edu.harvard.i2b2.crc.datavo.pdo.query.FilterListType; +import edu.harvard.i2b2.crc.datavo.pdo.query.InclusiveType; +import edu.harvard.i2b2.crc.datavo.pdo.query.InputOptionListType; +import edu.harvard.i2b2.crc.datavo.pdo.query.ItemType; +import edu.harvard.i2b2.crc.datavo.pdo.query.OutputOptionListType; +import edu.harvard.i2b2.crc.datavo.pdo.query.PanelType; +import edu.harvard.i2b2.crc.datavo.pdo.query.ItemType.ConstrainByDate; +import edu.harvard.i2b2.crc.datavo.pdo.query.PanelType.TotalItemOccurrences; +import edu.harvard.i2b2.crc.delegate.ontology.CallOntologyUtil; +import edu.harvard.i2b2.crc.util.ItemKeyUtil; +import edu.harvard.i2b2.crc.util.PMServiceAccountUtil; +import edu.harvard.i2b2.crc.util.ParamUtil; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + +/** + * Observation fact handler class for pdo request. This class uses given pdo + * request to generate pdo sql and build observation fact, unique list of fact's + * patient,concept code, visit and provider list + *

    + * This class handles fact related queries for both plain and table pdo $Id: + * FactRelatedQueryHandler.java,v 1.23 2008/06/10 14:59:04 rk903 Exp $ + * + * @author rkuttan + * @see VisitFactRelated + * @see ProviderFactRelated + * @see PatientFactRelated + * @see ObservationFactRelated + */ +public class FactRelatedQueryHandler extends CRCDAO implements +IFactRelatedQueryHandler { + /** Input option list from pdo request* */ + private InputOptionListType inputList = null; + + /** filter list from pdo request * */ + private FilterListType filterList = null; + + private OutputOptionListType outputOptionList = null; + + /** helper class for visit/event in pdo * */ + private VisitFactRelated visitFactRelated = null; + + /** helper class for observer/provider in pdo * */ + private ProviderFactRelated providerFactRelated = null; + + /** helper class for patient in pdo * */ + private PatientFactRelated patientFactRelated = null; + + /** helper class for concepts in pdo * */ + private ConceptFactRelated conceptFactRelated = null; + /** helper class for modifiers in pdo * */ + private ModifierFactRelated modifierFactRelated = null; + + private PidFactRelated pidFactRelated = null; + private EidFactRelated eidFactRelated = null; + + /** helper class for observation fact in pdo * */ + private ObservationFactFactRelated obsFactFactRelated = null; + /** to store unique patient number list present in fact* */ + List patientFactList = new Vector(); + /** to store unique concept code list present in fact* */ + List conceptFactList = new Vector(); + /** to store unique modifier code list present in fact* */ + List modifierFactList = new Vector(); + /** to store unique encounter number present in fact * */ + List visitFactList = new Vector(); + /** to store unique provider/observer id present in fact * */ + List providerFactList = new Vector(); + + /** Handler interface for input list, i.e Patient list or visit list * */ + private IInputOptionListHandler inputOptionListHandler = null; + + /** + * flag to see if concept filter is set, used in observation fact set + * element * + */ + private boolean checkFilter = false; + + /** + * field to keep track number of prepared statment parameters in the + * genereated pdo query* + */ + private int queryParameterCount = 0; + + private DataSourceLookup dataSourceLookup = null; + + // public static final String TEMP_PDO_OBSFACT_TABLE = "TEMP_PDO_OBSFACT"; + // public static final String TEMP_PDO_INPUTLIST_TABLE = + // "TEMP_PDO_INPUTLIST"; + public static final String TEMP_PARAM_TABLE = "GLOBAL_TEMP_PARAM_TABLE"; + public static final String TEMP_FACT_PARAM_TABLE = "GLOBAL_TEMP_FACT_PARAM_TABLE"; + + public static String TEMP_PDO_INPUTLIST_TABLE = "TEMP_PDO_INPUTLIST"; + + private List panelSqlList = new ArrayList(); + + private Map projectParamMap = null; + private Map modifierMetadataXmlMap = null; + private String requestVersion = ""; + + private String factTable = "observation_FACT"; + private boolean derivedFactTable = QueryProcessorUtil.getInstance().getDerivedFactTable(); + + private SecurityType security = null; + private String project = null; + + /** + * Constructor with parameter + * + * @param inputList + * @param filterList + * @param outputOptionList + */ + public FactRelatedQueryHandler(DataSourceLookup dataSourceLookup, + InputOptionListType inputList, FilterListType filterList, + OutputOptionListType outputOptionList) { + this.dataSourceLookup = dataSourceLookup; + setDbSchemaName(dataSourceLookup.getFullSchema()); + this.inputList = inputList; + this.filterList = filterList; + this.outputOptionList = outputOptionList; + + visitFactRelated = new VisitFactRelated(outputOptionList.getEventSet()); + providerFactRelated = new ProviderFactRelated(outputOptionList + .getObserverSetUsingFilterList()); + patientFactRelated = new PatientFactRelated(outputOptionList + .getPatientSet()); + conceptFactRelated = new ConceptFactRelated(outputOptionList + .getConceptSetUsingFilterList()); + modifierFactRelated = new ModifierFactRelated(outputOptionList + .getModifierSetUsingFilterList()); + obsFactFactRelated = new ObservationFactFactRelated(outputOptionList + .getObservationSet()); + pidFactRelated = new PidFactRelated(outputOptionList.getPidSet()); + eidFactRelated = new EidFactRelated(outputOptionList.getEidSet()); + + // check if concept filter present + if ((filterList != null) && (filterList.getPanel() != null) + && (filterList.getPanel().size() > 0)) { + checkFilter = true; + } + } + + @Override + public void setProjectParamMap(Map projectParamMap) { + this.projectParamMap = projectParamMap; + } + + @Override + public void setModifierMetadataXmlMap(Map modifierMetadataXmlMap) { + this.modifierMetadataXmlMap = modifierMetadataXmlMap; + } + + @Override + public void setRequestVersion(String requestVersion) { + this.requestVersion = requestVersion; + } + + + @Override + public List getPanelSqlList() { + return this.panelSqlList; + } + + + public void setSecurity(SecurityType security){ + this.security = security; + } + public void setProject(String project){ + this.project = project; + } + + public String getProject(){ + return this.project; + } + + public SecurityType getSecurity(){ + return this.security; + } + + + /** + * Function to build and execute pdo sql and build plain pdo's observation + * fact + * + * @return + * @throws Exception + */ + @Override + public List getPdoObservationFact() throws I2B2DAOException { + ResultSet resultSet = null; + Connection conn = null; + List observationFactSetList = new ArrayList(); + + try { + conn = this.getApplicationDataSource( + dataSourceLookup.getDataSource()).getConnection(); + + int sqlParamCount = 1; + boolean createTempTable = true; + if(checkFilter == false) { +//WAS if (filterList.getPanel().size() == 0) { + + if(derivedFactTable == true){ + + String sql= "select * from pg_tables where lower(tablename) = 'observation_fact'"; + sql += " and schemaname = '" + dataSourceLookup.getFullSchema() + "'"; + if(dataSourceLookup.getServerType().equals("ORACLE")){ + sql= "SELECT * FROM ALL_OBJECTS WHERE OBJECT_TYPE = 'TABLE' AND lower(OBJECT_NAME) = 'observation_fact'"; + sql += " and OWNER = '" + dataSourceLookup.getFullSchema() + "'"; + } + //log.info("no Filter sql: " + dataSourceLookup.getServerType() + " " + sql); + + PreparedStatement stmt1 = conn.prepareStatement(sql); + ResultSet resultSet1 = stmt1.executeQuery(); + + if(!(resultSet1.next())){ + resultSet1.close(); + createTempTable = false; + try { + JDBCUtil.closeJdbcResource(null, stmt1, conn); + } catch (SQLException e) { + log.error("Error trying to close connection:"+ e.getMessage()); + } + + return observationFactSetList; + } + + + } + // generate sql + String querySql = buildQuery(null, + PdoQueryHandler.PLAIN_PDO_TYPE); + log.debug("Executing sql PLAIN PDO[" + querySql + "]"); + panelSqlList.add(querySql); + if (createTempTable) { + if (inputOptionListHandler.isEnumerationSet()) { + inputOptionListHandler + .uploadEnumerationValueToTempTable(conn); + } + } + // execute fullsql + resultSet = executeQuery(conn, querySql, sqlParamCount); + // build facts + observationFactSetList.add(buildPDOFact(resultSet, "")); + } else { + for (PanelType panel : filterList.getPanel()) { + // generate sql + String querySql = buildQuery(panel, + PdoQueryHandler.PLAIN_PDO_TYPE); + if (querySql.trim().length() == 0 ) { + continue; + } + String defaultTableName = this.getDbSchemaName() + "observation_FACT" ; + // OMOP addition for multi domains + if(panel != null){ + if(derivedFactTable == true){ + if(panel.getItem().get(0).getFacttablecolumn().contains(".")){ + + String baseItemFactColumn = panel.getItem().get(0).getFacttablecolumn(); + int lastIndex = baseItemFactColumn.lastIndexOf("."); + String factTable = this.getDbSchemaName() + (baseItemFactColumn.substring(0, lastIndex)); + + DerivedFactColumnsType columns = getFactColumnsFromOntologyCell(panel.getItem().get(0).getItemKey()); + if(columns != null){ + if(columns.getDerivedFactTableColumn().size() > 1) { + // parse through solumns and build up replace string. + + Iterator it = columns.getDerivedFactTableColumn().iterator(); + String column = it.next(); + + lastIndex = column.lastIndexOf("."); + String table = this.getDbSchemaName() + (column.substring(0, lastIndex)); + + + factTable = "( select * from " + table; + while(it.hasNext()){ + column = it.next(); + + lastIndex = column.lastIndexOf("."); + table = this.getDbSchemaName() + (column.substring(0, lastIndex)); + + factTable += "\n UNION ALL \n" + + " select * from " + table; + } + factTable += " )"; + + } + } + log.debug("Parse columns " + factTable); + querySql=querySql.replaceAll(defaultTableName, factTable) ; + } + } + } + log.debug("Executing sql PLAIN PDO [" + querySql + "]"); + panelSqlList.add(querySql); + // execute fullsql + sqlParamCount = panel.getItem().size(); + if (panel.getInvert() == 1) { + sqlParamCount++; + } + if (createTempTable) { + if (inputOptionListHandler.isEnumerationSet()) { + inputOptionListHandler + .uploadEnumerationValueToTempTable(conn); + } + } + resultSet = executeQuery(conn, querySql, sqlParamCount); + + // build facts + observationFactSetList.add(buildPDOFact(resultSet, panel + .getName())); + createTempTable = false; + } + } + } catch (SQLException sqlEx) { + throw new I2B2DAOException("", sqlEx); + } catch (IOException ioEx) { + throw new I2B2DAOException("", ioEx); + } finally { + // IInputOptionListHandler inputOptionListHandler = PDOFactory + // .buildInputListHandler(inputList, dataSourceLookup); + try { + if(inputOptionListHandler != null && conn != null) + inputOptionListHandler.deleteTempTable(conn); + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + // close connection + try { + JDBCUtil.closeJdbcResource(null, null, conn); + } catch (SQLException e) { + log.error("Error trying to close connection", e); + } + } + + return observationFactSetList; + } + + /** + * Function to build and execute pdo sql and build table pdo's observation + * fact + * + * @return ObservationSet list + * @throws I2B2DAOException + */ + @Override + public List getTablePdoObservationFact() + throws I2B2DAOException { + Connection conn = null; + List observationSetList = new ArrayList(); + ResultSet resultSet = null; + + try { + conn = this.getApplicationDataSource( + dataSourceLookup.getDataSource()).getConnection(); + + int sqlParamCount = 1; + boolean createTempTable = true; + if(checkFilter == false) { +//WAS if (filterList.getPanel().size() == 0) { + + if(derivedFactTable == true){ + + String sql= "select * from pg_tables where lower(tablename) = 'observation_fact'"; + sql += " and schemaname = '" + dataSourceLookup.getFullSchema() + "'"; + if(dataSourceLookup.getServerType().equals("ORACLE")){ + sql= "SELECT * FROM ALL_OBJECTS WHERE OBJECT_TYPE = 'TABLE' AND lower(OBJECT_NAME) = 'observation_fact'"; + sql += " and OWNER = '" + dataSourceLookup.getFullSchema() + "'"; + } + //log.info("no Filter sql: " + dataSourceLookup.getServerType() + " " + sql); + PreparedStatement stmt1 = conn.prepareStatement(sql); + ResultSet resultSet1 = stmt1.executeQuery(); + + if(!(resultSet1.next())){ + resultSet1.close(); + createTempTable = false; + try { + JDBCUtil.closeJdbcResource(null, stmt1, conn); + } catch (SQLException e) { + log.error("Error trying to close connection:"+ e.getMessage()); + } + + return observationSetList; + } + + } + + // generate sql + String querySql = buildQuery(null, + PdoQueryHandler.PLAIN_PDO_TYPE); + + log.debug("Executing sql PLAIN PDO [" + querySql + "]"); + panelSqlList.add(querySql); + if (createTempTable) { + if (inputOptionListHandler.isEnumerationSet()) { + inputOptionListHandler + .uploadEnumerationValueToTempTable(conn); + } + } + // execute fullsql + resultSet = executeQuery(conn, querySql, sqlParamCount); + // build facts + observationSetList.add(buildPDOFact(resultSet, "")); + } else { + for (PanelType panel : filterList.getPanel()) { + + // generate sql + String querySql = buildQuery(panel, + PdoQueryHandler.TABLE_PDO_TYPE); + if (querySql.trim().length() == 0 ) { + continue; + } + log.debug("Executing sql[" + querySql + "]"); + // panelSqlList.add(querySql); + sqlParamCount = panel.getItem().size(); + if (panel.getInvert() == 1) { + sqlParamCount++; + } + if (createTempTable) { + if (inputOptionListHandler.isEnumerationSet()) { + inputOptionListHandler + .uploadEnumerationValueToTempTable(conn); + } + } + + String defaultTableName = this.getDbSchemaName() + "observation_FACT" ; + // OMOP addition for multi domains + if(panel != null){ + if(derivedFactTable == true){ + if(panel.getItem().get(0).getFacttablecolumn().contains(".")){ + + String baseItemFactColumn = panel.getItem().get(0).getFacttablecolumn(); + int lastIndex = baseItemFactColumn.lastIndexOf("."); + String factTable = this.getDbSchemaName() + (baseItemFactColumn.substring(0, lastIndex)); + + DerivedFactColumnsType columns = getFactColumnsFromOntologyCell(panel.getItem().get(0).getItemKey()); + if(columns != null){ + if(columns.getDerivedFactTableColumn().size() > 1) { + // parse through solumns and build up replace string. + + Iterator it = columns.getDerivedFactTableColumn().iterator(); + String column = it.next(); + + lastIndex = column.lastIndexOf("."); + String table = this.getDbSchemaName() + (column.substring(0, lastIndex)); + + + factTable = "( select * from " + table; + while(it.hasNext()){ + column = it.next(); + + lastIndex = column.lastIndexOf("."); + table = this.getDbSchemaName() + (column.substring(0, lastIndex)); + + factTable += "\n UNION ALL \n" + + " select * from " + table; + } + factTable += " )"; + + } + } + log.debug("Parse columns " + factTable); + querySql=querySql.replaceAll(defaultTableName, factTable) ; + } + } + } + + panelSqlList.add(querySql); + log.debug("TABLE PDO Executing sql [" + querySql + "]"); + // execute fullsql + resultSet = executeQuery(conn, querySql, sqlParamCount); + // build facts + observationSetList.add(buildTablePDOFact(resultSet, panel + .getName())); + // reset loading the temp table after first iteration + createTempTable = false; + } + } + } catch (SQLException sqlEx) { + log.error(sqlEx.getMessage()); + throw new I2B2DAOException("", sqlEx); + } catch (IOException ioEx) { + throw new I2B2DAOException("", ioEx); + } finally { + // IInputOptionListHandler inputOptionListHandler = PDOFactory + // .buildInputListHandler(inputList, dataSourceLookup); + try { + if(inputOptionListHandler != null && conn != null) + inputOptionListHandler.deleteTempTable(conn); + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + // close connection + try { + JDBCUtil.closeJdbcResource(null, null, conn); + } catch (SQLException e) { + log.error("Error trying to close connection", e); + } + } + + return observationSetList; + } + + /** + * Returns provider id, belong to the facts + * + * @return list of provider/observer id + */ + @Override + public List getProviderFactList() { + return providerFactList; + } + + /** + * Returns concept code belong to the facts + * + * @return + */ + @Override + public List getConceptFactList() { + return conceptFactList; + } + + /** + * Returns modifier code belong to the facts + * + * @return + */ + @Override + public List getModifierFactList() { + return modifierFactList; + } + + /** + * Returns patient number belong to the facts + * + * @return + */ + @Override + public List getPatientFactList() { + return patientFactList; + } + + /** + * Returns encounter number belong to the facts + * + * @return list of encounter number + */ + @Override + public List getVisitFactList() { + return visitFactList; + } + + @Override + public String buildTotalQuery(PanelType panel, String pdoType) + throws I2B2DAOException { + // TODO Auto-generated method stub + return buildQuery(panel, pdoType); + } + + /** + * This is the main function to build query for plain and table pdo request + * + * @param pdoType + * @return String + * @throws I2B2DAOException + */ + @Override + public String buildQuery(PanelType panel, String pdoType) + throws I2B2DAOException { + String obsFactSelectClause = null; +/* + * Original OMOP addition, superceded by mult domain solution. + if(panel != null){ + if(derivedFactTable == true){ + if(panel.getItem().get(0).getFacttablecolumn().contains(".")){ + + String factColumnName = panel.getItem().get(0).getFacttablecolumn(); + + int lastIndex = factColumnName.lastIndexOf("."); + setFactTable(factColumnName.substring(0, lastIndex)); + + + // if ((lastIndex+1) 1) { + int totOcurranceValue = totOccurance.getValue(); + String totOccuranceOperator = ">="; + if (totOccurance.getOperator() != null) { + String totOccuranceOperatorValue = totOccurance.getOperator() + .value(); + totOccuranceOperator = XMLOperatorLookup + .getComparisonOperatorFromAcronum(totOccuranceOperatorValue); + if (totOccuranceOperator == null) { + totOccuranceOperator = ">="; + } + } + + mainQuerySql += " AND seqNumber " + totOccuranceOperator + + totOcurranceValue; + } + + //check for version 1.5, if so return the fact without the duplicates in modifier_cd and instance num + //TODO Removed because not working in 1.6.05 + /* + if (this.requestVersion.startsWith("1.5")) { + mainQuerySql = " select * from (select *, rank() over(partition by obs_encounter_num, obs_patient_num,obs_concept_cd,obs_start_date,obs_provider_id order by obs_modifier_cd,obs_instance_num ) ordernum " + + " from ( " + mainQuerySql + ") ordersql ) ordersql1 where ordernum = 1 "; + } + */ + } + + if (this.outputOptionList.getObservationSet().getSelectionfilter()!= null) + { + //mainQuerySql = "with f as (" + mainQuerySql + ") select * from f where f.NVAL_NUM in (select min(nval_num) from OBSERVATION_FACT f2 where f2.PATIENT_NUM = f.PATIENT_NUM)"; + mainQuerySql = "with main_query as (" + mainQuerySql + ") select * from (select f1.*, " + + " rank() over(partition by obs_patient_num, obs_concept_cd order by "; + if (this.outputOptionList.getObservationSet().getSelectionfilter().value().equalsIgnoreCase("min_value")) + mainQuerySql += " obs_nval_num "; + else if (this.outputOptionList.getObservationSet().getSelectionfilter().value().equalsIgnoreCase("max_value")) + mainQuerySql += " obs_nval_num desc "; + else if (this.outputOptionList.getObservationSet().getSelectionfilter().value().equalsIgnoreCase("first_value")) + mainQuerySql += " obs_start_date "; + else if (this.outputOptionList.getObservationSet().getSelectionfilter().value().equalsIgnoreCase("last_value")) + mainQuerySql += " obs_start_date desc "; + else if (this.outputOptionList.getObservationSet().getSelectionfilter().value().equalsIgnoreCase("single_observation")) + mainQuerySql += " case when obs_modifier_cd = '@' then 1 else 0 end, obs_modifier_cd "; + else + mainQuerySql += " obs_start_date desc "; + + mainQuerySql += " ) rank " + + " from main_query f1 " ; + + if ((this.outputOptionList.getObservationSet().getSelectionfilter().value().equalsIgnoreCase("min_value")) || + (this.outputOptionList.getObservationSet().getSelectionfilter().value().equalsIgnoreCase("max_value")) ) + mainQuerySql += " where obs_nval_num is not null "; + + + if (this.outputOptionList.getObservationSet().getSelectionfilter().value().equalsIgnoreCase("last_n_values")) + { + mainQuerySql += ") f where f.rank < " + this.outputOptionList.getObservationSet().getValue(); + } else { + mainQuerySql += ") f where f.rank = 1 "; + } + + } + + return mainQuerySql; + } + + // ----------------------------------------- + // private helper functions start from here + // ----------------------------------------- + + /** + * Function to uses given select, join and where clause to build core pdo + * query, related to provider filter + * + * @param obsFactSelectClause + * @param tableLookupJoinClause + * @param fullWhereClause + * @return + */ + private String factQueryWithDimensionFilter(String obsFactSelectClause, + String tableLookupJoinClause, String fullWhereClause, + PanelType panel) throws I2B2Exception { + String factByProviderSql = ""; + int i = 0; + String panelName = null; + DateConstrainHandler dateConstrainHandler = new DateConstrainHandler( + dataSourceLookup); + + + + if (panel.getName() != null) { + panelName = JDBCUtil.escapeSingleQuote(panel.getName()); + } + + obsFactSelectClause += (", '" + panelName + "' panel_name "); + int totalItemOccurance = 0; + if (panel.getTotalItemOccurrences() != null) { + totalItemOccurance = panel.getTotalItemOccurrences().getValue(); + } + + int panelAccuracyScale = panel.getPanelAccuracyScale(); + //ignore panel accuracy scale value bcos the function is reverted + panelAccuracyScale = 0; + + String panelDateConstrain = null; + // generate panel date constrain + if (panel.getPanelDateFrom() != null || panel.getPanelDateTo() != null) { + panelDateConstrain = generatePanelDateConstrain( + dateConstrainHandler, panel.getPanelDateFrom(), panel + .getPanelDateTo()); + } + + for (ItemType item : panel.getItem()) { + + if (item.getFacttablecolumn() != null + || item.getDimColumnname() != null || item.getItemKey().toLowerCase().startsWith(ItemKeyUtil.ITEM_KEY_MASTERID)) { + + if (item.getDimTablename() != null) { + if (item.getDimTablename().equalsIgnoreCase("patient_dimension") || + item.getDimTablename().equalsIgnoreCase("visit_dimension")) { + continue; + } + } + + // read the first item + // ItemType item = panel.getItem().get(0); + + if (i == 0) { + i = 1; + } else { + if (totalItemOccurance > 1) { + factByProviderSql += "UNION ALL \n"; + } else { + factByProviderSql += "UNION \n"; + } + } + + factByProviderSql += (" SELECT " + + obsFactSelectClause + " FROM \n"); + + // check if the item key has "patient_set_coll_id:XXXX" as + // prefix + String itemKey = item.getItemKey(); + + if (itemKey.toLowerCase().startsWith(ItemKeyUtil.ITEM_KEY_PATIENT_SET)) { + String[] itemKeyParam = itemKey.split(":"); + factByProviderSql += (" select patient_num from " + + this.getDbSchemaName() + + "qt_patient_set_collection where patient_set_coll_id = " + + itemKeyParam[1] + " \n"); + item.setFacttablecolumn("patient_num"); + + } else if (itemKey.toLowerCase().startsWith(ItemKeyUtil.ITEM_KEY_PATIENT_ENCOUNTER_SET)) { // check + // if + // the + // item + // key + // has + // "patient_enc_coll_id:XXXX" + // as + // prefix + String[] itemKeyParam = itemKey.split(":"); + factByProviderSql += (" select encounter_num from " + + this.getDbSchemaName() + + "qt_patient_enc_collection where patient_enc_coll_id = " + + itemKeyParam[1] + " \n"); + item.setFacttablecolumn("encount_num"); + } else { + DimensionFilter providerFilter = new DimensionFilter(item, + this.getDbSchemaName(), dataSourceLookup); + factByProviderSql += (" " + + providerFilter.getFromSqlString() + " \n"); + + } + + String facttablecolumn = item.getFacttablecolumn(); + if(derivedFactTable == true){ + + if(item.getFacttablecolumn().contains(".")){ + String factColumnName = item.getFacttablecolumn(); + + int lastIndex = factColumnName.lastIndexOf("."); + facttablecolumn = (factColumnName.substring(lastIndex+1)); + + } + } + // OMOP WAS... + // factByProviderSql += ", " + this.getDbSchemaName() + // + "observation_FACT obs \n"; + factByProviderSql += ", " + this.getDbSchemaName() + + factTable + " obs \n"; + + String tempSqlClause = "",containsJoinSql = ""; + + String fullWhereClause1 = fullWhereClause + + (" AND obs." + facttablecolumn + + " = dimension." + facttablecolumn); + + //factByProviderSql += tableLookupJoinClause; + tempSqlClause += tableLookupJoinClause; + + //factByProviderSql += (" WHERE \n" + fullWhereClause1 + "\n"); + tempSqlClause += (" WHERE \n" + fullWhereClause1 + "\n"); + + //if output option has modifier option false, then select modifier_cd = '@' + if (outputOptionList.getObservationSet() != null && outputOptionList.getObservationSet().isWithmodifiers() == false) { + //factByProviderSql += (" AND obs.modifier_cd = '@' \n"); + tempSqlClause += (" AND obs.modifier_cd = '@' \n"); + } + + boolean itemConstrainValueFlag = false, modifierConstrainValueFlag = false; + //if modifier constrain is present in the request, then generate modifier constrain sql + ItemType.ConstrainByModifier modifierConstrain = item.getConstrainByModifier(); + if (modifierConstrain != null) { + // generate sql for item date constrain + ModifierConstrainsHandler modifierConstrainUtil = new ModifierConstrainsHandler(this.getDbSchemaName()); + String itemModifierConstrainSql = modifierConstrainUtil.constructModifierConstainClause(modifierConstrain); + if ((itemModifierConstrainSql != null) + && (itemModifierConstrainSql.length() > 0)) { + // factByProviderSql += (" AND (" + itemModifierConstrainSql + ")\n"); + tempSqlClause += (" AND (" + itemModifierConstrainSql + ")\n"); + } + if (modifierConstrain.getConstrainByValue() != null && + modifierConstrain.getConstrainByValue().size()>0) { + modifierConstrainValueFlag = true; + } + } + if (item.getConstrainByValue() != null + && item.getConstrainByValue().size() > 0) { + itemConstrainValueFlag = true; + } + + String unitCdSwitchClause = "", unitCdInClause = ""; + String modifierUnitCdSwitchClause = "", modifierUnitCdInClause = ""; + // if value constrain is given, generate value constrain sql + if (itemConstrainValueFlag || modifierConstrainValueFlag ) { + + //generate sql for unit_cd conversion + + if ( projectParamMap != null && projectParamMap.get(ParamUtil.CRC_ENABLE_UNITCD_CONVERSION) != null) { + String unitCdConversionFlag = (String)projectParamMap.get(ParamUtil.CRC_ENABLE_UNITCD_CONVERSION); + if (unitCdConversionFlag != null && unitCdConversionFlag.equalsIgnoreCase("ON")) { + if (item.getMetadataxml() != null && item.getMetadataxml().getContent().get(0) != null) { + Element valueMetadataElement = (Element)item.getMetadataxml().getContent().get(0); + UnitConverstionUtil unitConverstionUtil = new UnitConverstionUtil(); + unitCdSwitchClause = unitConverstionUtil.buildUnitCdSwitchClause(valueMetadataElement,false,"obs."); + unitCdInClause = unitConverstionUtil.buildUnitCdInClause(valueMetadataElement,""); + } + if (modifierConstrainValueFlag) { + XmlValueType xmlValueType = this.modifierMetadataXmlMap.get(item.getConstrainByModifier().getModifierKey()+item.getConstrainByModifier().getAppliedPath()); + if (xmlValueType != null && xmlValueType.getAny().get(0) != null) { + Element valueMetadataElement = xmlValueType.getAny().get(0); + UnitConverstionUtil unitConverstionUtil = new UnitConverstionUtil(); + modifierUnitCdSwitchClause = unitConverstionUtil.buildUnitCdSwitchClause(valueMetadataElement,false,"obs."); + modifierUnitCdInClause = unitConverstionUtil.buildUnitCdInClause(valueMetadataElement,""); + } else { + log.debug("No metadata xml for modifier key = " +item.getConstrainByModifier().getModifierKey() + " applied path " + item.getConstrainByModifier().getAppliedPath()); + } + } + } + } + } + + ValueConstrainsHandler vh = new ValueConstrainsHandler(); + + if (unitCdSwitchClause.length()>0) { + vh.setUnitCdConversionFlag(true, unitCdInClause, unitCdSwitchClause); + } + String[] valueConstrainSql = new String[] {"",""} ; + if (itemConstrainValueFlag) { + valueConstrainSql = vh + .constructValueConstainClause(item.getConstrainByValue(),this.dataSourceLookup.getServerType(),this.getDbSchemaName(),panelAccuracyScale); + if (panelAccuracyScale>0) { + containsJoinSql = valueConstrainSql[1]; + } + } + String[] modifierConstrainValueSql = new String[]{"",""}; + if (modifierConstrainValueFlag) { + if (modifierUnitCdInClause.length()>0) { + vh.setUnitCdConversionFlag(true, modifierUnitCdInClause, modifierUnitCdSwitchClause); + } + modifierConstrainValueSql = vh.constructValueConstainClause(buildItemValueConstrain(modifierConstrain.getConstrainByValue()),this.dataSourceLookup.getServerType(),this.getDbSchemaName(),panelAccuracyScale); + if (panelAccuracyScale>0) { + containsJoinSql += modifierConstrainValueSql[1]; + } + } + + if ((valueConstrainSql[0] != null + && valueConstrainSql[0].length() > 0) || (modifierConstrainValueSql[0] != null + && modifierConstrainValueSql[0].length() > 0)) { + // factByProviderSql += (" AND (" + valueConstrainSql + modifierConstrainValueSql + ")\n"); + tempSqlClause += (" AND (" + valueConstrainSql[0] + modifierConstrainValueSql[0] + ")\n"); + } + + factByProviderSql += containsJoinSql; + + factByProviderSql += tempSqlClause; + + // add start and end date constrains + + List constrainByDateList = item + .getConstrainByDate(); + for (ConstrainByDate constrainByDate : constrainByDateList) { + ConstrainDateType dateFrom = constrainByDate.getDateFrom(); + ConstrainDateType dateTo = constrainByDate.getDateTo(); + + String dateFromColumn = null, dateToColumn = null; + InclusiveType dateFromInclusive = null, dateToInclusive = null; + XMLGregorianCalendar dateFromValue = null, dateToValue = null; + String dateConstrainSql = null; + + if (dateFrom != null || dateTo != null) { + + if (dateFrom != null) { + dateFromInclusive = dateFrom.getInclusive(); + dateFromValue = dateFrom.getValue(); + dateFrom.getTime(); + if (dateFrom.getTime() != null + && dateFrom.getTime().name() != null + && dateFrom.getTime().name() + .equalsIgnoreCase( + ConstrainDateTimeType.END_DATE + .name())) { + dateFromColumn = "obs.end_date"; + } else { + dateFromColumn = "obs.start_date"; + } + + } + + if (dateTo != null) { + dateToInclusive = dateTo.getInclusive(); + dateToValue = dateTo.getValue(); + dateTo.getTime(); + if (dateTo.getTime() != null + && dateTo.getTime().name() != null + && dateTo.getTime().name() + .equalsIgnoreCase( + ConstrainDateTimeType.END_DATE + .name())) { + dateToColumn = "obs.end_date"; + } else { + dateToColumn = "obs.start_date"; + } + } + + dateConstrainSql = dateConstrainHandler + .constructDateConstrainClause(dateFromColumn, + dateToColumn, dateFromInclusive, + dateToInclusive, dateFromValue, + dateToValue); + if (dateConstrainSql != null) { + factByProviderSql += (" AND " + dateConstrainSql + "\n"); + } + + // item.getConstrainByModifier().get(0).getModifierName() + } + } + // generate panel date constrain + if (panelDateConstrain != null) { + factByProviderSql += (" AND (" + panelDateConstrain + ")\n"); + } + // item.getConstrainByModifier().get(0).getModifierName() + } + } + + if (factByProviderSql.trim().length()<10) { + return ""; + } + + int invert = panel.getInvert(); + + if (invert == 1) { + String invertSql = ("( SELECT " + obsFactSelectClause + " FROM \n"); + invertSql += " " + this.getDbSchemaName() + + getFactTable() + " obs \n"; + invertSql += tableLookupJoinClause; + invertSql += (" WHERE \n" + fullWhereClause + ")\n"); + factByProviderSql = invertSql + " MINUS \n " + "(" + + factByProviderSql + ")"; + } + + if (totalItemOccurance > 1) { + factByProviderSql = "SELECT a.*, rank() OVER (partition by obs_encounter_num,obs_patient_num,obs_start_date,obs_concept_cd order by rownum ) as seqNumber FROM (\n" + + factByProviderSql; + } else { + factByProviderSql = "SELECT a.* FROM (\n" + factByProviderSql; + } + + // factByProviderSql += " ORDER BY + // obs.patient_num,obs.start_date,obs.concept_cd,obs.rowid) a \n"; + if (this.requestVersion.startsWith("1.5")) { + factByProviderSql += " ) a \n"; + } else { + factByProviderSql += " ORDER BY 2,5,3,7,6) a \n"; + } + + return factByProviderSql; + } + + /** + * Function to uses given select, join and where clause to build core pdo + * query, without any filter (concept and provider) + * + * @param obsFactSelectClause + * @param tableLookupJoinClause + * @param fullWhereClause + * @return + */ + private String factQueryWithoutFilter(String obsFactSelectClause, + String tableLookupJoinClause, String fullWhereClause) { + String factSql = "SELECT b.*, ROWNUM rnum FROM (\n"; + // OMOP WAS + // factSql += (" SELECT " + // + obsFactSelectClause + " FROM " + this.getDbSchemaName() + "observation_FACT obs\n"); + + factSql += (" SELECT " + + obsFactSelectClause + " FROM " + this.getDbSchemaName() + getFactTable() + " obs\n"); + + factSql += tableLookupJoinClause; + + factSql += (" WHERE \n" + fullWhereClause + "\n"); + if (this.outputOptionList.getObservationSet().isWithmodifiers() == false) { + factSql += " AND obs.modifier_cd = '@' "; + } + factSql += " ORDER BY obs.patient_num,obs.start_date,obs.concept_cd,obs.instance_num,obs.modifier_cd,obs.rowid) b \n"; + + return factSql; + } + + /** + * Function to uses given select, join and where clause to build core pdo + * query, without any filter (concept and provider) + * + * @param obsFactSelectClause + * @param tableLookupJoinClause + * @param fullWhereClause + * @return + */ + private String postgresFactQueryWithoutFilter(String obsFactSelectClause, + String tableLookupJoinClause, String fullWhereClause) { + String factSql = "SELECT b.*, ROW_NUMBER() OVER (order by obs_patient_num) rnum FROM (\n"; + factSql += (" SELECT " + + obsFactSelectClause + " FROM " + this.getDbSchemaName() + getFactTable() + " obs\n"); + + factSql += tableLookupJoinClause; + + factSql += (" WHERE \n" + fullWhereClause + "\n"); + if (this.outputOptionList.getObservationSet().isWithmodifiers() == false) { + factSql += " AND obs.modifier_cd = '@' "; + } + + return factSql; + } + + /** + * Generate fact's join clause for table pdo + * + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return + */ + private String getLookupJoinClause(boolean detailFlag, boolean blobFlag, + boolean statusFlag) { + String joinClause = " "; + + if (detailFlag) { + joinClause = " left JOIN " + + this.getDbSchemaName() + + "code_lookup modifier_lookup \n" + + " ON (obs.modifier_cd = modifier_lookup.code_Cd AND modifier_lookup.column_cd = 'MODIFIER_CD') \n" + + " left JOIN " + + "(select name_char, concept_cd from " + + this.getDbSchemaName() + + "concept_dimension group by name_char, concept_cd) concept_lookup " + + "ON (obs.concept_cd = concept_lookup.concept_Cd) \n" + + " left JOIN " + + this.getDbSchemaName() + + "provider_dimension provider_lookup \n" + + " ON (obs.provider_id = provider_lookup.provider_id) \n" + + " left JOIN " + + this.getDbSchemaName() + + "code_lookup location_lookup \n" + + " ON (obs.location_Cd = location_lookup.code_Cd AND location_lookup.column_cd = 'LOCATION_CD') \n"; + } + + return joinClause; + } + + /** + * Helper function to build unique visit, patient, concept list from + * observation fact + * + * @param encounterNum + * @param patientNum + * @param providerId + * @param conceptCd + */ + private void addToDistinctList(String encounterNum, String patientNum, + String providerId, String conceptCd,String modifierCd) { + if (visitFactRelated.isSelected() || eidFactRelated.isSelected()) { + if (!visitFactList.contains(encounterNum)) { + visitFactList.add(encounterNum); + } + } + + if (patientFactRelated.isSelected() || pidFactRelated.isSelected()) { + if (!patientFactList.contains(patientNum)) { + patientFactList.add(patientNum); + } + } + + if (providerFactRelated.isSelected()) { + if (!providerFactList.contains(providerId)) { + providerFactList.add(providerId); + } + } + + if (conceptFactRelated.isSelected()) { + if (!conceptFactList.contains(conceptCd)) { + conceptFactList.add(conceptCd); + } + } + + if (modifierFactRelated.isSelected()) { + if (!modifierFactList.contains(modifierCd)) { + modifierFactList.add(modifierCd); + } + } + } + + /** + * Executive the given query + * + * @param conn + * @param querySql + * @return + * @throws SQLException + */ + private ResultSet executeQuery(Connection conn, String querySql, + int sqlParamCount) throws SQLException { + PreparedStatement stmt = conn.prepareStatement(querySql); + + if (inputOptionListHandler.isCollectionId()) { + for (int i = 1; i <= sqlParamCount; i++) { + stmt.setInt(i, Integer.parseInt(inputOptionListHandler + .getCollectionId())); + } + } + + ResultSet resultSet = stmt.executeQuery(); + + return resultSet; + + // JdbcRowSet rowSet = new JdbcRowSetImpl(resultSet); + // return rowSet; + } + + /** + * Build plain pdo's observation fact + * + * @param rowSet + * @return + * @throws SQLException + * @throws IOException + */ + private ObservationSet buildPDOFact(ResultSet rowSet, String panelName) + throws SQLException, IOException { + ObservationSet currentObsFactSetType = new ObservationSet(); + currentObsFactSetType.setPanelName(panelName); + + I2B2PdoFactory.ObservationFactBuilder observationFactBuilder = new I2B2PdoFactory().new ObservationFactBuilder( + obsFactFactRelated.isSelectDetail(), obsFactFactRelated + .isSelectBlob(), obsFactFactRelated.isSelectStatus(), dataSourceLookup.getServerType()); + + while (rowSet.next()) { + ObservationType obsFactType = null; + + obsFactType = observationFactBuilder.buildObservationSet(rowSet); + + if (obsFactFactRelated.isSelected()) { + currentObsFactSetType.getObservation().add(obsFactType); + } + + addToDistinctList(obsFactType.getEventId().getValue(), obsFactType + .getPatientId().getValue(), obsFactType.getObserverCd() + .getValue(), obsFactType.getConceptCd().getValue(),obsFactType.getModifierCd().getValue()); + } + + return currentObsFactSetType; + } + + /** + * Build table pdo observaton fact + * + * @param rowSet + * @return + * @throws SQLException + * @throws IOException + */ + private ObservationSet buildTablePDOFact(ResultSet rowSet, String panelName) + throws SQLException, IOException { + // obsFactSetTypeList = new + // Vector(); + boolean detailFlag = obsFactFactRelated.isSelectDetail(); + boolean booleanFlag = obsFactFactRelated.isSelectBlob(); + boolean statusFlag = obsFactFactRelated.isSelectStatus(); + ObservationSet currentObservationSet = new ObservationSet(); + currentObservationSet.setPanelName(panelName); + + RPDRPdoFactory.ObservationFactBuilder observationFactBuilder = new RPDRPdoFactory.ObservationFactBuilder( + detailFlag, booleanFlag, statusFlag); + + while (rowSet.next()) { + ObservationType observation = null; + observation = observationFactBuilder.buildObservationSet(rowSet, + "HIVE"); + + if (obsFactFactRelated.isSelected()) { + currentObservationSet.getObservation().add(observation); + } + + addToDistinctList(observation.getEventId().getValue(), observation.getPatientId().getValue(), + observation.getObserverCd().getValue(), observation.getConceptCd().getValue(),observation.getModifierCd().getValue()); + } + + return currentObservationSet; + } + + private List buildItemValueConstrain(List modifierConstrainList) { + List itemValueConstrainList = new ArrayList(); + for (ItemType.ConstrainByModifier.ConstrainByValue modifierValueConstrain : modifierConstrainList) { + ItemType.ConstrainByValue constrainByValue = new ItemType.ConstrainByValue(); + constrainByValue.setValueConstraint(modifierValueConstrain.getValueConstraint()); + constrainByValue.setValueOperator(modifierValueConstrain.getValueOperator()) ; + constrainByValue.setValueType(modifierValueConstrain.getValueType()); + constrainByValue.setValueUnitOfMeasure(modifierValueConstrain.getValueUnitOfMeasure()) ; + itemValueConstrainList.add(constrainByValue); + } + return itemValueConstrainList; + } + + private String generatePanelDateConstrain( + DateConstrainHandler dateConstrainHandler, + ConstrainDateType dateFrom, ConstrainDateType dateTo) + throws I2B2Exception { + + String dateFromColumn = null, dateToColumn = null; + InclusiveType dateFromInclusive = null, dateToInclusive = null; + XMLGregorianCalendar dateFromValue = null, dateToValue = null; + String dateConstrainSql = null; + + if (dateFrom != null || dateTo != null) { + + if (dateFrom != null) { + dateFromInclusive = dateFrom.getInclusive(); + dateFromValue = dateFrom.getValue(); + dateFrom.getTime(); + if (dateFrom.getTime() != null + && dateFrom.getTime().name() != null + && dateFrom.getTime().name().equalsIgnoreCase( + ConstrainDateTimeType.END_DATE.name())) { + dateFromColumn = "obs.end_date"; + } else { + dateFromColumn = "obs.start_date"; + } + + } + + if (dateTo != null) { + dateToInclusive = dateTo.getInclusive(); + dateToValue = dateTo.getValue(); + dateTo.getTime(); + if (dateTo.getTime() != null + && dateTo.getTime().name() != null + && dateTo.getTime().name().equalsIgnoreCase( + ConstrainDateTimeType.END_DATE.name())) { + dateToColumn = "obs.end_date"; + } else { + dateToColumn = "obs.start_date"; + } + } + + dateConstrainSql = dateConstrainHandler + .constructDateConstrainClause(dateFromColumn, dateToColumn, + dateFromInclusive, dateToInclusive, dateFromValue, + dateToValue); + } + return dateConstrainSql; + } + + public String getFactTable(){ + return this.factTable; + } + + public void setFactTable(String table){ + this.factTable = table; + } + + + protected DerivedFactColumnsType getFactColumnsFromOntologyCell(String itemKey) + throws ConceptNotFoundException, OntologyException { + DerivedFactColumnsType factColumns = new DerivedFactColumnsType(); + try { + + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + String ontologyUrl = qpUtil + .getCRCPropertyValue(QueryProcessorUtil.ONTOLOGYCELL_ROOT_WS_URL_PROPERTIES); + + SecurityType securityType = PMServiceAccountUtil + .getServiceSecurityType(dataSourceLookup.getDomainId()); + + factColumns = CallOntologyUtil.callGetFactColumns(itemKey, + securityType, dataSourceLookup.getProjectPath(), + ontologyUrl +"/getDerivedFactColumns"); + } catch (JAXBUtilException e) { + + log.error("Error while fetching metadata [" + itemKey + + "] from ontology ", e); + throw new OntologyException("Error while fetching metadata [" + + itemKey + "] from ontology " + + StackTraceUtil.getStackTrace(e)); + } catch (I2B2Exception e) { + log.error("Error while fetching metadata from ontology ", e); + throw new OntologyException("Error while fetching metadata [" + + itemKey + "] from ontology " + + StackTraceUtil.getStackTrace(e)); + } catch (AxisFault e) { + log.error("Error while fetching metadata from ontology ", e); + throw new OntologyException("Error while fetching metadata [" + + itemKey + "] from ontology " + + StackTraceUtil.getStackTrace(e)); + } catch (XMLStreamException e) { + log.error("Error while fetching metadata from ontology ", e); + throw new OntologyException("Error while fetching metadata [" + + itemKey + "] from ontology " + + StackTraceUtil.getStackTrace(e)); + } + + return factColumns; + } + + + } \ No newline at end of file diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/input/IFactRelatedQueryHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/input/IFactRelatedQueryHandler.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/input/IFactRelatedQueryHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/input/IFactRelatedQueryHandler.java index cfda4a71..f3eb19bb --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/input/IFactRelatedQueryHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/input/IFactRelatedQueryHandler.java @@ -1,99 +1,99 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.pdo.input; - -import java.util.List; -import java.util.Map; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.crc.datavo.ontology.XmlValueType; -import edu.harvard.i2b2.crc.datavo.pdo.ObservationSet; -import edu.harvard.i2b2.crc.datavo.pdo.query.PanelType; - -public interface IFactRelatedQueryHandler { - - /** - * Function to build and execute pdo sql and build plain pdo's observation - * fact - * - * @return - * @throws Exception - */ - public List getPdoObservationFact() throws I2B2DAOException; - - /** - * Function to build and execute pdo sql and build table pdo's observation - * fact - * - * @return ObservationSet list - * @throws I2B2DAOException - */ - public List getTablePdoObservationFact() - throws I2B2DAOException; - - /** - * Returns provider id, belong to the facts - * - * @return list of provider/observer id - */ - public List getProviderFactList(); - - /** - * Returns concept code belong to the facts - * - * @return - */ - public List getConceptFactList(); - - /** - * Returns modifier code belong to the facts - * - * @return - */ - public List getModifierFactList(); - - /** - * Returns patient number belong to the facts - * - * @return - */ - public List getPatientFactList(); - - /** - * Returns encounter number belong to the facts - * - * @return list of encounter number - */ - public List getVisitFactList(); - - - /** - * This is the main function to build query for plain and table pdo request - * - * @param pdoType - * @return String - * @throws I2B2DAOException - */ - public String buildQuery(PanelType panel, String pdoType) - throws I2B2DAOException; - - public String buildTotalQuery(PanelType panel, String pdoType) - throws I2B2DAOException; - - public List getPanelSqlList(); - - - public void setProjectParamMap(Map projectParamMap); - - public void setModifierMetadataXmlMap(Map modifierMetadataXmlMap) ; - - public void setRequestVersion(String requestVersion); - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.pdo.input; + +import java.util.List; +import java.util.Map; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.crc.datavo.ontology.XmlValueType; +import edu.harvard.i2b2.crc.datavo.pdo.ObservationSet; +import edu.harvard.i2b2.crc.datavo.pdo.query.PanelType; + +public interface IFactRelatedQueryHandler { + + /** + * Function to build and execute pdo sql and build plain pdo's observation + * fact + * + * @return + * @throws Exception + */ + public List getPdoObservationFact() throws I2B2DAOException; + + /** + * Function to build and execute pdo sql and build table pdo's observation + * fact + * + * @return ObservationSet list + * @throws I2B2DAOException + */ + public List getTablePdoObservationFact() + throws I2B2DAOException; + + /** + * Returns provider id, belong to the facts + * + * @return list of provider/observer id + */ + public List getProviderFactList(); + + /** + * Returns concept code belong to the facts + * + * @return + */ + public List getConceptFactList(); + + /** + * Returns modifier code belong to the facts + * + * @return + */ + public List getModifierFactList(); + + /** + * Returns patient number belong to the facts + * + * @return + */ + public List getPatientFactList(); + + /** + * Returns encounter number belong to the facts + * + * @return list of encounter number + */ + public List getVisitFactList(); + + + /** + * This is the main function to build query for plain and table pdo request + * + * @param pdoType + * @return String + * @throws I2B2DAOException + */ + public String buildQuery(PanelType panel, String pdoType) + throws I2B2DAOException; + + public String buildTotalQuery(PanelType panel, String pdoType) + throws I2B2DAOException; + + public List getPanelSqlList(); + + + public void setProjectParamMap(Map projectParamMap); + + public void setModifierMetadataXmlMap(Map modifierMetadataXmlMap) ; + + public void setRequestVersion(String requestVersion); + + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/input/IInputOptionListHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/input/IInputOptionListHandler.java old mode 100755 new mode 100644 similarity index 95% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/input/IInputOptionListHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/input/IInputOptionListHandler.java index 5dc56001..9bbabc4c --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/input/IInputOptionListHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/input/IInputOptionListHandler.java @@ -1,129 +1,129 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao.pdo.input; - -import java.sql.Connection; -import java.sql.SQLException; -import java.util.List; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; - -/** - * Interface for handler of InputOptionListType $Id: - * IInputOptionListHandler.java,v 1.5 2007/08/31 14:42:36 rk903 Exp $ - * - * @author rkuttan - * @see {@link InputOptionListType} - */ -public interface IInputOptionListHandler { - /** - * Get min index in enumeration list - * - * @return - */ - public int getMinIndex(); - - /** - * Get max index in enumeration list - * - * @return - */ - public int getMaxIndex(); - - /** - * Function to generate where clause of sql from input option list - * - * @return - */ - public String generateWhereClauseSql(); - - /** - * Function to generate sql string to fine min index of inputist - * - * @param panelSql - * @return - */ - public String generateMinIndexSql(String panelSql); - - /** - * Return true if list type is entire set - * - * @return - */ - public boolean isEntireSet(); - - /** - * Return true if list type is collection - * - * @return - */ - public boolean isCollectionId(); - - /** - * Return true if list type is enumeration - * - * @return - */ - public boolean isEnumerationSet(); - - /** - * Return collection id - * - * @return - */ - public String getCollectionId(); - - /** - * Return enumneration list - * - * @return - */ - public List getEnumerationList(); - - /** - * Upload the input enum values to temp table - * - * @param conn - * @throws SQLException - */ - public void uploadEnumerationValueToTempTable(Connection conn) - throws SQLException; - - /** - * Delete temp table data - * - * @param conn - * @throws SQLException - */ - public void deleteTempTable(Connection conn) throws SQLException; - - /** - * Returns input list's size. if the list is collection id, then collection - * set size, if the list is entire set, then total rows in dimension table - * if the list is enumeration, then size of enumeration set - * - * @return - * @throws I2B2DAOException - */ - public int getInputSize() throws I2B2DAOException; - - /** - * Set max index value - * - * @param maxIndex - */ - public void setMaxIndex(int maxIndex); - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao.pdo.input; + +import java.sql.Connection; +import java.sql.SQLException; +import java.util.List; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; + +/** + * Interface for handler of InputOptionListType $Id: + * IInputOptionListHandler.java,v 1.5 2007/08/31 14:42:36 rk903 Exp $ + * + * @author rkuttan + * @see {@link InputOptionListType} + */ +public interface IInputOptionListHandler { + /** + * Get min index in enumeration list + * + * @return + */ + public int getMinIndex(); + + /** + * Get max index in enumeration list + * + * @return + */ + public int getMaxIndex(); + + /** + * Function to generate where clause of sql from input option list + * + * @return + */ + public String generateWhereClauseSql(); + + /** + * Function to generate sql string to fine min index of inputist + * + * @param panelSql + * @return + */ + public String generateMinIndexSql(String panelSql); + + /** + * Return true if list type is entire set + * + * @return + */ + public boolean isEntireSet(); + + /** + * Return true if list type is collection + * + * @return + */ + public boolean isCollectionId(); + + /** + * Return true if list type is enumeration + * + * @return + */ + public boolean isEnumerationSet(); + + /** + * Return collection id + * + * @return + */ + public String getCollectionId(); + + /** + * Return enumneration list + * + * @return + */ + public List getEnumerationList(); + + /** + * Upload the input enum values to temp table + * + * @param conn + * @throws SQLException + */ + public void uploadEnumerationValueToTempTable(Connection conn) + throws SQLException; + + /** + * Delete temp table data + * + * @param conn + * @throws SQLException + */ + public void deleteTempTable(Connection conn) throws SQLException; + + /** + * Returns input list's size. if the list is collection id, then collection + * set size, if the list is entire set, then total rows in dimension table + * if the list is enumeration, then size of enumeration set + * + * @return + * @throws I2B2DAOException + */ + public int getInputSize() throws I2B2DAOException; + + /** + * Set max index value + * + * @param maxIndex + */ + public void setMaxIndex(int maxIndex); + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/input/ModifierConstrainsHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/input/ModifierConstrainsHandler.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/input/ModifierConstrainsHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/input/ModifierConstrainsHandler.java index eb09d18e..b0d4da15 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/input/ModifierConstrainsHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/input/ModifierConstrainsHandler.java @@ -1,80 +1,80 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao.pdo.input; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.crc.datavo.pdo.query.ItemType; - -/** - * Class to handle modifier constrains. Generates sql where clause based on the - * list of modifier constrains. - * - * @author rkuttan - */ -public class ModifierConstrainsHandler { - /** log **/ - protected final Log log = LogFactory.getLog(getClass()); - String schemaName = null; - - public ModifierConstrainsHandler(String schemaName) { - this.schemaName = schemaName; - } - - public String constructModifierConstainClause( - ItemType.ConstrainByModifier modifierConstrain) - throws I2B2DAOException { - - String dimPath = "", dimColumnName = "", dimCode = "", dimOperator = "", dimTableName = "", factTableColumn = ""; - - String constrainSql = null; - if (modifierConstrain != null) { - dimPath = modifierConstrain.getDimDimcode(); - dimColumnName = modifierConstrain.getDimColumnname(); - dimCode = modifierConstrain.getDimDimcode(); - dimOperator = modifierConstrain.getDimOperator(); - dimTableName = modifierConstrain.getDimTablename(); - factTableColumn = modifierConstrain.getFacttablecolumn(); - - if (dimPath == null || dimColumnName == null || dimCode == null - || dimOperator == null || dimTableName == null - || factTableColumn == null) { - throw new I2B2DAOException( - "Error modifier constrain information has null value path [" - + dimPath + "] column name [" + dimColumnName - + "] dim code [" + dimCode - + "] dim operator [ " + dimOperator - + "] dim table name [" + dimTableName - + "] fact table column [" + factTableColumn - + "]"); - } - } - - dimPath.replaceAll("'", "''"); - - constrainSql = " (" + factTableColumn + " IN ( select " - + factTableColumn + " from " + this.schemaName + dimTableName + " where " - + dimColumnName + " " + dimOperator + " " + dimCode - + " )) "; - - - - - return constrainSql; - } - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao.pdo.input; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.crc.datavo.pdo.query.ItemType; + +/** + * Class to handle modifier constrains. Generates sql where clause based on the + * list of modifier constrains. + * + * @author rkuttan + */ +public class ModifierConstrainsHandler { + /** log **/ + protected final Log log = LogFactory.getLog(getClass()); + String schemaName = null; + + public ModifierConstrainsHandler(String schemaName) { + this.schemaName = schemaName; + } + + public String constructModifierConstainClause( + ItemType.ConstrainByModifier modifierConstrain) + throws I2B2DAOException { + + String dimPath = "", dimColumnName = "", dimCode = "", dimOperator = "", dimTableName = "", factTableColumn = ""; + + String constrainSql = null; + if (modifierConstrain != null) { + dimPath = modifierConstrain.getDimDimcode(); + dimColumnName = modifierConstrain.getDimColumnname(); + dimCode = modifierConstrain.getDimDimcode(); + dimOperator = modifierConstrain.getDimOperator(); + dimTableName = modifierConstrain.getDimTablename(); + factTableColumn = modifierConstrain.getFacttablecolumn(); + + if (dimPath == null || dimColumnName == null || dimCode == null + || dimOperator == null || dimTableName == null + || factTableColumn == null) { + throw new I2B2DAOException( + "Error modifier constrain information has null value path [" + + dimPath + "] column name [" + dimColumnName + + "] dim code [" + dimCode + + "] dim operator [ " + dimOperator + + "] dim table name [" + dimTableName + + "] fact table column [" + factTableColumn + + "]"); + } + } + + dimPath.replaceAll("'", "''"); + + constrainSql = " (" + factTableColumn + " IN ( select " + + factTableColumn + " from " + this.schemaName + dimTableName + " where " + + dimColumnName + " " + dimOperator + " " + dimCode + + " )) "; + + + + + return constrainSql; + } + + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/input/OutputOptionFactRelatedHelper.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/input/OutputOptionFactRelatedHelper.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/input/OutputOptionFactRelatedHelper.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/input/OutputOptionFactRelatedHelper.java index 9e3c695d..34cbfa48 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/input/OutputOptionFactRelatedHelper.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/input/OutputOptionFactRelatedHelper.java @@ -1,70 +1,70 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.pdo.input; - -import edu.harvard.i2b2.crc.dao.pdo.output.ConceptFactRelated; -import edu.harvard.i2b2.crc.dao.pdo.output.EidFactRelated; -import edu.harvard.i2b2.crc.dao.pdo.output.ObservationFactFactRelated; -import edu.harvard.i2b2.crc.dao.pdo.output.PatientFactRelated; -import edu.harvard.i2b2.crc.dao.pdo.output.PidFactRelated; -import edu.harvard.i2b2.crc.dao.pdo.output.ProviderFactRelated; -import edu.harvard.i2b2.crc.dao.pdo.output.VisitFactRelated; -import edu.harvard.i2b2.crc.datavo.pdo.query.OutputOptionListType; - -public class OutputOptionFactRelatedHelper { - - private VisitFactRelated visitFactRelated = null; - /** Observer helper class to build Observer section in pdo **/ - private ProviderFactRelated providerFactRelated = null; - /** Patient helper class to build patient section in pdo **/ - private PatientFactRelated patientFactRelated = null; - /** Concept helper class to build concept section in pdo **/ - private ConceptFactRelated conceptFactRelated = null; - /** Observation fact helper class to build observationfact **/ - private ObservationFactFactRelated obsFactFactRelated = null; - private PidFactRelated pidFactRelated = null; - private EidFactRelated eidFactRelated = null; - - public OutputOptionFactRelatedHelper(OutputOptionListType outputOptionList) { - visitFactRelated = new VisitFactRelated(outputOptionList.getEventSet()); - providerFactRelated = new ProviderFactRelated(outputOptionList - .getObserverSetUsingFilterList()); - patientFactRelated = new PatientFactRelated(outputOptionList - .getPatientSet()); - conceptFactRelated = new ConceptFactRelated(outputOptionList - .getConceptSetUsingFilterList()); - obsFactFactRelated = new ObservationFactFactRelated(outputOptionList - .getObservationSet()); - pidFactRelated = new PidFactRelated(outputOptionList.getPidSet()); - eidFactRelated = new EidFactRelated(outputOptionList.getEidSet()); - } - - public boolean isFactRelated() { - // check if obsrvation_fact tag present - boolean obsFactSelected = obsFactFactRelated.isSelected(); - - // check if provider or concept present - boolean providerSelected = providerFactRelated.isSelected(); - boolean conceptSelected = conceptFactRelated.isSelected(); - - boolean patientFromFact = patientFactRelated.isFactRelated(); - boolean visitFromFact = visitFactRelated.isFactRelated(); - boolean pidFromFact = pidFactRelated.isFactRelated(); - boolean eidFromFact = eidFactRelated.isFactRelated(); - - if (obsFactSelected || providerSelected || conceptSelected - || patientFromFact || visitFromFact || pidFromFact - || eidFromFact) { - return true; - } else { - return false; - } - - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.pdo.input; + +import edu.harvard.i2b2.crc.dao.pdo.output.ConceptFactRelated; +import edu.harvard.i2b2.crc.dao.pdo.output.EidFactRelated; +import edu.harvard.i2b2.crc.dao.pdo.output.ObservationFactFactRelated; +import edu.harvard.i2b2.crc.dao.pdo.output.PatientFactRelated; +import edu.harvard.i2b2.crc.dao.pdo.output.PidFactRelated; +import edu.harvard.i2b2.crc.dao.pdo.output.ProviderFactRelated; +import edu.harvard.i2b2.crc.dao.pdo.output.VisitFactRelated; +import edu.harvard.i2b2.crc.datavo.pdo.query.OutputOptionListType; + +public class OutputOptionFactRelatedHelper { + + private VisitFactRelated visitFactRelated = null; + /** Observer helper class to build Observer section in pdo **/ + private ProviderFactRelated providerFactRelated = null; + /** Patient helper class to build patient section in pdo **/ + private PatientFactRelated patientFactRelated = null; + /** Concept helper class to build concept section in pdo **/ + private ConceptFactRelated conceptFactRelated = null; + /** Observation fact helper class to build observationfact **/ + private ObservationFactFactRelated obsFactFactRelated = null; + private PidFactRelated pidFactRelated = null; + private EidFactRelated eidFactRelated = null; + + public OutputOptionFactRelatedHelper(OutputOptionListType outputOptionList) { + visitFactRelated = new VisitFactRelated(outputOptionList.getEventSet()); + providerFactRelated = new ProviderFactRelated(outputOptionList + .getObserverSetUsingFilterList()); + patientFactRelated = new PatientFactRelated(outputOptionList + .getPatientSet()); + conceptFactRelated = new ConceptFactRelated(outputOptionList + .getConceptSetUsingFilterList()); + obsFactFactRelated = new ObservationFactFactRelated(outputOptionList + .getObservationSet()); + pidFactRelated = new PidFactRelated(outputOptionList.getPidSet()); + eidFactRelated = new EidFactRelated(outputOptionList.getEidSet()); + } + + public boolean isFactRelated() { + // check if obsrvation_fact tag present + boolean obsFactSelected = obsFactFactRelated.isSelected(); + + // check if provider or concept present + boolean providerSelected = providerFactRelated.isSelected(); + boolean conceptSelected = conceptFactRelated.isSelected(); + + boolean patientFromFact = patientFactRelated.isFactRelated(); + boolean visitFromFact = visitFactRelated.isFactRelated(); + boolean pidFromFact = pidFactRelated.isFactRelated(); + boolean eidFromFact = eidFactRelated.isFactRelated(); + + if (obsFactSelected || providerSelected || conceptSelected + || patientFromFact || visitFromFact || pidFromFact + || eidFromFact) { + return true; + } else { + return false; + } + + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/input/PDOFactory.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/input/PDOFactory.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/input/PDOFactory.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/input/PDOFactory.java index 94716f30..6ab190fe --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/input/PDOFactory.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/input/PDOFactory.java @@ -1,65 +1,65 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.pdo.input; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.pdo.query.InputOptionListType; -import edu.harvard.i2b2.crc.datavo.pdo.query.RangeType; - -public class PDOFactory { - - public static IInputOptionListHandler buildInputListHandler( - InputOptionListType inputOptionList, - DataSourceLookup dataSourceLookup) throws I2B2DAOException { - - IInputOptionListHandler inputOptionListHandler = null; - if (inputOptionList.getPatientList() != null) { - inputOptionListHandler = new PatientListTypeHandler( - dataSourceLookup, inputOptionList.getPatientList()); - - } else if (inputOptionList.getEventList() != null) { - inputOptionListHandler = new VisitListTypeHandler(dataSourceLookup, - inputOptionList.getEventList()); - - } else if (inputOptionList.getPidList() != null) { - inputOptionListHandler = new PidListTypeHandler(dataSourceLookup, - inputOptionList.getPidList()); - } else if (inputOptionList.getEidList() != null) { - inputOptionListHandler = new EidListTypeHandler(dataSourceLookup, - inputOptionList.getEidList()); - } else { - throw new I2B2DAOException( - "Input option list does not contain visit or patient list"); - } - return inputOptionListHandler; - - } - - public static RangeType getRangeType(InputOptionListType inputOptionList) - throws I2B2DAOException { - if (inputOptionList.getPatientList() != null) { - return inputOptionList.getPatientList(); - - } else if (inputOptionList.getEventList() != null) { - return inputOptionList.getEventList(); - - } else if (inputOptionList.getPidList() != null) { - return inputOptionList.getPidList(); - - } else if (inputOptionList.getEidList() != null) { - return inputOptionList.getEidList(); - - } else { - throw new I2B2DAOException( - "Input option list does not contain visit or patient list"); - } - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.pdo.input; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.pdo.query.InputOptionListType; +import edu.harvard.i2b2.crc.datavo.pdo.query.RangeType; + +public class PDOFactory { + + public static IInputOptionListHandler buildInputListHandler( + InputOptionListType inputOptionList, + DataSourceLookup dataSourceLookup) throws I2B2DAOException { + + IInputOptionListHandler inputOptionListHandler = null; + if (inputOptionList.getPatientList() != null) { + inputOptionListHandler = new PatientListTypeHandler( + dataSourceLookup, inputOptionList.getPatientList()); + + } else if (inputOptionList.getEventList() != null) { + inputOptionListHandler = new VisitListTypeHandler(dataSourceLookup, + inputOptionList.getEventList()); + + } else if (inputOptionList.getPidList() != null) { + inputOptionListHandler = new PidListTypeHandler(dataSourceLookup, + inputOptionList.getPidList()); + } else if (inputOptionList.getEidList() != null) { + inputOptionListHandler = new EidListTypeHandler(dataSourceLookup, + inputOptionList.getEidList()); + } else { + throw new I2B2DAOException( + "Input option list does not contain visit or patient list"); + } + return inputOptionListHandler; + + } + + public static RangeType getRangeType(InputOptionListType inputOptionList) + throws I2B2DAOException { + if (inputOptionList.getPatientList() != null) { + return inputOptionList.getPatientList(); + + } else if (inputOptionList.getEventList() != null) { + return inputOptionList.getEventList(); + + } else if (inputOptionList.getPidList() != null) { + return inputOptionList.getPidList(); + + } else if (inputOptionList.getEidList() != null) { + return inputOptionList.getEidList(); + + } else { + throw new I2B2DAOException( + "Input option list does not contain visit or patient list"); + } + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/input/PageMethod.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/input/PageMethod.java old mode 100755 new mode 100644 similarity index 98% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/input/PageMethod.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/input/PageMethod.java index 2e4f006f..8bb2d5f0 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/input/PageMethod.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/input/PageMethod.java @@ -1,14 +1,14 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.pdo.input; - -public interface PageMethod { - public int calculateListSize(int maxInputList, long totalObservations, - long pageSize); -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.pdo.input; + +public interface PageMethod { + public int calculateListSize(int maxInputList, long totalObservations, + long pageSize); +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/input/PageMethodFactory.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/input/PageMethodFactory.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/input/PageMethodFactory.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/input/PageMethodFactory.java index 5fdc7738..d41c504a --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/input/PageMethodFactory.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/input/PageMethodFactory.java @@ -1,37 +1,37 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.pdo.input; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; - -/** - * Factory class to return - * - * @author rkuttan - */ -public class PageMethodFactory { - - public final static String AVERAGE_OBSERVATION_METHOD = "AVERAGE_OBSERVATION_METHOD"; - public final static String SUBDIVIDE_INPUT_METHOD = "SUBDIVIDE_INPUT_METHOD"; - - public static PageMethod buildPageMethod(String pageMethodName) - throws I2B2DAOException { - PageMethod pageMethod = null; - if (pageMethodName.trim().equalsIgnoreCase(AVERAGE_OBSERVATION_METHOD)) { - pageMethod = new AverageObservationPageMethod(); - } else if (pageMethodName.trim().equalsIgnoreCase( - SUBDIVIDE_INPUT_METHOD)) { - pageMethod = new SubDividePageMethod(); - } else { - throw new I2B2DAOException("Could not find page method for [" - + pageMethodName + "]"); - } - return pageMethod; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.pdo.input; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; + +/** + * Factory class to return + * + * @author rkuttan + */ +public class PageMethodFactory { + + public final static String AVERAGE_OBSERVATION_METHOD = "AVERAGE_OBSERVATION_METHOD"; + public final static String SUBDIVIDE_INPUT_METHOD = "SUBDIVIDE_INPUT_METHOD"; + + public static PageMethod buildPageMethod(String pageMethodName) + throws I2B2DAOException { + PageMethod pageMethod = null; + if (pageMethodName.trim().equalsIgnoreCase(AVERAGE_OBSERVATION_METHOD)) { + pageMethod = new AverageObservationPageMethod(); + } else if (pageMethodName.trim().equalsIgnoreCase( + SUBDIVIDE_INPUT_METHOD)) { + pageMethod = new SubDividePageMethod(); + } else { + throw new I2B2DAOException("Could not find page method for [" + + pageMethodName + "]"); + } + return pageMethod; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/input/PagingHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/input/PagingHandler.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/input/PagingHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/input/PagingHandler.java index c87d63ad..d66a2a89 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/input/PagingHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/input/PagingHandler.java @@ -1,486 +1,486 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.pdo.input; - -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import javax.xml.stream.XMLStreamException; - -import org.apache.axis2.AxisFault; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.exception.StackTraceUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.dao.pdo.IPageDao; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.ConceptNotFoundException; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.OntologyException; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; -import edu.harvard.i2b2.crc.datavo.ontology.DerivedFactColumnsType; -import edu.harvard.i2b2.crc.datavo.ontology.XmlValueType; -import edu.harvard.i2b2.crc.datavo.pdo.query.FactOutputOptionType; -import edu.harvard.i2b2.crc.datavo.pdo.query.FilterListType; -import edu.harvard.i2b2.crc.datavo.pdo.query.InputOptionListType; -import edu.harvard.i2b2.crc.datavo.pdo.query.OutputOptionListType; -import edu.harvard.i2b2.crc.datavo.pdo.query.PanelType; -import edu.harvard.i2b2.crc.delegate.ontology.CallOntologyUtil; -import edu.harvard.i2b2.crc.util.PMServiceAccountUtil; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - -/** - * Paging Handler class. - * - * a)Calculate average observation per patient and keep trying until the - * iteration count reached. - * - * b)Then try with min percent of patient list specified in the property file. - * - * c)Then try with min size of patient list specified in the property file. - * - * @author rk903 - */ -public class PagingHandler extends CRCDAO { - - InputOptionListType inputList = null; - FilterListType filterList = null; - OutputOptionListType outputOptionList = null; - DataSourceLookup dataSourceLookup = null; - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - DAOFactoryHelper daoFactoryHelper = null; - PageMethod pageMethod = null; - Map projectParamMap = null; - Map modifierMetadataXmlMap = null; - - - public static final String TOTAL_OBSERVATION = "TOTAL_OBSERVATION"; - public static final String MAX_INPUT_LIST = "MAX_INPUT_LIST"; - public static final String PAGING_REQUIRED_FLAG = "PAGING_REQUIRED_FLAG"; - - public PagingHandler(DAOFactoryHelper helper, - final InputOptionListType inputList, - final FilterListType filterList, String pageMethodName) - throws I2B2DAOException { - this.daoFactoryHelper = helper; - this.dataSourceLookup = helper.getDataSourceLookup(); - this.inputList = inputList; - this.filterList = filterList; - this.outputOptionList = new OutputOptionListType(); - pageMethod = PageMethodFactory.buildPageMethod(pageMethodName); - } - - public void setProjectParamMap(Map projectParamMap) { - this.projectParamMap = projectParamMap; - } - - public void setModifierMetadataXmlMap(Map modifierMetadataXmlMap) { - this.modifierMetadataXmlMap = modifierMetadataXmlMap; - } - - - public long getTotal(int maxInputList) throws SQLException, I2B2Exception { - - IInputOptionListHandler inputOptionListHandler = PDOFactory - .buildInputListHandler(inputList, dataSourceLookup); - // inputList.getPatientList().setMax(maxInputList); - int minIndex = inputOptionListHandler.getMinIndex(); - inputOptionListHandler.setMaxIndex(minIndex + maxInputList); - - // iterate the panel and call total - IFactRelatedQueryHandler factRelatedHandler = null; - String countSqlFrom = " "; - String countClause = " COUNT(*) "; - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE) || dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) { - factRelatedHandler = new FactRelatedQueryHandler(dataSourceLookup, - inputList, filterList, outputOptionList); - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER)) { - countSqlFrom = "as"; - countClause = " COUNT_BIG(*) "; - factRelatedHandler = new SQLServerFactRelatedQueryHandler( - dataSourceLookup, inputList, filterList, outputOptionList); - } - factRelatedHandler.setProjectParamMap(this.projectParamMap); - factRelatedHandler.setModifierMetadataXmlMap(this.modifierMetadataXmlMap); - - FactOutputOptionType factOutputOptionType = new FactOutputOptionType(); - factOutputOptionType.setOnlykeys(true); - outputOptionList.setObservationSet(factOutputOptionType); - // outputOptionList.getObservationSet().setOnlykeys(true); - - // build sql for all the panel - // DAOFactoryHelper daoFactoryHelper = new DAOFactoryHelper( - // dataSourceLookup); - - IPageDao pageTotalDao = daoFactoryHelper.getDAOFactory() - .getPatientDataDAOFactory().getPageDAO(); - int panelCount = filterList.getPanel().size(); - List panelSqlList = new ArrayList(panelCount); - List sqlCountList = new ArrayList(panelCount); - long totalObservations = 0; - for (PanelType singlePanel : filterList.getPanel()) { - int sqlParamCount = singlePanel.getItem().size(); - if (singlePanel.getInvert() == 1) { - sqlParamCount++; - } - - sqlCountList.add(sqlParamCount); - String totalSql = pageTotalDao.buildTotalSql(factRelatedHandler, - singlePanel); - if (totalSql.trim().length() == 0) { - continue; - } - if((singlePanel != null)&&(singlePanel.getItem().get(0).getFacttablecolumn()!=null)){ - boolean derivedFactTable = QueryProcessorUtil.getInstance().getDerivedFactTable(); - - String defaultTableName = dataSourceLookup.getFullSchema() + ".observation_FACT" ; - if(derivedFactTable == true){ - if(singlePanel.getItem().get(0).getFacttablecolumn().contains(".")){ - - String baseItemFactColumn = singlePanel.getItem().get(0).getFacttablecolumn(); - int lastIndex = baseItemFactColumn.lastIndexOf("."); - String factTable = dataSourceLookup.getFullSchema() + "."+(baseItemFactColumn.substring(0, lastIndex)); - - DerivedFactColumnsType columns = getFactColumnsFromOntologyCell(singlePanel.getItem().get(0).getItemKey()); - if(columns != null){ - if(columns.getDerivedFactTableColumn().size() > 1) { - // parse through solumns and build up replace string. - - Iterator it = columns.getDerivedFactTableColumn().iterator(); - String column = it.next(); - - lastIndex = column.lastIndexOf("."); - String table = dataSourceLookup.getFullSchema() + "."+ (column.substring(0, lastIndex)); - - - factTable = "( select * from " + table; - while(it.hasNext()){ - column = it.next(); - - lastIndex = column.lastIndexOf("."); - table = dataSourceLookup.getFullSchema() + "."+ (column.substring(0, lastIndex)); - - factTable += "\n UNION ALL \n" - + " select * from " + table; - } - factTable += " )"; - - } - } - log.debug("Parse columns " + factTable); - totalSql=totalSql.replaceAll(defaultTableName, factTable) ; - - - - } - } - - - - - - } - - panelSqlList.add("SELECT " - + countClause - + " from ( " - + totalSql + " ) " + countSqlFrom + " totalsql"); - } - - totalObservations = pageTotalDao.getTotalForAllPanel(panelSqlList, - sqlCountList, inputOptionListHandler); - return totalObservations; - } - - public HashMap getMinPatientIndexAndTheTotal(int maxInputList) - throws SQLException, I2B2Exception { - - IInputOptionListHandler inputOptionListHandler = PDOFactory - .buildInputListHandler(inputList, dataSourceLookup); - - // inputList.getPatientList().setMax(maxInputList); - inputOptionListHandler.setMaxIndex(maxInputList); - - // iterate the panel and call total - IFactRelatedQueryHandler factRelatedHandler = null; - String countSqlFrom = " "; - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE) || dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) { - factRelatedHandler = new FactRelatedQueryHandler(dataSourceLookup, - inputList, filterList, outputOptionList); - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER)) { - countSqlFrom = "as"; - factRelatedHandler = new SQLServerFactRelatedQueryHandler( - dataSourceLookup, inputList, filterList, outputOptionList); - } - //set project param - factRelatedHandler.setProjectParamMap(this.projectParamMap); - factRelatedHandler.setModifierMetadataXmlMap(this.modifierMetadataXmlMap); - - FactOutputOptionType factOutputOptionType = new FactOutputOptionType(); - factOutputOptionType.setOnlykeys(true); - outputOptionList.setObservationSet(factOutputOptionType); - // outputOptionList.getObservationSet().setOnlykeys(true); - - // build sql for all the panel - // DAOFactoryHelper daoFactoryHelper = new DAOFactoryHelper( - // dataSourceLookup); - - IPageDao pageTotalDao = daoFactoryHelper.getDAOFactory() - .getPatientDataDAOFactory().getPageDAO(); - int panelCount = filterList.getPanel().size(); - List panelMinSqlList = new ArrayList(panelCount); - List sqlCountList = new ArrayList(panelCount); - long totalObservations = 0; - // things to consider to find the minimum - // a)How to handle the different input list (i.e. enumeration list,table - // or patient_dimension) - - String panelSql = ""; - for (PanelType singlePanel : filterList.getPanel()) { - int sqlParamCount = singlePanel.getItem().size(); - if (singlePanel.getInvert() == 1) { - sqlParamCount++; - } - if (inputOptionListHandler.isCollectionId()) { - sqlParamCount++; - } - - sqlCountList.add(sqlParamCount); - - panelSql = pageTotalDao.buildTotalSql(factRelatedHandler, - singlePanel); - if (panelSql.length() ==0) { - continue; - } - String minSql = inputOptionListHandler - .generateMinIndexSql(panelSql); - log.debug("min sql for panel " + minSql); - panelMinSqlList.add(minSql); - - } - - return pageTotalDao.getMinIndexAndCountAllPanel(panelMinSqlList, - sqlCountList, inputOptionListHandler); - - } - - public int getMinPercent() throws I2B2Exception { - return qpUtil.getPagingInputListMinPercent(); - - } - - public long getPageSize() throws I2B2Exception { - return qpUtil.getPagingObservationSize(); - } - - public int getPagingMaxIteration() throws I2B2Exception { - return qpUtil.getPagingIterationCount(); - - } - - public int getPagingMinSize() throws I2B2Exception { - return qpUtil.getPagingInputListMinSize(); - } - - /** - * @return - * @throws SQLException - * @throws I2B2Exception - */ - public HashMap calculateMaxPageInputList() throws SQLException, - I2B2Exception { - int maxIteration = getPagingMaxIteration(); - int i = 0; - long pageSize = getPageSize(); - boolean fitPagingFlag = false; - HashMap returnResultMap = new HashMap(); - returnResultMap.put("PAGING_REQUIRED_FLAG", true); - long totalObservations = 0; - // PatientListTypeHandler patientList = new PatientListTypeHandler( - // dataSourceLookup, inputList.getPatientList()); - - IInputOptionListHandler inputOptionListHandler = PDOFactory - .buildInputListHandler(inputList, dataSourceLookup); - - int maxInputList = inputOptionListHandler.getMaxIndex(); - int minInputList = inputOptionListHandler.getMinIndex(); - int originalMaxInputList = maxInputList; - int inputListCount = maxInputList - minInputList; - while (i < maxIteration) { - totalObservations = getTotal(inputListCount); - log.debug("Total observations for [" + inputListCount + " ] is [" - + totalObservations + " ]"); - // - if (i == 0) { - returnResultMap.put("TOTAL_OBSERVATION", totalObservations); - } - - // if total < page size then set max patient break - if (checkIfFitThePage(pageSize, totalObservations)) { - log.debug("Input list size of [" + inputListCount - + "] fits the page size [" + pageSize + "]"); - fitPagingFlag = true; - if (i == 0) { - returnResultMap.put("PAGING_REQUIRED_FLAG", false); - } - break; - } - - // call paging method with page size, total observation,.. - inputListCount = pageMethod.calculateListSize(inputListCount, - totalObservations, pageSize); - - if (inputListCount < 1) { - // need not continue the iteration if the list size is reduced - // to < 1 - break; - } - i++; - } - - if (fitPagingFlag) { - returnResultMap.put("MAX_INPUT_LIST", inputListCount); - return returnResultMap; - } else { - throw new I2B2Exception("Could not fit in a page after [" - + maxIteration + "] iteration"); - } - - /* - * // try with minimum percent of patient int minIndex = - * patientList.getMinIndex(); int maxIndex = originalMaxInputList; int - * listLength = maxIndex - minIndex; int minPercentInput = - * getMinPercentInput(listLength); - * log.debug("Trying with minimum input list percent of [ " + - * minPercentInput + "]"); - * - * if (minPercentInput > 0) { if (minPercentInput < maxInputList) { - * totalObservations = getTotal(minPercentInput); log - * .debug("Total observations for minimum input list percent [" + - * minPercentInput + " ] is [" + totalObservations + " ]"); if - * (totalObservations > 0 && checkIfFitThePage(pageSize, - * totalObservations)) { maxInputList = minIndex + minPercentInput; - * returnResultMap.put("MAX_INPUT_LIST", maxInputList); return - * returnResultMap; } } } else { log - * .debug("Skipping minimum input list percent, since the value is 0"); - * } - */ - - // try with minimun of single patient - // int minPagingSize = getPagingMinSize(); - // log.debug("Trying with minimum input list size of [" + minPagingSize - // + "]"); - // if (minPagingSize < 1) { - // throw new I2B2DAOException( - // "Paging failed, minimum page size should not be less than 1"); - // } - // - // HashMap minMap = getMinPatientIndexAndTheTotal(originalMaxInputList); - // int minDataIndex = (Integer) minMap.get("MIN_INDEX"); - // long minDataIndexTotal = (Long) minMap.get("MIN_INDEX_TOTAL"); - // - // System.out.println("min index" + minMap.get("MIN_INDEX")); - // System.out.println("min index total " + - // minMap.get("MIN_INDEX_TOTAL")); - // - // // totalObservations = getTotal(minPagingSize); - // log.debug("Total observation for first data index [" + minDataIndex - // + " ] is [" + minDataIndexTotal + "]"); - // - // if (!checkIfFitThePage(pageSize, minDataIndexTotal)) { - // throw new I2B2DAOException( - // "Paging failed, even the first patient index of [" - // + minDataIndex + "] patient observations [" - // + minDataIndexTotal - // + "] could not fit the page size [" + pageSize - // + "]"); - // } else { - // - // returnResultMap.put("MAX_INPUT_LIST", minDataIndex); - // return returnResultMap; - // } - } - - public int getMinPercentInput(int listLength) throws I2B2Exception { - int minPercent = getMinPercent(); - - int minPercentOfList = listLength * (minPercent / 100); - return minPercentOfList; - } - - private boolean checkIfFitThePage(long pageSize, long totalObservations) { - return (pageSize >= totalObservations); - - } - - - protected DerivedFactColumnsType getFactColumnsFromOntologyCell(String itemKey) - throws ConceptNotFoundException, OntologyException { - DerivedFactColumnsType factColumns = new DerivedFactColumnsType(); - try { - - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - String ontologyUrl = qpUtil - .getCRCPropertyValue(QueryProcessorUtil.ONTOLOGYCELL_ROOT_WS_URL_PROPERTIES); - - - SecurityType securityType = PMServiceAccountUtil - .getServiceSecurityType(dataSourceLookup.getDomainId()); - - - factColumns = CallOntologyUtil.callGetFactColumns(itemKey, - securityType, dataSourceLookup.getProjectPath(), - ontologyUrl +"/getDerivedFactColumns"); - } catch (JAXBUtilException e) { - - log.error("Error while fetching metadata [" + itemKey - + "] from ontology ", e); - throw new OntologyException("Error while fetching metadata [" - + itemKey + "] from ontology " - + StackTraceUtil.getStackTrace(e)); - } catch (I2B2Exception e) { - log.error("Error while fetching metadata from ontology ", e); - throw new OntologyException("Error while fetching metadata [" - + itemKey + "] from ontology " - + StackTraceUtil.getStackTrace(e)); - } catch (AxisFault e) { - log.error("Error while fetching metadata from ontology ", e); - throw new OntologyException("Error while fetching metadata [" - + itemKey + "] from ontology " - + StackTraceUtil.getStackTrace(e)); - } catch (XMLStreamException e) { - log.error("Error while fetching metadata from ontology ", e); - throw new OntologyException("Error while fetching metadata [" - + itemKey + "] from ontology " - + StackTraceUtil.getStackTrace(e)); - } - -// if (factColumns.isEmpty()) { -// throw new ConceptNotFoundException("[" + itemKey + "] "); - -// } - - return factColumns; - } - - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.pdo.input; + +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import javax.xml.stream.XMLStreamException; + +import org.apache.axis2.AxisFault; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.exception.StackTraceUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.dao.pdo.IPageDao; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.ConceptNotFoundException; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.OntologyException; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; +import edu.harvard.i2b2.crc.datavo.ontology.DerivedFactColumnsType; +import edu.harvard.i2b2.crc.datavo.ontology.XmlValueType; +import edu.harvard.i2b2.crc.datavo.pdo.query.FactOutputOptionType; +import edu.harvard.i2b2.crc.datavo.pdo.query.FilterListType; +import edu.harvard.i2b2.crc.datavo.pdo.query.InputOptionListType; +import edu.harvard.i2b2.crc.datavo.pdo.query.OutputOptionListType; +import edu.harvard.i2b2.crc.datavo.pdo.query.PanelType; +import edu.harvard.i2b2.crc.delegate.ontology.CallOntologyUtil; +import edu.harvard.i2b2.crc.util.PMServiceAccountUtil; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + +/** + * Paging Handler class. + * + * a)Calculate average observation per patient and keep trying until the + * iteration count reached. + * + * b)Then try with min percent of patient list specified in the property file. + * + * c)Then try with min size of patient list specified in the property file. + * + * @author rk903 + */ +public class PagingHandler extends CRCDAO { + + InputOptionListType inputList = null; + FilterListType filterList = null; + OutputOptionListType outputOptionList = null; + DataSourceLookup dataSourceLookup = null; + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + DAOFactoryHelper daoFactoryHelper = null; + PageMethod pageMethod = null; + Map projectParamMap = null; + Map modifierMetadataXmlMap = null; + + + public static final String TOTAL_OBSERVATION = "TOTAL_OBSERVATION"; + public static final String MAX_INPUT_LIST = "MAX_INPUT_LIST"; + public static final String PAGING_REQUIRED_FLAG = "PAGING_REQUIRED_FLAG"; + + public PagingHandler(DAOFactoryHelper helper, + final InputOptionListType inputList, + final FilterListType filterList, String pageMethodName) + throws I2B2DAOException { + this.daoFactoryHelper = helper; + this.dataSourceLookup = helper.getDataSourceLookup(); + this.inputList = inputList; + this.filterList = filterList; + this.outputOptionList = new OutputOptionListType(); + pageMethod = PageMethodFactory.buildPageMethod(pageMethodName); + } + + public void setProjectParamMap(Map projectParamMap) { + this.projectParamMap = projectParamMap; + } + + public void setModifierMetadataXmlMap(Map modifierMetadataXmlMap) { + this.modifierMetadataXmlMap = modifierMetadataXmlMap; + } + + + public long getTotal(int maxInputList) throws SQLException, I2B2Exception { + + IInputOptionListHandler inputOptionListHandler = PDOFactory + .buildInputListHandler(inputList, dataSourceLookup); + // inputList.getPatientList().setMax(maxInputList); + int minIndex = inputOptionListHandler.getMinIndex(); + inputOptionListHandler.setMaxIndex(minIndex + maxInputList); + + // iterate the panel and call total + IFactRelatedQueryHandler factRelatedHandler = null; + String countSqlFrom = " "; + String countClause = " COUNT(*) "; + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.ORACLE) || dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) { + factRelatedHandler = new FactRelatedQueryHandler(dataSourceLookup, + inputList, filterList, outputOptionList); + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER)) { + countSqlFrom = "as"; + countClause = " COUNT_BIG(*) "; + factRelatedHandler = new SQLServerFactRelatedQueryHandler( + dataSourceLookup, inputList, filterList, outputOptionList); + } + factRelatedHandler.setProjectParamMap(this.projectParamMap); + factRelatedHandler.setModifierMetadataXmlMap(this.modifierMetadataXmlMap); + + FactOutputOptionType factOutputOptionType = new FactOutputOptionType(); + factOutputOptionType.setOnlykeys(true); + outputOptionList.setObservationSet(factOutputOptionType); + // outputOptionList.getObservationSet().setOnlykeys(true); + + // build sql for all the panel + // DAOFactoryHelper daoFactoryHelper = new DAOFactoryHelper( + // dataSourceLookup); + + IPageDao pageTotalDao = daoFactoryHelper.getDAOFactory() + .getPatientDataDAOFactory().getPageDAO(); + int panelCount = filterList.getPanel().size(); + List panelSqlList = new ArrayList(panelCount); + List sqlCountList = new ArrayList(panelCount); + long totalObservations = 0; + for (PanelType singlePanel : filterList.getPanel()) { + int sqlParamCount = singlePanel.getItem().size(); + if (singlePanel.getInvert() == 1) { + sqlParamCount++; + } + + sqlCountList.add(sqlParamCount); + String totalSql = pageTotalDao.buildTotalSql(factRelatedHandler, + singlePanel); + if (totalSql.trim().length() == 0) { + continue; + } + if((singlePanel != null)&&(singlePanel.getItem().get(0).getFacttablecolumn()!=null)){ + boolean derivedFactTable = QueryProcessorUtil.getInstance().getDerivedFactTable(); + + String defaultTableName = dataSourceLookup.getFullSchema() + ".observation_FACT" ; + if(derivedFactTable == true){ + if(singlePanel.getItem().get(0).getFacttablecolumn().contains(".")){ + + String baseItemFactColumn = singlePanel.getItem().get(0).getFacttablecolumn(); + int lastIndex = baseItemFactColumn.lastIndexOf("."); + String factTable = dataSourceLookup.getFullSchema() + "."+(baseItemFactColumn.substring(0, lastIndex)); + + DerivedFactColumnsType columns = getFactColumnsFromOntologyCell(singlePanel.getItem().get(0).getItemKey()); + if(columns != null){ + if(columns.getDerivedFactTableColumn().size() > 1) { + // parse through solumns and build up replace string. + + Iterator it = columns.getDerivedFactTableColumn().iterator(); + String column = it.next(); + + lastIndex = column.lastIndexOf("."); + String table = dataSourceLookup.getFullSchema() + "."+ (column.substring(0, lastIndex)); + + + factTable = "( select * from " + table; + while(it.hasNext()){ + column = it.next(); + + lastIndex = column.lastIndexOf("."); + table = dataSourceLookup.getFullSchema() + "."+ (column.substring(0, lastIndex)); + + factTable += "\n UNION ALL \n" + + " select * from " + table; + } + factTable += " )"; + + } + } + log.debug("Parse columns " + factTable); + totalSql=totalSql.replaceAll(defaultTableName, factTable) ; + + + + } + } + + + + + + } + + panelSqlList.add("SELECT " + + countClause + + " from ( " + + totalSql + " ) " + countSqlFrom + " totalsql"); + } + + totalObservations = pageTotalDao.getTotalForAllPanel(panelSqlList, + sqlCountList, inputOptionListHandler); + return totalObservations; + } + + public HashMap getMinPatientIndexAndTheTotal(int maxInputList) + throws SQLException, I2B2Exception { + + IInputOptionListHandler inputOptionListHandler = PDOFactory + .buildInputListHandler(inputList, dataSourceLookup); + + // inputList.getPatientList().setMax(maxInputList); + inputOptionListHandler.setMaxIndex(maxInputList); + + // iterate the panel and call total + IFactRelatedQueryHandler factRelatedHandler = null; + String countSqlFrom = " "; + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.ORACLE) || dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) { + factRelatedHandler = new FactRelatedQueryHandler(dataSourceLookup, + inputList, filterList, outputOptionList); + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER)) { + countSqlFrom = "as"; + factRelatedHandler = new SQLServerFactRelatedQueryHandler( + dataSourceLookup, inputList, filterList, outputOptionList); + } + //set project param + factRelatedHandler.setProjectParamMap(this.projectParamMap); + factRelatedHandler.setModifierMetadataXmlMap(this.modifierMetadataXmlMap); + + FactOutputOptionType factOutputOptionType = new FactOutputOptionType(); + factOutputOptionType.setOnlykeys(true); + outputOptionList.setObservationSet(factOutputOptionType); + // outputOptionList.getObservationSet().setOnlykeys(true); + + // build sql for all the panel + // DAOFactoryHelper daoFactoryHelper = new DAOFactoryHelper( + // dataSourceLookup); + + IPageDao pageTotalDao = daoFactoryHelper.getDAOFactory() + .getPatientDataDAOFactory().getPageDAO(); + int panelCount = filterList.getPanel().size(); + List panelMinSqlList = new ArrayList(panelCount); + List sqlCountList = new ArrayList(panelCount); + long totalObservations = 0; + // things to consider to find the minimum + // a)How to handle the different input list (i.e. enumeration list,table + // or patient_dimension) + + String panelSql = ""; + for (PanelType singlePanel : filterList.getPanel()) { + int sqlParamCount = singlePanel.getItem().size(); + if (singlePanel.getInvert() == 1) { + sqlParamCount++; + } + if (inputOptionListHandler.isCollectionId()) { + sqlParamCount++; + } + + sqlCountList.add(sqlParamCount); + + panelSql = pageTotalDao.buildTotalSql(factRelatedHandler, + singlePanel); + if (panelSql.length() ==0) { + continue; + } + String minSql = inputOptionListHandler + .generateMinIndexSql(panelSql); + log.debug("min sql for panel " + minSql); + panelMinSqlList.add(minSql); + + } + + return pageTotalDao.getMinIndexAndCountAllPanel(panelMinSqlList, + sqlCountList, inputOptionListHandler); + + } + + public int getMinPercent() throws I2B2Exception { + return qpUtil.getPagingInputListMinPercent(); + + } + + public long getPageSize() throws I2B2Exception { + return qpUtil.getPagingObservationSize(); + } + + public int getPagingMaxIteration() throws I2B2Exception { + return qpUtil.getPagingIterationCount(); + + } + + public int getPagingMinSize() throws I2B2Exception { + return qpUtil.getPagingInputListMinSize(); + } + + /** + * @return + * @throws SQLException + * @throws I2B2Exception + */ + public HashMap calculateMaxPageInputList() throws SQLException, + I2B2Exception { + int maxIteration = getPagingMaxIteration(); + int i = 0; + long pageSize = getPageSize(); + boolean fitPagingFlag = false; + HashMap returnResultMap = new HashMap(); + returnResultMap.put("PAGING_REQUIRED_FLAG", true); + long totalObservations = 0; + // PatientListTypeHandler patientList = new PatientListTypeHandler( + // dataSourceLookup, inputList.getPatientList()); + + IInputOptionListHandler inputOptionListHandler = PDOFactory + .buildInputListHandler(inputList, dataSourceLookup); + + int maxInputList = inputOptionListHandler.getMaxIndex(); + int minInputList = inputOptionListHandler.getMinIndex(); + int originalMaxInputList = maxInputList; + int inputListCount = maxInputList - minInputList; + while (i < maxIteration) { + totalObservations = getTotal(inputListCount); + log.debug("Total observations for [" + inputListCount + " ] is [" + + totalObservations + " ]"); + // + if (i == 0) { + returnResultMap.put("TOTAL_OBSERVATION", totalObservations); + } + + // if total < page size then set max patient break + if (checkIfFitThePage(pageSize, totalObservations)) { + log.debug("Input list size of [" + inputListCount + + "] fits the page size [" + pageSize + "]"); + fitPagingFlag = true; + if (i == 0) { + returnResultMap.put("PAGING_REQUIRED_FLAG", false); + } + break; + } + + // call paging method with page size, total observation,.. + inputListCount = pageMethod.calculateListSize(inputListCount, + totalObservations, pageSize); + + if (inputListCount < 1) { + // need not continue the iteration if the list size is reduced + // to < 1 + break; + } + i++; + } + + if (fitPagingFlag) { + returnResultMap.put("MAX_INPUT_LIST", inputListCount); + return returnResultMap; + } else { + throw new I2B2Exception("Could not fit in a page after [" + + maxIteration + "] iteration"); + } + + /* + * // try with minimum percent of patient int minIndex = + * patientList.getMinIndex(); int maxIndex = originalMaxInputList; int + * listLength = maxIndex - minIndex; int minPercentInput = + * getMinPercentInput(listLength); + * log.debug("Trying with minimum input list percent of [ " + + * minPercentInput + "]"); + * + * if (minPercentInput > 0) { if (minPercentInput < maxInputList) { + * totalObservations = getTotal(minPercentInput); log + * .debug("Total observations for minimum input list percent [" + + * minPercentInput + " ] is [" + totalObservations + " ]"); if + * (totalObservations > 0 && checkIfFitThePage(pageSize, + * totalObservations)) { maxInputList = minIndex + minPercentInput; + * returnResultMap.put("MAX_INPUT_LIST", maxInputList); return + * returnResultMap; } } } else { log + * .debug("Skipping minimum input list percent, since the value is 0"); + * } + */ + + // try with minimun of single patient + // int minPagingSize = getPagingMinSize(); + // log.debug("Trying with minimum input list size of [" + minPagingSize + // + "]"); + // if (minPagingSize < 1) { + // throw new I2B2DAOException( + // "Paging failed, minimum page size should not be less than 1"); + // } + // + // HashMap minMap = getMinPatientIndexAndTheTotal(originalMaxInputList); + // int minDataIndex = (Integer) minMap.get("MIN_INDEX"); + // long minDataIndexTotal = (Long) minMap.get("MIN_INDEX_TOTAL"); + // + // System.out.println("min index" + minMap.get("MIN_INDEX")); + // System.out.println("min index total " + + // minMap.get("MIN_INDEX_TOTAL")); + // + // // totalObservations = getTotal(minPagingSize); + // log.debug("Total observation for first data index [" + minDataIndex + // + " ] is [" + minDataIndexTotal + "]"); + // + // if (!checkIfFitThePage(pageSize, minDataIndexTotal)) { + // throw new I2B2DAOException( + // "Paging failed, even the first patient index of [" + // + minDataIndex + "] patient observations [" + // + minDataIndexTotal + // + "] could not fit the page size [" + pageSize + // + "]"); + // } else { + // + // returnResultMap.put("MAX_INPUT_LIST", minDataIndex); + // return returnResultMap; + // } + } + + public int getMinPercentInput(int listLength) throws I2B2Exception { + int minPercent = getMinPercent(); + + int minPercentOfList = listLength * (minPercent / 100); + return minPercentOfList; + } + + private boolean checkIfFitThePage(long pageSize, long totalObservations) { + return (pageSize >= totalObservations); + + } + + + protected DerivedFactColumnsType getFactColumnsFromOntologyCell(String itemKey) + throws ConceptNotFoundException, OntologyException { + DerivedFactColumnsType factColumns = new DerivedFactColumnsType(); + try { + + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + String ontologyUrl = qpUtil + .getCRCPropertyValue(QueryProcessorUtil.ONTOLOGYCELL_ROOT_WS_URL_PROPERTIES); + + + SecurityType securityType = PMServiceAccountUtil + .getServiceSecurityType(dataSourceLookup.getDomainId()); + + + factColumns = CallOntologyUtil.callGetFactColumns(itemKey, + securityType, dataSourceLookup.getProjectPath(), + ontologyUrl +"/getDerivedFactColumns"); + } catch (JAXBUtilException e) { + + log.error("Error while fetching metadata [" + itemKey + + "] from ontology ", e); + throw new OntologyException("Error while fetching metadata [" + + itemKey + "] from ontology " + + StackTraceUtil.getStackTrace(e)); + } catch (I2B2Exception e) { + log.error("Error while fetching metadata from ontology ", e); + throw new OntologyException("Error while fetching metadata [" + + itemKey + "] from ontology " + + StackTraceUtil.getStackTrace(e)); + } catch (AxisFault e) { + log.error("Error while fetching metadata from ontology ", e); + throw new OntologyException("Error while fetching metadata [" + + itemKey + "] from ontology " + + StackTraceUtil.getStackTrace(e)); + } catch (XMLStreamException e) { + log.error("Error while fetching metadata from ontology ", e); + throw new OntologyException("Error while fetching metadata [" + + itemKey + "] from ontology " + + StackTraceUtil.getStackTrace(e)); + } + +// if (factColumns.isEmpty()) { +// throw new ConceptNotFoundException("[" + itemKey + "] "); + +// } + + return factColumns; + } + + + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/input/PatientListTypeHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/input/PatientListTypeHandler.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/input/PatientListTypeHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/input/PatientListTypeHandler.java index a99212be..9f6c619b --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/input/PatientListTypeHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/input/PatientListTypeHandler.java @@ -1,476 +1,476 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao.pdo.input; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.List; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.dao.setfinder.IQueryResultInstanceDao; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.db.QtQueryResultInstance; -import edu.harvard.i2b2.crc.datavo.pdo.query.PatientListType; -import edu.harvard.i2b2.crc.datavo.pdo.query.PatientListType.PatientId; - -/** - * Handler class for patient list type to generate "where" clause for pdo - * request $Id: PatientListTypeHandler.java,v 1.8 2008/06/10 14:59:04 rk903 Exp - * $ - * - * @author rkuttan - */ -public class PatientListTypeHandler extends CRCDAO implements - IInputOptionListHandler { - private PatientListType patientListType = null; - private int minIndex = 0; - private int maxIndex = 0; - private String patientSetCollId = ""; - private List patientNumList = null; - private DataSourceLookup dataSourceLookup = null; - private boolean deleteTempTableFlag = false; - - /** - * Constructor accepts {@link PatientListType} - * - * @param patientListType - * @throws I2B2DAOException - */ - public PatientListTypeHandler(DataSourceLookup dataSourceLookup, - final PatientListType patientListType) throws I2B2DAOException { - if (patientListType == null) { - throw new I2B2DAOException("Patient List Type is null"); - } - this.dataSourceLookup = dataSourceLookup; - this.setDbSchemaName(dataSourceLookup.getFullSchema()); - this.patientListType = patientListType; - - if (patientListType.getMin() != null) { - minIndex = patientListType.getMin(); - } - - if (patientListType.getMax() != null) { - maxIndex = patientListType.getMax(); - } - - } - - @Override - public int getMinIndex() { - return minIndex; - } - - @Override - public int getMaxIndex() { - return maxIndex; - } - - @Override - public void setMaxIndex(int maxIndex) { - patientListType.setMax(maxIndex); - } - - /** - * Function to generate "where" clause for patient list - */ - @Override - public String generateMinIndexSql(String panelSql) { - String sqlString = null; - - if (patientListType.getPatientSetCollId() != null) { - // set patient set coll id - this.patientSetCollId = this.getCollectionId(); - - String asClause = "as"; - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE)) { - asClause = " "; - } - - // set sql string - sqlString = "select min(set_index) ,count(*) from " - + this.getDbSchemaName() - + "qt_patient_set_collection pset where pset.result_instance_id = ? "; - - if (minIndex <= maxIndex) { - sqlString += (" and pset.set_index between " + minIndex - + " and " + maxIndex); - } - sqlString += " and pset.patient_num in (select obs_patient_num from ( " - + panelSql + " ) " + asClause + " panelPatientSubQuery ) "; - } else if ((patientListType.getPatientId() != null) - && (patientListType.getPatientId().size() > 0)) { - - this.getEnumerationList(); - - String tempTableName = ""; - String asClause = "as"; - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE)) { - tempTableName = FactRelatedQueryHandler.TEMP_PARAM_TABLE; - asClause = " "; - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER) || dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) { - tempTableName = SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE; - } - sqlString = " select min(set_index), count(*) from " - + this.getDbSchemaName() + tempTableName; - sqlString += " where "; - if (minIndex <= maxIndex) { - if (maxIndex == 1) { - minIndex = 0; - } - sqlString += " set_index between " + minIndex + " and " - + maxIndex; - } - sqlString += " and char_param1 in (select obs_patient_num from ( " - + panelSql + " )" + asClause + " panelPatientSubQuery )"; - - } else if (patientListType.getEntirePatientSet() != null) { - // by default get first 100 rows - if ((minIndex == 0) && (maxIndex == 0)) { - minIndex = 0; - maxIndex = 100; - } - - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE)) { - // do nothing - sqlString = " select patient_num from (select p.*, ROWNUM rnum from ( select patient_num from " - + this.getDbSchemaName() - + "patient_dimension order by patient_num) p " - + " where ROWNUM<=" - + maxIndex - + " ) where rnum>=" - + minIndex; - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER) || dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) { - sqlString = " select patient_num from (select *, ROW_number() over (order by patient_num asc) as rnum " - + " from " - + this.getDbSchemaName() - + "patient_dimension p) as p1 where rnum between " - + minIndex + " and " + maxIndex; - } - } - - return sqlString; - } - - /** - * Function to generate "where" clause for patient list - */ - @Override - public String generateWhereClauseSql() { - String sqlString = null; - - if (patientListType.getPatientSetCollId() != null) { - // set patient set coll id - this.patientSetCollId = this.getCollectionId(); - - // set sql string - sqlString = "select pset.patient_num from " - + this.getDbSchemaName() - + "qt_patient_set_collection pset where pset.result_instance_id = ? "; - - if (minIndex <= maxIndex) { - sqlString += (" and pset.set_index between " + minIndex - + " and " + maxIndex); - } - } else if ((patientListType.getPatientId() != null) - && (patientListType.getPatientId().size() > 0)) { - - // this.getEnumerationList(); - String tempTableName = this.getTempTableName(); - - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) - { - sqlString = " select cast(char_param1 as integer) from " + tempTableName + " "; - } - else { - sqlString = " select char_param1 from " + tempTableName + " "; - - } - } else if (patientListType.getEntirePatientSet() != null) { - // by default get first 100 rows - if ((minIndex == 0) && (maxIndex == 0)) { - minIndex = 0; - maxIndex = 100; - } - - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE)) { - // do nothing - sqlString = " select patient_num from (select p.*, ROWNUM rnum from ( select patient_num from " - + this.getDbSchemaName() - + "patient_dimension order by patient_num) p " - + " where ROWNUM<=" - + maxIndex - + " ) where rnum>=" - + minIndex; - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER) || dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) { - sqlString = " select patient_num from (select *, ROW_number() over (order by patient_num asc) as rnum " - + " from " - + this.getDbSchemaName() - + "patient_dimension p) as p1 where rnum between " - + minIndex + " and " + maxIndex; - } - } - - return sqlString; - } - - public List getIntListFromPatientNumList() { - return this.patientNumList; - } - - @Override - public String getCollectionId() { - if (isCollectionId()) { - return patientListType.getPatientSetCollId(); - } else { - return ""; - } - - } - - @Override - public List getEnumerationList() { - ArrayList patientNumArrayList = new ArrayList( - patientListType.getPatientId().size() + 1); - patientNumArrayList.add(""); - - // index 0 - // patientNumArrayList.add(""); - for (PatientListType.PatientId patientNum : patientListType - .getPatientId()) { - - // patientNum.getIndex() - // TODO see if we can use index value from patientNum - patientNumArrayList.add(patientNum.getValue()); - - } - - if (maxIndex >= patientListType.getPatientId().size() + 1) { - maxIndex = patientListType.getPatientId().size() + 1; - } else { - maxIndex += 1; - } - - // set int List - if (minIndex < maxIndex) { - this.patientNumList = patientNumArrayList.subList(minIndex, - maxIndex); - } else if (minIndex == maxIndex && minIndex > 0) { - // check if maxIndex is equal to last index - if (maxIndex == patientListType.getPatientId().size() - 1) { - this.patientNumList = new ArrayList(); - this.patientNumList.add(patientNumArrayList.get(maxIndex)); - } else { - this.patientNumList = patientNumArrayList.subList(minIndex, - maxIndex); - } - - } else { - maxIndex = patientNumArrayList.size(); - this.patientNumList = patientNumArrayList.subList(minIndex, - maxIndex); - } - log.debug(" MAX INDEX *** " + maxIndex); - return this.patientNumList; - } - - @Override - public boolean isCollectionId() { - if (patientListType.getPatientSetCollId() != null) { - return true; - } else { - return false; - } - } - - @Override - public boolean isEntireSet() { - if (patientListType.getEntirePatientSet() != null) { - return true; - } else { - return false; - } - } - - @Override - public boolean isEnumerationSet() { - if ((patientListType.getPatientId() != null) - && (patientListType.getPatientId().size() > 0)) { - return true; - } else { - return false; - } - } - - /** - * Returns input list's size. if the list is collection id, then collection - * set size, if the list is entire set, then total rows in dimension table - * if the list is enumeration, then size of enumeration set - * - * @return - * @throws I2B2DAOException - */ - @Override - public int getInputSize() throws I2B2DAOException { - if (this.isEnumerationSet()) { - return patientListType.getPatientId().size(); - } else if (this.isCollectionId()) { - DAOFactoryHelper helper = new DAOFactoryHelper(dataSourceLookup - .getDomainId(), dataSourceLookup.getProjectPath(), - dataSourceLookup.getOwnerId()); - IQueryResultInstanceDao resultInstanceDao = helper.getDAOFactory() - .getSetFinderDAOFactory().getPatientSetResultDAO(); - - QtQueryResultInstance resultInstance = resultInstanceDao - .getResultInstanceById(this.getCollectionId()); - return resultInstance.getSetSize(); - } else if (this.isEntireSet()) { - return 1000; - } else { - return 0; - } - } - - @Override - public void uploadEnumerationValueToTempTable(Connection conn) - throws SQLException { - - String tempTableName = this.getTempTableName(); - deleteTempTableFlag = true; - deleteTempTable(conn); - // create temp table - java.sql.Statement tempStmt = conn.createStatement(); - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER)) { - String createTempInputListTable = "create table " - + getTempTableName() - + " (set_index int, char_param1 varchar(100) )"; - tempStmt.executeUpdate(createTempInputListTable); - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) - { - String createTempInputListTable = "create temp table " - + getTempTableName() - + " (set_index int, char_param1 varchar(100) )"; - tempStmt.executeUpdate(createTempInputListTable); - } - int i = 0, j = 1; - - List pidList = patientListType.getPatientId(); - List finalPidList = new ArrayList(); - if (maxIndex > patientListType.getPatientId().size()) { - // log.warn("max size is more than list size"); - maxIndex = patientListType.getPatientId().size(); - } - if (minIndex < maxIndex) { - finalPidList = pidList.subList(minIndex, maxIndex); - } else if (minIndex == maxIndex && minIndex > 0) { - // check if maxIndex is equal to last index - if (maxIndex == patientListType.getPatientId().size() - 1) { - finalPidList.add(pidList.get(maxIndex)); - } else { - finalPidList = pidList.subList(minIndex, maxIndex); - } - - } else { - maxIndex = pidList.size(); - finalPidList = pidList.subList(minIndex, maxIndex); - } - PreparedStatement preparedStmt = conn.prepareStatement("insert into " - + tempTableName + "(set_index,char_param1) values (?,?)"); - for (PatientId pid : finalPidList) { - preparedStmt.setInt(1, j++); - preparedStmt.setString(2, pid.getValue()); - preparedStmt.addBatch(); - i++; - if (i % 100 == 0) { - preparedStmt.executeBatch(); - - } - - } - preparedStmt.executeBatch(); - } - - @Override - public void deleteTempTable(Connection conn) throws SQLException { - if (!deleteTempTableFlag) { - return; - } - Statement deleteStmt = null; - try { - deleteStmt = conn.createStatement(); - - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER) || dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) { - // conn.createStatement().executeUpdate( - // "drop table " + getTempTableName()); - deleteStmt.executeUpdate( - "drop table " + getTempTableName()); - - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE)) { - //conn.createStatement().executeUpdate( - // "delete " + getTempTableName()); - deleteStmt.executeUpdate( - "delete " + getTempTableName()); - } - } catch (SQLException sqle) { - //throw sqle; - } finally { - try { - if(deleteStmt != null) - deleteStmt.close(); - } catch (SQLException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } - - private String getTempTableName() { - String tempTableName = ""; - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE)) { - tempTableName = this.getDbSchemaName() - + FactRelatedQueryHandler.TEMP_PARAM_TABLE; - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) { - tempTableName = SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE.substring(1); - - } else { - tempTableName = this.getDbSchemaName() - + SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE; - } - return tempTableName; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao.pdo.input; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.dao.setfinder.IQueryResultInstanceDao; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.db.QtQueryResultInstance; +import edu.harvard.i2b2.crc.datavo.pdo.query.PatientListType; +import edu.harvard.i2b2.crc.datavo.pdo.query.PatientListType.PatientId; + +/** + * Handler class for patient list type to generate "where" clause for pdo + * request $Id: PatientListTypeHandler.java,v 1.8 2008/06/10 14:59:04 rk903 Exp + * $ + * + * @author rkuttan + */ +public class PatientListTypeHandler extends CRCDAO implements + IInputOptionListHandler { + private PatientListType patientListType = null; + private int minIndex = 0; + private int maxIndex = 0; + private String patientSetCollId = ""; + private List patientNumList = null; + private DataSourceLookup dataSourceLookup = null; + private boolean deleteTempTableFlag = false; + + /** + * Constructor accepts {@link PatientListType} + * + * @param patientListType + * @throws I2B2DAOException + */ + public PatientListTypeHandler(DataSourceLookup dataSourceLookup, + final PatientListType patientListType) throws I2B2DAOException { + if (patientListType == null) { + throw new I2B2DAOException("Patient List Type is null"); + } + this.dataSourceLookup = dataSourceLookup; + this.setDbSchemaName(dataSourceLookup.getFullSchema()); + this.patientListType = patientListType; + + if (patientListType.getMin() != null) { + minIndex = patientListType.getMin(); + } + + if (patientListType.getMax() != null) { + maxIndex = patientListType.getMax(); + } + + } + + @Override + public int getMinIndex() { + return minIndex; + } + + @Override + public int getMaxIndex() { + return maxIndex; + } + + @Override + public void setMaxIndex(int maxIndex) { + patientListType.setMax(maxIndex); + } + + /** + * Function to generate "where" clause for patient list + */ + @Override + public String generateMinIndexSql(String panelSql) { + String sqlString = null; + + if (patientListType.getPatientSetCollId() != null) { + // set patient set coll id + this.patientSetCollId = this.getCollectionId(); + + String asClause = "as"; + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.ORACLE)) { + asClause = " "; + } + + // set sql string + sqlString = "select min(set_index) ,count(*) from " + + this.getDbSchemaName() + + "qt_patient_set_collection pset where pset.result_instance_id = ? "; + + if (minIndex <= maxIndex) { + sqlString += (" and pset.set_index between " + minIndex + + " and " + maxIndex); + } + sqlString += " and pset.patient_num in (select obs_patient_num from ( " + + panelSql + " ) " + asClause + " panelPatientSubQuery ) "; + } else if ((patientListType.getPatientId() != null) + && (patientListType.getPatientId().size() > 0)) { + + this.getEnumerationList(); + + String tempTableName = ""; + String asClause = "as"; + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.ORACLE)) { + tempTableName = FactRelatedQueryHandler.TEMP_PARAM_TABLE; + asClause = " "; + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER) || dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) { + tempTableName = SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE; + } + sqlString = " select min(set_index), count(*) from " + + this.getDbSchemaName() + tempTableName; + sqlString += " where "; + if (minIndex <= maxIndex) { + if (maxIndex == 1) { + minIndex = 0; + } + sqlString += " set_index between " + minIndex + " and " + + maxIndex; + } + sqlString += " and char_param1 in (select obs_patient_num from ( " + + panelSql + " )" + asClause + " panelPatientSubQuery )"; + + } else if (patientListType.getEntirePatientSet() != null) { + // by default get first 100 rows + if ((minIndex == 0) && (maxIndex == 0)) { + minIndex = 0; + maxIndex = 100; + } + + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.ORACLE)) { + // do nothing + sqlString = " select patient_num from (select p.*, ROWNUM rnum from ( select patient_num from " + + this.getDbSchemaName() + + "patient_dimension order by patient_num) p " + + " where ROWNUM<=" + + maxIndex + + " ) where rnum>=" + + minIndex; + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER) || dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) { + sqlString = " select patient_num from (select *, ROW_number() over (order by patient_num asc) as rnum " + + " from " + + this.getDbSchemaName() + + "patient_dimension p) as p1 where rnum between " + + minIndex + " and " + maxIndex; + } + } + + return sqlString; + } + + /** + * Function to generate "where" clause for patient list + */ + @Override + public String generateWhereClauseSql() { + String sqlString = null; + + if (patientListType.getPatientSetCollId() != null) { + // set patient set coll id + this.patientSetCollId = this.getCollectionId(); + + // set sql string + sqlString = "select pset.patient_num from " + + this.getDbSchemaName() + + "qt_patient_set_collection pset where pset.result_instance_id = ? "; + + if (minIndex <= maxIndex) { + sqlString += (" and pset.set_index between " + minIndex + + " and " + maxIndex); + } + } else if ((patientListType.getPatientId() != null) + && (patientListType.getPatientId().size() > 0)) { + + // this.getEnumerationList(); + String tempTableName = this.getTempTableName(); + + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) + { + sqlString = " select cast(char_param1 as integer) from " + tempTableName + " "; + } + else { + sqlString = " select char_param1 from " + tempTableName + " "; + + } + } else if (patientListType.getEntirePatientSet() != null) { + // by default get first 100 rows + if ((minIndex == 0) && (maxIndex == 0)) { + minIndex = 0; + maxIndex = 100; + } + + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.ORACLE)) { + // do nothing + sqlString = " select patient_num from (select p.*, ROWNUM rnum from ( select patient_num from " + + this.getDbSchemaName() + + "patient_dimension order by patient_num) p " + + " where ROWNUM<=" + + maxIndex + + " ) where rnum>=" + + minIndex; + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER) || dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) { + sqlString = " select patient_num from (select *, ROW_number() over (order by patient_num asc) as rnum " + + " from " + + this.getDbSchemaName() + + "patient_dimension p) as p1 where rnum between " + + minIndex + " and " + maxIndex; + } + } + + return sqlString; + } + + public List getIntListFromPatientNumList() { + return this.patientNumList; + } + + @Override + public String getCollectionId() { + if (isCollectionId()) { + return patientListType.getPatientSetCollId(); + } else { + return ""; + } + + } + + @Override + public List getEnumerationList() { + ArrayList patientNumArrayList = new ArrayList( + patientListType.getPatientId().size() + 1); + patientNumArrayList.add(""); + + // index 0 + // patientNumArrayList.add(""); + for (PatientListType.PatientId patientNum : patientListType + .getPatientId()) { + + // patientNum.getIndex() + // TODO see if we can use index value from patientNum + patientNumArrayList.add(patientNum.getValue()); + + } + + if (maxIndex >= patientListType.getPatientId().size() + 1) { + maxIndex = patientListType.getPatientId().size() + 1; + } else { + maxIndex += 1; + } + + // set int List + if (minIndex < maxIndex) { + this.patientNumList = patientNumArrayList.subList(minIndex, + maxIndex); + } else if (minIndex == maxIndex && minIndex > 0) { + // check if maxIndex is equal to last index + if (maxIndex == patientListType.getPatientId().size() - 1) { + this.patientNumList = new ArrayList(); + this.patientNumList.add(patientNumArrayList.get(maxIndex)); + } else { + this.patientNumList = patientNumArrayList.subList(minIndex, + maxIndex); + } + + } else { + maxIndex = patientNumArrayList.size(); + this.patientNumList = patientNumArrayList.subList(minIndex, + maxIndex); + } + log.debug(" MAX INDEX *** " + maxIndex); + return this.patientNumList; + } + + @Override + public boolean isCollectionId() { + if (patientListType.getPatientSetCollId() != null) { + return true; + } else { + return false; + } + } + + @Override + public boolean isEntireSet() { + if (patientListType.getEntirePatientSet() != null) { + return true; + } else { + return false; + } + } + + @Override + public boolean isEnumerationSet() { + if ((patientListType.getPatientId() != null) + && (patientListType.getPatientId().size() > 0)) { + return true; + } else { + return false; + } + } + + /** + * Returns input list's size. if the list is collection id, then collection + * set size, if the list is entire set, then total rows in dimension table + * if the list is enumeration, then size of enumeration set + * + * @return + * @throws I2B2DAOException + */ + @Override + public int getInputSize() throws I2B2DAOException { + if (this.isEnumerationSet()) { + return patientListType.getPatientId().size(); + } else if (this.isCollectionId()) { + DAOFactoryHelper helper = new DAOFactoryHelper(dataSourceLookup + .getDomainId(), dataSourceLookup.getProjectPath(), + dataSourceLookup.getOwnerId()); + IQueryResultInstanceDao resultInstanceDao = helper.getDAOFactory() + .getSetFinderDAOFactory().getPatientSetResultDAO(); + + QtQueryResultInstance resultInstance = resultInstanceDao + .getResultInstanceById(this.getCollectionId()); + return resultInstance.getSetSize(); + } else if (this.isEntireSet()) { + return 1000; + } else { + return 0; + } + } + + @Override + public void uploadEnumerationValueToTempTable(Connection conn) + throws SQLException { + + String tempTableName = this.getTempTableName(); + deleteTempTableFlag = true; + deleteTempTable(conn); + // create temp table + java.sql.Statement tempStmt = conn.createStatement(); + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER)) { + String createTempInputListTable = "create table " + + getTempTableName() + + " (set_index int, char_param1 varchar(100) )"; + tempStmt.executeUpdate(createTempInputListTable); + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) + { + String createTempInputListTable = "create temp table " + + getTempTableName() + + " (set_index int, char_param1 varchar(100) )"; + tempStmt.executeUpdate(createTempInputListTable); + } + int i = 0, j = 1; + + List pidList = patientListType.getPatientId(); + List finalPidList = new ArrayList(); + if (maxIndex > patientListType.getPatientId().size()) { + // log.warn("max size is more than list size"); + maxIndex = patientListType.getPatientId().size(); + } + if (minIndex < maxIndex) { + finalPidList = pidList.subList(minIndex, maxIndex); + } else if (minIndex == maxIndex && minIndex > 0) { + // check if maxIndex is equal to last index + if (maxIndex == patientListType.getPatientId().size() - 1) { + finalPidList.add(pidList.get(maxIndex)); + } else { + finalPidList = pidList.subList(minIndex, maxIndex); + } + + } else { + maxIndex = pidList.size(); + finalPidList = pidList.subList(minIndex, maxIndex); + } + PreparedStatement preparedStmt = conn.prepareStatement("insert into " + + tempTableName + "(set_index,char_param1) values (?,?)"); + for (PatientId pid : finalPidList) { + preparedStmt.setInt(1, j++); + preparedStmt.setString(2, pid.getValue()); + preparedStmt.addBatch(); + i++; + if (i % 100 == 0) { + preparedStmt.executeBatch(); + + } + + } + preparedStmt.executeBatch(); + } + + @Override + public void deleteTempTable(Connection conn) throws SQLException { + if (!deleteTempTableFlag) { + return; + } + Statement deleteStmt = null; + try { + deleteStmt = conn.createStatement(); + + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER) || dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) { + // conn.createStatement().executeUpdate( + // "drop table " + getTempTableName()); + deleteStmt.executeUpdate( + "drop table " + getTempTableName()); + + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.ORACLE)) { + //conn.createStatement().executeUpdate( + // "delete " + getTempTableName()); + deleteStmt.executeUpdate( + "delete " + getTempTableName()); + } + } catch (SQLException sqle) { + //throw sqle; + } finally { + try { + if(deleteStmt != null) + deleteStmt.close(); + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + + private String getTempTableName() { + String tempTableName = ""; + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.ORACLE)) { + tempTableName = this.getDbSchemaName() + + FactRelatedQueryHandler.TEMP_PARAM_TABLE; + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) { + tempTableName = SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE.substring(1); + + } else { + tempTableName = this.getDbSchemaName() + + SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE; + } + return tempTableName; + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/input/PidListTypeHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/input/PidListTypeHandler.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/input/PidListTypeHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/input/PidListTypeHandler.java index 19defc23..b2bcfa45 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/input/PidListTypeHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/input/PidListTypeHandler.java @@ -1,268 +1,268 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao.pdo.input; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.List; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.pdo.query.EventListType; -import edu.harvard.i2b2.crc.datavo.pdo.query.PidListType; -import edu.harvard.i2b2.crc.datavo.pdo.query.PidListType.Pid; - -/** - * Handler class for pid list type to generate "where" clause for pdo request - * $Id: PidListTypeHandler.java,v 1.5 2009/10/23 19:54:02 rk903 Exp $ - * - * @author rkuttan - */ -public class PidListTypeHandler extends CRCDAO implements - IInputOptionListHandler { - private PidListType pidListType = null; - private int minIndex = 0; - private int maxIndex = 0; - private String encounterSetCollId = ""; - private List encounterNumList = null; - private DataSourceLookup dataSourceLookup = null; - private boolean deleteTempTableFlag = false; - - /** - * Constructor accepts {@link EventListType} - * - * @param visitListType - * @throws I2B2DAOException - */ - public PidListTypeHandler(DataSourceLookup dataSourceLookup, - PidListType pidListType) throws I2B2DAOException { - if (pidListType == null) { - throw new I2B2DAOException("Pid List Type is null"); - } - - this.dataSourceLookup = dataSourceLookup; - setDbSchemaName(dataSourceLookup.getFullSchema()); - this.pidListType = pidListType; - - if (pidListType.getMin() != null) { - minIndex = pidListType.getMin(); - } - - if (pidListType.getMax() != null) { - maxIndex = pidListType.getMax(); - } - } - - @Override - public int getMinIndex() { - return minIndex; - } - - @Override - public int getMaxIndex() { - return maxIndex; - } - - @Override - public boolean isCollectionId() { - return false; - } - - @Override - public boolean isEnumerationSet() { - if ((pidListType.getPid() != null) && (pidListType.getPid().size() > 0)) { - return true; - } else { - return false; - } - } - - @Override - public boolean isEntireSet() { - return false; - } - - /** - * Function to generate "where" clause for visit/event list - */ - @Override - public String generateWhereClauseSql() { - - String tempTableName = getTempTableName(); - - String sqlString = "SELECT " - + " pm.patient_num " - + " FROM " - + getDbSchemaName() - + "patient_mapping pm WHERE exists (select 1 FROM " - + tempTableName - + " where char_param1 = pm.patient_ide and char_param2 = pm.patient_ide_source) "; - return sqlString; - } - - public String generatePatentSql() { - String sqlString = null; - - return sqlString; - } - - @Override - public List getEnumerationList() { - ArrayList encounterNumArrayList = new ArrayList(); - return this.encounterNumList; - } - - @Override - public void uploadEnumerationValueToTempTable(Connection conn) - throws SQLException { - - String tempTableName = this.getTempTableName(); - deleteTempTableFlag = true; - // create temp table - java.sql.Statement tempStmt = conn.createStatement(); - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER)) { - String createTempInputListTable = "create table " - + getTempTableName() - + " (set_index int, char_param1 varchar(100), char_param2 varchar(100) )"; - tempStmt.executeUpdate(createTempInputListTable); - } - int i = 0, j = 1; - - List pidList = pidListType.getPid(); - List finalPidList = new ArrayList(); - if (maxIndex > pidListType.getPid().size()) { - // log.warn("max size is more than list size"); - maxIndex = pidListType.getPid().size(); - } - if (minIndex < maxIndex) { - finalPidList = pidList.subList(minIndex, maxIndex); - } else if (minIndex == maxIndex && minIndex > 0) { - // check if maxIndex is equal to last index - if (maxIndex == pidListType.getPid().size() - 1) { - finalPidList.add(pidList.get(maxIndex)); - } else { - finalPidList = pidList.subList(minIndex, maxIndex); - } - - } else { - maxIndex = pidList.size(); - finalPidList = pidList.subList(minIndex, maxIndex); - } - - PreparedStatement preparedStmt = conn.prepareStatement("insert into " - + tempTableName - + "(set_index,char_param1,char_param2) values (?,?,?)"); - for (Pid pid : finalPidList) { - preparedStmt.setInt(1, j++); - preparedStmt.setString(2, pid.getValue()); - preparedStmt.setString(3, pid.getSource()); - preparedStmt.addBatch(); - i++; - if (i % 100 == 0) { - preparedStmt.executeBatch(); - - } - log.debug("loading " + pid.getValue() + " " + pid.getSource()); - } - preparedStmt.executeBatch(); - } - - @Override - public void deleteTempTable(Connection conn) throws SQLException { - if (!deleteTempTableFlag) { - return; - } - Statement deleteStmt = null; - try { - deleteStmt = conn.createStatement(); - - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER) || dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) { - //conn.createStatement().executeUpdate( - // "drop table " + getTempTableName()); - deleteStmt.executeUpdate( - "drop table " + getTempTableName()); - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE)) { - //conn.createStatement().executeUpdate( - // "delete " + getTempTableName()); - deleteStmt.executeUpdate( - "delete " + getTempTableName()); - } - } catch (SQLException sqle) { - throw sqle; - } finally { - try { - if(deleteStmt == null) - deleteStmt.close(); - } catch (SQLException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } - - @Override - public String getCollectionId() { - return ""; - } - - @Override - public String generateMinIndexSql(String panelSql) { - // TODO Auto-generated method stub - return null; - } - - /** - * Returns input list's size. if the list is collection id, then collection - * set size, if the list is entire set, then total rows in dimension table - * if the list is enumeration, then size of enumeration set - * - * @return - * @throws I2B2DAOException - */ - @Override - public int getInputSize() throws I2B2DAOException { - - return 0; - - } - - @Override - public void setMaxIndex(int maxIndex) { - pidListType.setMax(maxIndex); - - } - - private String getTempTableName() { - String tempTableName = ""; - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE)) { - tempTableName = this.getDbSchemaName() - + FactRelatedQueryHandler.TEMP_PARAM_TABLE; - } else { - tempTableName = this.getDbSchemaName() - + SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE; - } - return tempTableName; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao.pdo.input; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.pdo.query.EventListType; +import edu.harvard.i2b2.crc.datavo.pdo.query.PidListType; +import edu.harvard.i2b2.crc.datavo.pdo.query.PidListType.Pid; + +/** + * Handler class for pid list type to generate "where" clause for pdo request + * $Id: PidListTypeHandler.java,v 1.5 2009/10/23 19:54:02 rk903 Exp $ + * + * @author rkuttan + */ +public class PidListTypeHandler extends CRCDAO implements + IInputOptionListHandler { + private PidListType pidListType = null; + private int minIndex = 0; + private int maxIndex = 0; + private String encounterSetCollId = ""; + private List encounterNumList = null; + private DataSourceLookup dataSourceLookup = null; + private boolean deleteTempTableFlag = false; + + /** + * Constructor accepts {@link EventListType} + * + * @param visitListType + * @throws I2B2DAOException + */ + public PidListTypeHandler(DataSourceLookup dataSourceLookup, + PidListType pidListType) throws I2B2DAOException { + if (pidListType == null) { + throw new I2B2DAOException("Pid List Type is null"); + } + + this.dataSourceLookup = dataSourceLookup; + setDbSchemaName(dataSourceLookup.getFullSchema()); + this.pidListType = pidListType; + + if (pidListType.getMin() != null) { + minIndex = pidListType.getMin(); + } + + if (pidListType.getMax() != null) { + maxIndex = pidListType.getMax(); + } + } + + @Override + public int getMinIndex() { + return minIndex; + } + + @Override + public int getMaxIndex() { + return maxIndex; + } + + @Override + public boolean isCollectionId() { + return false; + } + + @Override + public boolean isEnumerationSet() { + if ((pidListType.getPid() != null) && (pidListType.getPid().size() > 0)) { + return true; + } else { + return false; + } + } + + @Override + public boolean isEntireSet() { + return false; + } + + /** + * Function to generate "where" clause for visit/event list + */ + @Override + public String generateWhereClauseSql() { + + String tempTableName = getTempTableName(); + + String sqlString = "SELECT " + + " pm.patient_num " + + " FROM " + + getDbSchemaName() + + "patient_mapping pm WHERE exists (select 1 FROM " + + tempTableName + + " where char_param1 = pm.patient_ide and char_param2 = pm.patient_ide_source) "; + return sqlString; + } + + public String generatePatentSql() { + String sqlString = null; + + return sqlString; + } + + @Override + public List getEnumerationList() { + ArrayList encounterNumArrayList = new ArrayList(); + return this.encounterNumList; + } + + @Override + public void uploadEnumerationValueToTempTable(Connection conn) + throws SQLException { + + String tempTableName = this.getTempTableName(); + deleteTempTableFlag = true; + // create temp table + java.sql.Statement tempStmt = conn.createStatement(); + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER)) { + String createTempInputListTable = "create table " + + getTempTableName() + + " (set_index int, char_param1 varchar(100), char_param2 varchar(100) )"; + tempStmt.executeUpdate(createTempInputListTable); + } + int i = 0, j = 1; + + List pidList = pidListType.getPid(); + List finalPidList = new ArrayList(); + if (maxIndex > pidListType.getPid().size()) { + // log.warn("max size is more than list size"); + maxIndex = pidListType.getPid().size(); + } + if (minIndex < maxIndex) { + finalPidList = pidList.subList(minIndex, maxIndex); + } else if (minIndex == maxIndex && minIndex > 0) { + // check if maxIndex is equal to last index + if (maxIndex == pidListType.getPid().size() - 1) { + finalPidList.add(pidList.get(maxIndex)); + } else { + finalPidList = pidList.subList(minIndex, maxIndex); + } + + } else { + maxIndex = pidList.size(); + finalPidList = pidList.subList(minIndex, maxIndex); + } + + PreparedStatement preparedStmt = conn.prepareStatement("insert into " + + tempTableName + + "(set_index,char_param1,char_param2) values (?,?,?)"); + for (Pid pid : finalPidList) { + preparedStmt.setInt(1, j++); + preparedStmt.setString(2, pid.getValue()); + preparedStmt.setString(3, pid.getSource()); + preparedStmt.addBatch(); + i++; + if (i % 100 == 0) { + preparedStmt.executeBatch(); + + } + log.debug("loading " + pid.getValue() + " " + pid.getSource()); + } + preparedStmt.executeBatch(); + } + + @Override + public void deleteTempTable(Connection conn) throws SQLException { + if (!deleteTempTableFlag) { + return; + } + Statement deleteStmt = null; + try { + deleteStmt = conn.createStatement(); + + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER) || dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) { + //conn.createStatement().executeUpdate( + // "drop table " + getTempTableName()); + deleteStmt.executeUpdate( + "drop table " + getTempTableName()); + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.ORACLE)) { + //conn.createStatement().executeUpdate( + // "delete " + getTempTableName()); + deleteStmt.executeUpdate( + "delete " + getTempTableName()); + } + } catch (SQLException sqle) { + throw sqle; + } finally { + try { + if(deleteStmt == null) + deleteStmt.close(); + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + + @Override + public String getCollectionId() { + return ""; + } + + @Override + public String generateMinIndexSql(String panelSql) { + // TODO Auto-generated method stub + return null; + } + + /** + * Returns input list's size. if the list is collection id, then collection + * set size, if the list is entire set, then total rows in dimension table + * if the list is enumeration, then size of enumeration set + * + * @return + * @throws I2B2DAOException + */ + @Override + public int getInputSize() throws I2B2DAOException { + + return 0; + + } + + @Override + public void setMaxIndex(int maxIndex) { + pidListType.setMax(maxIndex); + + } + + private String getTempTableName() { + String tempTableName = ""; + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.ORACLE)) { + tempTableName = this.getDbSchemaName() + + FactRelatedQueryHandler.TEMP_PARAM_TABLE; + } else { + tempTableName = this.getDbSchemaName() + + SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE; + } + return tempTableName; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/input/SQLServerFactRelatedQueryHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/input/SQLServerFactRelatedQueryHandler.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/input/SQLServerFactRelatedQueryHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/input/SQLServerFactRelatedQueryHandler.java index 0c4620be..2d30c097 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/input/SQLServerFactRelatedQueryHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/input/SQLServerFactRelatedQueryHandler.java @@ -1,1524 +1,1524 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao.pdo.input; - -import java.io.IOException; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Vector; - -import javax.xml.datatype.XMLGregorianCalendar; -import javax.xml.stream.XMLStreamException; - -import org.apache.axis2.AxisFault; -import org.w3c.dom.Element; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.exception.StackTraceUtil; -import edu.harvard.i2b2.common.util.db.JDBCUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.common.util.xml.XMLOperatorLookup; -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.dao.pdo.I2B2PdoFactory; -import edu.harvard.i2b2.crc.dao.pdo.PdoQueryHandler; -import edu.harvard.i2b2.crc.dao.pdo.RPDRPdoFactory; -import edu.harvard.i2b2.crc.dao.pdo.filter.DimensionFilter; -import edu.harvard.i2b2.crc.dao.pdo.output.ConceptFactRelated; -import edu.harvard.i2b2.crc.dao.pdo.output.EidFactRelated; -import edu.harvard.i2b2.crc.dao.pdo.output.ModifierFactRelated; -import edu.harvard.i2b2.crc.dao.pdo.output.ObservationFactFactRelated; -import edu.harvard.i2b2.crc.dao.pdo.output.PatientFactRelated; -import edu.harvard.i2b2.crc.dao.pdo.output.PidFactRelated; -import edu.harvard.i2b2.crc.dao.pdo.output.ProviderFactRelated; -import edu.harvard.i2b2.crc.dao.pdo.output.VisitFactRelated; -import edu.harvard.i2b2.crc.dao.pdo.input.ModifierConstrainsHandler; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.ConceptNotFoundException; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.OntologyException; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.UnitConverstionUtil; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; -import edu.harvard.i2b2.crc.datavo.ontology.DerivedFactColumnsType; -import edu.harvard.i2b2.crc.datavo.ontology.XmlValueType; -import edu.harvard.i2b2.crc.datavo.pdo.ObservationSet; -import edu.harvard.i2b2.crc.datavo.pdo.ObservationType; -import edu.harvard.i2b2.crc.datavo.pdo.query.ConstrainDateTimeType; -import edu.harvard.i2b2.crc.datavo.pdo.query.ConstrainDateType; -import edu.harvard.i2b2.crc.datavo.pdo.query.FilterListType; -import edu.harvard.i2b2.crc.datavo.pdo.query.InclusiveType; -import edu.harvard.i2b2.crc.datavo.pdo.query.InputOptionListType; -import edu.harvard.i2b2.crc.datavo.pdo.query.ItemType; -import edu.harvard.i2b2.crc.datavo.pdo.query.OutputOptionListType; -import edu.harvard.i2b2.crc.datavo.pdo.query.PanelType; -import edu.harvard.i2b2.crc.datavo.pdo.query.ItemType.ConstrainByDate; -import edu.harvard.i2b2.crc.datavo.pdo.query.PanelType.TotalItemOccurrences; -import edu.harvard.i2b2.crc.delegate.ontology.CallOntologyUtil; -import edu.harvard.i2b2.crc.util.ItemKeyUtil; -import edu.harvard.i2b2.crc.util.PMServiceAccountUtil; -import edu.harvard.i2b2.crc.util.ParamUtil; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - -/** - * Observation fact handler class for pdo request. This class uses given pdo - * request to generate pdo sql and build observation fact, unique list of fact's - * patient,concept code, visit and provider list - *

    - * This class handles fact related queries for both plain and table pdo $Id: - * SQLServerFactRelatedQueryHandler.java,v 1.3 2008/06/10 14:59:05 rk903 Exp $ - * - * @author rkuttan - * @see VisitFactRelated - * @see ProviderFactRelated - * @see PatientFactRelated - * @see ObservationFactRelated - */ -public class SQLServerFactRelatedQueryHandler extends CRCDAO implements - IFactRelatedQueryHandler { - /** Input option list from pdo request* */ - private InputOptionListType inputList = null; - - /** filter list from pdo request * */ - private FilterListType filterList = null; - - private OutputOptionListType outputOptionList = null; - - /** helper class for visit/event in pdo * */ - private VisitFactRelated visitFactRelated = null; - - /** helper class for observer/provider in pdo * */ - private ProviderFactRelated providerFactRelated = null; - - /** helper class for patient in pdo * */ - private PatientFactRelated patientFactRelated = null; - - /** helper class for concepts in pdo * */ - private ConceptFactRelated conceptFactRelated = null; - - private ModifierFactRelated modifierFactRelated = null; - - private PidFactRelated pidFactRelated = null; - - private EidFactRelated eidFactRelated = null; - - /** helper class for observation fact in pdo * */ - private ObservationFactFactRelated obsFactFactRelated = null; - /** to store unique patient number list present in fact* */ - List patientFactList = new Vector(); - /** to store unique concept code list present in fact* */ - List conceptFactList = new Vector(); - /** to store unique modifier code list present in fact* */ - List modifierFactList = new Vector(); - /** to store unique encounter number present in fact * */ - List visitFactList = new Vector(); - /** to store unique provider/observer id present in fact * */ - List providerFactList = new Vector(); - - /** Handler interface for input list, i.e Patient list or visit list * */ - private IInputOptionListHandler inputOptionListHandler = null; - - /** - * flag to see if concept filter is set, used in observation fact set - * element * - */ - private boolean checkFilter = false; - - /** - * field to keep track number of prepared statment parameters in the - * genereated pdo query* - */ - private int queryParameterCount = 0; - - private DataSourceLookup dataSourceLookup = null; - - // public static final String TEMP_PDO_OBSFACT_TABLE = "#TEMP_PDO_OBSFACT"; - public static String TEMP_PDO_INPUTLIST_TABLE = "#TEMP_PDO_INPUTLIST"; - public static String TEMP_FACT_PARAM_TABLE = "#TEMP_FACT_PARAM_TABLE"; - // public static final String TEMP_PDO_INPUTLIST_TABLE1 = - // "#TEMP_PDO_INPUTLIST1"; - - private List panelSqlList = new ArrayList(); - private Map projectParamMap = null; - private Map modifierMetadataXmlMap = null; - private String requestVersion = ""; - - - private String factTable = "observation_FACT"; - private boolean derivedFactTable = QueryProcessorUtil.getInstance().getDerivedFactTable(); - - - /** - * Constructor with parameter - * - * @param inputList - * @param filterList - * @param outputOptionList - */ - public SQLServerFactRelatedQueryHandler(DataSourceLookup dataSourceLookup, - InputOptionListType inputList, FilterListType filterList, - OutputOptionListType outputOptionList) { - this.dataSourceLookup = dataSourceLookup; - this.setDbSchemaName(dataSourceLookup.getFullSchema()); - this.inputList = inputList; - this.filterList = filterList; - this.outputOptionList = outputOptionList; - - visitFactRelated = new VisitFactRelated(outputOptionList.getEventSet()); - providerFactRelated = new ProviderFactRelated(outputOptionList - .getObserverSetUsingFilterList()); - patientFactRelated = new PatientFactRelated(outputOptionList - .getPatientSet()); - conceptFactRelated = new ConceptFactRelated(outputOptionList - .getConceptSetUsingFilterList()); - modifierFactRelated = new ModifierFactRelated(outputOptionList - .getConceptSetUsingFilterList()); - obsFactFactRelated = new ObservationFactFactRelated(outputOptionList - .getObservationSet()); - pidFactRelated = new PidFactRelated(outputOptionList.getPidSet()); - eidFactRelated = new EidFactRelated(outputOptionList.getEidSet()); - - // If postgresql change temp table name - if (dataSourceLookup.getServerType().equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { - TEMP_PDO_INPUTLIST_TABLE = "TEMP_PDO_INPUTLIST"; - TEMP_FACT_PARAM_TABLE = "TEMP_FACT_PARAM_TABLE"; - - } - // check if concept filter present - if ((filterList != null) && (filterList.getPanel() != null) - && (filterList.getPanel().size() > 0)) { - checkFilter = true; - } - } - - @Override - public void setProjectParamMap(Map projectParamMap) { - this.projectParamMap = projectParamMap; - } - - @Override - public void setModifierMetadataXmlMap(Map modifierMetadataXmlMap) { - this.modifierMetadataXmlMap = modifierMetadataXmlMap; - } - - @Override - public void setRequestVersion(String requestVersion) { - this.requestVersion = requestVersion; - } - - - public String getFactTable(){ - return this.factTable; - } - - public void setFactTable(String table){ - this.factTable = table; - } - - - /** - * Function to build and execute pdo sql and build plain pdo's observation - * fact - * - * @return - * @throws Exception - */ - @Override - public List getPdoObservationFact() throws I2B2DAOException { - ResultSet resultSet = null; - Connection conn = null; - List observationFactSetList = new ArrayList(); - PreparedStatement stmt = null; - try { - conn = this.getApplicationDataSource( - dataSourceLookup.getDataSource()).getConnection(); - - int sqlParamCount = 1; - - boolean createTempTable = true; - - if(checkFilter == false) { -//WAS if (filterList.getPanel().size() == 0) { - - if(derivedFactTable == true){ - String sql= "select * from information_schema.tables where lower(table_name) = 'observation_fact'"; - if(dataSourceLookup.getFullSchema() != null){ - int lastIndex = dataSourceLookup.getFullSchema().lastIndexOf("."); - sql += " and table_catalog = '" + dataSourceLookup.getFullSchema().substring(0, lastIndex) + "'"; - sql += " and table_schema = '" + dataSourceLookup.getFullSchema().substring(lastIndex+1, (dataSourceLookup.getFullSchema().length())) + "'"; - } - PreparedStatement stmt1 = conn.prepareStatement(sql); - ResultSet resultSet1 = stmt1.executeQuery(); - // log.info("no filter Pdo sql: " + sql); - - if(!(resultSet1.next())){ - resultSet1.close(); - createTempTable = false; - try { - JDBCUtil.closeJdbcResource(null, stmt1, conn); - } catch (SQLException e) { - log.error("Error trying to close connection:"+ e.getMessage()); - } - - return observationFactSetList; - } - } - - // generate sql - String querySql = buildQuery(null, - PdoQueryHandler.PLAIN_PDO_TYPE); - panelSqlList.add(buildQueryCommon(null, - PdoQueryHandler.PLAIN_PDO_TYPE)); - log.debug("Executing sql[" + querySql + "]"); - if (inputOptionListHandler.isEnumerationSet()) { - inputOptionListHandler - .uploadEnumerationValueToTempTable(conn); - } - // execute fullsql - resultSet = executeQuery(conn, stmt, querySql, sqlParamCount); - // build facts - observationFactSetList.add(buildPDOFact(resultSet, "")); - } else { - for (PanelType panel : filterList.getPanel()) { - // generate sql - String querySql = buildQuery(panel, - PdoQueryHandler.PLAIN_PDO_TYPE); - if (querySql.length() ==0) { - continue; - } - - String defaultTableName = this.getDbSchemaName() + "observation_FACT" ; - // OMOP addition - if(panel != null){ - if(derivedFactTable == true){ - if(panel.getItem().get(0).getFacttablecolumn().contains(".")){ - - String baseItemFactColumn = panel.getItem().get(0).getFacttablecolumn(); - int lastIndex = baseItemFactColumn.lastIndexOf("."); - String factTable = this.getDbSchemaName() + (baseItemFactColumn.substring(0, lastIndex)); - - DerivedFactColumnsType columns = getFactColumnsFromOntologyCell(panel.getItem().get(0).getItemKey()); - if(columns != null){ - if(columns.getDerivedFactTableColumn().size() > 1) { - // parse through solumns and build up replace string. - - Iterator it = columns.getDerivedFactTableColumn().iterator(); - String column = it.next(); - - lastIndex = column.lastIndexOf("."); - String table = this.getDbSchemaName() + (column.substring(0, lastIndex)); - - - factTable = "( select * from " + table; - while(it.hasNext()){ - column = it.next(); - - lastIndex = column.lastIndexOf("."); - table = this.getDbSchemaName() + (column.substring(0, lastIndex)); - - factTable += "\n UNION ALL \n" - + " select * from " + table; - } - factTable += " )"; - - } - } - log.debug("Parse columns " + factTable); - querySql=querySql.replaceAll(defaultTableName, factTable) ; - } - } - } - panelSqlList.add(buildQueryCommon(panel, - PdoQueryHandler.PLAIN_PDO_TYPE)); - log.debug("PLAIN PDO Executing sql[" + querySql + "]"); - // execute fullsql - sqlParamCount = panel.getItem().size(); - if (panel.getInvert() == 1) { - sqlParamCount++; - } - long startTimeSql = System.currentTimeMillis(); - if (createTempTable) { - if (inputOptionListHandler.isEnumerationSet()) { - inputOptionListHandler - .uploadEnumerationValueToTempTable(conn); - } - } - - resultSet = executeQuery(conn, stmt, querySql, - sqlParamCount); - // set createTempTable flag to false after the first - // iteration - createTempTable = false; - // - long endTimeSql = System.currentTimeMillis(); - long totalTimeSql = endTimeSql - startTimeSql; - System.out - .println("******* Total time to execute observation sql" - + totalTimeSql); - long startTime = System.currentTimeMillis(); - // build facts - observationFactSetList.add(buildPDOFact(resultSet, panel - .getName())); - long endTime = System.currentTimeMillis(); - long totalTime = endTime - startTime; - System.out - .println("******* Total time to build observation " - + totalTime); - resultSet.close(); - } - } - } catch (SQLException sqlEx) { - throw new I2B2DAOException("", sqlEx); - } catch (IOException ioEx) { - throw new I2B2DAOException("", ioEx); - } finally { - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER)) { - // deleteTempTable(conn); - try { - if(inputOptionListHandler != null && conn != null) - inputOptionListHandler.deleteTempTable(conn); - } catch (SQLException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - // close connection - try { - JDBCUtil.closeJdbcResource(null, stmt, conn); - } catch (SQLException e) { - log.error("Error trying to close connection", e); - } - } - - return observationFactSetList; - } - - /** - * Function to build and execute pdo sql and build table pdo's observation - * fact - * - * @return ObservationSet list - * @throws I2B2DAOException - */ - @Override - public List getTablePdoObservationFact() - throws I2B2DAOException { - Connection conn = null; - List observationSetList = new ArrayList(); - ResultSet resultSet = null; - PreparedStatement stmt = null; - try { - conn = this.getApplicationDataSource( - dataSourceLookup.getDataSource()).getConnection(); - - int sqlParamCount = 1; - - // - boolean createTempTable = true; - - if(checkFilter == false) { -//WAS if (filterList.getPanel().size() == 0) { - - if(derivedFactTable == true){ - String sql= "select * from information_schema.tables where lower(table_name) = 'observation_fact'"; - if(dataSourceLookup.getFullSchema() != null){ - // log.info("schema: " + dataSourceLookup.getFullSchema()); - - int lastIndex = dataSourceLookup.getFullSchema().lastIndexOf("."); - sql += " and table_catalog = '" + dataSourceLookup.getFullSchema().substring(0, lastIndex) + "'"; - sql += " and table_schema = '" + dataSourceLookup.getFullSchema().substring(lastIndex+1, (dataSourceLookup.getFullSchema().length())) + "'"; - } - // log.info("no filter tablePDO sql: " + sql); - PreparedStatement stmt1 = conn.prepareStatement(sql); - ResultSet resultSet1 = stmt1.executeQuery(); - - if(!(resultSet1.next())){ - resultSet1.close(); - createTempTable = false; - try { - JDBCUtil.closeJdbcResource(null, stmt1, conn); - } catch (SQLException e) { - log.error("Error trying to close connection:"+ e.getMessage()); - } - - return observationSetList; - } - - } - // generate sql - String querySql = buildQuery(null, - PdoQueryHandler.PLAIN_PDO_TYPE); - - log.debug("Executing sql PLAIN PDO[" + querySql + "]"); - panelSqlList.add(buildQueryCommon(null, - PdoQueryHandler.PLAIN_PDO_TYPE)); - if (inputOptionListHandler.isEnumerationSet()) { - inputOptionListHandler - .uploadEnumerationValueToTempTable(conn); - } - - // execute fullsql - resultSet = executeQuery(conn, stmt, querySql, sqlParamCount); - // build facts - observationSetList.add(buildPDOFact(resultSet, "")); - } else { - for (PanelType panel : filterList.getPanel()) { - // generate sql - String querySql = buildQuery(panel, - PdoQueryHandler.TABLE_PDO_TYPE); - if (querySql.length() ==0 ) { - continue; - } - - // panelSqlList.add(buildQueryCommon(panel, - // PdoQueryHandler.TABLE_PDO_TYPE)); - sqlParamCount = panel.getItem().size(); - if (panel.getInvert() == 1) { - sqlParamCount++; - } - long startTimeSql = System.currentTimeMillis(); - if (createTempTable) { - if (inputOptionListHandler.isEnumerationSet()) { - inputOptionListHandler - .uploadEnumerationValueToTempTable(conn); - } - - } - String defaultTableName = this.getDbSchemaName() + "observation_FACT" ; - // OMOP addition - if(panel != null){ - if(derivedFactTable == true){ - if(panel.getItem().get(0).getFacttablecolumn().contains(".")){ - - String baseItemFactColumn = panel.getItem().get(0).getFacttablecolumn(); - int lastIndex = baseItemFactColumn.lastIndexOf("."); - String factTable = this.getDbSchemaName() + (baseItemFactColumn.substring(0, lastIndex)); - - DerivedFactColumnsType columns = getFactColumnsFromOntologyCell(panel.getItem().get(0).getItemKey()); - if(columns != null){ - if(columns.getDerivedFactTableColumn().size() > 1) { - // parse through solumns and build up replace string. - - Iterator it = columns.getDerivedFactTableColumn().iterator(); - String column = it.next(); - - lastIndex = column.lastIndexOf("."); - String table = this.getDbSchemaName() + (column.substring(0, lastIndex)); - - - factTable = "( select * from " + table; - while(it.hasNext()){ - column = it.next(); - - lastIndex = column.lastIndexOf("."); - table = this.getDbSchemaName() + (column.substring(0, lastIndex)); - - factTable += "\n UNION ALL \n" - + " select * from " + table; - } - factTable += " )"; - - } - } - log.debug("Parse columns " + factTable); - querySql=querySql.replaceAll(defaultTableName, factTable) ; - } - } - } - panelSqlList.add(querySql); - log.debug("TABLE PDO Executing sql[" + querySql + "]"); - - // execute fullsql - resultSet = executeQuery(conn, stmt, querySql, - sqlParamCount); - long endTimeSql = System.currentTimeMillis(); - long totalTimeSql = endTimeSql - startTimeSql; - System.out - .println("******* Total time to execute observation sql" - + totalTimeSql); - long startTime = System.currentTimeMillis(); - // build facts - observationSetList.add(buildTablePDOFact(resultSet, panel - .getName())); - long endTime = System.currentTimeMillis(); - long totalTime = endTime - startTime; - System.out - .println("******* Total time to build observation " - + totalTime); - resultSet.close(); - createTempTable = false; - } - } - } catch (SQLException sqlEx) { - log.error(sqlEx.getMessage()); - throw new I2B2DAOException("", sqlEx); - } catch (IOException ioEx) { - log.error(ioEx.getMessage()); - throw new I2B2DAOException("", ioEx); - } finally { - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER)) { - /* - * IInputOptionListHandler inputOptionListHandler = PDOFactory - * .buildInputListHandler(inputList, dataSourceLookup); - */ - try { - if(conn != null && inputOptionListHandler != null) - inputOptionListHandler.deleteTempTable(conn); - } catch (SQLException e) { - log.error(e.getMessage()); - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - // close connection - try { - JDBCUtil.closeJdbcResource(null, stmt, conn); - } catch (SQLException e) { - log.error("Error trying to close connection", e); - } - } - - return observationSetList; - } - - /** - * Returns provider id, belong to the facts - * - * @return list of provider/observer id - */ - @Override - public List getProviderFactList() { - return providerFactList; - } - - /** - * Returns concept code belong to the facts - * - * @return - */ - @Override - public List getConceptFactList() { - return conceptFactList; - } - - /** - * Returns modifier code belong to the facts - * - * @return - */ - @Override - public List getModifierFactList() { - return modifierFactList; - } - - /** - * Returns patient number belong to the facts - * - * @return - */ - @Override - public List getPatientFactList() { - return patientFactList; - } - - /** - * Returns encounter number belong to the facts - * - * @return list of encounter number - */ - @Override - public List getVisitFactList() { - return visitFactList; - } - - @Override - public String buildTotalQuery(PanelType panel, String pdoType) - throws I2B2DAOException { - // TODO Auto-generated method stub - return buildQueryCommon(panel, pdoType); - } - - private String buildQueryCommon(PanelType panel, String pdoType) - throws I2B2DAOException { - String obsFactSelectClause = null; - - if (obsFactFactRelated != null) { - obsFactSelectClause = obsFactFactRelated - .getSelectClauseWithoutBlob(); - - if (obsFactSelectClause.length() <= 0) { - obsFactSelectClause = obsFactFactRelated - .getDefaultSelectClause(); - } - } - - String tableLookupJoinClause = " "; - - if (pdoType.equals(PdoQueryHandler.TABLE_PDO_TYPE)) { - tableLookupJoinClause = getLookupJoinClause(obsFactFactRelated - .isSelectDetail(), obsFactFactRelated.isSelectBlob(), - obsFactFactRelated.isSelectStatus()); - obsFactSelectClause += " , concept_lookup.name_char concept_name, provider_lookup.name_char provider_name, modifier_lookup.name_char modifier_name"; - if (obsFactFactRelated.isSelectDetail()) { - obsFactSelectClause += " , location_lookup.name_char location_name "; - } - } - - String fullWhereClause = ""; - - if (inputOptionListHandler == null) { - inputOptionListHandler = PDOFactory.buildInputListHandler( - inputList, dataSourceLookup); - } - // fullWhereClause = patientSetWhereBuilder.getWhereClause(); - if (inputList.getPatientList() != null) { - fullWhereClause = " obs.patient_num IN "; - } else if (inputList.getEventList() != null) { - fullWhereClause = " obs.encounter_num IN \n"; - } else if (inputList.getPidList() != null) { - fullWhereClause = " obs.patient_num IN "; - } else if (inputList.getEidList() != null) { - fullWhereClause = " obs.encounter_num IN "; - } else { - throw new I2B2DAOException( - "Input option list does not contain visit or patient list"); - } - - fullWhereClause += (" ( " - + inputOptionListHandler.generateWhereClauseSql() + " ) \n"); - - String factByConceptSql = ""; - String factWithoutFilterSql = ""; - - String mainSelectBlobClause = " "; - if (obsFactFactRelated.isSelectBlob()) { - mainSelectBlobClause = " , observation_blob obs_observation_blob"; - } - - // String mainQuerySql = "SELECT * FROM ( \n"; - String mainQuerySql = "SELECT b.* " + mainSelectBlobClause + " FROM " - + this.getDbSchemaName() + getFactTable() + " obs ,( \n"; - try { - if (panel != null) { - factByConceptSql = factQueryWithDimensionFilter( - obsFactSelectClause, tableLookupJoinClause, - fullWhereClause, panel); - if (factByConceptSql.trim().length()==0) { - return ""; - } - if (panel.getTotalItemOccurrences() != null - && panel.getTotalItemOccurrences().getValue() > 0) { - mainQuerySql += " select *, rank() over (partition by obs_encounter_num,obs_patient_num,obs_start_date,obs_concept_cd order by rnum) as seqNumber from ( " - + factByConceptSql + " ) as t"; - } else { - mainQuerySql += factByConceptSql; - } - - } else { - factWithoutFilterSql = factQueryWithoutFilter( - obsFactSelectClause, tableLookupJoinClause, - fullWhereClause); - mainQuerySql += factWithoutFilterSql + ") b \n"; - } - - } catch (I2B2Exception i2b2Ex) { - throw new I2B2DAOException(i2b2Ex.getMessage(), i2b2Ex); - } - - mainQuerySql += " ) as b where rnum >= 0 "; - mainQuerySql += " and obs.encounter_num = b.obs_encounter_num and obs.patient_num = b.obs_patient_num "; - mainQuerySql += " and obs.concept_cd = b.obs_concept_cd and obs.provider_id = b.obs_provider_id and obs.start_date = b.obs_start_date and obs.modifier_cd = b.obs_modifier_cd and obs.instance_num = b.obs_instance_num "; - - if (panel != null) { - TotalItemOccurrences totOccurance = panel.getTotalItemOccurrences(); - if (totOccurance != null && totOccurance.getValue() > 1) { - int totOcurranceValue = totOccurance.getValue(); - String totOccuranceOperator = ">="; - if (totOccurance.getOperator() != null) { - String totOccuranceOperatorValue = totOccurance.getOperator() - .value(); - totOccuranceOperator = XMLOperatorLookup - .getComparisonOperatorFromAcronum(totOccuranceOperatorValue); - if (totOccuranceOperator == null) { - totOccuranceOperator = ">="; - } - } - - mainQuerySql += " AND seqNumber " + totOccuranceOperator - + totOcurranceValue; - } - - } - - - if (this.outputOptionList.getObservationSet().getSelectionfilter()!= null) - { - //mainQuerySql = "with main_query as (" + mainQuerySql + ") select * from (select f1.*, " + - String newMainQuerySql = "select * from (select f1.*, " + - - " rank() over(partition by obs_patient_num, obs_concept_cd order by "; - if (this.outputOptionList.getObservationSet().getSelectionfilter().value().equalsIgnoreCase("min_value")) - newMainQuerySql += " obs_nval_num "; - else if (this.outputOptionList.getObservationSet().getSelectionfilter().value().equalsIgnoreCase("max_value")) - newMainQuerySql += " obs_nval_num desc "; - else if (this.outputOptionList.getObservationSet().getSelectionfilter().value().equalsIgnoreCase("first_value")) - newMainQuerySql += " obs_start_date "; - else if (this.outputOptionList.getObservationSet().getSelectionfilter().value().equalsIgnoreCase("last_value")) - newMainQuerySql += " obs_start_date desc "; - else if (this.outputOptionList.getObservationSet().getSelectionfilter().value().equalsIgnoreCase("single_observation")) - newMainQuerySql += " case when obs_modifier_cd = '@' then 1 else 0 end, obs_modifier_cd "; - else - newMainQuerySql += " obs_start_date desc "; - - mainQuerySql = newMainQuerySql + " ) rank " + - " from (" + mainQuerySql + ") f1 " ; - - if ((this.outputOptionList.getObservationSet().getSelectionfilter().value().equalsIgnoreCase("min_value")) || - (this.outputOptionList.getObservationSet().getSelectionfilter().value().equalsIgnoreCase("max_value")) ) - mainQuerySql += " where obs_nval_num is not null "; - - - if (this.outputOptionList.getObservationSet().getSelectionfilter().value().equalsIgnoreCase("last_n_values")) - { - mainQuerySql += ") f where f.rank < " + this.outputOptionList.getObservationSet().getValue(); - } else { - mainQuerySql += ") f where f.rank = 1 "; - } - - } - - return mainQuerySql; - - } - - /** - * This is the main function to build query for plain and table pdo request - * - * @param pdoType - * @return String - * @throws I2B2DAOException - */ - @Override - public String buildQuery(PanelType panel, String pdoType) - throws I2B2DAOException { - String mainQuerySql = this.buildQueryCommon(panel, pdoType); - if (mainQuerySql.length() == 0) { - return ""; - } - //check for version 1.5, if so return the fact without the duplicates in modifier_cd and instance num - //TODO Removed because not working in 1.6.05 - /* - if (this.requestVersion.startsWith("1.5")) { - mainQuerySql = " select * from (select *, rank() over(partition by obs_encounter_num, obs_patient_num,obs_concept_cd,obs_start_date,obs_provider_id order by obs_modifier_cd,obs_instance_num ) ordernum " + - " from ( " + mainQuerySql + ") ordersql ) ordersql1 where ordernum = 1 "; - - } - */ - mainQuerySql += " ORDER BY obs_patient_num,obs_start_date,obs_concept_cd,obs_instance_num,obs_modifier_cd,rnum"; - - return mainQuerySql; - } - - // ----------------------------------------- - // private helper functions start from here - // ----------------------------------------- - - /** - * Function to uses given select, join and where clause to build core pdo - * query, related to provider filter - * - * @param obsFactSelectClause - * @param tableLookupJoinClause - * @param fullWhereClause - * @return - */ - private String factQueryWithDimensionFilter(String obsFactSelectClause, - String tableLookupJoinClause, String fullWhereClause, - PanelType panel) throws I2B2Exception { - String factByProviderSql = ""; - int i = 0; - String panelName = null; - DateConstrainHandler dateConstrainHandler = new DateConstrainHandler( - dataSourceLookup); - - - if (panel.getName() != null) { - panelName = JDBCUtil.escapeSingleQuote(panel.getName()); - } - - obsFactSelectClause += (", '" + panelName + "' panel_name "); - - int totalItemOccurance = 0; - if (panel.getTotalItemOccurrences() != null) { - totalItemOccurance = panel.getTotalItemOccurrences().getValue(); - } - int panelAccuracyScale = panel.getPanelAccuracyScale(); - //ignore the panel accuracy scale value, bcos the function is reverted - panelAccuracyScale = 0; - - String panelDateConstrain = null; - // generate panel date constrain - if (panel.getPanelDateFrom() != null || panel.getPanelDateTo() != null) { - panelDateConstrain = generatePanelDateConstrain( - dateConstrainHandler, panel.getPanelDateFrom(), panel - .getPanelDateTo()); - } - - for (ItemType item : panel.getItem()) { - // read the first item - // ItemType item = panel.getItem().get(0); - if (item.getFacttablecolumn() != null - || item.getDimColumnname() != null || item.getItemKey().toLowerCase().startsWith(ItemKeyUtil.ITEM_KEY_MASTERID)) { - - if (item.getDimTablename() != null) { - if (item.getDimTablename().equalsIgnoreCase("patient_dimension") || - item.getDimTablename().equalsIgnoreCase("visit_dimension")) { - continue; - } - } - - if (i == 0) { - i = 1; - } else { - if (totalItemOccurance > 1) { - factByProviderSql += "UNION ALL \n"; - } else { - factByProviderSql += "UNION \n"; - } - } - - factByProviderSql += (" SELECT " - + obsFactSelectClause + " FROM \n"); - - // check if the item key has "patient_set_coll_id:XXXX" as - // prefix - String itemKey = item.getItemKey(); - - if (itemKey.toLowerCase().startsWith(ItemKeyUtil.ITEM_KEY_PATIENT_SET)) { - String[] itemKeyParam = itemKey.split(":"); - factByProviderSql += (" select patient_num from " - + this.getDbSchemaName() - + "qt_patient_set_collection where patient_set_coll_id = " - + itemKeyParam[1] + " \n"); - item.setFacttablecolumn("patient_num"); - - } else if (itemKey.toLowerCase().startsWith(ItemKeyUtil.ITEM_KEY_PATIENT_ENCOUNTER_SET)) { // check - // if - // the - // item - // key - // has - // "patient_enc_coll_id:XXXX" - // as - // prefix - String[] itemKeyParam = itemKey.split(":"); - factByProviderSql += (" select encounter_num from " - + this.getDbSchemaName() - + "qt_patient_enc_collection where patient_enc_coll_id = " - + itemKeyParam[1] + " \n"); - //WAS item.setFacttablecolumn("encount_num"); - item.setFacttablecolumn("encounter_num"); - } else { - DimensionFilter providerFilter = new DimensionFilter(item, - this.getDbSchemaName(), dataSourceLookup); - factByProviderSql += (" " - + providerFilter.getFromSqlString() + " \n"); - - } - factByProviderSql += ", " + this.getDbSchemaName() - + getFactTable() + " obs \n"; - - String tempSqlClause = "",containsJoinSql = ""; - - //OMOP addition - String facttablecolumn = item.getFacttablecolumn(); - if(derivedFactTable == true){ - - if(item.getFacttablecolumn().contains(".")){ - - String factColumnName = item.getFacttablecolumn(); - - int lastIndex = factColumnName.lastIndexOf("."); - - facttablecolumn = (factColumnName.substring(lastIndex+1)); - } - } - - // OMOP WAS item.getFacttablecolumn(); - // String fullWhereClause1 = fullWhereClause - // + (" AND obs." + item.getFacttablecolumn() - // + " = dimension." + item.getFacttablecolumn()); - - - String fullWhereClause1 = fullWhereClause - + (" AND obs." + facttablecolumn - + " = dimension." + facttablecolumn); - - //factByProviderSql += tableLookupJoinClause; - tempSqlClause+= tableLookupJoinClause; - - //factByProviderSql += (" WHERE \n" + fullWhereClause1 + "\n"); - tempSqlClause+= (" WHERE \n" + fullWhereClause1 + "\n"); - - //if output option has modifier option false, then select modifier_cd = '@' - if (outputOptionList.getObservationSet() != null && outputOptionList.getObservationSet().isWithmodifiers() == false) { - //factByProviderSql += (" AND obs.modifier_cd = '@' \n"); - tempSqlClause+= (" AND obs.modifier_cd = '@' \n"); - } - - boolean itemConstrainValueFlag = false, modifierConstrainValueFlag = false; - //if modifier constrain is present in the request, then generate modifier constrain sql - ItemType.ConstrainByModifier modifierConstrain = item.getConstrainByModifier(); - if (modifierConstrain != null) { - // generate sql for item date constrain - ModifierConstrainsHandler modifierConstrainUtil = new ModifierConstrainsHandler(this.getDbSchemaName()); - String itemModifierConstrainSql = modifierConstrainUtil.constructModifierConstainClause(modifierConstrain); - if ((itemModifierConstrainSql != null) - && (itemModifierConstrainSql.length() > 0)) { - //factByProviderSql += (" AND (" + itemModifierConstrainSql + ")\n"); - tempSqlClause+=(" AND (" + itemModifierConstrainSql + ")\n"); - } - if (modifierConstrain.getConstrainByValue() != null && - modifierConstrain.getConstrainByValue().size()>0) { - modifierConstrainValueFlag = true; - } - - } - String unitCdSwitchClause = "", unitCdInClause = ""; - String modifierUnitCdSwitchClause = "", modifierUnitCdInClause = ""; - - if (item.getConstrainByValue() != null - && item.getConstrainByValue().size() > 0) { - itemConstrainValueFlag = true; - } - // if value constrain is given, generate value constrain sql - if ( itemConstrainValueFlag || modifierConstrainValueFlag ) { - //generate sql for unit_cd conversion - if ( projectParamMap != null && projectParamMap.get(ParamUtil.CRC_ENABLE_UNITCD_CONVERSION) != null) { - String unitCdConversionFlag = (String)projectParamMap.get(ParamUtil.CRC_ENABLE_UNITCD_CONVERSION); - if (unitCdConversionFlag != null && unitCdConversionFlag.equalsIgnoreCase("ON")) { - if (item.getMetadataxml() != null && item.getMetadataxml().getContent().get(0) != null) { - Element valueMetadataElement = (Element)item.getMetadataxml().getContent().get(0); - UnitConverstionUtil unitConverstionUtil = new UnitConverstionUtil(); - unitCdSwitchClause = unitConverstionUtil.buildUnitCdSwitchClause(valueMetadataElement,false,"obs."); - unitCdInClause = unitConverstionUtil.buildUnitCdInClause(valueMetadataElement,""); - } - - if (modifierConstrainValueFlag) { - XmlValueType xmlValueType = this.modifierMetadataXmlMap.get(item.getConstrainByModifier().getModifierKey()+item.getConstrainByModifier().getAppliedPath()); - if (xmlValueType != null && xmlValueType.getAny().get(0) != null) { - Element valueMetadataElement = xmlValueType.getAny().get(0); - UnitConverstionUtil unitConverstionUtil = new UnitConverstionUtil(); - modifierUnitCdSwitchClause = unitConverstionUtil.buildUnitCdSwitchClause(valueMetadataElement,false,"obs."); - modifierUnitCdInClause = unitConverstionUtil.buildUnitCdInClause(valueMetadataElement,""); - } - } - } - } - } - - ValueConstrainsHandler vh = new ValueConstrainsHandler(); - if (unitCdSwitchClause.length()>0) { - vh.setUnitCdConversionFlag(true, unitCdInClause, unitCdSwitchClause); - } - String[] valueConstrainSql = new String[] {"",""} ; - if (itemConstrainValueFlag) { - valueConstrainSql = vh - .constructValueConstainClause(item - .getConstrainByValue(), this.dataSourceLookup.getServerType(),this.getDbSchemaName(),panelAccuracyScale); - if (panelAccuracyScale>0) { - containsJoinSql = valueConstrainSql[1]; - } - } - - String[] modifierConstrainValueSql = new String[]{"",""}; - if (modifierConstrainValueFlag) { - if (modifierUnitCdInClause.length()>0) { - vh.setUnitCdConversionFlag(true, modifierUnitCdInClause, modifierUnitCdSwitchClause); - } - modifierConstrainValueSql = vh.constructValueConstainClause(buildItemValueConstrain(modifierConstrain.getConstrainByValue()),this.dataSourceLookup.getServerType(),this.getDbSchemaName(),panelAccuracyScale); - if (panelAccuracyScale>0) { - containsJoinSql += modifierConstrainValueSql[1]; - } - } - - if ((valueConstrainSql[0] != null - && valueConstrainSql[0].length() > 0)|| (modifierConstrainValueSql[0] != null - && modifierConstrainValueSql[0].length() > 0)) { - //factByProviderSql += (" AND (" + valueConstrainSql[0] + modifierConstrainValueSql[0] + ")\n"); - tempSqlClause+= (" AND (" + valueConstrainSql[0] + modifierConstrainValueSql[0] + ")\n"); - - } - - factByProviderSql += containsJoinSql; - - factByProviderSql += tempSqlClause; - - // add start and end date constrains - - List constrainByDateList = item - .getConstrainByDate(); - for (ConstrainByDate constrainByDate : constrainByDateList) { - - ConstrainDateType dateFrom = constrainByDate.getDateFrom(); - ConstrainDateType dateTo = constrainByDate.getDateTo(); - - String dateFromColumn = null, dateToColumn = null; - InclusiveType dateFromInclusive = null, dateToInclusive = null; - XMLGregorianCalendar dateFromValue = null, dateToValue = null; - String dateConstrainSql = null; - - // obs.start_date, obs.end_date - if (dateFrom != null || dateTo != null) { - - if (dateFrom != null) { - dateFromInclusive = dateFrom.getInclusive(); - dateFromValue = dateFrom.getValue(); - if (dateFrom.getTime() != null - && dateFrom.getTime().name() != null - && dateFrom - .getTime() - .name() - .equalsIgnoreCase( - ConstrainDateTimeType.END_DATE - .name())) { - dateFromColumn = "obs.end_date"; - } else { - dateFromColumn = "obs.start_date"; - } - - } - - if (dateTo != null) { - dateToInclusive = dateTo.getInclusive(); - dateToValue = dateTo.getValue(); - if (dateTo.getTime() != null - && dateTo.getTime().name() != null - && dateTo.getTime().name().equals( - ConstrainDateTimeType.END_DATE - .name())) { - dateToColumn = "obs.end_date"; - } else { - dateToColumn = "obs.start_date"; - } - } - - dateConstrainSql = dateConstrainHandler - .constructDateConstrainClause(dateFromColumn, - dateToColumn, dateFromInclusive, - dateToInclusive, dateFromValue, - dateToValue); - if (dateConstrainSql != null) { - factByProviderSql += (" AND " + dateConstrainSql + "\n"); - } - - // item.getConstrainByModifier().get(0).getModifierName() - } - } - // generate panel date constrain - if (panelDateConstrain != null) { - factByProviderSql += (" AND (" + panelDateConstrain + ")\n"); - } - } - } - - if (factByProviderSql.trim().length()<10) { - return ""; - } - - int invert = panel.getInvert(); - - if (invert == 1) { - String invertSql = ("( SELECT " + obsFactSelectClause + " FROM \n"); - invertSql += " " + this.getDbSchemaName() - + getFactTable() + " obs \n"; - invertSql += tableLookupJoinClause; - invertSql += (" WHERE \n" + fullWhereClause + ")\n"); - factByProviderSql = invertSql + " EXCEPT \n " + "(" - + factByProviderSql + ")"; - } - - if (totalItemOccurance > 1) { - factByProviderSql = "SELECT a.*, row_number() over(order by obs_patient_num) as rnum FROM (\n" - + factByProviderSql; - } else { - factByProviderSql = "SELECT a.*, row_number() over(order by obs_patient_num) as rnum FROM (\n" - + factByProviderSql; - } - - factByProviderSql += " ) a \n"; - // factByProviderSql += " ORDER BY 2,5,3) a \n"; - - return factByProviderSql; - } - - /** - * Function to uses given select, join and where clause to build core pdo - * query, without any filter (concept and provider) - * - * @param obsFactSelectClause - * @param tableLookupJoinClause - * @param fullWhereClause - * @return - */ - private String factQueryWithoutFilter(String obsFactSelectClause, - String tableLookupJoinClause, String fullWhereClause) { - String factSql = "SELECT b.*, ROW_NUMBER() OVER (order by obs_patient_num) rnum FROM (\n"; - factSql += (" SELECT " - + obsFactSelectClause + " FROM " + this.getDbSchemaName() + getFactTable() + " obs\n"); - - factSql += tableLookupJoinClause; - - factSql += (" WHERE \n" + fullWhereClause + "\n"); - if (this.outputOptionList.getObservationSet().isWithmodifiers() == false) { - factSql += " AND obs.modifier_cd = '@' "; - } - // lcp5 following was causing invalid sql 12/20/16 -// factSql += " ORDER BY obs.patient_num,obs.start_date,obs.concept_cd,obs.instance_num,obs.modifier_cd,obs.rowid) b \n"; - - return factSql; - } - - /** - * Generate fact's join clause for table pdo - * - * @param detailFlag - * @param blobFlag - * @param statusFlag - * @return - */ - private String getLookupJoinClause(boolean detailFlag, boolean blobFlag, - boolean statusFlag) { - String joinClause = " "; - - joinClause = " left JOIN " - + this.getDbSchemaName() - + "code_lookup modifier_lookup \n" - + " ON (obs.modifier_cd = modifier_lookup.code_Cd AND modifier_lookup.column_cd = 'MODIFIER_CD') \n" - + " left JOIN " - + "(select name_char, concept_cd from " - + this.getDbSchemaName() - + "concept_dimension group by name_char, concept_cd) concept_lookup " - + "ON (obs.concept_cd = concept_lookup.concept_Cd) \n" - + " left JOIN " + this.getDbSchemaName() - + "provider_dimension provider_lookup \n" - + " ON (obs.provider_id = provider_lookup.provider_id) \n"; - - if (detailFlag) { - joinClause += " left JOIN " - + this.getDbSchemaName() - + "code_lookup location_lookup \n" - + " ON (obs.location_Cd = location_lookup.code_Cd AND location_lookup.column_cd = 'LOCATION_CD') \n"; - } - - return joinClause; - } - - private void deleteTempTable(Connection conn) { - - Statement deleteStmt = null; - try { - deleteStmt = conn.createStatement(); - //conn - // .createStatement() - deleteStmt.executeUpdate( - "drop table " - + SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE); - - } catch (SQLException sqle) { - ; - } finally { - try { - if(deleteStmt != null) - deleteStmt.close(); - } catch (SQLException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - } - - private List buildItemValueConstrain(List modifierConstrainList) { - List itemValueConstrainList = new ArrayList(); - for (ItemType.ConstrainByModifier.ConstrainByValue modifierValueConstrain : modifierConstrainList) { - ItemType.ConstrainByValue constrainByValue = new ItemType.ConstrainByValue(); - constrainByValue.setValueConstraint(modifierValueConstrain.getValueConstraint()); - constrainByValue.setValueOperator(modifierValueConstrain.getValueOperator()) ; - constrainByValue.setValueType(modifierValueConstrain.getValueType()); - constrainByValue.setValueUnitOfMeasure(modifierValueConstrain.getValueUnitOfMeasure()) ; - itemValueConstrainList.add(constrainByValue); - } - return itemValueConstrainList; - } - - /** - * Helper function to build unique visit, patient, concept list from - * observation fact - * - * @param encounterNum - * @param patientNum - * @param providerId - * @param conceptCd - */ - private void addToDistinctList(String encounterNum, String patientNum, - String providerId, String conceptCd,String modifierCd) { - if (visitFactRelated.isSelected() || eidFactRelated.isSelected()) { - if (!visitFactList.contains(encounterNum)) { - visitFactList.add(encounterNum); - } - } - - if (patientFactRelated.isSelected() || pidFactRelated.isSelected()) { - if (!patientFactList.contains(patientNum)) { - patientFactList.add(patientNum); - } - } - - if (providerFactRelated.isSelected()) { - if (!providerFactList.contains(providerId)) { - providerFactList.add(providerId); - } - } - - if (conceptFactRelated.isSelected()) { - if (!conceptFactList.contains(conceptCd)) { - conceptFactList.add(conceptCd); - } - } - - if (modifierFactRelated.isSelected()) { - if (!modifierFactList.contains(modifierCd)) { - modifierFactList.add(modifierCd); - } - } - - } - - /** - * Executive the given query - * - * @param conn - * @param querySql - * @return - * @throws SQLException - */ - private ResultSet executeQuery(Connection conn, PreparedStatement stmt, - String querySql, int sqlParamCount) throws SQLException { - - stmt = conn.prepareStatement(querySql); - - if (inputOptionListHandler.isCollectionId()) { - for (int i = 1; i <= sqlParamCount; i++) { - stmt.setInt(i, Integer.parseInt(inputOptionListHandler - .getCollectionId())); - } - } - - ResultSet resultSet = stmt.executeQuery(); - - return resultSet; - - // JdbcRowSet rowSet = new JdbcRowSetImpl(resultSet); - // return rowSet; - } - - /** - * Build plain pdo's observation fact - * - * @param rowSet - * @return - * @throws SQLException - * @throws IOException - */ - private ObservationSet buildPDOFact(ResultSet rowSet, String panelName) - throws SQLException, IOException { - ObservationSet currentObsFactSetType = new ObservationSet(); - currentObsFactSetType.setPanelName(panelName); - - I2B2PdoFactory.ObservationFactBuilder observationFactBuilder = new I2B2PdoFactory().new ObservationFactBuilder( - obsFactFactRelated.isSelectDetail(), obsFactFactRelated - .isSelectBlob(), obsFactFactRelated.isSelectStatus(), dataSourceLookup.getServerType()); - - while (rowSet.next()) { - ObservationType obsFactType = null; - - obsFactType = observationFactBuilder.buildObservationSet(rowSet); - - if (obsFactFactRelated.isSelected()) { - currentObsFactSetType.getObservation().add(obsFactType); - } - - addToDistinctList(obsFactType.getEventId().getValue(), obsFactType - .getPatientId().getValue(), obsFactType.getObserverCd() - .getValue(), obsFactType.getConceptCd().getValue(), obsFactType.getModifierCd().getValue()); - } - - return currentObsFactSetType; - } - - /** - * Build table pdo observaton fact - * - * @param rowSet - * @return - * @throws SQLException - * @throws IOException - */ - private ObservationSet buildTablePDOFact(ResultSet rowSet, String panelName) - throws SQLException, IOException { - // obsFactSetTypeList = new - // Vector(); - boolean detailFlag = obsFactFactRelated.isSelectDetail(); - boolean booleanFlag = obsFactFactRelated.isSelectBlob(); - boolean statusFlag = obsFactFactRelated.isSelectStatus(); - ObservationSet currentObservationSet = new ObservationSet(); - currentObservationSet.setPanelName(panelName); - - RPDRPdoFactory.ObservationFactBuilder observationFactBuilder = new RPDRPdoFactory.ObservationFactBuilder( - detailFlag, booleanFlag, statusFlag); - - while (rowSet.next()) { - ObservationType observation = null; - observation = observationFactBuilder.buildObservationSet(rowSet, - "HIVE"); - - if (obsFactFactRelated.isSelected()) { - currentObservationSet.getObservation().add(observation); - } - - - addToDistinctList(observation.getEventId().getValue(), observation.getPatientId().getValue(), - observation.getObserverCd().getValue(), observation.getConceptCd().getValue(), observation.getModifierCd().getValue()); - } - - return currentObservationSet; - } - - private String generatePanelDateConstrain( - DateConstrainHandler dateConstrainHandler, - ConstrainDateType dateFrom, ConstrainDateType dateTo) - throws I2B2Exception { - - String dateFromColumn = null, dateToColumn = null; - InclusiveType dateFromInclusive = null, dateToInclusive = null; - XMLGregorianCalendar dateFromValue = null, dateToValue = null; - String dateConstrainSql = null; - - if (dateFrom != null || dateTo != null) { - - if (dateFrom != null) { - dateFromInclusive = dateFrom.getInclusive(); - dateFromValue = dateFrom.getValue(); - - dateFrom.getTime(); - if (dateFrom.getTime() != null - && dateFrom.getTime().name() != null - && dateFrom.getTime().name().equalsIgnoreCase( - ConstrainDateTimeType.END_DATE.name())) { - dateFromColumn = "obs.end_date"; - } else { - - dateFromColumn = "obs.start_date"; - } - - } - - if (dateTo != null) { - dateToInclusive = dateTo.getInclusive(); - dateToValue = dateTo.getValue(); - - dateTo.getTime(); - if (dateTo.getTime() != null - && dateTo.getTime().name() != null - && dateTo.getTime().name().equalsIgnoreCase( - ConstrainDateTimeType.END_DATE.name())) { - dateToColumn = "obs.end_date"; - } else { - - dateToColumn = "obs.start_date"; - } - - } - - dateConstrainSql = dateConstrainHandler - .constructDateConstrainClause(dateFromColumn, dateToColumn, - dateFromInclusive, dateToInclusive, dateFromValue, - dateToValue); - } - return dateConstrainSql; - } - - @Override - public List getPanelSqlList() { - return this.panelSqlList; - } - - protected DerivedFactColumnsType getFactColumnsFromOntologyCell(String itemKey) - throws ConceptNotFoundException, OntologyException { - DerivedFactColumnsType factColumns = new DerivedFactColumnsType(); - try { - - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - String ontologyUrl = qpUtil - .getCRCPropertyValue(QueryProcessorUtil.ONTOLOGYCELL_ROOT_WS_URL_PROPERTIES); - - SecurityType securityType = PMServiceAccountUtil - .getServiceSecurityType(dataSourceLookup.getDomainId()); - - factColumns = CallOntologyUtil.callGetFactColumns(itemKey, - securityType, dataSourceLookup.getProjectPath(), - ontologyUrl +"/getDerivedFactColumns"); - } catch (JAXBUtilException e) { - - log.error("Error while fetching metadata [" + itemKey - + "] from ontology ", e); - throw new OntologyException("Error while fetching metadata [" - + itemKey + "] from ontology " - + StackTraceUtil.getStackTrace(e)); - } catch (I2B2Exception e) { - log.error("Error while fetching metadata from ontology ", e); - throw new OntologyException("Error while fetching metadata [" - + itemKey + "] from ontology " - + StackTraceUtil.getStackTrace(e)); - } catch (AxisFault e) { - log.error("Error while fetching metadata from ontology ", e); - throw new OntologyException("Error while fetching metadata [" - + itemKey + "] from ontology " - + StackTraceUtil.getStackTrace(e)); - } catch (XMLStreamException e) { - log.error("Error while fetching metadata from ontology ", e); - throw new OntologyException("Error while fetching metadata [" - + itemKey + "] from ontology " - + StackTraceUtil.getStackTrace(e)); - } - -// if (factColumns.isEmpty()) { -// throw new ConceptNotFoundException("[" + itemKey + "] "); - -// } - - return factColumns; - } - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao.pdo.input; + +import java.io.IOException; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Vector; + +import javax.xml.datatype.XMLGregorianCalendar; +import javax.xml.stream.XMLStreamException; + +import org.apache.axis2.AxisFault; +import org.w3c.dom.Element; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.exception.StackTraceUtil; +import edu.harvard.i2b2.common.util.db.JDBCUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.common.util.xml.XMLOperatorLookup; +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.dao.pdo.I2B2PdoFactory; +import edu.harvard.i2b2.crc.dao.pdo.PdoQueryHandler; +import edu.harvard.i2b2.crc.dao.pdo.RPDRPdoFactory; +import edu.harvard.i2b2.crc.dao.pdo.filter.DimensionFilter; +import edu.harvard.i2b2.crc.dao.pdo.output.ConceptFactRelated; +import edu.harvard.i2b2.crc.dao.pdo.output.EidFactRelated; +import edu.harvard.i2b2.crc.dao.pdo.output.ModifierFactRelated; +import edu.harvard.i2b2.crc.dao.pdo.output.ObservationFactFactRelated; +import edu.harvard.i2b2.crc.dao.pdo.output.PatientFactRelated; +import edu.harvard.i2b2.crc.dao.pdo.output.PidFactRelated; +import edu.harvard.i2b2.crc.dao.pdo.output.ProviderFactRelated; +import edu.harvard.i2b2.crc.dao.pdo.output.VisitFactRelated; +import edu.harvard.i2b2.crc.dao.pdo.input.ModifierConstrainsHandler; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.ConceptNotFoundException; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.OntologyException; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.UnitConverstionUtil; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; +import edu.harvard.i2b2.crc.datavo.ontology.DerivedFactColumnsType; +import edu.harvard.i2b2.crc.datavo.ontology.XmlValueType; +import edu.harvard.i2b2.crc.datavo.pdo.ObservationSet; +import edu.harvard.i2b2.crc.datavo.pdo.ObservationType; +import edu.harvard.i2b2.crc.datavo.pdo.query.ConstrainDateTimeType; +import edu.harvard.i2b2.crc.datavo.pdo.query.ConstrainDateType; +import edu.harvard.i2b2.crc.datavo.pdo.query.FilterListType; +import edu.harvard.i2b2.crc.datavo.pdo.query.InclusiveType; +import edu.harvard.i2b2.crc.datavo.pdo.query.InputOptionListType; +import edu.harvard.i2b2.crc.datavo.pdo.query.ItemType; +import edu.harvard.i2b2.crc.datavo.pdo.query.OutputOptionListType; +import edu.harvard.i2b2.crc.datavo.pdo.query.PanelType; +import edu.harvard.i2b2.crc.datavo.pdo.query.ItemType.ConstrainByDate; +import edu.harvard.i2b2.crc.datavo.pdo.query.PanelType.TotalItemOccurrences; +import edu.harvard.i2b2.crc.delegate.ontology.CallOntologyUtil; +import edu.harvard.i2b2.crc.util.ItemKeyUtil; +import edu.harvard.i2b2.crc.util.PMServiceAccountUtil; +import edu.harvard.i2b2.crc.util.ParamUtil; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + +/** + * Observation fact handler class for pdo request. This class uses given pdo + * request to generate pdo sql and build observation fact, unique list of fact's + * patient,concept code, visit and provider list + *

    + * This class handles fact related queries for both plain and table pdo $Id: + * SQLServerFactRelatedQueryHandler.java,v 1.3 2008/06/10 14:59:05 rk903 Exp $ + * + * @author rkuttan + * @see VisitFactRelated + * @see ProviderFactRelated + * @see PatientFactRelated + * @see ObservationFactRelated + */ +public class SQLServerFactRelatedQueryHandler extends CRCDAO implements + IFactRelatedQueryHandler { + /** Input option list from pdo request* */ + private InputOptionListType inputList = null; + + /** filter list from pdo request * */ + private FilterListType filterList = null; + + private OutputOptionListType outputOptionList = null; + + /** helper class for visit/event in pdo * */ + private VisitFactRelated visitFactRelated = null; + + /** helper class for observer/provider in pdo * */ + private ProviderFactRelated providerFactRelated = null; + + /** helper class for patient in pdo * */ + private PatientFactRelated patientFactRelated = null; + + /** helper class for concepts in pdo * */ + private ConceptFactRelated conceptFactRelated = null; + + private ModifierFactRelated modifierFactRelated = null; + + private PidFactRelated pidFactRelated = null; + + private EidFactRelated eidFactRelated = null; + + /** helper class for observation fact in pdo * */ + private ObservationFactFactRelated obsFactFactRelated = null; + /** to store unique patient number list present in fact* */ + List patientFactList = new Vector(); + /** to store unique concept code list present in fact* */ + List conceptFactList = new Vector(); + /** to store unique modifier code list present in fact* */ + List modifierFactList = new Vector(); + /** to store unique encounter number present in fact * */ + List visitFactList = new Vector(); + /** to store unique provider/observer id present in fact * */ + List providerFactList = new Vector(); + + /** Handler interface for input list, i.e Patient list or visit list * */ + private IInputOptionListHandler inputOptionListHandler = null; + + /** + * flag to see if concept filter is set, used in observation fact set + * element * + */ + private boolean checkFilter = false; + + /** + * field to keep track number of prepared statment parameters in the + * genereated pdo query* + */ + private int queryParameterCount = 0; + + private DataSourceLookup dataSourceLookup = null; + + // public static final String TEMP_PDO_OBSFACT_TABLE = "#TEMP_PDO_OBSFACT"; + public static String TEMP_PDO_INPUTLIST_TABLE = "#TEMP_PDO_INPUTLIST"; + public static String TEMP_FACT_PARAM_TABLE = "#TEMP_FACT_PARAM_TABLE"; + // public static final String TEMP_PDO_INPUTLIST_TABLE1 = + // "#TEMP_PDO_INPUTLIST1"; + + private List panelSqlList = new ArrayList(); + private Map projectParamMap = null; + private Map modifierMetadataXmlMap = null; + private String requestVersion = ""; + + + private String factTable = "observation_FACT"; + private boolean derivedFactTable = QueryProcessorUtil.getInstance().getDerivedFactTable(); + + + /** + * Constructor with parameter + * + * @param inputList + * @param filterList + * @param outputOptionList + */ + public SQLServerFactRelatedQueryHandler(DataSourceLookup dataSourceLookup, + InputOptionListType inputList, FilterListType filterList, + OutputOptionListType outputOptionList) { + this.dataSourceLookup = dataSourceLookup; + this.setDbSchemaName(dataSourceLookup.getFullSchema()); + this.inputList = inputList; + this.filterList = filterList; + this.outputOptionList = outputOptionList; + + visitFactRelated = new VisitFactRelated(outputOptionList.getEventSet()); + providerFactRelated = new ProviderFactRelated(outputOptionList + .getObserverSetUsingFilterList()); + patientFactRelated = new PatientFactRelated(outputOptionList + .getPatientSet()); + conceptFactRelated = new ConceptFactRelated(outputOptionList + .getConceptSetUsingFilterList()); + modifierFactRelated = new ModifierFactRelated(outputOptionList + .getConceptSetUsingFilterList()); + obsFactFactRelated = new ObservationFactFactRelated(outputOptionList + .getObservationSet()); + pidFactRelated = new PidFactRelated(outputOptionList.getPidSet()); + eidFactRelated = new EidFactRelated(outputOptionList.getEidSet()); + + // If postgresql change temp table name + if (dataSourceLookup.getServerType().equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { + TEMP_PDO_INPUTLIST_TABLE = "TEMP_PDO_INPUTLIST"; + TEMP_FACT_PARAM_TABLE = "TEMP_FACT_PARAM_TABLE"; + + } + // check if concept filter present + if ((filterList != null) && (filterList.getPanel() != null) + && (filterList.getPanel().size() > 0)) { + checkFilter = true; + } + } + + @Override + public void setProjectParamMap(Map projectParamMap) { + this.projectParamMap = projectParamMap; + } + + @Override + public void setModifierMetadataXmlMap(Map modifierMetadataXmlMap) { + this.modifierMetadataXmlMap = modifierMetadataXmlMap; + } + + @Override + public void setRequestVersion(String requestVersion) { + this.requestVersion = requestVersion; + } + + + public String getFactTable(){ + return this.factTable; + } + + public void setFactTable(String table){ + this.factTable = table; + } + + + /** + * Function to build and execute pdo sql and build plain pdo's observation + * fact + * + * @return + * @throws Exception + */ + @Override + public List getPdoObservationFact() throws I2B2DAOException { + ResultSet resultSet = null; + Connection conn = null; + List observationFactSetList = new ArrayList(); + PreparedStatement stmt = null; + try { + conn = this.getApplicationDataSource( + dataSourceLookup.getDataSource()).getConnection(); + + int sqlParamCount = 1; + + boolean createTempTable = true; + + if(checkFilter == false) { +//WAS if (filterList.getPanel().size() == 0) { + + if(derivedFactTable == true){ + String sql= "select * from information_schema.tables where lower(table_name) = 'observation_fact'"; + if(dataSourceLookup.getFullSchema() != null){ + int lastIndex = dataSourceLookup.getFullSchema().lastIndexOf("."); + sql += " and table_catalog = '" + dataSourceLookup.getFullSchema().substring(0, lastIndex) + "'"; + sql += " and table_schema = '" + dataSourceLookup.getFullSchema().substring(lastIndex+1, (dataSourceLookup.getFullSchema().length())) + "'"; + } + PreparedStatement stmt1 = conn.prepareStatement(sql); + ResultSet resultSet1 = stmt1.executeQuery(); + // log.info("no filter Pdo sql: " + sql); + + if(!(resultSet1.next())){ + resultSet1.close(); + createTempTable = false; + try { + JDBCUtil.closeJdbcResource(null, stmt1, conn); + } catch (SQLException e) { + log.error("Error trying to close connection:"+ e.getMessage()); + } + + return observationFactSetList; + } + } + + // generate sql + String querySql = buildQuery(null, + PdoQueryHandler.PLAIN_PDO_TYPE); + panelSqlList.add(buildQueryCommon(null, + PdoQueryHandler.PLAIN_PDO_TYPE)); + log.debug("Executing sql[" + querySql + "]"); + if (inputOptionListHandler.isEnumerationSet()) { + inputOptionListHandler + .uploadEnumerationValueToTempTable(conn); + } + // execute fullsql + resultSet = executeQuery(conn, stmt, querySql, sqlParamCount); + // build facts + observationFactSetList.add(buildPDOFact(resultSet, "")); + } else { + for (PanelType panel : filterList.getPanel()) { + // generate sql + String querySql = buildQuery(panel, + PdoQueryHandler.PLAIN_PDO_TYPE); + if (querySql.length() ==0) { + continue; + } + + String defaultTableName = this.getDbSchemaName() + "observation_FACT" ; + // OMOP addition + if(panel != null){ + if(derivedFactTable == true){ + if(panel.getItem().get(0).getFacttablecolumn().contains(".")){ + + String baseItemFactColumn = panel.getItem().get(0).getFacttablecolumn(); + int lastIndex = baseItemFactColumn.lastIndexOf("."); + String factTable = this.getDbSchemaName() + (baseItemFactColumn.substring(0, lastIndex)); + + DerivedFactColumnsType columns = getFactColumnsFromOntologyCell(panel.getItem().get(0).getItemKey()); + if(columns != null){ + if(columns.getDerivedFactTableColumn().size() > 1) { + // parse through solumns and build up replace string. + + Iterator it = columns.getDerivedFactTableColumn().iterator(); + String column = it.next(); + + lastIndex = column.lastIndexOf("."); + String table = this.getDbSchemaName() + (column.substring(0, lastIndex)); + + + factTable = "( select * from " + table; + while(it.hasNext()){ + column = it.next(); + + lastIndex = column.lastIndexOf("."); + table = this.getDbSchemaName() + (column.substring(0, lastIndex)); + + factTable += "\n UNION ALL \n" + + " select * from " + table; + } + factTable += " )"; + + } + } + log.debug("Parse columns " + factTable); + querySql=querySql.replaceAll(defaultTableName, factTable) ; + } + } + } + panelSqlList.add(buildQueryCommon(panel, + PdoQueryHandler.PLAIN_PDO_TYPE)); + log.debug("PLAIN PDO Executing sql[" + querySql + "]"); + // execute fullsql + sqlParamCount = panel.getItem().size(); + if (panel.getInvert() == 1) { + sqlParamCount++; + } + long startTimeSql = System.currentTimeMillis(); + if (createTempTable) { + if (inputOptionListHandler.isEnumerationSet()) { + inputOptionListHandler + .uploadEnumerationValueToTempTable(conn); + } + } + + resultSet = executeQuery(conn, stmt, querySql, + sqlParamCount); + // set createTempTable flag to false after the first + // iteration + createTempTable = false; + // + long endTimeSql = System.currentTimeMillis(); + long totalTimeSql = endTimeSql - startTimeSql; + System.out + .println("******* Total time to execute observation sql" + + totalTimeSql); + long startTime = System.currentTimeMillis(); + // build facts + observationFactSetList.add(buildPDOFact(resultSet, panel + .getName())); + long endTime = System.currentTimeMillis(); + long totalTime = endTime - startTime; + System.out + .println("******* Total time to build observation " + + totalTime); + resultSet.close(); + } + } + } catch (SQLException sqlEx) { + throw new I2B2DAOException("", sqlEx); + } catch (IOException ioEx) { + throw new I2B2DAOException("", ioEx); + } finally { + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER)) { + // deleteTempTable(conn); + try { + if(inputOptionListHandler != null && conn != null) + inputOptionListHandler.deleteTempTable(conn); + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + // close connection + try { + JDBCUtil.closeJdbcResource(null, stmt, conn); + } catch (SQLException e) { + log.error("Error trying to close connection", e); + } + } + + return observationFactSetList; + } + + /** + * Function to build and execute pdo sql and build table pdo's observation + * fact + * + * @return ObservationSet list + * @throws I2B2DAOException + */ + @Override + public List getTablePdoObservationFact() + throws I2B2DAOException { + Connection conn = null; + List observationSetList = new ArrayList(); + ResultSet resultSet = null; + PreparedStatement stmt = null; + try { + conn = this.getApplicationDataSource( + dataSourceLookup.getDataSource()).getConnection(); + + int sqlParamCount = 1; + + // + boolean createTempTable = true; + + if(checkFilter == false) { +//WAS if (filterList.getPanel().size() == 0) { + + if(derivedFactTable == true){ + String sql= "select * from information_schema.tables where lower(table_name) = 'observation_fact'"; + if(dataSourceLookup.getFullSchema() != null){ + // log.info("schema: " + dataSourceLookup.getFullSchema()); + + int lastIndex = dataSourceLookup.getFullSchema().lastIndexOf("."); + sql += " and table_catalog = '" + dataSourceLookup.getFullSchema().substring(0, lastIndex) + "'"; + sql += " and table_schema = '" + dataSourceLookup.getFullSchema().substring(lastIndex+1, (dataSourceLookup.getFullSchema().length())) + "'"; + } + // log.info("no filter tablePDO sql: " + sql); + PreparedStatement stmt1 = conn.prepareStatement(sql); + ResultSet resultSet1 = stmt1.executeQuery(); + + if(!(resultSet1.next())){ + resultSet1.close(); + createTempTable = false; + try { + JDBCUtil.closeJdbcResource(null, stmt1, conn); + } catch (SQLException e) { + log.error("Error trying to close connection:"+ e.getMessage()); + } + + return observationSetList; + } + + } + // generate sql + String querySql = buildQuery(null, + PdoQueryHandler.PLAIN_PDO_TYPE); + + log.debug("Executing sql PLAIN PDO[" + querySql + "]"); + panelSqlList.add(buildQueryCommon(null, + PdoQueryHandler.PLAIN_PDO_TYPE)); + if (inputOptionListHandler.isEnumerationSet()) { + inputOptionListHandler + .uploadEnumerationValueToTempTable(conn); + } + + // execute fullsql + resultSet = executeQuery(conn, stmt, querySql, sqlParamCount); + // build facts + observationSetList.add(buildPDOFact(resultSet, "")); + } else { + for (PanelType panel : filterList.getPanel()) { + // generate sql + String querySql = buildQuery(panel, + PdoQueryHandler.TABLE_PDO_TYPE); + if (querySql.length() ==0 ) { + continue; + } + + // panelSqlList.add(buildQueryCommon(panel, + // PdoQueryHandler.TABLE_PDO_TYPE)); + sqlParamCount = panel.getItem().size(); + if (panel.getInvert() == 1) { + sqlParamCount++; + } + long startTimeSql = System.currentTimeMillis(); + if (createTempTable) { + if (inputOptionListHandler.isEnumerationSet()) { + inputOptionListHandler + .uploadEnumerationValueToTempTable(conn); + } + + } + String defaultTableName = this.getDbSchemaName() + "observation_FACT" ; + // OMOP addition + if(panel != null){ + if(derivedFactTable == true){ + if(panel.getItem().get(0).getFacttablecolumn().contains(".")){ + + String baseItemFactColumn = panel.getItem().get(0).getFacttablecolumn(); + int lastIndex = baseItemFactColumn.lastIndexOf("."); + String factTable = this.getDbSchemaName() + (baseItemFactColumn.substring(0, lastIndex)); + + DerivedFactColumnsType columns = getFactColumnsFromOntologyCell(panel.getItem().get(0).getItemKey()); + if(columns != null){ + if(columns.getDerivedFactTableColumn().size() > 1) { + // parse through solumns and build up replace string. + + Iterator it = columns.getDerivedFactTableColumn().iterator(); + String column = it.next(); + + lastIndex = column.lastIndexOf("."); + String table = this.getDbSchemaName() + (column.substring(0, lastIndex)); + + + factTable = "( select * from " + table; + while(it.hasNext()){ + column = it.next(); + + lastIndex = column.lastIndexOf("."); + table = this.getDbSchemaName() + (column.substring(0, lastIndex)); + + factTable += "\n UNION ALL \n" + + " select * from " + table; + } + factTable += " )"; + + } + } + log.debug("Parse columns " + factTable); + querySql=querySql.replaceAll(defaultTableName, factTable) ; + } + } + } + panelSqlList.add(querySql); + log.debug("TABLE PDO Executing sql[" + querySql + "]"); + + // execute fullsql + resultSet = executeQuery(conn, stmt, querySql, + sqlParamCount); + long endTimeSql = System.currentTimeMillis(); + long totalTimeSql = endTimeSql - startTimeSql; + System.out + .println("******* Total time to execute observation sql" + + totalTimeSql); + long startTime = System.currentTimeMillis(); + // build facts + observationSetList.add(buildTablePDOFact(resultSet, panel + .getName())); + long endTime = System.currentTimeMillis(); + long totalTime = endTime - startTime; + System.out + .println("******* Total time to build observation " + + totalTime); + resultSet.close(); + createTempTable = false; + } + } + } catch (SQLException sqlEx) { + log.error(sqlEx.getMessage()); + throw new I2B2DAOException("", sqlEx); + } catch (IOException ioEx) { + log.error(ioEx.getMessage()); + throw new I2B2DAOException("", ioEx); + } finally { + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER)) { + /* + * IInputOptionListHandler inputOptionListHandler = PDOFactory + * .buildInputListHandler(inputList, dataSourceLookup); + */ + try { + if(conn != null && inputOptionListHandler != null) + inputOptionListHandler.deleteTempTable(conn); + } catch (SQLException e) { + log.error(e.getMessage()); + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + // close connection + try { + JDBCUtil.closeJdbcResource(null, stmt, conn); + } catch (SQLException e) { + log.error("Error trying to close connection", e); + } + } + + return observationSetList; + } + + /** + * Returns provider id, belong to the facts + * + * @return list of provider/observer id + */ + @Override + public List getProviderFactList() { + return providerFactList; + } + + /** + * Returns concept code belong to the facts + * + * @return + */ + @Override + public List getConceptFactList() { + return conceptFactList; + } + + /** + * Returns modifier code belong to the facts + * + * @return + */ + @Override + public List getModifierFactList() { + return modifierFactList; + } + + /** + * Returns patient number belong to the facts + * + * @return + */ + @Override + public List getPatientFactList() { + return patientFactList; + } + + /** + * Returns encounter number belong to the facts + * + * @return list of encounter number + */ + @Override + public List getVisitFactList() { + return visitFactList; + } + + @Override + public String buildTotalQuery(PanelType panel, String pdoType) + throws I2B2DAOException { + // TODO Auto-generated method stub + return buildQueryCommon(panel, pdoType); + } + + private String buildQueryCommon(PanelType panel, String pdoType) + throws I2B2DAOException { + String obsFactSelectClause = null; + + if (obsFactFactRelated != null) { + obsFactSelectClause = obsFactFactRelated + .getSelectClauseWithoutBlob(); + + if (obsFactSelectClause.length() <= 0) { + obsFactSelectClause = obsFactFactRelated + .getDefaultSelectClause(); + } + } + + String tableLookupJoinClause = " "; + + if (pdoType.equals(PdoQueryHandler.TABLE_PDO_TYPE)) { + tableLookupJoinClause = getLookupJoinClause(obsFactFactRelated + .isSelectDetail(), obsFactFactRelated.isSelectBlob(), + obsFactFactRelated.isSelectStatus()); + obsFactSelectClause += " , concept_lookup.name_char concept_name, provider_lookup.name_char provider_name, modifier_lookup.name_char modifier_name"; + if (obsFactFactRelated.isSelectDetail()) { + obsFactSelectClause += " , location_lookup.name_char location_name "; + } + } + + String fullWhereClause = ""; + + if (inputOptionListHandler == null) { + inputOptionListHandler = PDOFactory.buildInputListHandler( + inputList, dataSourceLookup); + } + // fullWhereClause = patientSetWhereBuilder.getWhereClause(); + if (inputList.getPatientList() != null) { + fullWhereClause = " obs.patient_num IN "; + } else if (inputList.getEventList() != null) { + fullWhereClause = " obs.encounter_num IN \n"; + } else if (inputList.getPidList() != null) { + fullWhereClause = " obs.patient_num IN "; + } else if (inputList.getEidList() != null) { + fullWhereClause = " obs.encounter_num IN "; + } else { + throw new I2B2DAOException( + "Input option list does not contain visit or patient list"); + } + + fullWhereClause += (" ( " + + inputOptionListHandler.generateWhereClauseSql() + " ) \n"); + + String factByConceptSql = ""; + String factWithoutFilterSql = ""; + + String mainSelectBlobClause = " "; + if (obsFactFactRelated.isSelectBlob()) { + mainSelectBlobClause = " , observation_blob obs_observation_blob"; + } + + // String mainQuerySql = "SELECT * FROM ( \n"; + String mainQuerySql = "SELECT b.* " + mainSelectBlobClause + " FROM " + + this.getDbSchemaName() + getFactTable() + " obs ,( \n"; + try { + if (panel != null) { + factByConceptSql = factQueryWithDimensionFilter( + obsFactSelectClause, tableLookupJoinClause, + fullWhereClause, panel); + if (factByConceptSql.trim().length()==0) { + return ""; + } + if (panel.getTotalItemOccurrences() != null + && panel.getTotalItemOccurrences().getValue() > 0) { + mainQuerySql += " select *, rank() over (partition by obs_encounter_num,obs_patient_num,obs_start_date,obs_concept_cd order by rnum) as seqNumber from ( " + + factByConceptSql + " ) as t"; + } else { + mainQuerySql += factByConceptSql; + } + + } else { + factWithoutFilterSql = factQueryWithoutFilter( + obsFactSelectClause, tableLookupJoinClause, + fullWhereClause); + mainQuerySql += factWithoutFilterSql + ") b \n"; + } + + } catch (I2B2Exception i2b2Ex) { + throw new I2B2DAOException(i2b2Ex.getMessage(), i2b2Ex); + } + + mainQuerySql += " ) as b where rnum >= 0 "; + mainQuerySql += " and obs.encounter_num = b.obs_encounter_num and obs.patient_num = b.obs_patient_num "; + mainQuerySql += " and obs.concept_cd = b.obs_concept_cd and obs.provider_id = b.obs_provider_id and obs.start_date = b.obs_start_date and obs.modifier_cd = b.obs_modifier_cd and obs.instance_num = b.obs_instance_num "; + + if (panel != null) { + TotalItemOccurrences totOccurance = panel.getTotalItemOccurrences(); + if (totOccurance != null && totOccurance.getValue() > 1) { + int totOcurranceValue = totOccurance.getValue(); + String totOccuranceOperator = ">="; + if (totOccurance.getOperator() != null) { + String totOccuranceOperatorValue = totOccurance.getOperator() + .value(); + totOccuranceOperator = XMLOperatorLookup + .getComparisonOperatorFromAcronum(totOccuranceOperatorValue); + if (totOccuranceOperator == null) { + totOccuranceOperator = ">="; + } + } + + mainQuerySql += " AND seqNumber " + totOccuranceOperator + + totOcurranceValue; + } + + } + + + if (this.outputOptionList.getObservationSet().getSelectionfilter()!= null) + { + //mainQuerySql = "with main_query as (" + mainQuerySql + ") select * from (select f1.*, " + + String newMainQuerySql = "select * from (select f1.*, " + + + " rank() over(partition by obs_patient_num, obs_concept_cd order by "; + if (this.outputOptionList.getObservationSet().getSelectionfilter().value().equalsIgnoreCase("min_value")) + newMainQuerySql += " obs_nval_num "; + else if (this.outputOptionList.getObservationSet().getSelectionfilter().value().equalsIgnoreCase("max_value")) + newMainQuerySql += " obs_nval_num desc "; + else if (this.outputOptionList.getObservationSet().getSelectionfilter().value().equalsIgnoreCase("first_value")) + newMainQuerySql += " obs_start_date "; + else if (this.outputOptionList.getObservationSet().getSelectionfilter().value().equalsIgnoreCase("last_value")) + newMainQuerySql += " obs_start_date desc "; + else if (this.outputOptionList.getObservationSet().getSelectionfilter().value().equalsIgnoreCase("single_observation")) + newMainQuerySql += " case when obs_modifier_cd = '@' then 1 else 0 end, obs_modifier_cd "; + else + newMainQuerySql += " obs_start_date desc "; + + mainQuerySql = newMainQuerySql + " ) rank " + + " from (" + mainQuerySql + ") f1 " ; + + if ((this.outputOptionList.getObservationSet().getSelectionfilter().value().equalsIgnoreCase("min_value")) || + (this.outputOptionList.getObservationSet().getSelectionfilter().value().equalsIgnoreCase("max_value")) ) + mainQuerySql += " where obs_nval_num is not null "; + + + if (this.outputOptionList.getObservationSet().getSelectionfilter().value().equalsIgnoreCase("last_n_values")) + { + mainQuerySql += ") f where f.rank < " + this.outputOptionList.getObservationSet().getValue(); + } else { + mainQuerySql += ") f where f.rank = 1 "; + } + + } + + return mainQuerySql; + + } + + /** + * This is the main function to build query for plain and table pdo request + * + * @param pdoType + * @return String + * @throws I2B2DAOException + */ + @Override + public String buildQuery(PanelType panel, String pdoType) + throws I2B2DAOException { + String mainQuerySql = this.buildQueryCommon(panel, pdoType); + if (mainQuerySql.length() == 0) { + return ""; + } + //check for version 1.5, if so return the fact without the duplicates in modifier_cd and instance num + //TODO Removed because not working in 1.6.05 + /* + if (this.requestVersion.startsWith("1.5")) { + mainQuerySql = " select * from (select *, rank() over(partition by obs_encounter_num, obs_patient_num,obs_concept_cd,obs_start_date,obs_provider_id order by obs_modifier_cd,obs_instance_num ) ordernum " + + " from ( " + mainQuerySql + ") ordersql ) ordersql1 where ordernum = 1 "; + + } + */ + mainQuerySql += " ORDER BY obs_patient_num,obs_start_date,obs_concept_cd,obs_instance_num,obs_modifier_cd,rnum"; + + return mainQuerySql; + } + + // ----------------------------------------- + // private helper functions start from here + // ----------------------------------------- + + /** + * Function to uses given select, join and where clause to build core pdo + * query, related to provider filter + * + * @param obsFactSelectClause + * @param tableLookupJoinClause + * @param fullWhereClause + * @return + */ + private String factQueryWithDimensionFilter(String obsFactSelectClause, + String tableLookupJoinClause, String fullWhereClause, + PanelType panel) throws I2B2Exception { + String factByProviderSql = ""; + int i = 0; + String panelName = null; + DateConstrainHandler dateConstrainHandler = new DateConstrainHandler( + dataSourceLookup); + + + if (panel.getName() != null) { + panelName = JDBCUtil.escapeSingleQuote(panel.getName()); + } + + obsFactSelectClause += (", '" + panelName + "' panel_name "); + + int totalItemOccurance = 0; + if (panel.getTotalItemOccurrences() != null) { + totalItemOccurance = panel.getTotalItemOccurrences().getValue(); + } + int panelAccuracyScale = panel.getPanelAccuracyScale(); + //ignore the panel accuracy scale value, bcos the function is reverted + panelAccuracyScale = 0; + + String panelDateConstrain = null; + // generate panel date constrain + if (panel.getPanelDateFrom() != null || panel.getPanelDateTo() != null) { + panelDateConstrain = generatePanelDateConstrain( + dateConstrainHandler, panel.getPanelDateFrom(), panel + .getPanelDateTo()); + } + + for (ItemType item : panel.getItem()) { + // read the first item + // ItemType item = panel.getItem().get(0); + if (item.getFacttablecolumn() != null + || item.getDimColumnname() != null || item.getItemKey().toLowerCase().startsWith(ItemKeyUtil.ITEM_KEY_MASTERID)) { + + if (item.getDimTablename() != null) { + if (item.getDimTablename().equalsIgnoreCase("patient_dimension") || + item.getDimTablename().equalsIgnoreCase("visit_dimension")) { + continue; + } + } + + if (i == 0) { + i = 1; + } else { + if (totalItemOccurance > 1) { + factByProviderSql += "UNION ALL \n"; + } else { + factByProviderSql += "UNION \n"; + } + } + + factByProviderSql += (" SELECT " + + obsFactSelectClause + " FROM \n"); + + // check if the item key has "patient_set_coll_id:XXXX" as + // prefix + String itemKey = item.getItemKey(); + + if (itemKey.toLowerCase().startsWith(ItemKeyUtil.ITEM_KEY_PATIENT_SET)) { + String[] itemKeyParam = itemKey.split(":"); + factByProviderSql += (" select patient_num from " + + this.getDbSchemaName() + + "qt_patient_set_collection where patient_set_coll_id = " + + itemKeyParam[1] + " \n"); + item.setFacttablecolumn("patient_num"); + + } else if (itemKey.toLowerCase().startsWith(ItemKeyUtil.ITEM_KEY_PATIENT_ENCOUNTER_SET)) { // check + // if + // the + // item + // key + // has + // "patient_enc_coll_id:XXXX" + // as + // prefix + String[] itemKeyParam = itemKey.split(":"); + factByProviderSql += (" select encounter_num from " + + this.getDbSchemaName() + + "qt_patient_enc_collection where patient_enc_coll_id = " + + itemKeyParam[1] + " \n"); + //WAS item.setFacttablecolumn("encount_num"); + item.setFacttablecolumn("encounter_num"); + } else { + DimensionFilter providerFilter = new DimensionFilter(item, + this.getDbSchemaName(), dataSourceLookup); + factByProviderSql += (" " + + providerFilter.getFromSqlString() + " \n"); + + } + factByProviderSql += ", " + this.getDbSchemaName() + + getFactTable() + " obs \n"; + + String tempSqlClause = "",containsJoinSql = ""; + + //OMOP addition + String facttablecolumn = item.getFacttablecolumn(); + if(derivedFactTable == true){ + + if(item.getFacttablecolumn().contains(".")){ + + String factColumnName = item.getFacttablecolumn(); + + int lastIndex = factColumnName.lastIndexOf("."); + + facttablecolumn = (factColumnName.substring(lastIndex+1)); + } + } + + // OMOP WAS item.getFacttablecolumn(); + // String fullWhereClause1 = fullWhereClause + // + (" AND obs." + item.getFacttablecolumn() + // + " = dimension." + item.getFacttablecolumn()); + + + String fullWhereClause1 = fullWhereClause + + (" AND obs." + facttablecolumn + + " = dimension." + facttablecolumn); + + //factByProviderSql += tableLookupJoinClause; + tempSqlClause+= tableLookupJoinClause; + + //factByProviderSql += (" WHERE \n" + fullWhereClause1 + "\n"); + tempSqlClause+= (" WHERE \n" + fullWhereClause1 + "\n"); + + //if output option has modifier option false, then select modifier_cd = '@' + if (outputOptionList.getObservationSet() != null && outputOptionList.getObservationSet().isWithmodifiers() == false) { + //factByProviderSql += (" AND obs.modifier_cd = '@' \n"); + tempSqlClause+= (" AND obs.modifier_cd = '@' \n"); + } + + boolean itemConstrainValueFlag = false, modifierConstrainValueFlag = false; + //if modifier constrain is present in the request, then generate modifier constrain sql + ItemType.ConstrainByModifier modifierConstrain = item.getConstrainByModifier(); + if (modifierConstrain != null) { + // generate sql for item date constrain + ModifierConstrainsHandler modifierConstrainUtil = new ModifierConstrainsHandler(this.getDbSchemaName()); + String itemModifierConstrainSql = modifierConstrainUtil.constructModifierConstainClause(modifierConstrain); + if ((itemModifierConstrainSql != null) + && (itemModifierConstrainSql.length() > 0)) { + //factByProviderSql += (" AND (" + itemModifierConstrainSql + ")\n"); + tempSqlClause+=(" AND (" + itemModifierConstrainSql + ")\n"); + } + if (modifierConstrain.getConstrainByValue() != null && + modifierConstrain.getConstrainByValue().size()>0) { + modifierConstrainValueFlag = true; + } + + } + String unitCdSwitchClause = "", unitCdInClause = ""; + String modifierUnitCdSwitchClause = "", modifierUnitCdInClause = ""; + + if (item.getConstrainByValue() != null + && item.getConstrainByValue().size() > 0) { + itemConstrainValueFlag = true; + } + // if value constrain is given, generate value constrain sql + if ( itemConstrainValueFlag || modifierConstrainValueFlag ) { + //generate sql for unit_cd conversion + if ( projectParamMap != null && projectParamMap.get(ParamUtil.CRC_ENABLE_UNITCD_CONVERSION) != null) { + String unitCdConversionFlag = (String)projectParamMap.get(ParamUtil.CRC_ENABLE_UNITCD_CONVERSION); + if (unitCdConversionFlag != null && unitCdConversionFlag.equalsIgnoreCase("ON")) { + if (item.getMetadataxml() != null && item.getMetadataxml().getContent().get(0) != null) { + Element valueMetadataElement = (Element)item.getMetadataxml().getContent().get(0); + UnitConverstionUtil unitConverstionUtil = new UnitConverstionUtil(); + unitCdSwitchClause = unitConverstionUtil.buildUnitCdSwitchClause(valueMetadataElement,false,"obs."); + unitCdInClause = unitConverstionUtil.buildUnitCdInClause(valueMetadataElement,""); + } + + if (modifierConstrainValueFlag) { + XmlValueType xmlValueType = this.modifierMetadataXmlMap.get(item.getConstrainByModifier().getModifierKey()+item.getConstrainByModifier().getAppliedPath()); + if (xmlValueType != null && xmlValueType.getAny().get(0) != null) { + Element valueMetadataElement = xmlValueType.getAny().get(0); + UnitConverstionUtil unitConverstionUtil = new UnitConverstionUtil(); + modifierUnitCdSwitchClause = unitConverstionUtil.buildUnitCdSwitchClause(valueMetadataElement,false,"obs."); + modifierUnitCdInClause = unitConverstionUtil.buildUnitCdInClause(valueMetadataElement,""); + } + } + } + } + } + + ValueConstrainsHandler vh = new ValueConstrainsHandler(); + if (unitCdSwitchClause.length()>0) { + vh.setUnitCdConversionFlag(true, unitCdInClause, unitCdSwitchClause); + } + String[] valueConstrainSql = new String[] {"",""} ; + if (itemConstrainValueFlag) { + valueConstrainSql = vh + .constructValueConstainClause(item + .getConstrainByValue(), this.dataSourceLookup.getServerType(),this.getDbSchemaName(),panelAccuracyScale); + if (panelAccuracyScale>0) { + containsJoinSql = valueConstrainSql[1]; + } + } + + String[] modifierConstrainValueSql = new String[]{"",""}; + if (modifierConstrainValueFlag) { + if (modifierUnitCdInClause.length()>0) { + vh.setUnitCdConversionFlag(true, modifierUnitCdInClause, modifierUnitCdSwitchClause); + } + modifierConstrainValueSql = vh.constructValueConstainClause(buildItemValueConstrain(modifierConstrain.getConstrainByValue()),this.dataSourceLookup.getServerType(),this.getDbSchemaName(),panelAccuracyScale); + if (panelAccuracyScale>0) { + containsJoinSql += modifierConstrainValueSql[1]; + } + } + + if ((valueConstrainSql[0] != null + && valueConstrainSql[0].length() > 0)|| (modifierConstrainValueSql[0] != null + && modifierConstrainValueSql[0].length() > 0)) { + //factByProviderSql += (" AND (" + valueConstrainSql[0] + modifierConstrainValueSql[0] + ")\n"); + tempSqlClause+= (" AND (" + valueConstrainSql[0] + modifierConstrainValueSql[0] + ")\n"); + + } + + factByProviderSql += containsJoinSql; + + factByProviderSql += tempSqlClause; + + // add start and end date constrains + + List constrainByDateList = item + .getConstrainByDate(); + for (ConstrainByDate constrainByDate : constrainByDateList) { + + ConstrainDateType dateFrom = constrainByDate.getDateFrom(); + ConstrainDateType dateTo = constrainByDate.getDateTo(); + + String dateFromColumn = null, dateToColumn = null; + InclusiveType dateFromInclusive = null, dateToInclusive = null; + XMLGregorianCalendar dateFromValue = null, dateToValue = null; + String dateConstrainSql = null; + + // obs.start_date, obs.end_date + if (dateFrom != null || dateTo != null) { + + if (dateFrom != null) { + dateFromInclusive = dateFrom.getInclusive(); + dateFromValue = dateFrom.getValue(); + if (dateFrom.getTime() != null + && dateFrom.getTime().name() != null + && dateFrom + .getTime() + .name() + .equalsIgnoreCase( + ConstrainDateTimeType.END_DATE + .name())) { + dateFromColumn = "obs.end_date"; + } else { + dateFromColumn = "obs.start_date"; + } + + } + + if (dateTo != null) { + dateToInclusive = dateTo.getInclusive(); + dateToValue = dateTo.getValue(); + if (dateTo.getTime() != null + && dateTo.getTime().name() != null + && dateTo.getTime().name().equals( + ConstrainDateTimeType.END_DATE + .name())) { + dateToColumn = "obs.end_date"; + } else { + dateToColumn = "obs.start_date"; + } + } + + dateConstrainSql = dateConstrainHandler + .constructDateConstrainClause(dateFromColumn, + dateToColumn, dateFromInclusive, + dateToInclusive, dateFromValue, + dateToValue); + if (dateConstrainSql != null) { + factByProviderSql += (" AND " + dateConstrainSql + "\n"); + } + + // item.getConstrainByModifier().get(0).getModifierName() + } + } + // generate panel date constrain + if (panelDateConstrain != null) { + factByProviderSql += (" AND (" + panelDateConstrain + ")\n"); + } + } + } + + if (factByProviderSql.trim().length()<10) { + return ""; + } + + int invert = panel.getInvert(); + + if (invert == 1) { + String invertSql = ("( SELECT " + obsFactSelectClause + " FROM \n"); + invertSql += " " + this.getDbSchemaName() + + getFactTable() + " obs \n"; + invertSql += tableLookupJoinClause; + invertSql += (" WHERE \n" + fullWhereClause + ")\n"); + factByProviderSql = invertSql + " EXCEPT \n " + "(" + + factByProviderSql + ")"; + } + + if (totalItemOccurance > 1) { + factByProviderSql = "SELECT a.*, row_number() over(order by obs_patient_num) as rnum FROM (\n" + + factByProviderSql; + } else { + factByProviderSql = "SELECT a.*, row_number() over(order by obs_patient_num) as rnum FROM (\n" + + factByProviderSql; + } + + factByProviderSql += " ) a \n"; + // factByProviderSql += " ORDER BY 2,5,3) a \n"; + + return factByProviderSql; + } + + /** + * Function to uses given select, join and where clause to build core pdo + * query, without any filter (concept and provider) + * + * @param obsFactSelectClause + * @param tableLookupJoinClause + * @param fullWhereClause + * @return + */ + private String factQueryWithoutFilter(String obsFactSelectClause, + String tableLookupJoinClause, String fullWhereClause) { + String factSql = "SELECT b.*, ROW_NUMBER() OVER (order by obs_patient_num) rnum FROM (\n"; + factSql += (" SELECT " + + obsFactSelectClause + " FROM " + this.getDbSchemaName() + getFactTable() + " obs\n"); + + factSql += tableLookupJoinClause; + + factSql += (" WHERE \n" + fullWhereClause + "\n"); + if (this.outputOptionList.getObservationSet().isWithmodifiers() == false) { + factSql += " AND obs.modifier_cd = '@' "; + } + // lcp5 following was causing invalid sql 12/20/16 +// factSql += " ORDER BY obs.patient_num,obs.start_date,obs.concept_cd,obs.instance_num,obs.modifier_cd,obs.rowid) b \n"; + + return factSql; + } + + /** + * Generate fact's join clause for table pdo + * + * @param detailFlag + * @param blobFlag + * @param statusFlag + * @return + */ + private String getLookupJoinClause(boolean detailFlag, boolean blobFlag, + boolean statusFlag) { + String joinClause = " "; + + joinClause = " left JOIN " + + this.getDbSchemaName() + + "code_lookup modifier_lookup \n" + + " ON (obs.modifier_cd = modifier_lookup.code_Cd AND modifier_lookup.column_cd = 'MODIFIER_CD') \n" + + " left JOIN " + + "(select name_char, concept_cd from " + + this.getDbSchemaName() + + "concept_dimension group by name_char, concept_cd) concept_lookup " + + "ON (obs.concept_cd = concept_lookup.concept_Cd) \n" + + " left JOIN " + this.getDbSchemaName() + + "provider_dimension provider_lookup \n" + + " ON (obs.provider_id = provider_lookup.provider_id) \n"; + + if (detailFlag) { + joinClause += " left JOIN " + + this.getDbSchemaName() + + "code_lookup location_lookup \n" + + " ON (obs.location_Cd = location_lookup.code_Cd AND location_lookup.column_cd = 'LOCATION_CD') \n"; + } + + return joinClause; + } + + private void deleteTempTable(Connection conn) { + + Statement deleteStmt = null; + try { + deleteStmt = conn.createStatement(); + //conn + // .createStatement() + deleteStmt.executeUpdate( + "drop table " + + SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE); + + } catch (SQLException sqle) { + ; + } finally { + try { + if(deleteStmt != null) + deleteStmt.close(); + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + } + + private List buildItemValueConstrain(List modifierConstrainList) { + List itemValueConstrainList = new ArrayList(); + for (ItemType.ConstrainByModifier.ConstrainByValue modifierValueConstrain : modifierConstrainList) { + ItemType.ConstrainByValue constrainByValue = new ItemType.ConstrainByValue(); + constrainByValue.setValueConstraint(modifierValueConstrain.getValueConstraint()); + constrainByValue.setValueOperator(modifierValueConstrain.getValueOperator()) ; + constrainByValue.setValueType(modifierValueConstrain.getValueType()); + constrainByValue.setValueUnitOfMeasure(modifierValueConstrain.getValueUnitOfMeasure()) ; + itemValueConstrainList.add(constrainByValue); + } + return itemValueConstrainList; + } + + /** + * Helper function to build unique visit, patient, concept list from + * observation fact + * + * @param encounterNum + * @param patientNum + * @param providerId + * @param conceptCd + */ + private void addToDistinctList(String encounterNum, String patientNum, + String providerId, String conceptCd,String modifierCd) { + if (visitFactRelated.isSelected() || eidFactRelated.isSelected()) { + if (!visitFactList.contains(encounterNum)) { + visitFactList.add(encounterNum); + } + } + + if (patientFactRelated.isSelected() || pidFactRelated.isSelected()) { + if (!patientFactList.contains(patientNum)) { + patientFactList.add(patientNum); + } + } + + if (providerFactRelated.isSelected()) { + if (!providerFactList.contains(providerId)) { + providerFactList.add(providerId); + } + } + + if (conceptFactRelated.isSelected()) { + if (!conceptFactList.contains(conceptCd)) { + conceptFactList.add(conceptCd); + } + } + + if (modifierFactRelated.isSelected()) { + if (!modifierFactList.contains(modifierCd)) { + modifierFactList.add(modifierCd); + } + } + + } + + /** + * Executive the given query + * + * @param conn + * @param querySql + * @return + * @throws SQLException + */ + private ResultSet executeQuery(Connection conn, PreparedStatement stmt, + String querySql, int sqlParamCount) throws SQLException { + + stmt = conn.prepareStatement(querySql); + + if (inputOptionListHandler.isCollectionId()) { + for (int i = 1; i <= sqlParamCount; i++) { + stmt.setInt(i, Integer.parseInt(inputOptionListHandler + .getCollectionId())); + } + } + + ResultSet resultSet = stmt.executeQuery(); + + return resultSet; + + // JdbcRowSet rowSet = new JdbcRowSetImpl(resultSet); + // return rowSet; + } + + /** + * Build plain pdo's observation fact + * + * @param rowSet + * @return + * @throws SQLException + * @throws IOException + */ + private ObservationSet buildPDOFact(ResultSet rowSet, String panelName) + throws SQLException, IOException { + ObservationSet currentObsFactSetType = new ObservationSet(); + currentObsFactSetType.setPanelName(panelName); + + I2B2PdoFactory.ObservationFactBuilder observationFactBuilder = new I2B2PdoFactory().new ObservationFactBuilder( + obsFactFactRelated.isSelectDetail(), obsFactFactRelated + .isSelectBlob(), obsFactFactRelated.isSelectStatus(), dataSourceLookup.getServerType()); + + while (rowSet.next()) { + ObservationType obsFactType = null; + + obsFactType = observationFactBuilder.buildObservationSet(rowSet); + + if (obsFactFactRelated.isSelected()) { + currentObsFactSetType.getObservation().add(obsFactType); + } + + addToDistinctList(obsFactType.getEventId().getValue(), obsFactType + .getPatientId().getValue(), obsFactType.getObserverCd() + .getValue(), obsFactType.getConceptCd().getValue(), obsFactType.getModifierCd().getValue()); + } + + return currentObsFactSetType; + } + + /** + * Build table pdo observaton fact + * + * @param rowSet + * @return + * @throws SQLException + * @throws IOException + */ + private ObservationSet buildTablePDOFact(ResultSet rowSet, String panelName) + throws SQLException, IOException { + // obsFactSetTypeList = new + // Vector(); + boolean detailFlag = obsFactFactRelated.isSelectDetail(); + boolean booleanFlag = obsFactFactRelated.isSelectBlob(); + boolean statusFlag = obsFactFactRelated.isSelectStatus(); + ObservationSet currentObservationSet = new ObservationSet(); + currentObservationSet.setPanelName(panelName); + + RPDRPdoFactory.ObservationFactBuilder observationFactBuilder = new RPDRPdoFactory.ObservationFactBuilder( + detailFlag, booleanFlag, statusFlag); + + while (rowSet.next()) { + ObservationType observation = null; + observation = observationFactBuilder.buildObservationSet(rowSet, + "HIVE"); + + if (obsFactFactRelated.isSelected()) { + currentObservationSet.getObservation().add(observation); + } + + + addToDistinctList(observation.getEventId().getValue(), observation.getPatientId().getValue(), + observation.getObserverCd().getValue(), observation.getConceptCd().getValue(), observation.getModifierCd().getValue()); + } + + return currentObservationSet; + } + + private String generatePanelDateConstrain( + DateConstrainHandler dateConstrainHandler, + ConstrainDateType dateFrom, ConstrainDateType dateTo) + throws I2B2Exception { + + String dateFromColumn = null, dateToColumn = null; + InclusiveType dateFromInclusive = null, dateToInclusive = null; + XMLGregorianCalendar dateFromValue = null, dateToValue = null; + String dateConstrainSql = null; + + if (dateFrom != null || dateTo != null) { + + if (dateFrom != null) { + dateFromInclusive = dateFrom.getInclusive(); + dateFromValue = dateFrom.getValue(); + + dateFrom.getTime(); + if (dateFrom.getTime() != null + && dateFrom.getTime().name() != null + && dateFrom.getTime().name().equalsIgnoreCase( + ConstrainDateTimeType.END_DATE.name())) { + dateFromColumn = "obs.end_date"; + } else { + + dateFromColumn = "obs.start_date"; + } + + } + + if (dateTo != null) { + dateToInclusive = dateTo.getInclusive(); + dateToValue = dateTo.getValue(); + + dateTo.getTime(); + if (dateTo.getTime() != null + && dateTo.getTime().name() != null + && dateTo.getTime().name().equalsIgnoreCase( + ConstrainDateTimeType.END_DATE.name())) { + dateToColumn = "obs.end_date"; + } else { + + dateToColumn = "obs.start_date"; + } + + } + + dateConstrainSql = dateConstrainHandler + .constructDateConstrainClause(dateFromColumn, dateToColumn, + dateFromInclusive, dateToInclusive, dateFromValue, + dateToValue); + } + return dateConstrainSql; + } + + @Override + public List getPanelSqlList() { + return this.panelSqlList; + } + + protected DerivedFactColumnsType getFactColumnsFromOntologyCell(String itemKey) + throws ConceptNotFoundException, OntologyException { + DerivedFactColumnsType factColumns = new DerivedFactColumnsType(); + try { + + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + String ontologyUrl = qpUtil + .getCRCPropertyValue(QueryProcessorUtil.ONTOLOGYCELL_ROOT_WS_URL_PROPERTIES); + + SecurityType securityType = PMServiceAccountUtil + .getServiceSecurityType(dataSourceLookup.getDomainId()); + + factColumns = CallOntologyUtil.callGetFactColumns(itemKey, + securityType, dataSourceLookup.getProjectPath(), + ontologyUrl +"/getDerivedFactColumns"); + } catch (JAXBUtilException e) { + + log.error("Error while fetching metadata [" + itemKey + + "] from ontology ", e); + throw new OntologyException("Error while fetching metadata [" + + itemKey + "] from ontology " + + StackTraceUtil.getStackTrace(e)); + } catch (I2B2Exception e) { + log.error("Error while fetching metadata from ontology ", e); + throw new OntologyException("Error while fetching metadata [" + + itemKey + "] from ontology " + + StackTraceUtil.getStackTrace(e)); + } catch (AxisFault e) { + log.error("Error while fetching metadata from ontology ", e); + throw new OntologyException("Error while fetching metadata [" + + itemKey + "] from ontology " + + StackTraceUtil.getStackTrace(e)); + } catch (XMLStreamException e) { + log.error("Error while fetching metadata from ontology ", e); + throw new OntologyException("Error while fetching metadata [" + + itemKey + "] from ontology " + + StackTraceUtil.getStackTrace(e)); + } + +// if (factColumns.isEmpty()) { +// throw new ConceptNotFoundException("[" + itemKey + "] "); + +// } + + return factColumns; + } + + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/input/SubDividePageMethod.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/input/SubDividePageMethod.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/input/SubDividePageMethod.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/input/SubDividePageMethod.java index da7ee1ab..86c7c4e6 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/input/SubDividePageMethod.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/input/SubDividePageMethod.java @@ -1,20 +1,20 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.pdo.input; - -public class SubDividePageMethod implements PageMethod { - - @Override - public int calculateListSize(int maxInputList, long totalObservations, - long pageSize) { - int newMaxInputList = maxInputList / 2; - return newMaxInputList; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.pdo.input; + +public class SubDividePageMethod implements PageMethod { + + @Override + public int calculateListSize(int maxInputList, long totalObservations, + long pageSize) { + int newMaxInputList = maxInputList / 2; + return newMaxInputList; + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/input/ValueConstrainsHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/input/ValueConstrainsHandler.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/input/ValueConstrainsHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/input/ValueConstrainsHandler.java index 577dcb74..114b8ea4 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/input/ValueConstrainsHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/input/ValueConstrainsHandler.java @@ -1,314 +1,314 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao.pdo.input; - -import java.util.List; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.datavo.pdo.query.ConstrainOperatorType; -import edu.harvard.i2b2.crc.datavo.pdo.query.ConstrainValueType; -import edu.harvard.i2b2.crc.datavo.pdo.query.ItemType; -import edu.harvard.i2b2.crc.util.ContainsUtil; -import edu.harvard.i2b2.crc.util.RegExUtil; -import edu.harvard.i2b2.crc.util.SqlClauseUtil; - -/** - * Class to handle value constrains. Generates sql where clause based on the - * list of value constrains. - * - * @author rkuttan - */ -public class ValueConstrainsHandler { - /** log **/ - protected final Log log = LogFactory.getLog(getClass()); - - private boolean unitCdConverstionFlag = false; - private String unitCdInClause = "", unitCdSwitchClause = ""; - - public void setUnitCdConversionFlag(boolean unitCdConverstionFlag, String unitCdInClause, String unitCdSwitchClause) { - this.unitCdConverstionFlag = unitCdConverstionFlag; - this.unitCdInClause = unitCdInClause; - this.unitCdSwitchClause = unitCdSwitchClause; - } - - public String[] constructValueConstainClause( - List valueConstrainList, String dbServerType,String dbSchemaName,int panelAccuracyScale) - throws I2B2Exception { - String fullConstrainSql = "",containsJoinSql = ""; - log.debug("panel accuracy scale" + panelAccuracyScale ); - panelAccuracyScale = 0; - - boolean oracleFlag = false; - if (dbServerType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { - oracleFlag = true; - } - int j = 0 ; - for (ItemType.ConstrainByValue valueConstrain : valueConstrainList) { - ConstrainValueType valueType = valueConstrain.getValueType(); - ConstrainOperatorType operatorType = valueConstrain - .getValueOperator(); - String value = valueConstrain.getValueConstraint(); - String unitCd = valueConstrain.getValueUnitOfMeasure(); - - String constrainSql = null; - // check if value type is not null - if (valueType == null) { - continue; - } - if (valueType.equals(ConstrainValueType.LARGETEXT)) { - String containsSql = ""; - ContainsUtil containsUtil = new ContainsUtil(); - if (operatorType.value().equalsIgnoreCase( - ConstrainOperatorType.CONTAINS.value())) { - containsSql = containsUtil.formatValue(value,dbServerType); - } else if(operatorType.value().equalsIgnoreCase( - ConstrainOperatorType.CONTAINS_DATABASE.value())) { - containsSql = containsUtil.formatValue("[" + value + "]",dbServerType); - } else { - log.debug("LARGETEXT : Invalid operator skipped [" + operatorType.value() + "]" ); - continue; - } - //panelAccuracyScale = 100 - panelAccuracyScale; - - constrainSql = " valtype_cd = 'B' AND " ; - if (dbServerType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) - { - - constrainSql += " observation_blob like '%" + containsSql + "%' "; - } - else if (oracleFlag == true) { - constrainSql += " contains(observation_blob,'" + containsSql + "') "; - if (panelAccuracyScale>0) { - constrainSql += " >= " + panelAccuracyScale + " "; - } else { - constrainSql += " > 0 "; - } - } else { - if (panelAccuracyScale>0) { - panelAccuracyScale = panelAccuracyScale * 10; - j++; - containsJoinSql += " INNER JOIN freetexttable(" + dbSchemaName + "observation_fact,observation_blob,'"+ containsSql + "') " - + " AS ft" + j + " ON text_search_index = ft" +j+ ".[KEY] "; - - constrainSql += " ft"+j+".[RANK] >= " + panelAccuracyScale + " "; - - } else { - constrainSql += " CONTAINS(observation_blob,'" + containsSql + "') "; - } - - } - - - - - } else if (valueType.equals(ConstrainValueType.TEXT)) { - // check if operator and value not null - if (operatorType == null || value == null) { - continue; - } - boolean notLikeFlag = false; - if (operatorType.value().startsWith( - ConstrainOperatorType.LIKE.value())) { - //call the utility to find the like operation - String operatorOption = RegExUtil.getOperatorOption(operatorType.value()); - if (operatorOption ==null) { - operatorOption = "[begin]"; - } - String likeValueFormat = ""; - if (operatorOption.equalsIgnoreCase("[begin]")) { - likeValueFormat = "'" + value.replaceAll("'", "''") + "%'"; - } else if (operatorOption.equalsIgnoreCase("[end]")) { - likeValueFormat = "'%" + value.replaceAll("'", "''") + "'"; - } else if (operatorOption.equalsIgnoreCase("[contains]")) { - likeValueFormat = "'%" + value.replaceAll("'", "''") + "%'"; - } else if (operatorOption.equalsIgnoreCase("[exact]")) { - likeValueFormat = "'" + value.replaceAll("'", "''") + "'"; - if (oracleFlag) { - constrainSql = " obs.valtype_cd = 'T' AND upper(obs.tval_char) = " + " upper(" + likeValueFormat + ")"; - } else { - constrainSql = " obs.valtype_cd = 'T' AND obs.tval_char = " + likeValueFormat; - } - notLikeFlag = true; - } - if (notLikeFlag == false) { - if (oracleFlag) { - constrainSql = " obs.valtype_cd = 'T' AND upper(obs.tval_char) LIKE " + " upper(" + likeValueFormat + ")"; - } else { - constrainSql = " obs.valtype_cd = 'T' AND obs.tval_char LIKE " + likeValueFormat; - } - } - - } else if (operatorType.value().equalsIgnoreCase( - ConstrainOperatorType.EQ.value())) { - constrainSql = " obs.valtype_cd = 'T' AND obs.tval_char = '" - + value.replaceAll("'", "''") + "' "; - } else if (operatorType.value().equalsIgnoreCase( - ConstrainOperatorType.IN.value())) { - value = SqlClauseUtil.buildINClause(value, true); - constrainSql = " obs.valtype_cd = 'T' AND obs.tval_char IN (" - + value + ")"; - } else if (operatorType.value().equalsIgnoreCase( - ConstrainOperatorType.BETWEEN.value())) { - throw new I2B2Exception("Error in value constrain, BETWEEN operator not supported in TEXT value type [" + value + "]"); - /* - value = SqlClauseUtil.buildBetweenClause(value); - constrainSql = " obs.valtype_cd = 'T' AND obs.tval_char BETWEEN " - + value; - */ - - } else if (operatorType.value().equalsIgnoreCase( - ConstrainOperatorType.NE.value())) { - String emptyStringCheck = " "; - if (oracleFlag==false) { - emptyStringCheck = " AND obs.tval_char <> '' "; - } - constrainSql = " obs.valtype_cd = 'T' AND obs.tval_char <> '" - + value.replaceAll("'", "''") + "' " + emptyStringCheck; - } else { - throw new I2B2Exception( - "Error TEXT value constrain because operator(" - + operatorType.toString() + ")is invalid"); - } - } else if (valueType.equals(ConstrainValueType.NUMBER)) { - // check if operator and value not null - if (operatorType == null || value == null) { - continue; - } - value.replaceAll("'", "''"); - - String nvalNum = " nval_num ", unitsCdInClause = ""; - if (this.unitCdConverstionFlag) { - nvalNum = unitCdSwitchClause; - //unitsCdInClause = this.unitCdInClause + " AND "; - //commented not needed -// if (unitCd != null) { -// unitCd = unitCd.replace("'", "''"); -// unitsCdInClause = " case when '" + unitCd + "' in " + this.unitCdInClause + " then 1 else 0 end =1 AND "; -// } - unitsCdInClause = " "; - - } - - if (operatorType.value().equalsIgnoreCase( - ConstrainOperatorType.GT.value())) { - constrainSql = unitsCdInClause + " ((obs.valtype_cd = 'N' AND "+ nvalNum + " > " - + value - + " AND obs.tval_char IN ('E','GE')) OR (obs.valtype_cd = 'N' AND "+ nvalNum +" >= " - + value + " AND obs.tval_char = 'G' )) "; - } else if (operatorType.value().equalsIgnoreCase( - ConstrainOperatorType.GE.value())) { - constrainSql = unitsCdInClause + " obs.valtype_cd = 'N' AND " + nvalNum + " >= " - + value + " AND obs.tval_char IN ('E','GE','G') "; - } else if (operatorType.value().equalsIgnoreCase( - ConstrainOperatorType.LT.value())) { - constrainSql = unitsCdInClause + " ((obs.valtype_cd = 'N' AND " + nvalNum + " < " - + value - + " AND obs.tval_char IN ('E','LE')) OR (obs.valtype_cd = 'N' AND " + nvalNum + " <= " - + value + " AND obs.tval_char = 'L' )) "; - } else if (operatorType.value().equalsIgnoreCase( - ConstrainOperatorType.LE.value())) { - constrainSql = unitsCdInClause + " obs.valtype_cd = 'N' AND " + nvalNum + " <= " - + value + " AND obs.tval_char IN ('E','LE','L') "; - } else if (operatorType.value().equalsIgnoreCase( - ConstrainOperatorType.EQ.value())) { - constrainSql = unitsCdInClause + " obs.valtype_cd = 'N' AND " + nvalNum + " = " - + value + " AND obs.tval_char='E' "; - } else if (operatorType.value().equalsIgnoreCase( - ConstrainOperatorType.BETWEEN.value())) { - value = SqlClauseUtil.buildBetweenClause(value); - constrainSql = unitsCdInClause + " obs.valtype_cd = 'N' AND " + nvalNum + " BETWEEN " - + value + " AND obs.tval_char ='E' "; - } else if (operatorType.value().equalsIgnoreCase( - ConstrainOperatorType.NE.value())) { - constrainSql = unitsCdInClause + " ((obs.valtype_cd = 'N' AND " + nvalNum + " <> " - + value - + " AND obs.tval_char <> 'NE') OR (obs.valtype_cd = 'N' AND " + nvalNum + " = " - + value + " AND obs.tval_char ='NE' )) "; - } else { - throw new I2B2Exception( - "Error NUMBER value constrain because operator(" - + operatorType.toString() + ")is invalid"); - } - } else if (valueType.equals(ConstrainValueType.FLAG)) { - // check if operator and value not null - if (operatorType == null || value == null) { - continue; - } - if (operatorType.value().equalsIgnoreCase( - ConstrainOperatorType.EQ.value())) { - constrainSql = " obs.valueflag_cd = '" - + value.replaceAll("'", "''") + "' "; - } else if (operatorType.value().equalsIgnoreCase( - ConstrainOperatorType.NE.value())) { - String emptyStringCheck = " "; - if (oracleFlag==false) { - emptyStringCheck = " AND obs.valueflag_cd <> '' "; - } - constrainSql = " obs.valueflag_cd <> '" - + value.replaceAll("'", "''") + "' " + emptyStringCheck; - } else if (operatorType.value().equalsIgnoreCase( - ConstrainOperatorType.IN.value())) { - value = SqlClauseUtil.buildINClause(value, true); - constrainSql = " obs.valueflag_cd IN (" + value +")"; - } else { - throw new I2B2Exception( - "Error FLAG value constrain because operator(" - + operatorType.toString() + ")is invalid"); - } - } else if (valueType.equals(ConstrainValueType.MODIFIER)) { - // check if operator and value not null - if (operatorType == null || value == null) { - continue; - } - if (value != null) { - if (operatorType.value().equalsIgnoreCase( - ConstrainOperatorType.EQ.value())) { - constrainSql = " obs.valtype_cd = 'M' and obs.tval_char = '" - + value.replaceAll("'", "''") + "' "; - } else if (operatorType.value().equalsIgnoreCase( - ConstrainOperatorType.NE.value())) { - constrainSql = " obs.valtype_cd = 'M' and obs.tval_char <> '" - + value.replaceAll("'", "''") + "' AND tval_char <> ''"; - } else if (operatorType.value().equalsIgnoreCase( - ConstrainOperatorType.IN.value())) { - value = SqlClauseUtil.buildINClause(value, true); - constrainSql = " obs.valtype_cd = 'M' and obs.tval_char IN (" - + value + ") "; - } - - } - - } else { - throw new I2B2Exception( - "Error value constrain, invalid value type (" - + valueType.toString() + ")"); - } - - if (constrainSql != null) { - if (fullConstrainSql.length() > 0) { - fullConstrainSql += " AND "; - } - - fullConstrainSql += constrainSql; - } - } - - return new String[] { fullConstrainSql, containsJoinSql}; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao.pdo.input; + +import java.util.List; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.datavo.pdo.query.ConstrainOperatorType; +import edu.harvard.i2b2.crc.datavo.pdo.query.ConstrainValueType; +import edu.harvard.i2b2.crc.datavo.pdo.query.ItemType; +import edu.harvard.i2b2.crc.util.ContainsUtil; +import edu.harvard.i2b2.crc.util.RegExUtil; +import edu.harvard.i2b2.crc.util.SqlClauseUtil; + +/** + * Class to handle value constrains. Generates sql where clause based on the + * list of value constrains. + * + * @author rkuttan + */ +public class ValueConstrainsHandler { + /** log **/ + protected final Log log = LogFactory.getLog(getClass()); + + private boolean unitCdConverstionFlag = false; + private String unitCdInClause = "", unitCdSwitchClause = ""; + + public void setUnitCdConversionFlag(boolean unitCdConverstionFlag, String unitCdInClause, String unitCdSwitchClause) { + this.unitCdConverstionFlag = unitCdConverstionFlag; + this.unitCdInClause = unitCdInClause; + this.unitCdSwitchClause = unitCdSwitchClause; + } + + public String[] constructValueConstainClause( + List valueConstrainList, String dbServerType,String dbSchemaName,int panelAccuracyScale) + throws I2B2Exception { + String fullConstrainSql = "",containsJoinSql = ""; + log.debug("panel accuracy scale" + panelAccuracyScale ); + panelAccuracyScale = 0; + + boolean oracleFlag = false; + if (dbServerType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { + oracleFlag = true; + } + int j = 0 ; + for (ItemType.ConstrainByValue valueConstrain : valueConstrainList) { + ConstrainValueType valueType = valueConstrain.getValueType(); + ConstrainOperatorType operatorType = valueConstrain + .getValueOperator(); + String value = valueConstrain.getValueConstraint(); + String unitCd = valueConstrain.getValueUnitOfMeasure(); + + String constrainSql = null; + // check if value type is not null + if (valueType == null) { + continue; + } + if (valueType.equals(ConstrainValueType.LARGETEXT)) { + String containsSql = ""; + ContainsUtil containsUtil = new ContainsUtil(); + if (operatorType.value().equalsIgnoreCase( + ConstrainOperatorType.CONTAINS.value())) { + containsSql = containsUtil.formatValue(value,dbServerType); + } else if(operatorType.value().equalsIgnoreCase( + ConstrainOperatorType.CONTAINS_DATABASE.value())) { + containsSql = containsUtil.formatValue("[" + value + "]",dbServerType); + } else { + log.debug("LARGETEXT : Invalid operator skipped [" + operatorType.value() + "]" ); + continue; + } + //panelAccuracyScale = 100 - panelAccuracyScale; + + constrainSql = " valtype_cd = 'B' AND " ; + if (dbServerType.equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) + { + + constrainSql += " observation_blob like '%" + containsSql + "%' "; + } + else if (oracleFlag == true) { + constrainSql += " contains(observation_blob,'" + containsSql + "') "; + if (panelAccuracyScale>0) { + constrainSql += " >= " + panelAccuracyScale + " "; + } else { + constrainSql += " > 0 "; + } + } else { + if (panelAccuracyScale>0) { + panelAccuracyScale = panelAccuracyScale * 10; + j++; + containsJoinSql += " INNER JOIN freetexttable(" + dbSchemaName + "observation_fact,observation_blob,'"+ containsSql + "') " + + " AS ft" + j + " ON text_search_index = ft" +j+ ".[KEY] "; + + constrainSql += " ft"+j+".[RANK] >= " + panelAccuracyScale + " "; + + } else { + constrainSql += " CONTAINS(observation_blob,'" + containsSql + "') "; + } + + } + + + + + } else if (valueType.equals(ConstrainValueType.TEXT)) { + // check if operator and value not null + if (operatorType == null || value == null) { + continue; + } + boolean notLikeFlag = false; + if (operatorType.value().startsWith( + ConstrainOperatorType.LIKE.value())) { + //call the utility to find the like operation + String operatorOption = RegExUtil.getOperatorOption(operatorType.value()); + if (operatorOption ==null) { + operatorOption = "[begin]"; + } + String likeValueFormat = ""; + if (operatorOption.equalsIgnoreCase("[begin]")) { + likeValueFormat = "'" + value.replaceAll("'", "''") + "%'"; + } else if (operatorOption.equalsIgnoreCase("[end]")) { + likeValueFormat = "'%" + value.replaceAll("'", "''") + "'"; + } else if (operatorOption.equalsIgnoreCase("[contains]")) { + likeValueFormat = "'%" + value.replaceAll("'", "''") + "%'"; + } else if (operatorOption.equalsIgnoreCase("[exact]")) { + likeValueFormat = "'" + value.replaceAll("'", "''") + "'"; + if (oracleFlag) { + constrainSql = " obs.valtype_cd = 'T' AND upper(obs.tval_char) = " + " upper(" + likeValueFormat + ")"; + } else { + constrainSql = " obs.valtype_cd = 'T' AND obs.tval_char = " + likeValueFormat; + } + notLikeFlag = true; + } + if (notLikeFlag == false) { + if (oracleFlag) { + constrainSql = " obs.valtype_cd = 'T' AND upper(obs.tval_char) LIKE " + " upper(" + likeValueFormat + ")"; + } else { + constrainSql = " obs.valtype_cd = 'T' AND obs.tval_char LIKE " + likeValueFormat; + } + } + + } else if (operatorType.value().equalsIgnoreCase( + ConstrainOperatorType.EQ.value())) { + constrainSql = " obs.valtype_cd = 'T' AND obs.tval_char = '" + + value.replaceAll("'", "''") + "' "; + } else if (operatorType.value().equalsIgnoreCase( + ConstrainOperatorType.IN.value())) { + value = SqlClauseUtil.buildINClause(value, true); + constrainSql = " obs.valtype_cd = 'T' AND obs.tval_char IN (" + + value + ")"; + } else if (operatorType.value().equalsIgnoreCase( + ConstrainOperatorType.BETWEEN.value())) { + throw new I2B2Exception("Error in value constrain, BETWEEN operator not supported in TEXT value type [" + value + "]"); + /* + value = SqlClauseUtil.buildBetweenClause(value); + constrainSql = " obs.valtype_cd = 'T' AND obs.tval_char BETWEEN " + + value; + */ + + } else if (operatorType.value().equalsIgnoreCase( + ConstrainOperatorType.NE.value())) { + String emptyStringCheck = " "; + if (oracleFlag==false) { + emptyStringCheck = " AND obs.tval_char <> '' "; + } + constrainSql = " obs.valtype_cd = 'T' AND obs.tval_char <> '" + + value.replaceAll("'", "''") + "' " + emptyStringCheck; + } else { + throw new I2B2Exception( + "Error TEXT value constrain because operator(" + + operatorType.toString() + ")is invalid"); + } + } else if (valueType.equals(ConstrainValueType.NUMBER)) { + // check if operator and value not null + if (operatorType == null || value == null) { + continue; + } + value.replaceAll("'", "''"); + + String nvalNum = " nval_num ", unitsCdInClause = ""; + if (this.unitCdConverstionFlag) { + nvalNum = unitCdSwitchClause; + //unitsCdInClause = this.unitCdInClause + " AND "; + //commented not needed +// if (unitCd != null) { +// unitCd = unitCd.replace("'", "''"); +// unitsCdInClause = " case when '" + unitCd + "' in " + this.unitCdInClause + " then 1 else 0 end =1 AND "; +// } + unitsCdInClause = " "; + + } + + if (operatorType.value().equalsIgnoreCase( + ConstrainOperatorType.GT.value())) { + constrainSql = unitsCdInClause + " ((obs.valtype_cd = 'N' AND "+ nvalNum + " > " + + value + + " AND obs.tval_char IN ('E','GE')) OR (obs.valtype_cd = 'N' AND "+ nvalNum +" >= " + + value + " AND obs.tval_char = 'G' )) "; + } else if (operatorType.value().equalsIgnoreCase( + ConstrainOperatorType.GE.value())) { + constrainSql = unitsCdInClause + " obs.valtype_cd = 'N' AND " + nvalNum + " >= " + + value + " AND obs.tval_char IN ('E','GE','G') "; + } else if (operatorType.value().equalsIgnoreCase( + ConstrainOperatorType.LT.value())) { + constrainSql = unitsCdInClause + " ((obs.valtype_cd = 'N' AND " + nvalNum + " < " + + value + + " AND obs.tval_char IN ('E','LE')) OR (obs.valtype_cd = 'N' AND " + nvalNum + " <= " + + value + " AND obs.tval_char = 'L' )) "; + } else if (operatorType.value().equalsIgnoreCase( + ConstrainOperatorType.LE.value())) { + constrainSql = unitsCdInClause + " obs.valtype_cd = 'N' AND " + nvalNum + " <= " + + value + " AND obs.tval_char IN ('E','LE','L') "; + } else if (operatorType.value().equalsIgnoreCase( + ConstrainOperatorType.EQ.value())) { + constrainSql = unitsCdInClause + " obs.valtype_cd = 'N' AND " + nvalNum + " = " + + value + " AND obs.tval_char='E' "; + } else if (operatorType.value().equalsIgnoreCase( + ConstrainOperatorType.BETWEEN.value())) { + value = SqlClauseUtil.buildBetweenClause(value); + constrainSql = unitsCdInClause + " obs.valtype_cd = 'N' AND " + nvalNum + " BETWEEN " + + value + " AND obs.tval_char ='E' "; + } else if (operatorType.value().equalsIgnoreCase( + ConstrainOperatorType.NE.value())) { + constrainSql = unitsCdInClause + " ((obs.valtype_cd = 'N' AND " + nvalNum + " <> " + + value + + " AND obs.tval_char <> 'NE') OR (obs.valtype_cd = 'N' AND " + nvalNum + " = " + + value + " AND obs.tval_char ='NE' )) "; + } else { + throw new I2B2Exception( + "Error NUMBER value constrain because operator(" + + operatorType.toString() + ")is invalid"); + } + } else if (valueType.equals(ConstrainValueType.FLAG)) { + // check if operator and value not null + if (operatorType == null || value == null) { + continue; + } + if (operatorType.value().equalsIgnoreCase( + ConstrainOperatorType.EQ.value())) { + constrainSql = " obs.valueflag_cd = '" + + value.replaceAll("'", "''") + "' "; + } else if (operatorType.value().equalsIgnoreCase( + ConstrainOperatorType.NE.value())) { + String emptyStringCheck = " "; + if (oracleFlag==false) { + emptyStringCheck = " AND obs.valueflag_cd <> '' "; + } + constrainSql = " obs.valueflag_cd <> '" + + value.replaceAll("'", "''") + "' " + emptyStringCheck; + } else if (operatorType.value().equalsIgnoreCase( + ConstrainOperatorType.IN.value())) { + value = SqlClauseUtil.buildINClause(value, true); + constrainSql = " obs.valueflag_cd IN (" + value +")"; + } else { + throw new I2B2Exception( + "Error FLAG value constrain because operator(" + + operatorType.toString() + ")is invalid"); + } + } else if (valueType.equals(ConstrainValueType.MODIFIER)) { + // check if operator and value not null + if (operatorType == null || value == null) { + continue; + } + if (value != null) { + if (operatorType.value().equalsIgnoreCase( + ConstrainOperatorType.EQ.value())) { + constrainSql = " obs.valtype_cd = 'M' and obs.tval_char = '" + + value.replaceAll("'", "''") + "' "; + } else if (operatorType.value().equalsIgnoreCase( + ConstrainOperatorType.NE.value())) { + constrainSql = " obs.valtype_cd = 'M' and obs.tval_char <> '" + + value.replaceAll("'", "''") + "' AND tval_char <> ''"; + } else if (operatorType.value().equalsIgnoreCase( + ConstrainOperatorType.IN.value())) { + value = SqlClauseUtil.buildINClause(value, true); + constrainSql = " obs.valtype_cd = 'M' and obs.tval_char IN (" + + value + ") "; + } + + } + + } else { + throw new I2B2Exception( + "Error value constrain, invalid value type (" + + valueType.toString() + ")"); + } + + if (constrainSql != null) { + if (fullConstrainSql.length() > 0) { + fullConstrainSql += " AND "; + } + + fullConstrainSql += constrainSql; + } + } + + return new String[] { fullConstrainSql, containsJoinSql}; + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/input/VisitListTypeHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/input/VisitListTypeHandler.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/input/VisitListTypeHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/input/VisitListTypeHandler.java index a9b2935c..659b2baf --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/input/VisitListTypeHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/input/VisitListTypeHandler.java @@ -1,384 +1,384 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao.pdo.input; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.List; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.dao.setfinder.IQueryResultInstanceDao; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.db.QtQueryResultInstance; -import edu.harvard.i2b2.crc.datavo.pdo.query.EventListType; -import edu.harvard.i2b2.crc.datavo.pdo.query.EventListType.EventId; - -/** - * Handler class for visit/event list type to generate "where" clause for pdo - * request $Id: VisitListTypeHandler.java,v 1.17 2009/10/23 19:54:02 rk903 Exp $ - * - * @author rkuttan - */ -public class VisitListTypeHandler extends CRCDAO implements - IInputOptionListHandler { - private EventListType visitListType = null; - private int minIndex = 0; - private int maxIndex = 0; - private String encounterSetCollId = ""; - private List encounterNumList = null; - private DataSourceLookup dataSourceLookup = null; - private boolean deleteTempTableFlag = false; - - /** - * Constructor accepts {@link EventListType} - * - * @param visitListType - * @throws I2B2DAOException - */ - public VisitListTypeHandler(DataSourceLookup dataSourceLookup, - EventListType visitListType) throws I2B2DAOException { - if (visitListType == null) { - throw new I2B2DAOException("Visit List Type is null"); - } - - this.dataSourceLookup = dataSourceLookup; - setDbSchemaName(dataSourceLookup.getFullSchema()); - this.visitListType = visitListType; - - if (visitListType.getMin() != null) { - minIndex = visitListType.getMin(); - } - - if (visitListType.getMax() != null) { - maxIndex = visitListType.getMax(); - } - } - - @Override - public int getMinIndex() { - return minIndex; - } - - @Override - public int getMaxIndex() { - return maxIndex; - } - - @Override - public void setMaxIndex(int maxIndex) { - visitListType.setMax(maxIndex); - } - - @Override - public boolean isCollectionId() { - if (visitListType.getPatientEventCollId() != null) { - return true; - } else { - return false; - } - } - - @Override - public boolean isEnumerationSet() { - if ((visitListType.getEventId() != null) - && (visitListType.getEventId().size() > 0)) { - return true; - } else { - return false; - } - } - - @Override - public boolean isEntireSet() { - if (visitListType.getEntireEventSet() != null) { - return true; - } else { - return false; - } - } - - /** - * Function to generate "where" clause for visit/event list - */ - @Override - public String generateWhereClauseSql() { - String sqlString = null; - - if (visitListType.getPatientEventCollId() != null) { - // set patient set coll id - this.encounterSetCollId = this.getCollectionId(); - - // set sql string - sqlString = "select eset.encounter_num from " - + this.getDbSchemaName() - + "qt_patient_enc_collection eset where eset.result_instance_id = ? "; - - if (minIndex <= maxIndex) { - sqlString += (" and eset.set_index between " + minIndex - + " and " + maxIndex); - } - } else if ((visitListType.getEventId() != null) - && (visitListType.getEventId().size() > 0)) { - - String tempTableName = this.getTempTableName(); - - sqlString = " select char_param1 from " + tempTableName + " "; - - } else if (visitListType.getEntireEventSet() != null) { - // by default get first 100 rows - if ((minIndex == 0) && (maxIndex == 0)) { - minIndex = 0; - maxIndex = 100; - } - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE)) { - // do nothing - sqlString = " select encounter_num from (select a.*, ROWNUM rnum from ( select encounter_num from " - + this.getDbSchemaName() - + "visit_dimension order by encounter_num) a " - + " where ROWNUM<=" - + maxIndex - + " ) where rnum>=" - + minIndex; - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER) || dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) { - sqlString = " select encounter_num from ( select encounter_num,row_number() over(order by encounter_num) as rnum from " - + this.getDbSchemaName() - + "visit_dimension ) as v " - + " where rnum between " - + minIndex - + " and " - + maxIndex; - } - } - - return sqlString; - } - - public String generatePatentSql() { - String sqlString = null; - - if (visitListType.getPatientEventCollId() != null) { - // set patient set coll id - this.encounterSetCollId = visitListType.getPatientEventCollId(); - - // set sql string - sqlString = "select eset.patient_num from " - + getDbSchemaName() - + "qt_patient_enc_collection eset where eset.result_instance_id = ? "; - - if (minIndex < maxIndex) { - sqlString += (" and eset.set_index between " + minIndex - + " and " + maxIndex); - } - } - - return sqlString; - } - - @Override - public List getEnumerationList() { - ArrayList encounterNumArrayList = new ArrayList(); - - for (EventListType.EventId encounterNum : visitListType.getEventId()) { - // TODO see if we can use index value from encounterNum - encounterNumArrayList.add(encounterNum.getValue()); - } - - if (maxIndex > visitListType.getEventId().size()) { - // log.warn("max size is more than list size"); - maxIndex = visitListType.getEventId().size(); - } - - // set int List - if (minIndex < maxIndex) { - this.encounterNumList = encounterNumArrayList.subList(minIndex, - maxIndex); - } else if (minIndex == maxIndex && minIndex > 0) { - // check if maxIndex is equal to last index - if (maxIndex == visitListType.getEventId().size() - 1) { - this.encounterNumList = new ArrayList(); - this.encounterNumList.add(encounterNumArrayList.get(maxIndex)); - } else { - this.encounterNumList = encounterNumArrayList.subList(minIndex, - maxIndex); - } - } else { - maxIndex = encounterNumArrayList.size(); - this.encounterNumList = encounterNumArrayList.subList(minIndex, - maxIndex); - } - - return this.encounterNumList; - } - - @Override - public String getCollectionId() { - if (isCollectionId()) { - encounterSetCollId = visitListType.getPatientEventCollId(); - } else { - - } - return encounterSetCollId; - } - - @Override - public String generateMinIndexSql(String panelSql) { - // TODO Auto-generated method stub - return null; - } - - /** - * Returns input list's size. if the list is collection id, then collection - * set size, if the list is entire set, then total rows in dimension table - * if the list is enumeration, then size of enumeration set - * - * @return - * @throws I2B2DAOException - */ - @Override - public int getInputSize() throws I2B2DAOException { - if (this.isEnumerationSet()) { - return visitListType.getEventId().size(); - } else if (this.isCollectionId()) { - DAOFactoryHelper helper = new DAOFactoryHelper(dataSourceLookup - .getDomainId(), dataSourceLookup.getProjectPath(), - dataSourceLookup.getOwnerId()); - IQueryResultInstanceDao resultInstanceDao = helper.getDAOFactory() - .getSetFinderDAOFactory().getPatientSetResultDAO(); - - QtQueryResultInstance resultInstance = resultInstanceDao - .getResultInstanceById(this.getCollectionId()); - return resultInstance.getSetSize(); - } else if (this.isEntireSet()) { - return 1000; - } else { - return 0; - } - } - - @Override - public void uploadEnumerationValueToTempTable(Connection conn) - throws SQLException { - - String tempTableName = this.getTempTableName(); - deleteTempTableFlag = true; - // create temp table - java.sql.Statement tempStmt = conn.createStatement(); - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER)) { - String createTempInputListTable = "create table " - + getTempTableName() - + " (set_index int, char_param1 varchar(100) )"; - tempStmt.executeUpdate(createTempInputListTable); - } - int i = 0, j = 1; - - List pidList = visitListType.getEventId(); - List finalPidList = new ArrayList(); - - if (maxIndex > visitListType.getEventId().size()) { - // log.warn("max size is more than list size"); - maxIndex = visitListType.getEventId().size(); - } - if (minIndex < maxIndex) { - finalPidList = pidList.subList(minIndex, maxIndex); - } else if (minIndex == maxIndex && minIndex > 0) { - // check if maxIndex is equal to last index - if (maxIndex == visitListType.getEventId().size() - 1) { - finalPidList.add(pidList.get(maxIndex)); - } else { - finalPidList = pidList.subList(minIndex, maxIndex); - } - - } else { - maxIndex = pidList.size(); - finalPidList = pidList.subList(minIndex, maxIndex); - } - - PreparedStatement preparedStmt = conn.prepareStatement("insert into " - + tempTableName + "(set_index,char_param1) values (?,?)"); - for (EventId pid : finalPidList) { - preparedStmt.setInt(1, j++); - preparedStmt.setString(2, pid.getValue()); - - preparedStmt.addBatch(); - i++; - if (i % 100 == 0) { - preparedStmt.executeBatch(); - - } - - } - preparedStmt.executeBatch(); - } - - @Override - public void deleteTempTable(Connection conn) throws SQLException { - if (!deleteTempTableFlag) { - return; - } - Statement deleteStmt = null; - try { - deleteStmt = conn.createStatement(); - - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER) || dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) { - // conn.createStatement().executeUpdate( - // "drop table " + getTempTableName()); - deleteStmt.executeUpdate( - "drop table " + getTempTableName()); - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE)) { - /// System.out.println("delete table " + getTempTableName()); - // conn.createStatement().executeUpdate( - // "delete " + getTempTableName()); - deleteStmt.executeUpdate( - "delete " + getTempTableName()); - } - } catch (SQLException sqle) { - throw sqle; - } finally { - try { - if(deleteStmt != null) - deleteStmt.close(); - } catch (SQLException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - } - - private String getTempTableName() { - String tempTableName = ""; - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE)) { - tempTableName = this.getDbSchemaName() - + FactRelatedQueryHandler.TEMP_PARAM_TABLE; - } else { - tempTableName = this.getDbSchemaName() - + SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE; - } - return tempTableName; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao.pdo.input; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.dao.setfinder.IQueryResultInstanceDao; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.db.QtQueryResultInstance; +import edu.harvard.i2b2.crc.datavo.pdo.query.EventListType; +import edu.harvard.i2b2.crc.datavo.pdo.query.EventListType.EventId; + +/** + * Handler class for visit/event list type to generate "where" clause for pdo + * request $Id: VisitListTypeHandler.java,v 1.17 2009/10/23 19:54:02 rk903 Exp $ + * + * @author rkuttan + */ +public class VisitListTypeHandler extends CRCDAO implements + IInputOptionListHandler { + private EventListType visitListType = null; + private int minIndex = 0; + private int maxIndex = 0; + private String encounterSetCollId = ""; + private List encounterNumList = null; + private DataSourceLookup dataSourceLookup = null; + private boolean deleteTempTableFlag = false; + + /** + * Constructor accepts {@link EventListType} + * + * @param visitListType + * @throws I2B2DAOException + */ + public VisitListTypeHandler(DataSourceLookup dataSourceLookup, + EventListType visitListType) throws I2B2DAOException { + if (visitListType == null) { + throw new I2B2DAOException("Visit List Type is null"); + } + + this.dataSourceLookup = dataSourceLookup; + setDbSchemaName(dataSourceLookup.getFullSchema()); + this.visitListType = visitListType; + + if (visitListType.getMin() != null) { + minIndex = visitListType.getMin(); + } + + if (visitListType.getMax() != null) { + maxIndex = visitListType.getMax(); + } + } + + @Override + public int getMinIndex() { + return minIndex; + } + + @Override + public int getMaxIndex() { + return maxIndex; + } + + @Override + public void setMaxIndex(int maxIndex) { + visitListType.setMax(maxIndex); + } + + @Override + public boolean isCollectionId() { + if (visitListType.getPatientEventCollId() != null) { + return true; + } else { + return false; + } + } + + @Override + public boolean isEnumerationSet() { + if ((visitListType.getEventId() != null) + && (visitListType.getEventId().size() > 0)) { + return true; + } else { + return false; + } + } + + @Override + public boolean isEntireSet() { + if (visitListType.getEntireEventSet() != null) { + return true; + } else { + return false; + } + } + + /** + * Function to generate "where" clause for visit/event list + */ + @Override + public String generateWhereClauseSql() { + String sqlString = null; + + if (visitListType.getPatientEventCollId() != null) { + // set patient set coll id + this.encounterSetCollId = this.getCollectionId(); + + // set sql string + sqlString = "select eset.encounter_num from " + + this.getDbSchemaName() + + "qt_patient_enc_collection eset where eset.result_instance_id = ? "; + + if (minIndex <= maxIndex) { + sqlString += (" and eset.set_index between " + minIndex + + " and " + maxIndex); + } + } else if ((visitListType.getEventId() != null) + && (visitListType.getEventId().size() > 0)) { + + String tempTableName = this.getTempTableName(); + + sqlString = " select char_param1 from " + tempTableName + " "; + + } else if (visitListType.getEntireEventSet() != null) { + // by default get first 100 rows + if ((minIndex == 0) && (maxIndex == 0)) { + minIndex = 0; + maxIndex = 100; + } + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.ORACLE)) { + // do nothing + sqlString = " select encounter_num from (select a.*, ROWNUM rnum from ( select encounter_num from " + + this.getDbSchemaName() + + "visit_dimension order by encounter_num) a " + + " where ROWNUM<=" + + maxIndex + + " ) where rnum>=" + + minIndex; + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER) || dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) { + sqlString = " select encounter_num from ( select encounter_num,row_number() over(order by encounter_num) as rnum from " + + this.getDbSchemaName() + + "visit_dimension ) as v " + + " where rnum between " + + minIndex + + " and " + + maxIndex; + } + } + + return sqlString; + } + + public String generatePatentSql() { + String sqlString = null; + + if (visitListType.getPatientEventCollId() != null) { + // set patient set coll id + this.encounterSetCollId = visitListType.getPatientEventCollId(); + + // set sql string + sqlString = "select eset.patient_num from " + + getDbSchemaName() + + "qt_patient_enc_collection eset where eset.result_instance_id = ? "; + + if (minIndex < maxIndex) { + sqlString += (" and eset.set_index between " + minIndex + + " and " + maxIndex); + } + } + + return sqlString; + } + + @Override + public List getEnumerationList() { + ArrayList encounterNumArrayList = new ArrayList(); + + for (EventListType.EventId encounterNum : visitListType.getEventId()) { + // TODO see if we can use index value from encounterNum + encounterNumArrayList.add(encounterNum.getValue()); + } + + if (maxIndex > visitListType.getEventId().size()) { + // log.warn("max size is more than list size"); + maxIndex = visitListType.getEventId().size(); + } + + // set int List + if (minIndex < maxIndex) { + this.encounterNumList = encounterNumArrayList.subList(minIndex, + maxIndex); + } else if (minIndex == maxIndex && minIndex > 0) { + // check if maxIndex is equal to last index + if (maxIndex == visitListType.getEventId().size() - 1) { + this.encounterNumList = new ArrayList(); + this.encounterNumList.add(encounterNumArrayList.get(maxIndex)); + } else { + this.encounterNumList = encounterNumArrayList.subList(minIndex, + maxIndex); + } + } else { + maxIndex = encounterNumArrayList.size(); + this.encounterNumList = encounterNumArrayList.subList(minIndex, + maxIndex); + } + + return this.encounterNumList; + } + + @Override + public String getCollectionId() { + if (isCollectionId()) { + encounterSetCollId = visitListType.getPatientEventCollId(); + } else { + + } + return encounterSetCollId; + } + + @Override + public String generateMinIndexSql(String panelSql) { + // TODO Auto-generated method stub + return null; + } + + /** + * Returns input list's size. if the list is collection id, then collection + * set size, if the list is entire set, then total rows in dimension table + * if the list is enumeration, then size of enumeration set + * + * @return + * @throws I2B2DAOException + */ + @Override + public int getInputSize() throws I2B2DAOException { + if (this.isEnumerationSet()) { + return visitListType.getEventId().size(); + } else if (this.isCollectionId()) { + DAOFactoryHelper helper = new DAOFactoryHelper(dataSourceLookup + .getDomainId(), dataSourceLookup.getProjectPath(), + dataSourceLookup.getOwnerId()); + IQueryResultInstanceDao resultInstanceDao = helper.getDAOFactory() + .getSetFinderDAOFactory().getPatientSetResultDAO(); + + QtQueryResultInstance resultInstance = resultInstanceDao + .getResultInstanceById(this.getCollectionId()); + return resultInstance.getSetSize(); + } else if (this.isEntireSet()) { + return 1000; + } else { + return 0; + } + } + + @Override + public void uploadEnumerationValueToTempTable(Connection conn) + throws SQLException { + + String tempTableName = this.getTempTableName(); + deleteTempTableFlag = true; + // create temp table + java.sql.Statement tempStmt = conn.createStatement(); + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER)) { + String createTempInputListTable = "create table " + + getTempTableName() + + " (set_index int, char_param1 varchar(100) )"; + tempStmt.executeUpdate(createTempInputListTable); + } + int i = 0, j = 1; + + List pidList = visitListType.getEventId(); + List finalPidList = new ArrayList(); + + if (maxIndex > visitListType.getEventId().size()) { + // log.warn("max size is more than list size"); + maxIndex = visitListType.getEventId().size(); + } + if (minIndex < maxIndex) { + finalPidList = pidList.subList(minIndex, maxIndex); + } else if (minIndex == maxIndex && minIndex > 0) { + // check if maxIndex is equal to last index + if (maxIndex == visitListType.getEventId().size() - 1) { + finalPidList.add(pidList.get(maxIndex)); + } else { + finalPidList = pidList.subList(minIndex, maxIndex); + } + + } else { + maxIndex = pidList.size(); + finalPidList = pidList.subList(minIndex, maxIndex); + } + + PreparedStatement preparedStmt = conn.prepareStatement("insert into " + + tempTableName + "(set_index,char_param1) values (?,?)"); + for (EventId pid : finalPidList) { + preparedStmt.setInt(1, j++); + preparedStmt.setString(2, pid.getValue()); + + preparedStmt.addBatch(); + i++; + if (i % 100 == 0) { + preparedStmt.executeBatch(); + + } + + } + preparedStmt.executeBatch(); + } + + @Override + public void deleteTempTable(Connection conn) throws SQLException { + if (!deleteTempTableFlag) { + return; + } + Statement deleteStmt = null; + try { + deleteStmt = conn.createStatement(); + + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER) || dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) { + // conn.createStatement().executeUpdate( + // "drop table " + getTempTableName()); + deleteStmt.executeUpdate( + "drop table " + getTempTableName()); + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.ORACLE)) { + /// System.out.println("delete table " + getTempTableName()); + // conn.createStatement().executeUpdate( + // "delete " + getTempTableName()); + deleteStmt.executeUpdate( + "delete " + getTempTableName()); + } + } catch (SQLException sqle) { + throw sqle; + } finally { + try { + if(deleteStmt != null) + deleteStmt.close(); + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + } + + private String getTempTableName() { + String tempTableName = ""; + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.ORACLE)) { + tempTableName = this.getDbSchemaName() + + FactRelatedQueryHandler.TEMP_PARAM_TABLE; + } else { + tempTableName = this.getDbSchemaName() + + SQLServerFactRelatedQueryHandler.TEMP_PDO_INPUTLIST_TABLE; + } + return tempTableName; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/output/ConceptFactRelated.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/output/ConceptFactRelated.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/output/ConceptFactRelated.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/output/ConceptFactRelated.java index de80964e..832edd56 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/output/ConceptFactRelated.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/output/ConceptFactRelated.java @@ -1,83 +1,83 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao.pdo.output; - -import java.sql.ResultSet; -import java.sql.SQLException; - -import edu.harvard.i2b2.crc.datavo.pdo.query.OutputOptionType; - -/** - * Class to generate select, join, where clause for concept dimenstion based on - * pdo's OutputOptionType $Id: ConceptFactRelated.java,v 1.3 2007/08/31 14:43:33 - * rk903 Exp $ - * - * @author rkuttan - */ -public class ConceptFactRelated extends FactRelated { - /** - * Constructor accepts OutputOptionType - * - * @param outputOptionType - */ - public ConceptFactRelated(OutputOptionType outputOptionType) { - super(outputOptionType); - } - - /** - * Function which selects fields based on ouput option flag - * - * @return select sql clause - */ - public String getSelectClause() { - String selectClause = ""; - - if (isSelected()) { - selectClause = " concept.concept_cd concept_concept_cd"; - - if (isSelectDetail()) { - selectClause += " ,concept.concept_path concept_concept_path, concept.name_char concept_name_char "; - } - - if (isSelectBlob()) { - selectClause += ", concept.concept_blob concept_concept_blob "; - } - - if (isSelectStatus()) { - selectClause += " , concept.update_date concept_update_date, concept.download_date concept_download_date, concept.import_date concept_import_date, concept.sourcesystem_cd concept_sourcesystem_cd, concept.upload_id concept_upload_id "; - } - } - - return selectClause; - } - - /** - * Function to generate join clause with concept dimension table - * - * @return - */ - public String joinClause() { - if (isSelected()) { - return " left join CONCEPT_DIMENSION concept on (obs.concept_cd = concept.concept_cd) "; - } else { - return ""; - } - } - - public String getConceptCdFromResultSet(ResultSet resultSet) - throws SQLException { - return resultSet.getString("obs_concept_cd"); - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao.pdo.output; + +import java.sql.ResultSet; +import java.sql.SQLException; + +import edu.harvard.i2b2.crc.datavo.pdo.query.OutputOptionType; + +/** + * Class to generate select, join, where clause for concept dimenstion based on + * pdo's OutputOptionType $Id: ConceptFactRelated.java,v 1.3 2007/08/31 14:43:33 + * rk903 Exp $ + * + * @author rkuttan + */ +public class ConceptFactRelated extends FactRelated { + /** + * Constructor accepts OutputOptionType + * + * @param outputOptionType + */ + public ConceptFactRelated(OutputOptionType outputOptionType) { + super(outputOptionType); + } + + /** + * Function which selects fields based on ouput option flag + * + * @return select sql clause + */ + public String getSelectClause() { + String selectClause = ""; + + if (isSelected()) { + selectClause = " concept.concept_cd concept_concept_cd"; + + if (isSelectDetail()) { + selectClause += " ,concept.concept_path concept_concept_path, concept.name_char concept_name_char "; + } + + if (isSelectBlob()) { + selectClause += ", concept.concept_blob concept_concept_blob "; + } + + if (isSelectStatus()) { + selectClause += " , concept.update_date concept_update_date, concept.download_date concept_download_date, concept.import_date concept_import_date, concept.sourcesystem_cd concept_sourcesystem_cd, concept.upload_id concept_upload_id "; + } + } + + return selectClause; + } + + /** + * Function to generate join clause with concept dimension table + * + * @return + */ + public String joinClause() { + if (isSelected()) { + return " left join CONCEPT_DIMENSION concept on (obs.concept_cd = concept.concept_cd) "; + } else { + return ""; + } + } + + public String getConceptCdFromResultSet(ResultSet resultSet) + throws SQLException { + return resultSet.getString("obs_concept_cd"); + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/output/EidFactRelated.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/output/EidFactRelated.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/output/EidFactRelated.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/output/EidFactRelated.java index 2c5ef059..86d1b928 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/output/EidFactRelated.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/output/EidFactRelated.java @@ -1,72 +1,72 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao.pdo.output; - -import edu.harvard.i2b2.crc.datavo.pdo.query.OutputOptionType; - -/** - * Class to generate select, join, where clause for concept dimenstion based on - * pdo's OutputOptionType $Id: ConceptFactRelated.java,v 1.3 2007/08/31 14:43:33 - * rk903 Exp $ - * - * @author rkuttan - */ -public class EidFactRelated extends FactRelated { - /** - * Constructor accepts OutputOptionType - * - * @param outputOptionType - */ - public EidFactRelated(OutputOptionType outputOptionType) { - super(outputOptionType); - } - - /** - * Function which selects fields based on ouput option flag - * - * @return select sql clause - */ - public String getSelectClause() { - String selectClause = ""; - - if (isSelected()) { - selectClause = " em.encounter_ide em_encounter_ide, em.encounter_ide_source em_encounter_ide_source, em.patient_ide em_patient_ide, em.patient_ide_source em_patient_ide_source, em.encounter_num em_encounter_num"; - - if (isSelectDetail()) { - selectClause += " ,em.encounter_ide_status em_encounter_ide_status"; - } - - if (isSelectStatus()) { - selectClause += " , em.update_date em_update_date, em.download_date em_download_date, em.import_date em_import_date, em.sourcesystem_cd em_sourcesystem_cd , em.upload_id em_upload_id "; - } - } - - return selectClause; - } - - /** - * Function to generate join clause with concept dimension table - * - * @return - */ - public String joinClause() { - if (isSelected()) { - return " left join ENCOUNTER_MAPPING enc_map on (obs.encounter_num = enc_map.encounter_num) "; - } else { - return ""; - } - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao.pdo.output; + +import edu.harvard.i2b2.crc.datavo.pdo.query.OutputOptionType; + +/** + * Class to generate select, join, where clause for concept dimenstion based on + * pdo's OutputOptionType $Id: ConceptFactRelated.java,v 1.3 2007/08/31 14:43:33 + * rk903 Exp $ + * + * @author rkuttan + */ +public class EidFactRelated extends FactRelated { + /** + * Constructor accepts OutputOptionType + * + * @param outputOptionType + */ + public EidFactRelated(OutputOptionType outputOptionType) { + super(outputOptionType); + } + + /** + * Function which selects fields based on ouput option flag + * + * @return select sql clause + */ + public String getSelectClause() { + String selectClause = ""; + + if (isSelected()) { + selectClause = " em.encounter_ide em_encounter_ide, em.encounter_ide_source em_encounter_ide_source, em.patient_ide em_patient_ide, em.patient_ide_source em_patient_ide_source, em.encounter_num em_encounter_num"; + + if (isSelectDetail()) { + selectClause += " ,em.encounter_ide_status em_encounter_ide_status"; + } + + if (isSelectStatus()) { + selectClause += " , em.update_date em_update_date, em.download_date em_download_date, em.import_date em_import_date, em.sourcesystem_cd em_sourcesystem_cd , em.upload_id em_upload_id "; + } + } + + return selectClause; + } + + /** + * Function to generate join clause with concept dimension table + * + * @return + */ + public String joinClause() { + if (isSelected()) { + return " left join ENCOUNTER_MAPPING enc_map on (obs.encounter_num = enc_map.encounter_num) "; + } else { + return ""; + } + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/output/FactRelated.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/output/FactRelated.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/output/FactRelated.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/output/FactRelated.java index 032edeb3..b589244f --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/output/FactRelated.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/output/FactRelated.java @@ -1,85 +1,85 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao.pdo.output; - -import edu.harvard.i2b2.crc.datavo.pdo.query.OutputOptionSelectType; -import edu.harvard.i2b2.crc.datavo.pdo.query.OutputOptionType; - - -/** - * Class to support operation of {@link OutputOptionType} - * in pdo request - * $Id: FactRelated.java,v 1.3 2007/08/31 14:43:33 rk903 Exp $ - * @author rkuttan - */ -public abstract class FactRelated { - private OutputOptionType outputOptionType = null; - - public FactRelated(OutputOptionType outputOptionType) { - this.outputOptionType = outputOptionType; - } - - public boolean isSelected() { - if (outputOptionType != null && outputOptionType.getSelect() !=null) { - return true; - } - else { - return false; - } - } - - public boolean isFactRelated() { - if (outputOptionType != null && outputOptionType.getSelect() !=null) { - outputOptionType.getSelect(); - if (outputOptionType.getSelect().equals(OutputOptionSelectType.USING_FILTER_LIST)) { - return true; - } - else { - return false; - } - } - else { - return false; - } - } - - public boolean isSelectDetail() { - if (outputOptionType != null) { - if (outputOptionType.isOnlykeys()) { - return false; - } else { - return true; - } - } else { - return false; - } - } - - public boolean isSelectStatus() { - if (outputOptionType != null) { - return outputOptionType.isTechdata(); - } else { - return false; - } - } - - public boolean isSelectBlob() { - if (outputOptionType != null) { - return outputOptionType.isBlob(); - } else { - return false; - } - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao.pdo.output; + +import edu.harvard.i2b2.crc.datavo.pdo.query.OutputOptionSelectType; +import edu.harvard.i2b2.crc.datavo.pdo.query.OutputOptionType; + + +/** + * Class to support operation of {@link OutputOptionType} + * in pdo request + * $Id: FactRelated.java,v 1.3 2007/08/31 14:43:33 rk903 Exp $ + * @author rkuttan + */ +public abstract class FactRelated { + private OutputOptionType outputOptionType = null; + + public FactRelated(OutputOptionType outputOptionType) { + this.outputOptionType = outputOptionType; + } + + public boolean isSelected() { + if (outputOptionType != null && outputOptionType.getSelect() !=null) { + return true; + } + else { + return false; + } + } + + public boolean isFactRelated() { + if (outputOptionType != null && outputOptionType.getSelect() !=null) { + outputOptionType.getSelect(); + if (outputOptionType.getSelect().equals(OutputOptionSelectType.USING_FILTER_LIST)) { + return true; + } + else { + return false; + } + } + else { + return false; + } + } + + public boolean isSelectDetail() { + if (outputOptionType != null) { + if (outputOptionType.isOnlykeys()) { + return false; + } else { + return true; + } + } else { + return false; + } + } + + public boolean isSelectStatus() { + if (outputOptionType != null) { + return outputOptionType.isTechdata(); + } else { + return false; + } + } + + public boolean isSelectBlob() { + if (outputOptionType != null) { + return outputOptionType.isBlob(); + } else { + return false; + } + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/output/ModifierFactRelated.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/output/ModifierFactRelated.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/output/ModifierFactRelated.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/output/ModifierFactRelated.java index 4b74b07e..35ffe9cf --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/output/ModifierFactRelated.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/output/ModifierFactRelated.java @@ -1,83 +1,83 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao.pdo.output; - -import java.sql.ResultSet; -import java.sql.SQLException; - -import edu.harvard.i2b2.crc.datavo.pdo.query.OutputOptionType; - -/** - * Class to generate select, join, where clause for concept dimenstion based on - * pdo's OutputOptionType $Id: ModifierFactRelated.java,v 1.3 2007/08/31 14:43:33 - * rk903 Exp $ - * - * @author rkuttan - */ -public class ModifierFactRelated extends FactRelated { - /** - * Constructor accepts OutputOptionType - * - * @param outputOptionType - */ - public ModifierFactRelated(OutputOptionType outputOptionType) { - super(outputOptionType); - } - - /** - * Function which selects fields based on ouput option flag - * - * @return select sql clause - */ - public String getSelectClause() { - String selectClause = ""; - - if (isSelected()) { - selectClause = " modifier.modifier_cd modifier_modifier_cd"; - - if (isSelectDetail()) { - selectClause += " ,modifier.modifier_path modifier_modifier_path, modifier.name_char modifier_name_char "; - } - - if (isSelectBlob()) { - selectClause += ", modifier.modifier_blob modifier_modifier_blob "; - } - - if (isSelectStatus()) { - selectClause += " , modifier.update_date modifier_update_date, modifier.download_date modifier_download_date, modifier.import_date modifier_import_date, modifier.sourcesystem_cd modifier_sourcesystem_cd, modifier.upload_id modifier_upload_id "; - } - } - - return selectClause; - } - - /** - * Function to generate join clause with concept dimension table - * - * @return - */ - public String joinClause() { - if (isSelected()) { - return " left join MODIFIER_DIMENSION modifier on (obs.modifier_cd = modifier.modifier_cd) "; - } else { - return ""; - } - } - - public String getModifierCdFromResultSet(ResultSet resultSet) - throws SQLException { - return resultSet.getString("obs_modifier_cd"); - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao.pdo.output; + +import java.sql.ResultSet; +import java.sql.SQLException; + +import edu.harvard.i2b2.crc.datavo.pdo.query.OutputOptionType; + +/** + * Class to generate select, join, where clause for concept dimenstion based on + * pdo's OutputOptionType $Id: ModifierFactRelated.java,v 1.3 2007/08/31 14:43:33 + * rk903 Exp $ + * + * @author rkuttan + */ +public class ModifierFactRelated extends FactRelated { + /** + * Constructor accepts OutputOptionType + * + * @param outputOptionType + */ + public ModifierFactRelated(OutputOptionType outputOptionType) { + super(outputOptionType); + } + + /** + * Function which selects fields based on ouput option flag + * + * @return select sql clause + */ + public String getSelectClause() { + String selectClause = ""; + + if (isSelected()) { + selectClause = " modifier.modifier_cd modifier_modifier_cd"; + + if (isSelectDetail()) { + selectClause += " ,modifier.modifier_path modifier_modifier_path, modifier.name_char modifier_name_char "; + } + + if (isSelectBlob()) { + selectClause += ", modifier.modifier_blob modifier_modifier_blob "; + } + + if (isSelectStatus()) { + selectClause += " , modifier.update_date modifier_update_date, modifier.download_date modifier_download_date, modifier.import_date modifier_import_date, modifier.sourcesystem_cd modifier_sourcesystem_cd, modifier.upload_id modifier_upload_id "; + } + } + + return selectClause; + } + + /** + * Function to generate join clause with concept dimension table + * + * @return + */ + public String joinClause() { + if (isSelected()) { + return " left join MODIFIER_DIMENSION modifier on (obs.modifier_cd = modifier.modifier_cd) "; + } else { + return ""; + } + } + + public String getModifierCdFromResultSet(ResultSet resultSet) + throws SQLException { + return resultSet.getString("obs_modifier_cd"); + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/output/ObservationFactFactRelated.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/output/ObservationFactFactRelated.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/output/ObservationFactFactRelated.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/output/ObservationFactFactRelated.java index 0a83ca20..b12c6ccd --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/output/ObservationFactFactRelated.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/output/ObservationFactFactRelated.java @@ -1,109 +1,109 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao.pdo.output; - -import edu.harvard.i2b2.crc.datavo.pdo.query.OutputOptionType; - -/** - * Class to generate select, join, where clause for ObservationFact based on - * pdo's OutputOptionType $Id: ObservationFactFactRelated.java,v 1.4 2007/08/31 - * 14:43:33 rk903 Exp $ - * - * @author rkuttan - */ -public class ObservationFactFactRelated extends FactRelated { - - public ObservationFactFactRelated(OutputOptionType outputOptionType) { - super(outputOptionType); - } - - public String getDefaultSelectClause() { - return " obs.encounter_num obs_encounter_num, obs.patient_num obs_patient_num, obs.concept_cd obs_concept_cd,obs.provider_id obs_provider_id, obs.start_date obs_start_date , obs.modifier_cd obs_modifier_cd , obs.instance_num obs_instance_num "; - } - - /** - * Function which selects observation fact fields based on ouput option flag - * - * @return - */ - public String getSelectClause() { - String selectClause = ""; - - if (isSelected()) { - selectClause = " obs.encounter_num obs_encounter_num, obs.patient_num obs_patient_num, obs.concept_cd obs_concept_cd, obs.provider_id obs_provider_id, obs.start_date obs_start_date , obs.modifier_cd obs_modifier_cd , obs.instance_num obs_instance_num "; - - // Adding modifier_cd slow down the query , obs.modifier_cd - // obs_modifier_cd " - if (isSelectDetail()) { - selectClause += ", obs.valtype_cd obs_valtype_cd, obs.tval_char obs_tval_char, obs.nval_num obs_nval_num, obs.valueflag_cd obs_valueflag_cd,obs.quantity_num obs_quantity_num, obs.units_cd obs_units_cd, obs.end_date obs_end_date,obs.location_cd obs_location_cd, obs.confidence_num obs_confidence_num"; - } - - if (isSelectBlob()) { - selectClause += ", obs.observation_blob obs_observation_blob "; - } - - if (isSelectStatus()) { - selectClause += " , obs.update_date obs_update_date, obs.download_date obs_download_date, obs.import_date obs_import_date, obs.sourcesystem_cd obs_sourcesystem_cd, obs.upload_id obs_upload_id "; - } - } - - return selectClause; - } - - /** - * Function which selects observation fact fields based on ouput option flag - * - * @return - */ - public String getSelectClauseWithoutBlob() { - String selectClause = ""; - - if (isSelected()) { - selectClause = " obs.encounter_num obs_encounter_num, obs.patient_num obs_patient_num, obs.concept_cd obs_concept_cd, obs.provider_id obs_provider_id, obs.start_date obs_start_date , obs.modifier_cd obs_modifier_cd, obs.instance_num obs_instance_num "; - - // Adding modifier_cd slow down the query , obs.modifier_cd - // obs_modifier_cd " - if (isSelectDetail()) { - selectClause += ", obs.valtype_cd obs_valtype_cd, obs.tval_char obs_tval_char, obs.nval_num obs_nval_num, obs.valueflag_cd obs_valueflag_cd,obs.quantity_num obs_quantity_num, obs.units_cd obs_units_cd, obs.end_date obs_end_date,obs.location_cd obs_location_cd, obs.confidence_num obs_confidence_num"; - } - - // if (isSelectBlob()) { - // selectClause += - // ", to_clob(obs.observation_blob) obs_observation_blob "; - // } - - if (isSelectStatus()) { - selectClause += " , obs.update_date obs_update_date, obs.download_date obs_download_date, obs.import_date obs_import_date, obs.sourcesystem_cd obs_sourcesystem_cd, obs.upload_id obs_upload_id "; - } - } - - return selectClause; - } - - public String getLookupTableSelectClause() { - String lookupTableSelectClause = " "; - lookupTableSelectClause = " , modifier_lookup.name_char modifier_name "; - - return lookupTableSelectClause; - } - - public String joinClause() { - if (isSelected()) { - return " left join VISIT_DIMENSION visit on (obs.encounter_num = visit.encounter_num) "; - } else { - return ""; - } - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao.pdo.output; + +import edu.harvard.i2b2.crc.datavo.pdo.query.OutputOptionType; + +/** + * Class to generate select, join, where clause for ObservationFact based on + * pdo's OutputOptionType $Id: ObservationFactFactRelated.java,v 1.4 2007/08/31 + * 14:43:33 rk903 Exp $ + * + * @author rkuttan + */ +public class ObservationFactFactRelated extends FactRelated { + + public ObservationFactFactRelated(OutputOptionType outputOptionType) { + super(outputOptionType); + } + + public String getDefaultSelectClause() { + return " obs.encounter_num obs_encounter_num, obs.patient_num obs_patient_num, obs.concept_cd obs_concept_cd,obs.provider_id obs_provider_id, obs.start_date obs_start_date , obs.modifier_cd obs_modifier_cd , obs.instance_num obs_instance_num "; + } + + /** + * Function which selects observation fact fields based on ouput option flag + * + * @return + */ + public String getSelectClause() { + String selectClause = ""; + + if (isSelected()) { + selectClause = " obs.encounter_num obs_encounter_num, obs.patient_num obs_patient_num, obs.concept_cd obs_concept_cd, obs.provider_id obs_provider_id, obs.start_date obs_start_date , obs.modifier_cd obs_modifier_cd , obs.instance_num obs_instance_num "; + + // Adding modifier_cd slow down the query , obs.modifier_cd + // obs_modifier_cd " + if (isSelectDetail()) { + selectClause += ", obs.valtype_cd obs_valtype_cd, obs.tval_char obs_tval_char, obs.nval_num obs_nval_num, obs.valueflag_cd obs_valueflag_cd,obs.quantity_num obs_quantity_num, obs.units_cd obs_units_cd, obs.end_date obs_end_date,obs.location_cd obs_location_cd, obs.confidence_num obs_confidence_num"; + } + + if (isSelectBlob()) { + selectClause += ", obs.observation_blob obs_observation_blob "; + } + + if (isSelectStatus()) { + selectClause += " , obs.update_date obs_update_date, obs.download_date obs_download_date, obs.import_date obs_import_date, obs.sourcesystem_cd obs_sourcesystem_cd, obs.upload_id obs_upload_id "; + } + } + + return selectClause; + } + + /** + * Function which selects observation fact fields based on ouput option flag + * + * @return + */ + public String getSelectClauseWithoutBlob() { + String selectClause = ""; + + if (isSelected()) { + selectClause = " obs.encounter_num obs_encounter_num, obs.patient_num obs_patient_num, obs.concept_cd obs_concept_cd, obs.provider_id obs_provider_id, obs.start_date obs_start_date , obs.modifier_cd obs_modifier_cd, obs.instance_num obs_instance_num "; + + // Adding modifier_cd slow down the query , obs.modifier_cd + // obs_modifier_cd " + if (isSelectDetail()) { + selectClause += ", obs.valtype_cd obs_valtype_cd, obs.tval_char obs_tval_char, obs.nval_num obs_nval_num, obs.valueflag_cd obs_valueflag_cd,obs.quantity_num obs_quantity_num, obs.units_cd obs_units_cd, obs.end_date obs_end_date,obs.location_cd obs_location_cd, obs.confidence_num obs_confidence_num"; + } + + // if (isSelectBlob()) { + // selectClause += + // ", to_clob(obs.observation_blob) obs_observation_blob "; + // } + + if (isSelectStatus()) { + selectClause += " , obs.update_date obs_update_date, obs.download_date obs_download_date, obs.import_date obs_import_date, obs.sourcesystem_cd obs_sourcesystem_cd, obs.upload_id obs_upload_id "; + } + } + + return selectClause; + } + + public String getLookupTableSelectClause() { + String lookupTableSelectClause = " "; + lookupTableSelectClause = " , modifier_lookup.name_char modifier_name "; + + return lookupTableSelectClause; + } + + public String joinClause() { + if (isSelected()) { + return " left join VISIT_DIMENSION visit on (obs.encounter_num = visit.encounter_num) "; + } else { + return ""; + } + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/output/PatientFactRelated.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/output/PatientFactRelated.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/output/PatientFactRelated.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/output/PatientFactRelated.java index f2bcbee9..eec08a6d --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/output/PatientFactRelated.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/output/PatientFactRelated.java @@ -1,93 +1,93 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao.pdo.output; - -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.Iterator; -import java.util.List; - -import edu.harvard.i2b2.crc.datavo.pdo.query.OutputOptionType; -import edu.harvard.i2b2.crc.datavo.pdo.ParamType; - -/** - * Class to generate select, join, where clause - * for patient dimenstion based on pdo's OutputOptionType - * $Id: PatientFactRelated.java,v 1.3 2007/08/31 14:43:33 rk903 Exp $ - * @author rkuttan - */ -public class PatientFactRelated extends FactRelated { - - List metaDataParamList ; - - public PatientFactRelated(OutputOptionType outputOptionType) { - super(outputOptionType); - } - - public void setMetaDataParamList(List metaDataParamList) { - this.metaDataParamList = metaDataParamList; - } - - - private String buildCustomSelectClause(String prefix) { - String detailSelectClause = " "; - for (Iterator iterator = this.metaDataParamList.iterator();iterator.hasNext();) { - ParamType paramType = iterator.next(); - detailSelectClause += prefix + "." + paramType.getColumn() + " " + prefix + "_" + paramType.getColumn(); - if (iterator.hasNext()) { - detailSelectClause += " , "; - } - } - return detailSelectClause; - } - - - public String getSelectClause() { - String selectClause = ""; - - if (isSelected()) { - selectClause = " patient.patient_num patient_patient_num"; - - if (isSelectDetail()) { - selectClause += ", patient.Vital_Status_Cd patient_Vital_Status_Cd, patient.birth_date patient_birth_date"; - selectClause += "," + buildCustomSelectClause("patient"); - } - - if (isSelectBlob()) { - selectClause += ", patient.patient_blob patient_patient_blob "; - } - - if (isSelectStatus()) { - selectClause += " , patient.update_date patient_update_date, patient.download_date patient_download_date, patient.import_date patient_import_date, patient.sourcesystem_cd patient_sourcesystem_cd, patient.upload_id patient_upload_id "; - } - } - - return selectClause; - } - - - public String joinClause() { - if (isSelected()) { - return " left join PATIENT_DIMENSION patient on (obs.patient_num = patient.patient_num) "; - } else { - return ""; - } - } - - public int getPatientNumFromResultSet(ResultSet resultSet) - throws SQLException { - return resultSet.getInt("obs_patient_num"); - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao.pdo.output; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Iterator; +import java.util.List; + +import edu.harvard.i2b2.crc.datavo.pdo.query.OutputOptionType; +import edu.harvard.i2b2.crc.datavo.pdo.ParamType; + +/** + * Class to generate select, join, where clause + * for patient dimenstion based on pdo's OutputOptionType + * $Id: PatientFactRelated.java,v 1.3 2007/08/31 14:43:33 rk903 Exp $ + * @author rkuttan + */ +public class PatientFactRelated extends FactRelated { + + List metaDataParamList ; + + public PatientFactRelated(OutputOptionType outputOptionType) { + super(outputOptionType); + } + + public void setMetaDataParamList(List metaDataParamList) { + this.metaDataParamList = metaDataParamList; + } + + + private String buildCustomSelectClause(String prefix) { + String detailSelectClause = " "; + for (Iterator iterator = this.metaDataParamList.iterator();iterator.hasNext();) { + ParamType paramType = iterator.next(); + detailSelectClause += prefix + "." + paramType.getColumn() + " " + prefix + "_" + paramType.getColumn(); + if (iterator.hasNext()) { + detailSelectClause += " , "; + } + } + return detailSelectClause; + } + + + public String getSelectClause() { + String selectClause = ""; + + if (isSelected()) { + selectClause = " patient.patient_num patient_patient_num"; + + if (isSelectDetail()) { + selectClause += ", patient.Vital_Status_Cd patient_Vital_Status_Cd, patient.birth_date patient_birth_date"; + selectClause += "," + buildCustomSelectClause("patient"); + } + + if (isSelectBlob()) { + selectClause += ", patient.patient_blob patient_patient_blob "; + } + + if (isSelectStatus()) { + selectClause += " , patient.update_date patient_update_date, patient.download_date patient_download_date, patient.import_date patient_import_date, patient.sourcesystem_cd patient_sourcesystem_cd, patient.upload_id patient_upload_id "; + } + } + + return selectClause; + } + + + public String joinClause() { + if (isSelected()) { + return " left join PATIENT_DIMENSION patient on (obs.patient_num = patient.patient_num) "; + } else { + return ""; + } + } + + public int getPatientNumFromResultSet(ResultSet resultSet) + throws SQLException { + return resultSet.getInt("obs_patient_num"); + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/output/PidFactRelated.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/output/PidFactRelated.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/output/PidFactRelated.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/output/PidFactRelated.java index b676dc0c..e5447314 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/output/PidFactRelated.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/output/PidFactRelated.java @@ -1,72 +1,72 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao.pdo.output; - -import edu.harvard.i2b2.crc.datavo.pdo.query.OutputOptionType; - -/** - * Class to generate select, join, where clause for concept dimenstion based on - * pdo's OutputOptionType $Id: ConceptFactRelated.java,v 1.3 2007/08/31 14:43:33 - * rk903 Exp $ - * - * @author rkuttan - */ -public class PidFactRelated extends FactRelated { - /** - * Constructor accepts OutputOptionType - * - * @param outputOptionType - */ - public PidFactRelated(OutputOptionType outputOptionType) { - super(outputOptionType); - } - - /** - * Function which selects fields based on ouput option flag - * - * @return select sql clause - */ - public String getSelectClause() { - String selectClause = ""; - - if (isSelected()) { - selectClause = " pm.patient_ide pm_patient_ide, pm.patient_ide_source pm_patient_ide_source, pm.patient_num pm_patient_num"; - - if (isSelectDetail()) { - selectClause += " ,pm.patient_ide_status pm_patient_ide_status"; - } - - if (isSelectStatus()) { - selectClause += " , pm.update_date pm_update_date, pm.download_date pm_download_date, pm.import_date pm_import_date, pm.sourcesystem_cd pm_sourcesystem_cd, pm.upload_id pm_upload_id "; - } - } - - return selectClause; - } - - /** - * Function to generate join clause with concept dimension table - * - * @return - */ - public String joinClause() { - if (isSelected()) { - return " left join PATIENT_MAPPING pat_map on (obs.patient_num = pat_map.patient_num) "; - } else { - return ""; - } - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao.pdo.output; + +import edu.harvard.i2b2.crc.datavo.pdo.query.OutputOptionType; + +/** + * Class to generate select, join, where clause for concept dimenstion based on + * pdo's OutputOptionType $Id: ConceptFactRelated.java,v 1.3 2007/08/31 14:43:33 + * rk903 Exp $ + * + * @author rkuttan + */ +public class PidFactRelated extends FactRelated { + /** + * Constructor accepts OutputOptionType + * + * @param outputOptionType + */ + public PidFactRelated(OutputOptionType outputOptionType) { + super(outputOptionType); + } + + /** + * Function which selects fields based on ouput option flag + * + * @return select sql clause + */ + public String getSelectClause() { + String selectClause = ""; + + if (isSelected()) { + selectClause = " pm.patient_ide pm_patient_ide, pm.patient_ide_source pm_patient_ide_source, pm.patient_num pm_patient_num"; + + if (isSelectDetail()) { + selectClause += " ,pm.patient_ide_status pm_patient_ide_status"; + } + + if (isSelectStatus()) { + selectClause += " , pm.update_date pm_update_date, pm.download_date pm_download_date, pm.import_date pm_import_date, pm.sourcesystem_cd pm_sourcesystem_cd, pm.upload_id pm_upload_id "; + } + } + + return selectClause; + } + + /** + * Function to generate join clause with concept dimension table + * + * @return + */ + public String joinClause() { + if (isSelected()) { + return " left join PATIENT_MAPPING pat_map on (obs.patient_num = pat_map.patient_num) "; + } else { + return ""; + } + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/output/ProviderFactRelated.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/output/ProviderFactRelated.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/output/ProviderFactRelated.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/output/ProviderFactRelated.java index 01e42dac..864155bd --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/output/ProviderFactRelated.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/output/ProviderFactRelated.java @@ -1,68 +1,68 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao.pdo.output; - -import java.sql.ResultSet; -import java.sql.SQLException; - -import edu.harvard.i2b2.crc.datavo.pdo.query.OutputOptionType; - - -/** - * Class to generate select, join, where clause - * for Provider dimenstion based on pdo's OutputOptionType - * $Id: ProviderFactRelated.java,v 1.3 2007/08/31 14:43:33 rk903 Exp $ - * @author rkuttan - */ -public class ProviderFactRelated extends FactRelated { - public ProviderFactRelated(OutputOptionType outputOptionType) { - super(outputOptionType); - } - - public String getSelectClause() { - String selectClause = ""; - - if (isSelected()) { - selectClause = " provider.provider_id provider_provider_id, provider.provider_path provider_provider_path "; - - if (isSelectDetail()) { - selectClause += ", provider.name_char provider_name_char "; - } - - if (isSelectBlob()) { - selectClause += ", provider.provider_blob provider_provider_blob "; - } - - if (isSelectStatus()) { - selectClause += " , provider.update_date provider_update_date, provider.download_date provider_download_date, provider.import_date provider_import_date, provider.sourcesystem_cd provider_sourcesystem_cd, provider.upload_id provider_upload_id "; - } - } - - return selectClause; - } - - public String joinClause() { - if (isSelected()) { - return " left join PROVIDER_DIMENSION provider on (obs.provider_id = provider.provider_id) "; - } else { - return ""; - } - } - - public String getProviderIdFromResultSet(ResultSet resultSet) - throws SQLException { - return resultSet.getString("obs_provider_id"); - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao.pdo.output; + +import java.sql.ResultSet; +import java.sql.SQLException; + +import edu.harvard.i2b2.crc.datavo.pdo.query.OutputOptionType; + + +/** + * Class to generate select, join, where clause + * for Provider dimenstion based on pdo's OutputOptionType + * $Id: ProviderFactRelated.java,v 1.3 2007/08/31 14:43:33 rk903 Exp $ + * @author rkuttan + */ +public class ProviderFactRelated extends FactRelated { + public ProviderFactRelated(OutputOptionType outputOptionType) { + super(outputOptionType); + } + + public String getSelectClause() { + String selectClause = ""; + + if (isSelected()) { + selectClause = " provider.provider_id provider_provider_id, provider.provider_path provider_provider_path "; + + if (isSelectDetail()) { + selectClause += ", provider.name_char provider_name_char "; + } + + if (isSelectBlob()) { + selectClause += ", provider.provider_blob provider_provider_blob "; + } + + if (isSelectStatus()) { + selectClause += " , provider.update_date provider_update_date, provider.download_date provider_download_date, provider.import_date provider_import_date, provider.sourcesystem_cd provider_sourcesystem_cd, provider.upload_id provider_upload_id "; + } + } + + return selectClause; + } + + public String joinClause() { + if (isSelected()) { + return " left join PROVIDER_DIMENSION provider on (obs.provider_id = provider.provider_id) "; + } else { + return ""; + } + } + + public String getProviderIdFromResultSet(ResultSet resultSet) + throws SQLException { + return resultSet.getString("obs_provider_id"); + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/output/VisitFactRelated.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/output/VisitFactRelated.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/output/VisitFactRelated.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/output/VisitFactRelated.java index 480d765a..3b6905e3 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/pdo/output/VisitFactRelated.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/pdo/output/VisitFactRelated.java @@ -1,107 +1,107 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao.pdo.output; - -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.Iterator; -import java.util.List; - -import edu.harvard.i2b2.crc.datavo.pdo.ParamType; -import edu.harvard.i2b2.crc.datavo.pdo.query.OutputOptionType; - -/** - * Class to generate select, join, where clause for Visit dimenstion based on - * pdo's OutputOptionType $Id: VisitFactRelated.java,v 1.4 2007/08/31 14:43:33 - * rk903 Exp $ - * - * @author rkuttan - */ -public class VisitFactRelated extends FactRelated { - List metaDataParamList ; - - public VisitFactRelated(OutputOptionType outputOptionType) { - super(outputOptionType); - } - - public void setMetaDataParamList(List metaDataParamList) { - this.metaDataParamList = metaDataParamList; - } - - private String buildCustomSelectClause(String prefix) { - String detailSelectClause = " "; - for (Iterator iterator = this.metaDataParamList.iterator();iterator.hasNext();) { - ParamType paramType = iterator.next(); - detailSelectClause += prefix + "." + paramType.getColumn() + " " + prefix + "_" + paramType.getColumn(); - if (iterator.hasNext()) { - detailSelectClause += " , "; - } - } - return detailSelectClause; - } - - public String getSelectClause() { - String selectClause = ""; - - if (isSelected()) { - selectClause = " visit.encounter_num visit_encounter_num, visit.patient_num visit_patient_num "; - - if (isSelectDetail()) { - selectClause += ", visit.start_date visit_start_date,visit.end_date visit_end_date "; - selectClause += "," + buildCustomSelectClause("visit"); - } - - if (isSelectBlob()) { - selectClause += ", visit.visit_blob visit_visit_blob "; - } - - if (isSelectStatus()) { - selectClause += " , visit.update_date visit_update_date, visit.download_date visit_download_date, visit.import_date visit_import_date, visit.sourcesystem_cd visit_sourcesystem_cd, visit.upload_id visit_upload_id "; - } - } - - return selectClause; - } - - public String joinClause() { - if (isSelected()) { - return " left join VISIT_DIMENSION visit on (obs.encounter_num = visit.encounter_num and obs.patient_num = visit.patient_num) "; - } else { - return ""; - } - } - - public String[] getAliasFieldName() { - // get select clause and fetch corresponding data to build visit - // dimension - String selectClause = getSelectClause(); - String[] fields = selectClause.split(","); - int i = 0; - String[] aliasFieldName = new String[fields.length]; - - while (i <= fields.length) { - aliasFieldName[i] = fields[i].substring(fields[i].indexOf(' '), - fields[i].length()); - i++; - } - - return aliasFieldName; - } - - public int getEncounterNumFromResultSet(ResultSet resultSet) - throws SQLException { - return resultSet.getInt("obs_encounter_num"); - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao.pdo.output; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Iterator; +import java.util.List; + +import edu.harvard.i2b2.crc.datavo.pdo.ParamType; +import edu.harvard.i2b2.crc.datavo.pdo.query.OutputOptionType; + +/** + * Class to generate select, join, where clause for Visit dimenstion based on + * pdo's OutputOptionType $Id: VisitFactRelated.java,v 1.4 2007/08/31 14:43:33 + * rk903 Exp $ + * + * @author rkuttan + */ +public class VisitFactRelated extends FactRelated { + List metaDataParamList ; + + public VisitFactRelated(OutputOptionType outputOptionType) { + super(outputOptionType); + } + + public void setMetaDataParamList(List metaDataParamList) { + this.metaDataParamList = metaDataParamList; + } + + private String buildCustomSelectClause(String prefix) { + String detailSelectClause = " "; + for (Iterator iterator = this.metaDataParamList.iterator();iterator.hasNext();) { + ParamType paramType = iterator.next(); + detailSelectClause += prefix + "." + paramType.getColumn() + " " + prefix + "_" + paramType.getColumn(); + if (iterator.hasNext()) { + detailSelectClause += " , "; + } + } + return detailSelectClause; + } + + public String getSelectClause() { + String selectClause = ""; + + if (isSelected()) { + selectClause = " visit.encounter_num visit_encounter_num, visit.patient_num visit_patient_num "; + + if (isSelectDetail()) { + selectClause += ", visit.start_date visit_start_date,visit.end_date visit_end_date "; + selectClause += "," + buildCustomSelectClause("visit"); + } + + if (isSelectBlob()) { + selectClause += ", visit.visit_blob visit_visit_blob "; + } + + if (isSelectStatus()) { + selectClause += " , visit.update_date visit_update_date, visit.download_date visit_download_date, visit.import_date visit_import_date, visit.sourcesystem_cd visit_sourcesystem_cd, visit.upload_id visit_upload_id "; + } + } + + return selectClause; + } + + public String joinClause() { + if (isSelected()) { + return " left join VISIT_DIMENSION visit on (obs.encounter_num = visit.encounter_num and obs.patient_num = visit.patient_num) "; + } else { + return ""; + } + } + + public String[] getAliasFieldName() { + // get select clause and fetch corresponding data to build visit + // dimension + String selectClause = getSelectClause(); + String[] fields = selectClause.split(","); + int i = 0; + String[] aliasFieldName = new String[fields.length]; + + while (i <= fields.length) { + aliasFieldName[i] = fields[i].substring(fields[i].indexOf(' '), + fields[i].length()); + i++; + } + + return aliasFieldName; + } + + public int getEncounterNumFromResultSet(ResultSet resultSet) + throws SQLException { + return resultSet.getInt("obs_encounter_num"); + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/quartz/QuartzExec.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/quartz/QuartzExec.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/quartz/QuartzExec.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/quartz/QuartzExec.java index 0b891456..12fa3a5d --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/quartz/QuartzExec.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/quartz/QuartzExec.java @@ -1,90 +1,90 @@ -package edu.harvard.i2b2.crc.dao.quartz; - -import java.util.Date; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.quartz.JobDetail; -import org.quartz.Scheduler; -import org.quartz.SchedulerFactory; -import org.quartz.Trigger; -import org.quartz.impl.StdSchedulerFactory; - -import static org.quartz.DateBuilder.*; -import static org.quartz.JobBuilder.newJob; -import static org.quartz.TriggerBuilder.newTrigger; - - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.setfinder.query.JobType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ScheduleType; - - - -public class QuartzExec { - - protected final Log logger = LogFactory.getLog(getClass()); - protected final Log logesapi = LogFactory.getLog(getClass()); - SchedulerFactory sf = null; - Scheduler sched = null; - - public void run(JobDetail job, Trigger trigger) throws Exception { - - - // First we must get a reference to a scheduler - sf = new StdSchedulerFactory(); - sched = sf.getScheduler(); - - // Trigger the job to run on the next round minute - - // Tell quartz to schedule the job using our trigger - sched.scheduleJob(job, trigger); - - // Start up the scheduler (nothing can actually run until the - // scheduler has been started) - sched.start(); - - logger.info("------- Started Scheduler -----------------"); - - // wait long enough so that the scheduler as an opportunity to - // run the job! - logger.info("------- Waiting 65 seconds... -------------"); - try { - // wait 65 seconds to show job - Thread.sleep(65L * 1000L); - // executing... - } catch (Exception e) { - // - } - - // shut down the scheduler - logger.info("------- Shutting Down ---------------------"); - sched.shutdown(true); - logger.info("------- Shutdown Complete -----------------"); - } - - public void addJob(DataSourceLookup dataSourceLookup, JobType job) throws I2B2Exception { - JobDetail nweJob = newJob(i2b2QuartzSP.class) - .withIdentity("storedProcecure", job.getName()) - // .usingJobData("alpha", 1.23f) - // .usingJobData("beta", 3.141f) - .build(); - - ScheduleType schedule = job.getSchedule(); - Date runTime = null; - - switch(schedule.getIntervalIn()) { - case "MINUTE" : runTime = evenMinuteDate(new Date()); - case "HOUR" : runTime = evenHourDate(new Date()); - } - - Trigger trigger = newTrigger().withIdentity("trigger1", "group1").startAt(runTime).build(); - - - } - - -} +package edu.harvard.i2b2.crc.dao.quartz; + +import java.util.Date; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.quartz.JobDetail; +import org.quartz.Scheduler; +import org.quartz.SchedulerFactory; +import org.quartz.Trigger; +import org.quartz.impl.StdSchedulerFactory; + +import static org.quartz.DateBuilder.*; +import static org.quartz.JobBuilder.newJob; +import static org.quartz.TriggerBuilder.newTrigger; + + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.setfinder.query.JobType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ScheduleType; + + + +public class QuartzExec { + + protected final Log logger = LogFactory.getLog(getClass()); + protected final Log logesapi = LogFactory.getLog(getClass()); + SchedulerFactory sf = null; + Scheduler sched = null; + + public void run(JobDetail job, Trigger trigger) throws Exception { + + + // First we must get a reference to a scheduler + sf = new StdSchedulerFactory(); + sched = sf.getScheduler(); + + // Trigger the job to run on the next round minute + + // Tell quartz to schedule the job using our trigger + sched.scheduleJob(job, trigger); + + // Start up the scheduler (nothing can actually run until the + // scheduler has been started) + sched.start(); + + logger.info("------- Started Scheduler -----------------"); + + // wait long enough so that the scheduler as an opportunity to + // run the job! + logger.info("------- Waiting 65 seconds... -------------"); + try { + // wait 65 seconds to show job + Thread.sleep(65L * 1000L); + // executing... + } catch (Exception e) { + // + } + + // shut down the scheduler + logger.info("------- Shutting Down ---------------------"); + sched.shutdown(true); + logger.info("------- Shutdown Complete -----------------"); + } + + public void addJob(DataSourceLookup dataSourceLookup, JobType job) throws I2B2Exception { + JobDetail nweJob = newJob(i2b2QuartzSP.class) + .withIdentity("storedProcecure", job.getName()) + // .usingJobData("alpha", 1.23f) + // .usingJobData("beta", 3.141f) + .build(); + + ScheduleType schedule = job.getSchedule(); + Date runTime = null; + + switch(schedule.getIntervalIn()) { + case "MINUTE" : runTime = evenMinuteDate(new Date()); + case "HOUR" : runTime = evenHourDate(new Date()); + } + + Trigger trigger = newTrigger().withIdentity("trigger1", "group1").startAt(runTime).build(); + + + } + + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/quartz/i2b2QuartzSP.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/quartz/i2b2QuartzSP.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/quartz/i2b2QuartzSP.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/quartz/i2b2QuartzSP.java index 8b65de09..c5c218ea --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/quartz/i2b2QuartzSP.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/quartz/i2b2QuartzSP.java @@ -1,47 +1,47 @@ -package edu.harvard.i2b2.crc.dao.quartz; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.logging.log4j.Logger; -import org.quartz.Job; -import org.quartz.JobExecutionContext; -import org.quartz.JobExecutionException; - -public class i2b2QuartzSP implements Job { - - /** - *

    - * Empty constructor for job initilization - *

    - *

    - * Quartz requires a public empty constructor so that the - * scheduler can instantiate the class whenever it needs. - *

    - */ - - - - protected final Log logger = LogFactory.getLog(getClass()); - - public i2b2QuartzSP() { - } - - /** - *

    - * Called by the {@link org.quartz.Scheduler} when a - * {@link org.quartz.Trigger} fires that is associated with - * the Job. - *

    - * - * @throws JobExecutionException - * if there is an exception while executing the job. - */ - public void execute(JobExecutionContext context) - throws JobExecutionException { - - logger.info("test"); - } - - - -} +package edu.harvard.i2b2.crc.dao.quartz; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.logging.log4j.Logger; +import org.quartz.Job; +import org.quartz.JobExecutionContext; +import org.quartz.JobExecutionException; + +public class i2b2QuartzSP implements Job { + + /** + *

    + * Empty constructor for job initilization + *

    + *

    + * Quartz requires a public empty constructor so that the + * scheduler can instantiate the class whenever it needs. + *

    + */ + + + + protected final Log logger = LogFactory.getLog(getClass()); + + public i2b2QuartzSP() { + } + + /** + *

    + * Called by the {@link org.quartz.Scheduler} when a + * {@link org.quartz.Trigger} fires that is associated with + * the Job. + *

    + * + * @throws JobExecutionException + * if there is an exception while executing the job. + */ + public void execute(JobExecutionContext context) + throws JobExecutionException { + + logger.info("test"); + } + + + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/redcap/APISurveyResponse.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/redcap/APISurveyResponse.java similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/redcap/APISurveyResponse.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/redcap/APISurveyResponse.java index 7f240dfe..d06c6105 100644 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/redcap/APISurveyResponse.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/redcap/APISurveyResponse.java @@ -1,64 +1,64 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ - -package edu.harvard.i2b2.crc.dao.redcap; - -import java.util.ArrayList; - -import org.apache.hc.core5.http.HttpStatus; - -//import org.apache.http.HttpStatus; - -public class APISurveyResponse { - private HttpStatus status; - private ArrayList records = new ArrayList<>(); - private ArrayList metadatas = new ArrayList<>(); - - public APISurveyResponse() { - } - - public void setStatus(HttpStatus status) { - this.status = status; - } - - public HttpStatus getStatus() { - return status; - } - - public ArrayList getRecords() { - return records; - } - - public ArrayList getMetadata() { - return metadatas; - } - public DataCollectionInstrumentMetadata getMetadata(String metadata) { - for (DataCollectionInstrumentMetadata surveyMetadata: metadatas ) { - if (surveyMetadata.getFieldName().equals(metadata)) - return surveyMetadata; - } - return null; - } - - public void process() { - - for (int i=0; i < records.size(); i++) - { - for ( int j=i+1; j < records.size(); j++) { - if (records.get(i).getFieldName().equals(records.get(j).getFieldName())) { - records.get(i).setModiferCd(records.get(i).getValue()); - records.get(j).setModiferCd(records.get(j).getValue()); - } - } - } - - - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ + +package edu.harvard.i2b2.crc.dao.redcap; + +import java.util.ArrayList; + +import org.apache.hc.core5.http.HttpStatus; + +//import org.apache.http.HttpStatus; + +public class APISurveyResponse { + private HttpStatus status; + private ArrayList records = new ArrayList<>(); + private ArrayList metadatas = new ArrayList<>(); + + public APISurveyResponse() { + } + + public void setStatus(HttpStatus status) { + this.status = status; + } + + public HttpStatus getStatus() { + return status; + } + + public ArrayList getRecords() { + return records; + } + + public ArrayList getMetadata() { + return metadatas; + } + public DataCollectionInstrumentMetadata getMetadata(String metadata) { + for (DataCollectionInstrumentMetadata surveyMetadata: metadatas ) { + if (surveyMetadata.getFieldName().equals(metadata)) + return surveyMetadata; + } + return null; + } + + public void process() { + + for (int i=0; i < records.size(); i++) + { + for ( int j=i+1; j < records.size(); j++) { + if (records.get(i).getFieldName().equals(records.get(j).getFieldName())) { + records.get(i).setModiferCd(records.get(i).getValue()); + records.get(j).setModiferCd(records.get(j).getValue()); + } + } + } + + + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/redcap/DataCollectionInstrument.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/redcap/DataCollectionInstrument.java similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/redcap/DataCollectionInstrument.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/redcap/DataCollectionInstrument.java index dfbc2ff7..df594b19 100644 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/redcap/DataCollectionInstrument.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/redcap/DataCollectionInstrument.java @@ -1,53 +1,53 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ - -package edu.harvard.i2b2.crc.dao.redcap; - -import com.google.gson.annotations.SerializedName; - -public class DataCollectionInstrument { - @SerializedName("record") - protected String record; - - @SerializedName("event_id") - protected String eventId; - - @SerializedName("subject_id") - protected String subjectId; - - public DataCollectionInstrument() { - } - - public DataCollectionInstrument(String record, String eventName) { - this.record = record; - this.subjectId = record; - this.eventId = eventName; - } - - public String getSubjectIsd() { - return subjectId; - } - - public void setSubjsectId(String subjectId) { - this.subjectId = subjectId; - } - - public String getRecordId() { - return record; - } - - public void setEventId(String eventName) { - this.eventId = eventName; - } - - public String getEventId() { - return eventId; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ + +package edu.harvard.i2b2.crc.dao.redcap; + +import com.google.gson.annotations.SerializedName; + +public class DataCollectionInstrument { + @SerializedName("record") + protected String record; + + @SerializedName("event_id") + protected String eventId; + + @SerializedName("subject_id") + protected String subjectId; + + public DataCollectionInstrument() { + } + + public DataCollectionInstrument(String record, String eventName) { + this.record = record; + this.subjectId = record; + this.eventId = eventName; + } + + public String getSubjectIsd() { + return subjectId; + } + + public void setSubjsectId(String subjectId) { + this.subjectId = subjectId; + } + + public String getRecordId() { + return record; + } + + public void setEventId(String eventName) { + this.eventId = eventName; + } + + public String getEventId() { + return eventId; + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/redcap/DataCollectionInstrumentMetadata.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/redcap/DataCollectionInstrumentMetadata.java similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/redcap/DataCollectionInstrumentMetadata.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/redcap/DataCollectionInstrumentMetadata.java index 6e1884df..83988419 100644 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/redcap/DataCollectionInstrumentMetadata.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/redcap/DataCollectionInstrumentMetadata.java @@ -1,214 +1,214 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ - -package edu.harvard.i2b2.crc.dao.redcap; - -import com.google.gson.annotations.SerializedName; - -public class DataCollectionInstrumentMetadata { - - @SerializedName("field_name") - private String fieldName; - - @SerializedName("field_label") - private String fieldLabel; - - @SerializedName("field_note") - private String fieldNote; - - - @SerializedName("field_type") - private String fieldType; - - @SerializedName("text_validation_type_or_show_slider_number") - private String fieldContent; - - @SerializedName("select_choices_or_calculations") - private String choices; - - // private String[] choicesArr; - - @SerializedName("identifier") - private String isPHI; - - @SerializedName("form_name") - private String formName; - - private String value; - - public DataCollectionInstrumentMetadata() { - super(); - } - - public DataCollectionInstrumentMetadata(String record, String fieldName, String eventName, String value) { - this.fieldName = fieldName; - this.value = value; - } - - public void setFieldName(String fieldName) { - this.fieldName = fieldName; - } - - public void setValue(String value) { - this.value = value; - } - - public String getFieldName() { - if (fieldName.length() > 42) - return fieldName.substring(0, 41); - else - return fieldName; - - } - - public String getValue() { - return value; - } - - public String getFieldLabel() { - return fieldLabel; - } - - public void setFieldLabel(String fieldLabel) { - this.fieldLabel = fieldLabel; - } - - public String getFieldType() { - if ((fieldType.equals("text")) && ((fieldContent.equals("date_ymd")) || (fieldContent.equals("date_mdy")) || (fieldContent.equals("dmy")) || - (fieldContent.equals("datetime_ymd")) ||(fieldContent.equals("datetime_mdy")) ||(fieldContent.equals("datetime_dmy")) || - (fieldContent.equals("datetime_seconds_ymd")) || (fieldContent.equals("datetime_seconds_mdy")) || (fieldContent.equals("datetime_seconds_dmy")) - )) - return "date"; - else - return fieldType; - } - - public String getFieldContent() { - return fieldContent; - } - - public void setFieldContent(String fieldContent) { - this.fieldContent = fieldContent; - } - - public void setFieldType(String fieldType) { - - this.fieldType = fieldType; - } - - public boolean isHasCheckBoxOptions() { - //yesno, text, radio, descriptive, checkbox, notes, dropdown - if (fieldType.equals("checkbox") ) - return true; - else - return false; - } - - public boolean isYesNoOptions() { - //yesno, text, radio, descriptive, checkbox, notes, dropdown - if (fieldType.equals("yesno") ) - return true; - else - return false; - } - - public boolean isTrueFalseOptions() { - //yesno, text, radio, descriptive, checkbox, notes, dropdown - if (fieldType.equals("truefalse") ) - return true; - else - return false; - } - - public boolean isHasEnumOptions() { - //yesno, text, radio, descriptive, checkbox, notes, dropdown - if ((fieldType.equals("yesno") || fieldType.equals("truefalse") || fieldType.equals("radio") || fieldType.equals("dropdown"))) - return true; - else - return false; - - } - - public boolean isNoteOptions() { - if ((fieldType.equals("descriptive") || fieldType.equals("notes"))) - return true; - else - return false; - } - public boolean isTextOptions() { - if (fieldType.equals("sql") || (fieldType.equals("text") && (!getFieldType().equals("date_ymd")))) - return true; - else - return false; - } - - public boolean isSliderOptions() { - if (fieldType.equals("slider")) - return true; - else - return false; - } - - - public String[] getChoices() { - String[] tmpChoices = new String[0]; - if (fieldType.equals("yesno")) - { - tmpChoices = new String[] {"Yes", "No"}; - } else if (fieldType.equals("truefalse")) - { - tmpChoices = new String[] {"True", "False"}; - } else if ((fieldType.equals("checkbox") || fieldType.equals("radio") || fieldType.equals("dropdown"))){ - if ((choices == null || choices.length() == 0)) - return tmpChoices; - - tmpChoices = choices.split("\\|"); - //this.tmpChoices = tmpChoices; - } - - return tmpChoices; - } - - public String[] getChoice(int i) { - - String[] tmpChoices = choices.split("\\|"); - if (fieldType.equals("yesno")) - tmpChoices = new String[] {"1, Yes", "0, No"}; - else if (fieldType.equals("truefalse")) - tmpChoices = new String[] {"1, True", "0, False"}; - //int startComma = tmpChoices[i].indexOf(',') + 2; - //return tmpChoices[i].substring(startComma); - - return tmpChoices[i].split(","); - } - - public boolean isPHI() { - if (isPHI.equalsIgnoreCase("Y")) - return true; - else - return false; - } - - public String getFieldNote() { - return fieldNote; - } - - public void setFieldNote(String fieldNote) { - this.fieldNote = fieldNote; - } - - public String getFormName() { - return formName; - } - - public void setFormName(String formName) { - this.formName = formName; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ + +package edu.harvard.i2b2.crc.dao.redcap; + +import com.google.gson.annotations.SerializedName; + +public class DataCollectionInstrumentMetadata { + + @SerializedName("field_name") + private String fieldName; + + @SerializedName("field_label") + private String fieldLabel; + + @SerializedName("field_note") + private String fieldNote; + + + @SerializedName("field_type") + private String fieldType; + + @SerializedName("text_validation_type_or_show_slider_number") + private String fieldContent; + + @SerializedName("select_choices_or_calculations") + private String choices; + + // private String[] choicesArr; + + @SerializedName("identifier") + private String isPHI; + + @SerializedName("form_name") + private String formName; + + private String value; + + public DataCollectionInstrumentMetadata() { + super(); + } + + public DataCollectionInstrumentMetadata(String record, String fieldName, String eventName, String value) { + this.fieldName = fieldName; + this.value = value; + } + + public void setFieldName(String fieldName) { + this.fieldName = fieldName; + } + + public void setValue(String value) { + this.value = value; + } + + public String getFieldName() { + if (fieldName.length() > 42) + return fieldName.substring(0, 41); + else + return fieldName; + + } + + public String getValue() { + return value; + } + + public String getFieldLabel() { + return fieldLabel; + } + + public void setFieldLabel(String fieldLabel) { + this.fieldLabel = fieldLabel; + } + + public String getFieldType() { + if ((fieldType.equals("text")) && ((fieldContent.equals("date_ymd")) || (fieldContent.equals("date_mdy")) || (fieldContent.equals("dmy")) || + (fieldContent.equals("datetime_ymd")) ||(fieldContent.equals("datetime_mdy")) ||(fieldContent.equals("datetime_dmy")) || + (fieldContent.equals("datetime_seconds_ymd")) || (fieldContent.equals("datetime_seconds_mdy")) || (fieldContent.equals("datetime_seconds_dmy")) + )) + return "date"; + else + return fieldType; + } + + public String getFieldContent() { + return fieldContent; + } + + public void setFieldContent(String fieldContent) { + this.fieldContent = fieldContent; + } + + public void setFieldType(String fieldType) { + + this.fieldType = fieldType; + } + + public boolean isHasCheckBoxOptions() { + //yesno, text, radio, descriptive, checkbox, notes, dropdown + if (fieldType.equals("checkbox") ) + return true; + else + return false; + } + + public boolean isYesNoOptions() { + //yesno, text, radio, descriptive, checkbox, notes, dropdown + if (fieldType.equals("yesno") ) + return true; + else + return false; + } + + public boolean isTrueFalseOptions() { + //yesno, text, radio, descriptive, checkbox, notes, dropdown + if (fieldType.equals("truefalse") ) + return true; + else + return false; + } + + public boolean isHasEnumOptions() { + //yesno, text, radio, descriptive, checkbox, notes, dropdown + if ((fieldType.equals("yesno") || fieldType.equals("truefalse") || fieldType.equals("radio") || fieldType.equals("dropdown"))) + return true; + else + return false; + + } + + public boolean isNoteOptions() { + if ((fieldType.equals("descriptive") || fieldType.equals("notes"))) + return true; + else + return false; + } + public boolean isTextOptions() { + if (fieldType.equals("sql") || (fieldType.equals("text") && (!getFieldType().equals("date_ymd")))) + return true; + else + return false; + } + + public boolean isSliderOptions() { + if (fieldType.equals("slider")) + return true; + else + return false; + } + + + public String[] getChoices() { + String[] tmpChoices = new String[0]; + if (fieldType.equals("yesno")) + { + tmpChoices = new String[] {"Yes", "No"}; + } else if (fieldType.equals("truefalse")) + { + tmpChoices = new String[] {"True", "False"}; + } else if ((fieldType.equals("checkbox") || fieldType.equals("radio") || fieldType.equals("dropdown"))){ + if ((choices == null || choices.length() == 0)) + return tmpChoices; + + tmpChoices = choices.split("\\|"); + //this.tmpChoices = tmpChoices; + } + + return tmpChoices; + } + + public String[] getChoice(int i) { + + String[] tmpChoices = choices.split("\\|"); + if (fieldType.equals("yesno")) + tmpChoices = new String[] {"1, Yes", "0, No"}; + else if (fieldType.equals("truefalse")) + tmpChoices = new String[] {"1, True", "0, False"}; + //int startComma = tmpChoices[i].indexOf(',') + 2; + //return tmpChoices[i].substring(startComma); + + return tmpChoices[i].split(","); + } + + public boolean isPHI() { + if (isPHI.equalsIgnoreCase("Y")) + return true; + else + return false; + } + + public String getFieldNote() { + return fieldNote; + } + + public void setFieldNote(String fieldNote) { + this.fieldNote = fieldNote; + } + + public String getFormName() { + return formName; + } + + public void setFormName(String formName) { + this.formName = formName; + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/redcap/RedcapPuller.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/redcap/RedcapPuller.java similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/redcap/RedcapPuller.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/redcap/RedcapPuller.java index b7ce779a..d94178e9 100644 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/redcap/RedcapPuller.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/redcap/RedcapPuller.java @@ -1,838 +1,838 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ - -package edu.harvard.i2b2.crc.dao.redcap; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.dao.redcap.xml.EnumValues; -import edu.harvard.i2b2.crc.dao.redcap.xml.Val; -import edu.harvard.i2b2.crc.dao.redcap.xml.ValueMetadata; -import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; -import edu.harvard.i2b2.crc.datavo.ontology.DeleteChildType; -import edu.harvard.i2b2.crc.datavo.ontology.MetadataLoadType; -import edu.harvard.i2b2.crc.datavo.ontology.OntologyDataType; -import edu.harvard.i2b2.crc.datavo.ontology.XmlValueType; -import edu.harvard.i2b2.crc.datavo.pdo.BlobType; -import edu.harvard.i2b2.crc.datavo.pdo.ConceptType; -import edu.harvard.i2b2.crc.datavo.pdo.EidType; -import edu.harvard.i2b2.crc.datavo.pdo.ObservationType; -import edu.harvard.i2b2.crc.datavo.pdo.ObservationType.ConceptCd; -import edu.harvard.i2b2.crc.datavo.pdo.ObservationType.EventId; -import edu.harvard.i2b2.crc.datavo.pdo.ObservationType.InstanceNum; -import edu.harvard.i2b2.crc.datavo.pdo.ObservationType.ModifierCd; -import edu.harvard.i2b2.crc.datavo.pdo.ObservationType.NvalNum; -import edu.harvard.i2b2.crc.datavo.pdo.ObservationType.ObserverCd; -import edu.harvard.i2b2.crc.datavo.pdo.PatientIdType; -import edu.harvard.i2b2.crc.datavo.pdo.PidType; -import edu.harvard.i2b2.crc.datavo.pdo.PidType.PatientId; -import edu.harvard.i2b2.crc.datavo.pm.ParamType; -import edu.harvard.i2b2.crc.datavo.pm.ProjectType; -import edu.harvard.i2b2.crc.delegate.ontology.CallOntologyUtil; -import edu.harvard.i2b2.crc.delegate.pm.CallPMUtil; -import edu.harvard.i2b2.crc.loader.dao.ILoaderDAOFactory; -import edu.harvard.i2b2.crc.loader.dao.IUploaderDAOFactory; -import edu.harvard.i2b2.crc.loader.dao.LoaderDAOFactoryHelper; -import edu.harvard.i2b2.crc.loader.dao.ObservationFactInsertHandle; -import edu.harvard.i2b2.crc.loader.dao.TempConceptInsertHandler; -import edu.harvard.i2b2.crc.loader.dao.TempEidInsertHandler; -import edu.harvard.i2b2.crc.loader.dao.TempPidInsertHandler; -import edu.harvard.i2b2.crc.loader.datavo.loader.DataSourceLookup; -import edu.harvard.i2b2.crc.util.Base64; -import edu.harvard.i2b2.crc.util.PMServiceAccountUtil; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - -import org.apache.axis2.AxisFault; -import org.apache.commons.io.IOUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.hc.client5.http.entity.UrlEncodedFormEntity; -import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; -import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; -import org.apache.hc.client5.http.impl.classic.HttpClientBuilder; -import org.apache.hc.core5.http.HttpEntity; -import org.apache.hc.core5.http.HttpStatus; -import org.apache.hc.core5.http.io.entity.EntityUtils; -import org.apache.hc.core5.http.message.BasicNameValuePair; -import org.apache.hc.core5.http.NameValuePair; -import org.apache.hc.client5.http.classic.methods.HttpPost; - -/* -import org.apache.http.HttpEntity; -import org.apache.http.HttpStatus; -import org.apache.http.NameValuePair; -import org.apache.http.client.entity.UrlEncodedFormEntity; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.message.BasicNameValuePair; -import org.apache.http.protocol.HTTP; -import org.apache.http.util.EntityUtils; -*/ -import org.w3c.dom.Document; -import org.w3c.dom.Element; - -import com.google.gson.Gson; - -import java.io.IOException; -import java.io.InputStream; -import java.io.StringWriter; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.List; -import java.util.Scanner; -import java.util.stream.Stream; - -import jakarta.xml.bind.JAXBContext; -import javax.xml.datatype.DatatypeConfigurationException; -import javax.xml.datatype.DatatypeFactory; -import javax.xml.datatype.XMLGregorianCalendar; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.stream.XMLStreamException; - -import java.math.*; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Paths; - - -public class RedcapPuller { - protected final Log logger = LogFactory.getLog(getClass()); - protected final Log logesapi = LogFactory.getLog(getClass()); - - private final String FORMAT = "json"; - private final String CONTENT = "record"; - - - String rootOntology = "\\REDCAP\\"; - String setSourcesystemCd = "REDCAP"; - String protectedRole = "DATA_PROT"; - String refreshOntology = "Y"; - boolean isPHI = false; - //String ontologyFormat = "tree"; //tree = For Tree format, popup = For popup with selection - String api = null; - String redcapApiUrl = null; - String startDateName = null; - - public void pullRecordRequest(String redcapUrl, String record, String recordId, String surveyForm, String pid) throws I2B2Exception { - if (record == null || record.isEmpty()) { - throw new I2B2Exception("record is null"); - } - if (redcapUrl == null || redcapUrl.isEmpty()) { - throw new I2B2Exception("url is null"); - } - - APISurveyResponse redcapResult = new APISurveyResponse(); - - try { - redcapApiUrl = redcapUrl + "api/"; - - String responseStr = null; - CloseableHttpResponse response = null; - - SecurityType securityType = PMServiceAccountUtil - .getServiceSecurityType(""); - - ProjectType projectParams = CallPMUtil.callUserProjectRedcap(securityType,pid);// surveyForm); - - DataCollectionInstrumentMetadata[] metadatas = null; - try { - - - for (ParamType projectParam: projectParams.getParam()) - { - if (projectParam.getName().equalsIgnoreCase("REDCAP_TOKEN_PID_" + pid)) // Located in the PM_USER_PARAM - api = projectParam.getValue(); - else if (projectParam.getName().equalsIgnoreCase("REDCAP_ROOT_ONTOLOGY")) - rootOntology = projectParam.getValue(); - else if (projectParam.getName().equalsIgnoreCase("REDCAP_SOURCESYSTEM")) - setSourcesystemCd = projectParam.getValue(); - // else if (projectParam.getName().equalsIgnoreCase("REDCAP_ONTOLOGY_FORMAT")) - // ontologyFormat = projectParam.getValue(); - else if (projectParam.getName().equalsIgnoreCase("REDCAP_PROTECTED_ROLE")) - protectedRole = projectParam.getValue(); - else if (projectParam.getName().equalsIgnoreCase("REDCAP_ONTOLOGY_REFRESH")) - refreshOntology = projectParam.getValue(); - else if (projectParam.getName().equalsIgnoreCase("REDCAP_STARTDATE_NAME")) - startDateName = projectParam.getValue(); - - } - - if (api == null) - throw new I2B2Exception("Project " + surveyForm + " does not have a param called REDCAP_TOKEN_PID_" + pid + " with the token number."); - - if (redcapApiUrl.startsWith("file:")) { - responseStr = readLineByLineJava8( redcapApiUrl.substring(7) ) ; - metadatas = new Gson().fromJson(responseStr, DataCollectionInstrumentMetadata[].class); - if (metadatas != null) { - redcapResult.getMetadata().addAll(Arrays.asList(metadatas)); - } - } else { - List apiCall = new ArrayList (); - apiCall.add(new BasicNameValuePair("token", api)); - apiCall.add(new BasicNameValuePair("content", "metadata")); - apiCall.add(new BasicNameValuePair("format", FORMAT)); - - HttpPost httpPost = new HttpPost(redcapApiUrl); - - httpPost.setEntity(new UrlEncodedFormEntity(apiCall)); - httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded"); - - CloseableHttpClient client = HttpClientBuilder.create().build(); - response = client.execute(httpPost); - //response..getCode() - if (response.getCode() >= 300) { - throw new I2B2Exception(String.format("failure - received a %d for %s.", - response.getCode(), httpPost.toString())); - } - - HttpEntity entity = response.getEntity(); - responseStr = EntityUtils.toString(entity, "UTF-8"); - - if (response.getCode() == HttpStatus.SC_OK) { - metadatas = new Gson().fromJson(responseStr, DataCollectionInstrumentMetadata[].class); - if (metadatas != null) { - redcapResult.getMetadata().addAll(Arrays.asList(metadatas)); - } - } - } - - } catch (Exception e) { - throw new Exception(e); - } - - try { - - List apiCall = new ArrayList (); - apiCall.add(new BasicNameValuePair("token", api)); - apiCall.add(new BasicNameValuePair("content", CONTENT)); - apiCall.add(new BasicNameValuePair("format", FORMAT)); - apiCall.add(new BasicNameValuePair("type", record)); - apiCall.add(new BasicNameValuePair("exportSurveyFields", "true")); - apiCall.add(new BasicNameValuePair("rawOrLabel", "raw")); - apiCall.add(new BasicNameValuePair("exportCheckboxLabel", "true")); - if (surveyForm != null && !surveyForm.isEmpty()) { - apiCall.add(new BasicNameValuePair("forms", surveyForm)); - } - if (recordId != null && !recordId.isEmpty()) { - apiCall.add(new BasicNameValuePair("records", recordId)); - } - //if (eventName != null && !eventName.isEmpty()) { - // apiCall.add(new BasicNameValuePair("events", eventName)); - // } - - HttpPost httpPost = new HttpPost(redcapApiUrl); - - httpPost.setEntity(new UrlEncodedFormEntity(apiCall)); - httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded"); - - CloseableHttpClient client = HttpClientBuilder.create().build(); - response = client.execute(httpPost); - if (response.getCode() >= 300) { - throw new I2B2Exception(String.format("failure - received a %d for %s.", - response.getCode(), httpPost.toString())); - } - - - HttpEntity entity = response.getEntity(); - responseStr = EntityUtils.toString(entity, "UTF-8"); - - - - } catch (Exception e) { - throw new Exception(e); - } - // Create Table_access - - logesapi.debug("Response body: " + responseStr); - - if (response.getCode() == HttpStatus.SC_OK) { - SurveyRecord[] records = new Gson().fromJson(responseStr, SurveyRecord[].class); - insertI2B2(records, redcapResult, surveyForm, projectParams, securityType, metadatas); - - } - - } catch (Exception ie) { - logger.error("Unexpected IO exception", ie); - - } - } - - private static String readLineByLineJava8(String filePath) - { - StringBuilder contentBuilder = new StringBuilder(); - - - /* TODO - try (Stream stream = Files.lines( Paths.get(filePath), StandardCharsets.UTF_8)) - { - stream.forEach(s -> contentBuilder.append(s).append("\n")); - } - catch (IOException e) - { - e.printStackTrace(); - } - */ - - return contentBuilder.toString(); - } - - private void insertI2B2(SurveyRecord[] records, APISurveyResponse redcapResult, String surveyForm, ProjectType projectParams - , SecurityType securityType, DataCollectionInstrumentMetadata[] metadatas ) throws I2B2Exception, DatatypeConfigurationException, AxisFault, XMLStreamException, JAXBUtilException { - if (records != null) { - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - String ontologyUrl = qpUtil - .getCRCPropertyValue(QueryProcessorUtil.ONTOLOGYCELL_ROOT_WS_URL_PROPERTIES); - - - List c = new ArrayList(); - - - redcapResult.getRecords().addAll(Arrays.asList(records)); - - redcapResult.process(); - - DataSourceLookup dataSourceLookup = new DataSourceLookup(); - dataSourceLookup.setProjectPath(projectParams.getId()); - dataSourceLookup.setDomainId(securityType.getDomain()); - dataSourceLookup.setOwnerId(securityType.getUsername()); - - //DataMartLoaderAsyncBeanLocal loader = CRCLoaderUtil.getInstance().getDataMartLoaderBean(); - - - LoaderDAOFactoryHelper daoHelper = new LoaderDAOFactoryHelper( - dataSourceLookup.getDomainId(), dataSourceLookup - .getProjectPath(), dataSourceLookup.getOwnerId()); - ILoaderDAOFactory loaderDaoFactory = daoHelper.getDAOFactory(); - IUploaderDAOFactory uploaderDaoFactory = loaderDaoFactory - .getUpLoaderDAOFactory(); - - - GregorianCalendar gcal = (GregorianCalendar) GregorianCalendar.getInstance(); - XMLGregorianCalendar startDate = DatatypeFactory.newInstance() - .newXMLGregorianCalendar(gcal); - - - - - - - ObserverCd observer = new ObserverCd(); - observer.setName("@"); - observer.setValue("@"); - - InstanceNum instance = new InstanceNum(); - instance.setValue("1"); - - int uploadId = -1; - String tempObsTableName = "TEMP_OBS_MAP_" + gcal.getTime().getDay()+gcal.getTime().getMonth()+gcal.getTime().getYear() - +gcal.getTime().getHours()+gcal.getTime().getMinutes(); - String tempPidTableName = "TEMP_PID_MAP_" + gcal.getTime().getDay()+gcal.getTime().getMonth()+gcal.getTime().getYear() - +gcal.getTime().getHours()+gcal.getTime().getMinutes(); - - String tempEidTableName = "TEMP_EID_MAP_" + gcal.getTime().getDay()+gcal.getTime().getMonth()+gcal.getTime().getYear() - +gcal.getTime().getHours()+gcal.getTime().getMinutes(); - - String tempConceptTableName = "TEMP_CONCEPT_MAP_" + gcal.getTime().getDay()+gcal.getTime().getMonth()+gcal.getTime().getYear() - +gcal.getTime().getHours()+gcal.getTime().getMinutes(); - - uploaderDaoFactory.getPidDAO().createTempTable(tempPidTableName); - uploaderDaoFactory.getEidDAO().createTempTable(tempEidTableName); - uploaderDaoFactory.getObservationDAO().createTempTable(tempObsTableName); - uploaderDaoFactory.getConceptDAO().createTempTable(tempConceptTableName); - - ObservationFactInsertHandle observationFactInsertHandle = uploaderDaoFactory.getObservationDAO() - .createObservationFactInserter(tempObsTableName); - - TempPidInsertHandler pidInsertHandle = uploaderDaoFactory.getPidDAO().createTempPidInsert(tempPidTableName); - - TempEidInsertHandler eidInsertHandle = uploaderDaoFactory.getEidDAO().createTempEidInsert(tempEidTableName); - - TempConceptInsertHandler conceptInsertHandle = uploaderDaoFactory.getConceptDAO().createTempConceptInsert(tempConceptTableName); - //observationFactInsertHandle.c - - if (records.length > 0) { - PidType pidType = new PidType(); - PatientId patientId = new PatientId(); - patientId.setSource("REDCAP"); - patientId.setValue(records[0].getRecordId()); - patientId.setStatus("A"); - patientId.setSourcesystemCd(setSourcesystemCd); - patientId.setDownloadDate(startDate); - patientId.setUpdateDate(startDate); - patientId.setImportDate(startDate); - pidType.setPatientId(patientId); - - pidInsertHandle.insertPid(pidType); - - - EidType eidType = new EidType(); - edu.harvard.i2b2.crc.datavo.pdo.EidType.EventId eventId = new edu.harvard.i2b2.crc.datavo.pdo.EidType.EventId(); - - eventId.setPatientId(records[0].getRecordId()); - eventId.setPatientIdSource("REDCAP"); - eventId.setSourcesystemCd(setSourcesystemCd); - eventId.setStatus("A"); - eventId.setSource("REDCAP"); - eventId.setValue("0"); - eidType.setEventId(eventId); - eidInsertHandle.insertEid(eidType); - uploaderDaoFactory.getPidDAO().createPidFromTempTable(tempPidTableName, uploadId); - uploaderDaoFactory.getEidDAO().createEidFromTempTable(tempEidTableName, uploadId); - uploaderDaoFactory.getObservationDAO().removeTempTable(tempPidTableName); - uploaderDaoFactory.getObservationDAO().removeTempTable(tempEidTableName); - } - - //Create root node in metadata in table_access - OntologyDataType ontologyData = new OntologyDataType(); - ontologyData.setLevel(0); - ontologyData.setFullname(rootOntology); - ontologyData.setName(surveyForm); - ontologyData.setSynonymCd("N"); - ontologyData.setVisualattributes("FAE"); - ontologyData.setFacttablecolumn("concept_cd"); - ontologyData.setDimtablename("concept_dimension"); - ontologyData.setColumnname("concept_path"); - ontologyData.setColumndatatype("T"); - ontologyData.setOperator("LIKE"); - ontologyData.setTooltip(rootOntology); - ontologyData.setDimcode(rootOntology ); - ontologyData.setAppliedPath("@"); - ontologyData.setDownloadDate(startDate); - ontologyData.setUpdateDate(startDate); - ontologyData.setImportDate(startDate); - c.add(ontologyData); - - for (DataCollectionInstrumentMetadata metadata: metadatas) { - if (surveyForm.equalsIgnoreCase(metadata.getFormName())) { - //Check to see if PHI, if so set gloval variable - if (metadata.isPHI()) - isPHI = true; - - - // Insert Concept Dimension - // if ((metadata.isHasEnumOptions() || metadata.isTextOptions())) { - ConceptType conceptType = new ConceptType(); - conceptType.setConceptCd("REDCAP:" + metadata.getFieldName()); - conceptType.setNameChar("REDCAP:" + metadata.getFieldLabel()); - conceptType.setConceptPath(rootOntology + metadata.getFieldName()+ "\\"); - - conceptType.setSourcesystemCd(setSourcesystemCd); - conceptType.setUploadId(String.valueOf(uploadId)); - conceptInsertHandle.insertConcept(conceptType); - - // Insert meta data - ontologyData = new OntologyDataType(); - ontologyData.setLevel(1); - ontologyData.setFullname(rootOntology + metadata.getFieldName()+ "\\"); - ontologyData.setName(metadata.getFieldLabel()); - ontologyData.setSynonymCd("N"); - //if ((metadata.isTextOptions() == true) || (metadata.isHasMultpleOptions() == true)) - - - //if (ontologyFormat.equalsIgnoreCase("popup") - //|| metadata.isHasEnumOptions() == true)) - // (metadata.isHasCheckBoxOptions() == true) - //if ((ontologyFormat.equalsIgnoreCase("tree") && ((metadata.isHasEnumOptions() == true) || (metadata.isHasCheckBoxOptions() == true)))) - if ((metadata.isHasEnumOptions() == true) || (metadata.isHasCheckBoxOptions() == true) ) - ontologyData.setVisualattributes("FAE"); - // else if ((ontologyFormat.equalsIgnoreCase("popup") && (metadata.isHasCheckBoxOptions() == true) )) - // ontologyData.setVisualattributes("FAE"); - else - ontologyData.setVisualattributes("LAE"); - - ontologyData.setBasecode(metadata.getFieldName()); - ontologyData.setFacttablecolumn("concept_cd"); - ontologyData.setDimtablename("concept_dimension"); - ontologyData.setColumnname("concept_path"); - ontologyData.setColumndatatype("T"); - ontologyData.setOperator("LIKE"); - ontologyData.setDimcode(rootOntology + metadata.getFieldName()+ "\\"); - ontologyData.setTooltip(metadata.getFieldName()); - ontologyData.setAppliedPath("@"); - ontologyData.setDownloadDate(startDate); - ontologyData.setUpdateDate(startDate); - ontologyData.setImportDate(startDate); - - if ((metadata.isSliderOptions()) || (metadata.isNoteOptions()) || (metadata.isTextOptions() == true) ) - - { - ValueMetadata metadataxml = new ValueMetadata(); - - metadataxml.setVersion("3.2"); - metadataxml.setCreationDateTime(startDate.toString()); - metadataxml.setTestID(metadata.getFieldName()); - metadataxml.setTestName(metadata.getFieldLabel()); - if (metadata.isTextOptions()) { - metadataxml.setDataType("String"); - - }else if (metadata.isNoteOptions()) { - metadataxml.setDataType("largestring"); - }else if (metadata.isSliderOptions()) { - metadataxml.setDataType("PosInteger"); - metadataxml.setLowofLowValue("1"); - metadataxml.setLowofHighValue("100"); - metadataxml.setHighofHighValue("100"); - metadataxml.setHighofLowValue("1"); - }else { - metadataxml.setDataType("Enum"); - EnumValues enumValues = new EnumValues(); - - - Val[] vals = new Val[metadata.getChoices().length]; - - //for (String enums: metadata.getChoices()) - for (int i=0; i < metadata.getChoices().length; i++) - { - Val val = new Val(); - val.setDescription(metadata.getChoice(i)[1].trim()); - val.setValue(Integer.toString(i+1)); - vals[i] = val; - - } - - enumValues.setVal(vals); - metadataxml.setEnumValues(enumValues); - - } - Element rootElement = null; - String xmlString = ""; - XmlValueType xml = null; - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - //dbf.setNamespaceAware(true); - Document doc = dbf.newDocumentBuilder().newDocument(); - - JAXBContext context = JAXBContext.newInstance(metadataxml.getClass()); - context.createMarshaller().marshal(metadataxml, doc); - // Element element = metadataxml; - rootElement = doc.getDocumentElement(); - } catch (Exception e1) { - e1.printStackTrace(); - } - if (rootElement != null) { - xml = new XmlValueType(); - xml.getAny().add(rootElement); - - //if (ontologyFormat.equalsIgnoreCase("popup") || metadata.isHasEnumOptions() == true) - ontologyData.setMetadataxml(xml); - } - } - - //check what way to save metadata - for (int i=0; i < metadata.getChoices().length; i++) - { - //if ((ontologyFormat.equalsIgnoreCase("tree")) )//|| metadata.isHasCheckBoxOptions() == true) - //{ - ConceptType leafType = new ConceptType(); - //String endnode = Integer.toString(i); - - leafType.setConceptCd("REDCAP:" + metadata.getFieldName() + ":" + metadata.getChoice(i)[0].trim()); - try { - leafType.setNameChar("REDCAP:" + metadata.getChoice(i)[1].trim()); - } catch (Exception meta) - { - logger.error("Metadata Issue: " + metadata.getFieldName()); - - } - leafType.setConceptPath(rootOntology + metadata.getFieldName() + "\\" + i+ "\\"); - - leafType.setSourcesystemCd(setSourcesystemCd); - leafType.setUploadId(String.valueOf(uploadId)); - conceptInsertHandle.insertConcept(leafType); - - // Insert meta data - OntologyDataType leafData = new OntologyDataType(); - //ontologyData.setColumnname(surveyForm); - //ontologyData.setTableCd(surveyForm); - //ontologyData.setTableName(surveyForm); - - - - leafData.setLevel(2); - leafData.setFullname(rootOntology + metadata.getFieldName()+ "\\" + i+ "\\"); - leafData.setName(metadata.getChoice(i)[1].trim()); - leafData.setSynonymCd("N"); - leafData.setVisualattributes("LAE"); - leafData.setBasecode(leafType.getConceptCd()); - leafData.setFacttablecolumn("concept_cd"); - leafData.setDimtablename("concept_dimension"); - leafData.setColumnname("concept_path"); - leafData.setColumndatatype("T"); - leafData.setOperator("LIKE"); - leafData.setDimcode(rootOntology + metadata.getFieldName()+ "\\" + i+ "\\"); - leafData.setTooltip(metadata.getFieldName()); - leafData.setAppliedPath("@"); - leafData.setDownloadDate(startDate); - leafData.setUpdateDate(startDate); - leafData.setImportDate(startDate); - - c.add(leafData); - - ///} - } - - - c.add(ontologyData); - - } - } - - - // Save Records to Observation Fact Table - for (SurveyRecord record: records) { - - // get Metadata for record - DataCollectionInstrumentMetadata metadata = redcapResult.getMetadata(record.getFieldName()); - - if (metadata != null) { - String blob = ""; - ObservationType observationType = new ObservationType(); - PatientIdType patid = new PatientIdType(); - patid.setSource("REDCAP"); - patid.setValue(record.getRecordId()); - observationType.setPatientId(patid); - ConceptCd conceptCd = new ConceptCd(); - if ( (metadata.getFieldType().equals("yesno") || metadata.getFieldType().equals("truefalse") || metadata.getFieldType().equals("radio") - || metadata.getFieldType().equals("checkbox") || metadata.getFieldType().equals("dropdown"))) - { - conceptCd.setName("REDCAP:" + record.getFieldName() + ":" + record.getValue()); - conceptCd.setValue("REDCAP:" + record.getFieldName() + ":" + record.getValue()); - } else { - conceptCd.setName("REDCAP:" + record.getFieldName()); - conceptCd.setValue("REDCAP:" + record.getFieldName()); - } - observationType.setConceptCd(conceptCd); - - observationType.setUploadId(String.valueOf(uploadId)); - - String modifierCd = "@"; - //if (metadata.getFieldType().equals("checkbox")) { - - // modifierCd = record.getValue(); - //} - ModifierCd modifer = new ModifierCd(); - modifer.setName(modifierCd); - modifer.setValue(modifierCd); - observationType.setModifierCd(modifer); - - observationType.setInstanceNum(instance); - - observationType.setObserverCd(observer); - observationType.setSourcesystemCd(setSourcesystemCd); - EventId eventId = new EventId(); - eventId.setSource("REDCAP"); - eventId.setValue("0");//record.getRecordId()); - observationType.setEventId(eventId); - - if (modifierCd.equals("@")) - if ( (metadata.getFieldType().equals("notes") || metadata.getFieldType().equals("descriptive"))) - { - observationType.setValuetypeCd("B"); - blob += record.getValue(); - } else if (metadata.getFieldType().equals("slider") ) { - observationType.setValuetypeCd("N"); - NvalNum value = new NvalNum(); - value.setValue(new BigDecimal(record.getValue())); - observationType.setNvalNum(value); //(record.getValue()); - observationType.setTvalChar("E"); - } else if (metadata.getFieldType().equals("file") ) { - - observationType.setValuetypeCd("B"); - blob += getFile( metadata.getFieldName(), record.record); - } - else if (metadata.getFieldType().equals("text") || metadata.getFieldType().equals("sql")) - { - observationType.setValuetypeCd("T"); - observationType.setTvalChar(record.getValue()); - } - - if (startDateName != null && startDateName.equals(record.getFieldName())) - { - - } - - else if (metadata.getFieldType().equals("date")) { - try { - - String FORMATER = "yyyy-MM-dd"; - - if (metadata.getFieldContent().equals("date_ymd")) - FORMATER = "yyyy-MM-dd"; - else if (metadata.getFieldContent().equals("date_mdy")) - FORMATER = "yyyy-MM-dd"; - else if (metadata.getFieldContent().equals("date_dmy")) - FORMATER = "yyyy-MM-dd"; - else if (metadata.getFieldContent().equals("datetime_ymd")) - FORMATER = "yyyy-MM-dd kk:mm"; - else if (metadata.getFieldContent().equals("datetime_mdy")) - FORMATER = "yyyy-MM-dd kk:mm"; - else if (metadata.getFieldContent().equals("datetime_dmy")) - FORMATER = "yyyy-MM-dd kk:mm"; - else if (metadata.getFieldContent().equals("datetime_seconds_ymd")) - FORMATER = "yyyy-MM-dd kk:mm:ss"; - else if (metadata.getFieldContent().equals("datetime_seconds_mdy")) - FORMATER = "yyyy-MM-dd kk:mm:ss"; - else if (metadata.getFieldContent().equals("datetime_seconds_dmy")) - FORMATER = "yyyy-MM-dd kk:mm:ss"; - - DateFormat format = new SimpleDateFormat(FORMATER); - Date date = format.parse(record.getValue()); - - GregorianCalendar gregorianCalendar = - (GregorianCalendar)GregorianCalendar.getInstance(); - gregorianCalendar.setTime(date); - XMLGregorianCalendar gDateFormatted = - DatatypeFactory.newInstance().newXMLGregorianCalendar(gregorianCalendar); - - observationType.setStartDate(gDateFormatted); - } catch (Exception e3) - { - // Error savind or converting date, switching to Text - blob += "\nError converting Date: " + e3.getMessage(); - observationType.setValuetypeCd("T"); - e3.printStackTrace(); - observationType.setStartDate(startDate); - } - } else { - observationType.setStartDate(startDate); - } - - if (blob.length() > 0) { - BlobType blobType = new BlobType(); - blobType.getContent().add(blob); - observationType.setObservationBlob(blobType); - } - observationFactInsertHandle - .insertObservationFact(observationType); - - } - - } - uploaderDaoFactory.getConceptDAO().createConceptFromTempTable(tempConceptTableName, uploadId); - - uploaderDaoFactory.getObservationDAO().doTempTableMerge(tempObsTableName, uploadId, false); - - // Add to tabel access - List cTableAccess = new ArrayList(); - OntologyDataType e = new OntologyDataType(); - e.setColumnname(surveyForm); - e.setTableCd(surveyForm); - e.setTableName(surveyForm); - e.setLevel(0); - if (isPHI) - { - e.setProtectedAccess("Y"); - e.setOntologyProtection(protectedRole); - - } - else - { - e.setProtectedAccess("N"); - } - e.setFullname(rootOntology); - e.setName(surveyForm); - e.setSynonymCd("N"); - e.setVisualattributes("CA"); - e.setFacttablecolumn("concept_cd"); - e.setDimtablename("concept_dimension"); - e.setColumnname("concept_path"); - e.setColumndatatype("T"); - e.setOperator("LIKE"); - e.setDimcode(rootOntology); - //e.setTooltip("FIX ME"); - e.setDimcode(rootOntology); - cTableAccess.add(e); - - - if (refreshOntology.equalsIgnoreCase("Y")) { - - // Delete old Ontolgy - DeleteChildType deleteChild = new DeleteChildType(); - deleteChild.setName(rootOntology); - deleteChild.setKey("\\\\" + surveyForm + rootOntology ); - deleteChild.setIncludeChildren(true); - CallOntologyUtil.callDeleteChild(deleteChild, - securityType, projectParams.getPath(), - ontologyUrl +"/deleteChild"); - - MetadataLoadType factColumns = CallOntologyUtil.callLoadData("table_access", cTableAccess, - securityType, projectParams.getPath(), - ontologyUrl +"/loadMetadata"); - - // Add children to ontology - - factColumns = CallOntologyUtil.callLoadData(surveyForm, c, - securityType, projectParams.getPath(), - ontologyUrl +"/loadMetadata"); - } - - - uploaderDaoFactory.getObservationDAO().removeTempTable(tempConceptTableName); - uploaderDaoFactory.getObservationDAO().removeTempTable(tempObsTableName); - } - } - - - private String getFile( String fieldType, String recordId) { - CloseableHttpResponse response = null; - String responseStr = null; - Base64.Encoder encoder = Base64.getEncoder(); - - try { - - List apiCall = new ArrayList (); - - apiCall.add(new BasicNameValuePair("token", api)); - apiCall.add(new BasicNameValuePair("content", "file")); - apiCall.add(new BasicNameValuePair("action", "export")); - apiCall.add(new BasicNameValuePair("record", recordId)); - apiCall.add(new BasicNameValuePair("field", fieldType)); - apiCall.add(new BasicNameValuePair("event", "")); - apiCall.add(new BasicNameValuePair("returnFormat", "json")); - - HttpPost httpPost = new HttpPost(redcapApiUrl); - - httpPost.setEntity(new UrlEncodedFormEntity(apiCall)); - httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded"); - - CloseableHttpClient client = HttpClientBuilder.create().build(); - response = client.execute(httpPost); - if (response.getCode() >= 300) { - throw new I2B2Exception(String.format("failure - received a %d for %s.", - response.getCode(), httpPost.toString())); - } - - - HttpEntity entity = response.getEntity(); - InputStream is = entity.getContent(); - byte[] isByte = IOUtils.toByteArray(is); - responseStr = encoder.encodeToString(isByte); - // responseStr = EntityUtils.toString(entity, "UTF-8"); - - - - } catch (Exception e) { - //throw new Exception(e); - } - // Create Table_access - - - return responseStr; - } - - - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ + +package edu.harvard.i2b2.crc.dao.redcap; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.dao.redcap.xml.EnumValues; +import edu.harvard.i2b2.crc.dao.redcap.xml.Val; +import edu.harvard.i2b2.crc.dao.redcap.xml.ValueMetadata; +import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; +import edu.harvard.i2b2.crc.datavo.ontology.DeleteChildType; +import edu.harvard.i2b2.crc.datavo.ontology.MetadataLoadType; +import edu.harvard.i2b2.crc.datavo.ontology.OntologyDataType; +import edu.harvard.i2b2.crc.datavo.ontology.XmlValueType; +import edu.harvard.i2b2.crc.datavo.pdo.BlobType; +import edu.harvard.i2b2.crc.datavo.pdo.ConceptType; +import edu.harvard.i2b2.crc.datavo.pdo.EidType; +import edu.harvard.i2b2.crc.datavo.pdo.ObservationType; +import edu.harvard.i2b2.crc.datavo.pdo.ObservationType.ConceptCd; +import edu.harvard.i2b2.crc.datavo.pdo.ObservationType.EventId; +import edu.harvard.i2b2.crc.datavo.pdo.ObservationType.InstanceNum; +import edu.harvard.i2b2.crc.datavo.pdo.ObservationType.ModifierCd; +import edu.harvard.i2b2.crc.datavo.pdo.ObservationType.NvalNum; +import edu.harvard.i2b2.crc.datavo.pdo.ObservationType.ObserverCd; +import edu.harvard.i2b2.crc.datavo.pdo.PatientIdType; +import edu.harvard.i2b2.crc.datavo.pdo.PidType; +import edu.harvard.i2b2.crc.datavo.pdo.PidType.PatientId; +import edu.harvard.i2b2.crc.datavo.pm.ParamType; +import edu.harvard.i2b2.crc.datavo.pm.ProjectType; +import edu.harvard.i2b2.crc.delegate.ontology.CallOntologyUtil; +import edu.harvard.i2b2.crc.delegate.pm.CallPMUtil; +import edu.harvard.i2b2.crc.loader.dao.ILoaderDAOFactory; +import edu.harvard.i2b2.crc.loader.dao.IUploaderDAOFactory; +import edu.harvard.i2b2.crc.loader.dao.LoaderDAOFactoryHelper; +import edu.harvard.i2b2.crc.loader.dao.ObservationFactInsertHandle; +import edu.harvard.i2b2.crc.loader.dao.TempConceptInsertHandler; +import edu.harvard.i2b2.crc.loader.dao.TempEidInsertHandler; +import edu.harvard.i2b2.crc.loader.dao.TempPidInsertHandler; +import edu.harvard.i2b2.crc.loader.datavo.loader.DataSourceLookup; +import edu.harvard.i2b2.crc.util.Base64; +import edu.harvard.i2b2.crc.util.PMServiceAccountUtil; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + +import org.apache.axis2.AxisFault; +import org.apache.commons.io.IOUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.hc.client5.http.entity.UrlEncodedFormEntity; +import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; +import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; +import org.apache.hc.client5.http.impl.classic.HttpClientBuilder; +import org.apache.hc.core5.http.HttpEntity; +import org.apache.hc.core5.http.HttpStatus; +import org.apache.hc.core5.http.io.entity.EntityUtils; +import org.apache.hc.core5.http.message.BasicNameValuePair; +import org.apache.hc.core5.http.NameValuePair; +import org.apache.hc.client5.http.classic.methods.HttpPost; + +/* +import org.apache.http.HttpEntity; +import org.apache.http.HttpStatus; +import org.apache.http.NameValuePair; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.protocol.HTTP; +import org.apache.http.util.EntityUtils; +*/ +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +import com.google.gson.Gson; + +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.List; +import java.util.Scanner; +import java.util.stream.Stream; + +import jakarta.xml.bind.JAXBContext; +import javax.xml.datatype.DatatypeConfigurationException; +import javax.xml.datatype.DatatypeFactory; +import javax.xml.datatype.XMLGregorianCalendar; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.stream.XMLStreamException; + +import java.math.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Paths; + + +public class RedcapPuller { + protected final Log logger = LogFactory.getLog(getClass()); + protected final Log logesapi = LogFactory.getLog(getClass()); + + private final String FORMAT = "json"; + private final String CONTENT = "record"; + + + String rootOntology = "\\REDCAP\\"; + String setSourcesystemCd = "REDCAP"; + String protectedRole = "DATA_PROT"; + String refreshOntology = "Y"; + boolean isPHI = false; + //String ontologyFormat = "tree"; //tree = For Tree format, popup = For popup with selection + String api = null; + String redcapApiUrl = null; + String startDateName = null; + + public void pullRecordRequest(String redcapUrl, String record, String recordId, String surveyForm, String pid) throws I2B2Exception { + if (record == null || record.isEmpty()) { + throw new I2B2Exception("record is null"); + } + if (redcapUrl == null || redcapUrl.isEmpty()) { + throw new I2B2Exception("url is null"); + } + + APISurveyResponse redcapResult = new APISurveyResponse(); + + try { + redcapApiUrl = redcapUrl + "api/"; + + String responseStr = null; + CloseableHttpResponse response = null; + + SecurityType securityType = PMServiceAccountUtil + .getServiceSecurityType(""); + + ProjectType projectParams = CallPMUtil.callUserProjectRedcap(securityType,pid);// surveyForm); + + DataCollectionInstrumentMetadata[] metadatas = null; + try { + + + for (ParamType projectParam: projectParams.getParam()) + { + if (projectParam.getName().equalsIgnoreCase("REDCAP_TOKEN_PID_" + pid)) // Located in the PM_USER_PARAM + api = projectParam.getValue(); + else if (projectParam.getName().equalsIgnoreCase("REDCAP_ROOT_ONTOLOGY")) + rootOntology = projectParam.getValue(); + else if (projectParam.getName().equalsIgnoreCase("REDCAP_SOURCESYSTEM")) + setSourcesystemCd = projectParam.getValue(); + // else if (projectParam.getName().equalsIgnoreCase("REDCAP_ONTOLOGY_FORMAT")) + // ontologyFormat = projectParam.getValue(); + else if (projectParam.getName().equalsIgnoreCase("REDCAP_PROTECTED_ROLE")) + protectedRole = projectParam.getValue(); + else if (projectParam.getName().equalsIgnoreCase("REDCAP_ONTOLOGY_REFRESH")) + refreshOntology = projectParam.getValue(); + else if (projectParam.getName().equalsIgnoreCase("REDCAP_STARTDATE_NAME")) + startDateName = projectParam.getValue(); + + } + + if (api == null) + throw new I2B2Exception("Project " + surveyForm + " does not have a param called REDCAP_TOKEN_PID_" + pid + " with the token number."); + + if (redcapApiUrl.startsWith("file:")) { + responseStr = readLineByLineJava8( redcapApiUrl.substring(7) ) ; + metadatas = new Gson().fromJson(responseStr, DataCollectionInstrumentMetadata[].class); + if (metadatas != null) { + redcapResult.getMetadata().addAll(Arrays.asList(metadatas)); + } + } else { + List apiCall = new ArrayList (); + apiCall.add(new BasicNameValuePair("token", api)); + apiCall.add(new BasicNameValuePair("content", "metadata")); + apiCall.add(new BasicNameValuePair("format", FORMAT)); + + HttpPost httpPost = new HttpPost(redcapApiUrl); + + httpPost.setEntity(new UrlEncodedFormEntity(apiCall)); + httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded"); + + CloseableHttpClient client = HttpClientBuilder.create().build(); + response = client.execute(httpPost); + //response..getCode() + if (response.getCode() >= 300) { + throw new I2B2Exception(String.format("failure - received a %d for %s.", + response.getCode(), httpPost.toString())); + } + + HttpEntity entity = response.getEntity(); + responseStr = EntityUtils.toString(entity, "UTF-8"); + + if (response.getCode() == HttpStatus.SC_OK) { + metadatas = new Gson().fromJson(responseStr, DataCollectionInstrumentMetadata[].class); + if (metadatas != null) { + redcapResult.getMetadata().addAll(Arrays.asList(metadatas)); + } + } + } + + } catch (Exception e) { + throw new Exception(e); + } + + try { + + List apiCall = new ArrayList (); + apiCall.add(new BasicNameValuePair("token", api)); + apiCall.add(new BasicNameValuePair("content", CONTENT)); + apiCall.add(new BasicNameValuePair("format", FORMAT)); + apiCall.add(new BasicNameValuePair("type", record)); + apiCall.add(new BasicNameValuePair("exportSurveyFields", "true")); + apiCall.add(new BasicNameValuePair("rawOrLabel", "raw")); + apiCall.add(new BasicNameValuePair("exportCheckboxLabel", "true")); + if (surveyForm != null && !surveyForm.isEmpty()) { + apiCall.add(new BasicNameValuePair("forms", surveyForm)); + } + if (recordId != null && !recordId.isEmpty()) { + apiCall.add(new BasicNameValuePair("records", recordId)); + } + //if (eventName != null && !eventName.isEmpty()) { + // apiCall.add(new BasicNameValuePair("events", eventName)); + // } + + HttpPost httpPost = new HttpPost(redcapApiUrl); + + httpPost.setEntity(new UrlEncodedFormEntity(apiCall)); + httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded"); + + CloseableHttpClient client = HttpClientBuilder.create().build(); + response = client.execute(httpPost); + if (response.getCode() >= 300) { + throw new I2B2Exception(String.format("failure - received a %d for %s.", + response.getCode(), httpPost.toString())); + } + + + HttpEntity entity = response.getEntity(); + responseStr = EntityUtils.toString(entity, "UTF-8"); + + + + } catch (Exception e) { + throw new Exception(e); + } + // Create Table_access + + logesapi.debug("Response body: " + responseStr); + + if (response.getCode() == HttpStatus.SC_OK) { + SurveyRecord[] records = new Gson().fromJson(responseStr, SurveyRecord[].class); + insertI2B2(records, redcapResult, surveyForm, projectParams, securityType, metadatas); + + } + + } catch (Exception ie) { + logger.error("Unexpected IO exception", ie); + + } + } + + private static String readLineByLineJava8(String filePath) + { + StringBuilder contentBuilder = new StringBuilder(); + + + /* TODO + try (Stream stream = Files.lines( Paths.get(filePath), StandardCharsets.UTF_8)) + { + stream.forEach(s -> contentBuilder.append(s).append("\n")); + } + catch (IOException e) + { + e.printStackTrace(); + } + */ + + return contentBuilder.toString(); + } + + private void insertI2B2(SurveyRecord[] records, APISurveyResponse redcapResult, String surveyForm, ProjectType projectParams + , SecurityType securityType, DataCollectionInstrumentMetadata[] metadatas ) throws I2B2Exception, DatatypeConfigurationException, AxisFault, XMLStreamException, JAXBUtilException { + if (records != null) { + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + String ontologyUrl = qpUtil + .getCRCPropertyValue(QueryProcessorUtil.ONTOLOGYCELL_ROOT_WS_URL_PROPERTIES); + + + List c = new ArrayList(); + + + redcapResult.getRecords().addAll(Arrays.asList(records)); + + redcapResult.process(); + + DataSourceLookup dataSourceLookup = new DataSourceLookup(); + dataSourceLookup.setProjectPath(projectParams.getId()); + dataSourceLookup.setDomainId(securityType.getDomain()); + dataSourceLookup.setOwnerId(securityType.getUsername()); + + //DataMartLoaderAsyncBeanLocal loader = CRCLoaderUtil.getInstance().getDataMartLoaderBean(); + + + LoaderDAOFactoryHelper daoHelper = new LoaderDAOFactoryHelper( + dataSourceLookup.getDomainId(), dataSourceLookup + .getProjectPath(), dataSourceLookup.getOwnerId()); + ILoaderDAOFactory loaderDaoFactory = daoHelper.getDAOFactory(); + IUploaderDAOFactory uploaderDaoFactory = loaderDaoFactory + .getUpLoaderDAOFactory(); + + + GregorianCalendar gcal = (GregorianCalendar) GregorianCalendar.getInstance(); + XMLGregorianCalendar startDate = DatatypeFactory.newInstance() + .newXMLGregorianCalendar(gcal); + + + + + + + ObserverCd observer = new ObserverCd(); + observer.setName("@"); + observer.setValue("@"); + + InstanceNum instance = new InstanceNum(); + instance.setValue("1"); + + int uploadId = -1; + String tempObsTableName = "TEMP_OBS_MAP_" + gcal.getTime().getDay()+gcal.getTime().getMonth()+gcal.getTime().getYear() + +gcal.getTime().getHours()+gcal.getTime().getMinutes(); + String tempPidTableName = "TEMP_PID_MAP_" + gcal.getTime().getDay()+gcal.getTime().getMonth()+gcal.getTime().getYear() + +gcal.getTime().getHours()+gcal.getTime().getMinutes(); + + String tempEidTableName = "TEMP_EID_MAP_" + gcal.getTime().getDay()+gcal.getTime().getMonth()+gcal.getTime().getYear() + +gcal.getTime().getHours()+gcal.getTime().getMinutes(); + + String tempConceptTableName = "TEMP_CONCEPT_MAP_" + gcal.getTime().getDay()+gcal.getTime().getMonth()+gcal.getTime().getYear() + +gcal.getTime().getHours()+gcal.getTime().getMinutes(); + + uploaderDaoFactory.getPidDAO().createTempTable(tempPidTableName); + uploaderDaoFactory.getEidDAO().createTempTable(tempEidTableName); + uploaderDaoFactory.getObservationDAO().createTempTable(tempObsTableName); + uploaderDaoFactory.getConceptDAO().createTempTable(tempConceptTableName); + + ObservationFactInsertHandle observationFactInsertHandle = uploaderDaoFactory.getObservationDAO() + .createObservationFactInserter(tempObsTableName); + + TempPidInsertHandler pidInsertHandle = uploaderDaoFactory.getPidDAO().createTempPidInsert(tempPidTableName); + + TempEidInsertHandler eidInsertHandle = uploaderDaoFactory.getEidDAO().createTempEidInsert(tempEidTableName); + + TempConceptInsertHandler conceptInsertHandle = uploaderDaoFactory.getConceptDAO().createTempConceptInsert(tempConceptTableName); + //observationFactInsertHandle.c + + if (records.length > 0) { + PidType pidType = new PidType(); + PatientId patientId = new PatientId(); + patientId.setSource("REDCAP"); + patientId.setValue(records[0].getRecordId()); + patientId.setStatus("A"); + patientId.setSourcesystemCd(setSourcesystemCd); + patientId.setDownloadDate(startDate); + patientId.setUpdateDate(startDate); + patientId.setImportDate(startDate); + pidType.setPatientId(patientId); + + pidInsertHandle.insertPid(pidType); + + + EidType eidType = new EidType(); + edu.harvard.i2b2.crc.datavo.pdo.EidType.EventId eventId = new edu.harvard.i2b2.crc.datavo.pdo.EidType.EventId(); + + eventId.setPatientId(records[0].getRecordId()); + eventId.setPatientIdSource("REDCAP"); + eventId.setSourcesystemCd(setSourcesystemCd); + eventId.setStatus("A"); + eventId.setSource("REDCAP"); + eventId.setValue("0"); + eidType.setEventId(eventId); + eidInsertHandle.insertEid(eidType); + uploaderDaoFactory.getPidDAO().createPidFromTempTable(tempPidTableName, uploadId); + uploaderDaoFactory.getEidDAO().createEidFromTempTable(tempEidTableName, uploadId); + uploaderDaoFactory.getObservationDAO().removeTempTable(tempPidTableName); + uploaderDaoFactory.getObservationDAO().removeTempTable(tempEidTableName); + } + + //Create root node in metadata in table_access + OntologyDataType ontologyData = new OntologyDataType(); + ontologyData.setLevel(0); + ontologyData.setFullname(rootOntology); + ontologyData.setName(surveyForm); + ontologyData.setSynonymCd("N"); + ontologyData.setVisualattributes("FAE"); + ontologyData.setFacttablecolumn("concept_cd"); + ontologyData.setDimtablename("concept_dimension"); + ontologyData.setColumnname("concept_path"); + ontologyData.setColumndatatype("T"); + ontologyData.setOperator("LIKE"); + ontologyData.setTooltip(rootOntology); + ontologyData.setDimcode(rootOntology ); + ontologyData.setAppliedPath("@"); + ontologyData.setDownloadDate(startDate); + ontologyData.setUpdateDate(startDate); + ontologyData.setImportDate(startDate); + c.add(ontologyData); + + for (DataCollectionInstrumentMetadata metadata: metadatas) { + if (surveyForm.equalsIgnoreCase(metadata.getFormName())) { + //Check to see if PHI, if so set gloval variable + if (metadata.isPHI()) + isPHI = true; + + + // Insert Concept Dimension + // if ((metadata.isHasEnumOptions() || metadata.isTextOptions())) { + ConceptType conceptType = new ConceptType(); + conceptType.setConceptCd("REDCAP:" + metadata.getFieldName()); + conceptType.setNameChar("REDCAP:" + metadata.getFieldLabel()); + conceptType.setConceptPath(rootOntology + metadata.getFieldName()+ "\\"); + + conceptType.setSourcesystemCd(setSourcesystemCd); + conceptType.setUploadId(String.valueOf(uploadId)); + conceptInsertHandle.insertConcept(conceptType); + + // Insert meta data + ontologyData = new OntologyDataType(); + ontologyData.setLevel(1); + ontologyData.setFullname(rootOntology + metadata.getFieldName()+ "\\"); + ontologyData.setName(metadata.getFieldLabel()); + ontologyData.setSynonymCd("N"); + //if ((metadata.isTextOptions() == true) || (metadata.isHasMultpleOptions() == true)) + + + //if (ontologyFormat.equalsIgnoreCase("popup") + //|| metadata.isHasEnumOptions() == true)) + // (metadata.isHasCheckBoxOptions() == true) + //if ((ontologyFormat.equalsIgnoreCase("tree") && ((metadata.isHasEnumOptions() == true) || (metadata.isHasCheckBoxOptions() == true)))) + if ((metadata.isHasEnumOptions() == true) || (metadata.isHasCheckBoxOptions() == true) ) + ontologyData.setVisualattributes("FAE"); + // else if ((ontologyFormat.equalsIgnoreCase("popup") && (metadata.isHasCheckBoxOptions() == true) )) + // ontologyData.setVisualattributes("FAE"); + else + ontologyData.setVisualattributes("LAE"); + + ontologyData.setBasecode(metadata.getFieldName()); + ontologyData.setFacttablecolumn("concept_cd"); + ontologyData.setDimtablename("concept_dimension"); + ontologyData.setColumnname("concept_path"); + ontologyData.setColumndatatype("T"); + ontologyData.setOperator("LIKE"); + ontologyData.setDimcode(rootOntology + metadata.getFieldName()+ "\\"); + ontologyData.setTooltip(metadata.getFieldName()); + ontologyData.setAppliedPath("@"); + ontologyData.setDownloadDate(startDate); + ontologyData.setUpdateDate(startDate); + ontologyData.setImportDate(startDate); + + if ((metadata.isSliderOptions()) || (metadata.isNoteOptions()) || (metadata.isTextOptions() == true) ) + + { + ValueMetadata metadataxml = new ValueMetadata(); + + metadataxml.setVersion("3.2"); + metadataxml.setCreationDateTime(startDate.toString()); + metadataxml.setTestID(metadata.getFieldName()); + metadataxml.setTestName(metadata.getFieldLabel()); + if (metadata.isTextOptions()) { + metadataxml.setDataType("String"); + + }else if (metadata.isNoteOptions()) { + metadataxml.setDataType("largestring"); + }else if (metadata.isSliderOptions()) { + metadataxml.setDataType("PosInteger"); + metadataxml.setLowofLowValue("1"); + metadataxml.setLowofHighValue("100"); + metadataxml.setHighofHighValue("100"); + metadataxml.setHighofLowValue("1"); + }else { + metadataxml.setDataType("Enum"); + EnumValues enumValues = new EnumValues(); + + + Val[] vals = new Val[metadata.getChoices().length]; + + //for (String enums: metadata.getChoices()) + for (int i=0; i < metadata.getChoices().length; i++) + { + Val val = new Val(); + val.setDescription(metadata.getChoice(i)[1].trim()); + val.setValue(Integer.toString(i+1)); + vals[i] = val; + + } + + enumValues.setVal(vals); + metadataxml.setEnumValues(enumValues); + + } + Element rootElement = null; + String xmlString = ""; + XmlValueType xml = null; + try { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + //dbf.setNamespaceAware(true); + Document doc = dbf.newDocumentBuilder().newDocument(); + + JAXBContext context = JAXBContext.newInstance(metadataxml.getClass()); + context.createMarshaller().marshal(metadataxml, doc); + // Element element = metadataxml; + rootElement = doc.getDocumentElement(); + } catch (Exception e1) { + e1.printStackTrace(); + } + if (rootElement != null) { + xml = new XmlValueType(); + xml.getAny().add(rootElement); + + //if (ontologyFormat.equalsIgnoreCase("popup") || metadata.isHasEnumOptions() == true) + ontologyData.setMetadataxml(xml); + } + } + + //check what way to save metadata + for (int i=0; i < metadata.getChoices().length; i++) + { + //if ((ontologyFormat.equalsIgnoreCase("tree")) )//|| metadata.isHasCheckBoxOptions() == true) + //{ + ConceptType leafType = new ConceptType(); + //String endnode = Integer.toString(i); + + leafType.setConceptCd("REDCAP:" + metadata.getFieldName() + ":" + metadata.getChoice(i)[0].trim()); + try { + leafType.setNameChar("REDCAP:" + metadata.getChoice(i)[1].trim()); + } catch (Exception meta) + { + logger.error("Metadata Issue: " + metadata.getFieldName()); + + } + leafType.setConceptPath(rootOntology + metadata.getFieldName() + "\\" + i+ "\\"); + + leafType.setSourcesystemCd(setSourcesystemCd); + leafType.setUploadId(String.valueOf(uploadId)); + conceptInsertHandle.insertConcept(leafType); + + // Insert meta data + OntologyDataType leafData = new OntologyDataType(); + //ontologyData.setColumnname(surveyForm); + //ontologyData.setTableCd(surveyForm); + //ontologyData.setTableName(surveyForm); + + + + leafData.setLevel(2); + leafData.setFullname(rootOntology + metadata.getFieldName()+ "\\" + i+ "\\"); + leafData.setName(metadata.getChoice(i)[1].trim()); + leafData.setSynonymCd("N"); + leafData.setVisualattributes("LAE"); + leafData.setBasecode(leafType.getConceptCd()); + leafData.setFacttablecolumn("concept_cd"); + leafData.setDimtablename("concept_dimension"); + leafData.setColumnname("concept_path"); + leafData.setColumndatatype("T"); + leafData.setOperator("LIKE"); + leafData.setDimcode(rootOntology + metadata.getFieldName()+ "\\" + i+ "\\"); + leafData.setTooltip(metadata.getFieldName()); + leafData.setAppliedPath("@"); + leafData.setDownloadDate(startDate); + leafData.setUpdateDate(startDate); + leafData.setImportDate(startDate); + + c.add(leafData); + + ///} + } + + + c.add(ontologyData); + + } + } + + + // Save Records to Observation Fact Table + for (SurveyRecord record: records) { + + // get Metadata for record + DataCollectionInstrumentMetadata metadata = redcapResult.getMetadata(record.getFieldName()); + + if (metadata != null) { + String blob = ""; + ObservationType observationType = new ObservationType(); + PatientIdType patid = new PatientIdType(); + patid.setSource("REDCAP"); + patid.setValue(record.getRecordId()); + observationType.setPatientId(patid); + ConceptCd conceptCd = new ConceptCd(); + if ( (metadata.getFieldType().equals("yesno") || metadata.getFieldType().equals("truefalse") || metadata.getFieldType().equals("radio") + || metadata.getFieldType().equals("checkbox") || metadata.getFieldType().equals("dropdown"))) + { + conceptCd.setName("REDCAP:" + record.getFieldName() + ":" + record.getValue()); + conceptCd.setValue("REDCAP:" + record.getFieldName() + ":" + record.getValue()); + } else { + conceptCd.setName("REDCAP:" + record.getFieldName()); + conceptCd.setValue("REDCAP:" + record.getFieldName()); + } + observationType.setConceptCd(conceptCd); + + observationType.setUploadId(String.valueOf(uploadId)); + + String modifierCd = "@"; + //if (metadata.getFieldType().equals("checkbox")) { + + // modifierCd = record.getValue(); + //} + ModifierCd modifer = new ModifierCd(); + modifer.setName(modifierCd); + modifer.setValue(modifierCd); + observationType.setModifierCd(modifer); + + observationType.setInstanceNum(instance); + + observationType.setObserverCd(observer); + observationType.setSourcesystemCd(setSourcesystemCd); + EventId eventId = new EventId(); + eventId.setSource("REDCAP"); + eventId.setValue("0");//record.getRecordId()); + observationType.setEventId(eventId); + + if (modifierCd.equals("@")) + if ( (metadata.getFieldType().equals("notes") || metadata.getFieldType().equals("descriptive"))) + { + observationType.setValuetypeCd("B"); + blob += record.getValue(); + } else if (metadata.getFieldType().equals("slider") ) { + observationType.setValuetypeCd("N"); + NvalNum value = new NvalNum(); + value.setValue(new BigDecimal(record.getValue())); + observationType.setNvalNum(value); //(record.getValue()); + observationType.setTvalChar("E"); + } else if (metadata.getFieldType().equals("file") ) { + + observationType.setValuetypeCd("B"); + blob += getFile( metadata.getFieldName(), record.record); + } + else if (metadata.getFieldType().equals("text") || metadata.getFieldType().equals("sql")) + { + observationType.setValuetypeCd("T"); + observationType.setTvalChar(record.getValue()); + } + + if (startDateName != null && startDateName.equals(record.getFieldName())) + { + + } + + else if (metadata.getFieldType().equals("date")) { + try { + + String FORMATER = "yyyy-MM-dd"; + + if (metadata.getFieldContent().equals("date_ymd")) + FORMATER = "yyyy-MM-dd"; + else if (metadata.getFieldContent().equals("date_mdy")) + FORMATER = "yyyy-MM-dd"; + else if (metadata.getFieldContent().equals("date_dmy")) + FORMATER = "yyyy-MM-dd"; + else if (metadata.getFieldContent().equals("datetime_ymd")) + FORMATER = "yyyy-MM-dd kk:mm"; + else if (metadata.getFieldContent().equals("datetime_mdy")) + FORMATER = "yyyy-MM-dd kk:mm"; + else if (metadata.getFieldContent().equals("datetime_dmy")) + FORMATER = "yyyy-MM-dd kk:mm"; + else if (metadata.getFieldContent().equals("datetime_seconds_ymd")) + FORMATER = "yyyy-MM-dd kk:mm:ss"; + else if (metadata.getFieldContent().equals("datetime_seconds_mdy")) + FORMATER = "yyyy-MM-dd kk:mm:ss"; + else if (metadata.getFieldContent().equals("datetime_seconds_dmy")) + FORMATER = "yyyy-MM-dd kk:mm:ss"; + + DateFormat format = new SimpleDateFormat(FORMATER); + Date date = format.parse(record.getValue()); + + GregorianCalendar gregorianCalendar = + (GregorianCalendar)GregorianCalendar.getInstance(); + gregorianCalendar.setTime(date); + XMLGregorianCalendar gDateFormatted = + DatatypeFactory.newInstance().newXMLGregorianCalendar(gregorianCalendar); + + observationType.setStartDate(gDateFormatted); + } catch (Exception e3) + { + // Error savind or converting date, switching to Text + blob += "\nError converting Date: " + e3.getMessage(); + observationType.setValuetypeCd("T"); + e3.printStackTrace(); + observationType.setStartDate(startDate); + } + } else { + observationType.setStartDate(startDate); + } + + if (blob.length() > 0) { + BlobType blobType = new BlobType(); + blobType.getContent().add(blob); + observationType.setObservationBlob(blobType); + } + observationFactInsertHandle + .insertObservationFact(observationType); + + } + + } + uploaderDaoFactory.getConceptDAO().createConceptFromTempTable(tempConceptTableName, uploadId); + + uploaderDaoFactory.getObservationDAO().doTempTableMerge(tempObsTableName, uploadId, false); + + // Add to tabel access + List cTableAccess = new ArrayList(); + OntologyDataType e = new OntologyDataType(); + e.setColumnname(surveyForm); + e.setTableCd(surveyForm); + e.setTableName(surveyForm); + e.setLevel(0); + if (isPHI) + { + e.setProtectedAccess("Y"); + e.setOntologyProtection(protectedRole); + + } + else + { + e.setProtectedAccess("N"); + } + e.setFullname(rootOntology); + e.setName(surveyForm); + e.setSynonymCd("N"); + e.setVisualattributes("CA"); + e.setFacttablecolumn("concept_cd"); + e.setDimtablename("concept_dimension"); + e.setColumnname("concept_path"); + e.setColumndatatype("T"); + e.setOperator("LIKE"); + e.setDimcode(rootOntology); + //e.setTooltip("FIX ME"); + e.setDimcode(rootOntology); + cTableAccess.add(e); + + + if (refreshOntology.equalsIgnoreCase("Y")) { + + // Delete old Ontolgy + DeleteChildType deleteChild = new DeleteChildType(); + deleteChild.setName(rootOntology); + deleteChild.setKey("\\\\" + surveyForm + rootOntology ); + deleteChild.setIncludeChildren(true); + CallOntologyUtil.callDeleteChild(deleteChild, + securityType, projectParams.getPath(), + ontologyUrl +"/deleteChild"); + + MetadataLoadType factColumns = CallOntologyUtil.callLoadData("table_access", cTableAccess, + securityType, projectParams.getPath(), + ontologyUrl +"/loadMetadata"); + + // Add children to ontology + + factColumns = CallOntologyUtil.callLoadData(surveyForm, c, + securityType, projectParams.getPath(), + ontologyUrl +"/loadMetadata"); + } + + + uploaderDaoFactory.getObservationDAO().removeTempTable(tempConceptTableName); + uploaderDaoFactory.getObservationDAO().removeTempTable(tempObsTableName); + } + } + + + private String getFile( String fieldType, String recordId) { + CloseableHttpResponse response = null; + String responseStr = null; + Base64.Encoder encoder = Base64.getEncoder(); + + try { + + List apiCall = new ArrayList (); + + apiCall.add(new BasicNameValuePair("token", api)); + apiCall.add(new BasicNameValuePair("content", "file")); + apiCall.add(new BasicNameValuePair("action", "export")); + apiCall.add(new BasicNameValuePair("record", recordId)); + apiCall.add(new BasicNameValuePair("field", fieldType)); + apiCall.add(new BasicNameValuePair("event", "")); + apiCall.add(new BasicNameValuePair("returnFormat", "json")); + + HttpPost httpPost = new HttpPost(redcapApiUrl); + + httpPost.setEntity(new UrlEncodedFormEntity(apiCall)); + httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded"); + + CloseableHttpClient client = HttpClientBuilder.create().build(); + response = client.execute(httpPost); + if (response.getCode() >= 300) { + throw new I2B2Exception(String.format("failure - received a %d for %s.", + response.getCode(), httpPost.toString())); + } + + + HttpEntity entity = response.getEntity(); + InputStream is = entity.getContent(); + byte[] isByte = IOUtils.toByteArray(is); + responseStr = encoder.encodeToString(isByte); + // responseStr = EntityUtils.toString(entity, "UTF-8"); + + + + } catch (Exception e) { + //throw new Exception(e); + } + // Create Table_access + + + return responseStr; + } + + + + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/redcap/SurveyRecord.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/redcap/SurveyRecord.java similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/redcap/SurveyRecord.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/redcap/SurveyRecord.java index d2a01a9b..967b79a8 100644 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/redcap/SurveyRecord.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/redcap/SurveyRecord.java @@ -1,58 +1,58 @@ - -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ - -package edu.harvard.i2b2.crc.dao.redcap; - -import com.google.gson.annotations.SerializedName; - -public class SurveyRecord extends DataCollectionInstrument { - - @SerializedName("field_name") - private String fieldName; - - private String value; - - private String modiferCd = "@"; - - public String getModiferCd() { - return modiferCd; - } - - public void setModiferCd(String modiferCd) { - this.modiferCd = modiferCd; - } - - public SurveyRecord() { - super(); - } - - public SurveyRecord(String record, String fieldName, String eventName, String value) { - super(record, eventName); - this.fieldName = fieldName; - this.value = value; - } - - public void setFieldName(String fieldName) { - this.fieldName = fieldName; - } - - public void setValue(String value) { - this.value = value; - } - - public String getFieldName() { - return fieldName; - } - - public String getValue() { - return value; - } - -} + +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ + +package edu.harvard.i2b2.crc.dao.redcap; + +import com.google.gson.annotations.SerializedName; + +public class SurveyRecord extends DataCollectionInstrument { + + @SerializedName("field_name") + private String fieldName; + + private String value; + + private String modiferCd = "@"; + + public String getModiferCd() { + return modiferCd; + } + + public void setModiferCd(String modiferCd) { + this.modiferCd = modiferCd; + } + + public SurveyRecord() { + super(); + } + + public SurveyRecord(String record, String fieldName, String eventName, String value) { + super(record, eventName); + this.fieldName = fieldName; + this.value = value; + } + + public void setFieldName(String fieldName) { + this.fieldName = fieldName; + } + + public void setValue(String value) { + this.value = value; + } + + public String getFieldName() { + return fieldName; + } + + public String getValue() { + return value; + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/redcap/xml/Analysis.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/redcap/xml/Analysis.java similarity index 95% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/redcap/xml/Analysis.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/redcap/xml/Analysis.java index a9198ce3..e8ddd24d 100644 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/redcap/xml/Analysis.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/redcap/xml/Analysis.java @@ -1,58 +1,58 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ - -package edu.harvard.i2b2.crc.dao.redcap.xml; - - -public class Analysis -{ - private String New = ""; - - private String Enums = ""; - - private String Counts = ""; - - public String getNew () - { - return New; - } - - public void setNew (String New) - { - this.New = New; - } - - public String getEnums () - { - return Enums; - } - - public void setEnums (String Enums) - { - this.Enums = Enums; - } - - public String getCounts () - { - return Counts; - } - - public void setCounts (String Counts) - { - this.Counts = Counts; - } - - @Override - public String toString() - { - return "ClassPojo [New = "+New+", Enums = "+Enums+", Counts = "+Counts+"]"; - } -} - +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ + +package edu.harvard.i2b2.crc.dao.redcap.xml; + + +public class Analysis +{ + private String New = ""; + + private String Enums = ""; + + private String Counts = ""; + + public String getNew () + { + return New; + } + + public void setNew (String New) + { + this.New = New; + } + + public String getEnums () + { + return Enums; + } + + public void setEnums (String Enums) + { + this.Enums = Enums; + } + + public String getCounts () + { + return Counts; + } + + public void setCounts (String Counts) + { + this.Counts = Counts; + } + + @Override + public String toString() + { + return "ClassPojo [New = "+New+", Enums = "+Enums+", Counts = "+Counts+"]"; + } +} + \ No newline at end of file diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/redcap/xml/CommentsDeterminingExclusion.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/redcap/xml/CommentsDeterminingExclusion.java similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/redcap/xml/CommentsDeterminingExclusion.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/redcap/xml/CommentsDeterminingExclusion.java index b54c3779..ad907242 100644 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/redcap/xml/CommentsDeterminingExclusion.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/redcap/xml/CommentsDeterminingExclusion.java @@ -1,33 +1,33 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ - -package edu.harvard.i2b2.crc.dao.redcap.xml; - - -public class CommentsDeterminingExclusion -{ -private String Com = ""; - -public String getCom () -{ -return Com; -} - -public void setCom (String Com) -{ -this.Com = Com; -} - -@Override -public String toString() -{ -return "ClassPojo [Com = "+Com+"]"; -} -} - +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ + +package edu.harvard.i2b2.crc.dao.redcap.xml; + + +public class CommentsDeterminingExclusion +{ +private String Com = ""; + +public String getCom () +{ +return Com; +} + +public void setCom (String Com) +{ +this.Com = Com; +} + +@Override +public String toString() +{ +return "ClassPojo [Com = "+Com+"]"; +} +} + diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/redcap/xml/ConvertingUnits.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/redcap/xml/ConvertingUnits.java similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/redcap/xml/ConvertingUnits.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/redcap/xml/ConvertingUnits.java index e9d80662..ab966e8f 100644 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/redcap/xml/ConvertingUnits.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/redcap/xml/ConvertingUnits.java @@ -1,45 +1,45 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ - -package edu.harvard.i2b2.crc.dao.redcap.xml; - - -public class ConvertingUnits -{ -private String MultiplyingFactor = ""; - -private String Units = ""; - -public String getMultiplyingFactor () -{ -return MultiplyingFactor; -} - -public void setMultiplyingFactor (String MultiplyingFactor) -{ -this.MultiplyingFactor = MultiplyingFactor; -} - -public String getUnits () -{ -return Units; -} - -public void setUnits (String Units) -{ -this.Units = Units; -} - -@Override -public String toString() -{ -return "ClassPojo [MultiplyingFactor = "+MultiplyingFactor+", Units = "+Units+"]"; -} -} - +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ + +package edu.harvard.i2b2.crc.dao.redcap.xml; + + +public class ConvertingUnits +{ +private String MultiplyingFactor = ""; + +private String Units = ""; + +public String getMultiplyingFactor () +{ +return MultiplyingFactor; +} + +public void setMultiplyingFactor (String MultiplyingFactor) +{ +this.MultiplyingFactor = MultiplyingFactor; +} + +public String getUnits () +{ +return Units; +} + +public void setUnits (String Units) +{ +this.Units = Units; +} + +@Override +public String toString() +{ +return "ClassPojo [MultiplyingFactor = "+MultiplyingFactor+", Units = "+Units+"]"; +} +} + diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/redcap/xml/EnumValues.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/redcap/xml/EnumValues.java similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/redcap/xml/EnumValues.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/redcap/xml/EnumValues.java index dd8a403a..a116ccbe 100644 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/redcap/xml/EnumValues.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/redcap/xml/EnumValues.java @@ -1,34 +1,34 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ - -package edu.harvard.i2b2.crc.dao.redcap.xml; - -import jakarta.xml.bind.annotation.XmlElement; - -public class EnumValues -{ - @XmlElement(name = "Val") - private Val[] Val; - - public Val[] getVal () - { - return Val; - } - - public void setVal (Val[] Val) - { - this.Val = Val; - } - - @Override - public String toString() - { - return "ClassPojo [Val = "+Val+"]"; - } +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ + +package edu.harvard.i2b2.crc.dao.redcap.xml; + +import jakarta.xml.bind.annotation.XmlElement; + +public class EnumValues +{ + @XmlElement(name = "Val") + private Val[] Val; + + public Val[] getVal () + { + return Val; + } + + public void setVal (Val[] Val) + { + this.Val = Val; + } + + @Override + public String toString() + { + return "ClassPojo [Val = "+Val+"]"; + } } \ No newline at end of file diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/redcap/xml/MetadataXml.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/redcap/xml/MetadataXml.java similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/redcap/xml/MetadataXml.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/redcap/xml/MetadataXml.java index c6130b12..503de7df 100644 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/redcap/xml/MetadataXml.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/redcap/xml/MetadataXml.java @@ -1,32 +1,32 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ - -package edu.harvard.i2b2.crc.dao.redcap.xml; - - -public class MetadataXml -{ - private ValueMetadata ValueMetadata; - - public ValueMetadata getValueMetadata () - { - return ValueMetadata; - } - - public void setValueMetadata (ValueMetadata ValueMetadata) - { - this.ValueMetadata = ValueMetadata; - } - - @Override - public String toString() - { - return "ClassPojo [ValueMetadata = "+ValueMetadata+"]"; - } +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ + +package edu.harvard.i2b2.crc.dao.redcap.xml; + + +public class MetadataXml +{ + private ValueMetadata ValueMetadata; + + public ValueMetadata getValueMetadata () + { + return ValueMetadata; + } + + public void setValueMetadata (ValueMetadata ValueMetadata) + { + this.ValueMetadata = ValueMetadata; + } + + @Override + public String toString() + { + return "ClassPojo [ValueMetadata = "+ValueMetadata+"]"; + } } \ No newline at end of file diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/redcap/xml/UnitValues.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/redcap/xml/UnitValues.java similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/redcap/xml/UnitValues.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/redcap/xml/UnitValues.java index 013a7c2e..6ba5148b 100644 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/redcap/xml/UnitValues.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/redcap/xml/UnitValues.java @@ -1,69 +1,69 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ - -package edu.harvard.i2b2.crc.dao.redcap.xml; - -public class UnitValues -{ - private String NormalUnits = ""; - - private String ExcludingUnits = ""; - - private ConvertingUnits ConvertingUnits = new ConvertingUnits(); - - private String EqualUnits = ""; - - public String getNormalUnits () - { - return NormalUnits; - } - - public void setNormalUnits (String NormalUnits) - { - this.NormalUnits = NormalUnits; - } - - public String getExcludingUnits () - { - return ExcludingUnits; - } - - public void setExcludingUnits (String ExcludingUnits) - { - this.ExcludingUnits = ExcludingUnits; - } - - public ConvertingUnits getConvertingUnits () - { - return ConvertingUnits; - } - - public void setConvertingUnits (ConvertingUnits ConvertingUnits) - { - this.ConvertingUnits = ConvertingUnits; - } - - public String getEqualUnits () - { - return EqualUnits; - } - - public void setEqualUnits (String EqualUnits) - { - this.EqualUnits = EqualUnits; - } - - @Override - public String toString() - { - return "ClassPojo [NormalUnits = "+NormalUnits+", ExcludingUnits = "+ExcludingUnits+", ConvertingUnits = "+ConvertingUnits+", EqualUnits = "+EqualUnits+"]"; - } -} - +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ + +package edu.harvard.i2b2.crc.dao.redcap.xml; + +public class UnitValues +{ + private String NormalUnits = ""; + + private String ExcludingUnits = ""; + + private ConvertingUnits ConvertingUnits = new ConvertingUnits(); + + private String EqualUnits = ""; + + public String getNormalUnits () + { + return NormalUnits; + } + + public void setNormalUnits (String NormalUnits) + { + this.NormalUnits = NormalUnits; + } + + public String getExcludingUnits () + { + return ExcludingUnits; + } + + public void setExcludingUnits (String ExcludingUnits) + { + this.ExcludingUnits = ExcludingUnits; + } + + public ConvertingUnits getConvertingUnits () + { + return ConvertingUnits; + } + + public void setConvertingUnits (ConvertingUnits ConvertingUnits) + { + this.ConvertingUnits = ConvertingUnits; + } + + public String getEqualUnits () + { + return EqualUnits; + } + + public void setEqualUnits (String EqualUnits) + { + this.EqualUnits = EqualUnits; + } + + @Override + public String toString() + { + return "ClassPojo [NormalUnits = "+NormalUnits+", ExcludingUnits = "+ExcludingUnits+", ConvertingUnits = "+ConvertingUnits+", EqualUnits = "+EqualUnits+"]"; + } +} + \ No newline at end of file diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/redcap/xml/Val.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/redcap/xml/Val.java similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/redcap/xml/Val.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/redcap/xml/Val.java index 229881e1..85e94dbd 100644 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/redcap/xml/Val.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/redcap/xml/Val.java @@ -1,57 +1,57 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ - -package edu.harvard.i2b2.crc.dao.redcap.xml; - -import jakarta.xml.bind.annotation.XmlAccessType; -import jakarta.xml.bind.annotation.XmlAccessorType; -import jakarta.xml.bind.annotation.XmlAttribute; -import jakarta.xml.bind.annotation.XmlType; -import jakarta.xml.bind.annotation.XmlValue; - -@XmlAccessorType(XmlAccessType.FIELD) -/*@XmlType(name = "Val", propOrder = { - "value" -}) -*/ -public class Val -{ - @XmlAttribute - private String description = ""; - - @XmlValue - private String value = ""; - - public String getDescription () - { - return description; - } - - public void setDescription (String description) - { - this.description = description; - } - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } - @Override - public String toString() - { - return "ClassPojo [description = "+description+", content = "+value+"]"; - } - - -} - +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ + +package edu.harvard.i2b2.crc.dao.redcap.xml; + +import jakarta.xml.bind.annotation.XmlAccessType; +import jakarta.xml.bind.annotation.XmlAccessorType; +import jakarta.xml.bind.annotation.XmlAttribute; +import jakarta.xml.bind.annotation.XmlType; +import jakarta.xml.bind.annotation.XmlValue; + +@XmlAccessorType(XmlAccessType.FIELD) +/*@XmlType(name = "Val", propOrder = { + "value" +}) +*/ +public class Val +{ + @XmlAttribute + private String description = ""; + + @XmlValue + private String value = ""; + + public String getDescription () + { + return description; + } + + public void setDescription (String description) + { + this.description = description; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + @Override + public String toString() + { + return "ClassPojo [description = "+description+", content = "+value+"]"; + } + + +} + \ No newline at end of file diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/redcap/xml/ValueMetadata.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/redcap/xml/ValueMetadata.java similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/redcap/xml/ValueMetadata.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/redcap/xml/ValueMetadata.java index b9cc988d..010e5cb7 100644 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/redcap/xml/ValueMetadata.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/redcap/xml/ValueMetadata.java @@ -1,288 +1,288 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ - -package edu.harvard.i2b2.crc.dao.redcap.xml; - -import jakarta.xml.bind.annotation.XmlAccessType; -import jakarta.xml.bind.annotation.XmlAccessorType; -import jakarta.xml.bind.annotation.XmlElement; -import jakarta.xml.bind.annotation.XmlRootElement; -import jakarta.xml.bind.annotation.XmlType; - -@XmlRootElement (name = "ValueMetadata") -@XmlAccessorType(XmlAccessType.FIELD) -public class ValueMetadata -{ - private CommentsDeterminingExclusion CommentsDeterminingExclusion; - - @XmlElement(name = "TestName") - private String TestName; - - @XmlElement(name = "LowofHighValue") - private String LowofHighValue; - - @XmlElement(name = "Oktousevalues") - private String Oktousevalues = ""; - - @XmlElement(name = "UnitValues") - private UnitValues UnitValues; - - @XmlElement(name = "HighofToxicValue") - private String HighofToxicValue; - - @XmlElement(name = "HighofHighValue") - private String HighofHighValue; - - @XmlElement(name = "EnumValues") - private EnumValues EnumValues; - - @XmlElement(name = "LowofToxicValue") - private String LowofToxicValue; - - @XmlElement(name = "TestID") - private String TestID; - - @XmlElement(name = "MaxStringLength") - private String MaxStringLength =""; - - @XmlElement(name = "HighofLowValue") - private String HighofLowValue; - - @XmlElement(name = "CreationDateTime") - private String CreationDateTime; - - @XmlElement(name = "Version") - private String version; - - @XmlElement(name = "Analysis") - private Analysis Analysis; - - @XmlElement(name = "LowofLowValue") - private String LowofLowValue; - - @XmlElement(name = "Loinc") - private String Loinc; - - @XmlElement(name = "DataType") - private String DataType; - - @XmlElement(name = "CodeType") - private String CodeType; - - @XmlElement(name = "Flagstouse") - private String Flagstouse =""; - - public CommentsDeterminingExclusion getCommentsDeterminingExclusion () - { - return CommentsDeterminingExclusion; - } - - public void setCommentsDeterminingExclusion (CommentsDeterminingExclusion CommentsDeterminingExclusion) - { - this.CommentsDeterminingExclusion = CommentsDeterminingExclusion; - } - - public String getTestName () - { - return TestName; - } - - public void setTestName (String TestName) - { - this.TestName = TestName; - } - - public String getLowofHighValue () - { - return LowofHighValue; - } - - public void setLowofHighValue (String LowofHighValue) - { - this.LowofHighValue = LowofHighValue; - } - - public String getOktousevalues () - { - return Oktousevalues; - } - - public void setOktousevalues (String Oktousevalues) - { - this.Oktousevalues = Oktousevalues; - } - - public UnitValues getUnitValues () - { - return UnitValues; - } - - public void setUnitValues (UnitValues UnitValues) - { - this.UnitValues = UnitValues; - } - - public String getHighofToxicValue () - { - return HighofToxicValue; - } - - public void setHighofToxicValue (String HighofToxicValue) - { - this.HighofToxicValue = HighofToxicValue; - } - - public String getHighofHighValue () - { - return HighofHighValue; - } - - public void setHighofHighValue (String HighofHighValue) - { - this.HighofHighValue = HighofHighValue; - } - - public EnumValues getEnumValues () - { - return EnumValues; - } - - public void setEnumValues (EnumValues EnumValues) - { - this.EnumValues = EnumValues; - } - - public String getLowofToxicValue () - { - return LowofToxicValue; - } - - public void setLowofToxicValue (String LowofToxicValue) - { - this.LowofToxicValue = LowofToxicValue; - } - - public String getTestID () - { - return TestID; - } - - public void setTestID (String TestID) - { - this.TestID = TestID; - } - - public String getMaxStringLength () - { - return MaxStringLength; - } - - public void setMaxStringLength (String MaxStringLength) - { - this.MaxStringLength = MaxStringLength; - } - - public String getHighofLowValue () - { - return HighofLowValue; - } - - public void setHighofLowValue (String HighofLowValue) - { - this.HighofLowValue = HighofLowValue; - } - - public String getCreationDateTime () - { - return CreationDateTime; - } - - public void setCreationDateTime (String CreationDateTime) - { - this.CreationDateTime = CreationDateTime; - } - - public String getVersion () - { - return version; - } - - public void setVersion (String Version) - { - this.version = Version; - } - - public Analysis getAnalysis () - { - return Analysis; - } - - public void setAnalysis (Analysis Analysis) - { - this.Analysis = Analysis; - } - - public String getLowofLowValue () - { - return LowofLowValue; - } - - public void setLowofLowValue (String LowofLowValue) - { - this.LowofLowValue = LowofLowValue; - } - - public String getLoinc () - { - return Loinc; - } - - public void setLoinc (String Loinc) - { - this.Loinc = Loinc; - } - - public String getDataType () - { - return DataType; - } - - public void setDataType (String DataType) - { - this.DataType = DataType; - } - - public String getCodeType () - { - return CodeType; - } - - public void setCodeType (String CodeType) - { - this.CodeType = CodeType; - } - - public String getFlagstouse () - { - return Flagstouse; - } - - public void setFlagstouse (String Flagstouse) - { - this.Flagstouse = Flagstouse; - } - - @Override - public String toString() - { - return "ClassPojo [CommentsDeterminingExclusion = "+CommentsDeterminingExclusion+", TestName = "+TestName+", LowofHighValue = "+LowofHighValue+", Oktousevalues = "+Oktousevalues+", UnitValues = "+UnitValues+", HighofToxicValue = "+HighofToxicValue+", HighofHighValue = "+HighofHighValue+", EnumValues = "+EnumValues+", LowofToxicValue = "+LowofToxicValue+", TestID = "+TestID+", MaxStringLength = "+MaxStringLength+", HighofLowValue = "+HighofLowValue+", CreationDateTime = "+CreationDateTime+", Version = "+version+", Analysis = "+Analysis+", LowofLowValue = "+LowofLowValue+", Loinc = "+Loinc+", DataType = "+DataType+", CodeType = "+CodeType+", Flagstouse = "+Flagstouse+"]"; - } -} - +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ + +package edu.harvard.i2b2.crc.dao.redcap.xml; + +import jakarta.xml.bind.annotation.XmlAccessType; +import jakarta.xml.bind.annotation.XmlAccessorType; +import jakarta.xml.bind.annotation.XmlElement; +import jakarta.xml.bind.annotation.XmlRootElement; +import jakarta.xml.bind.annotation.XmlType; + +@XmlRootElement (name = "ValueMetadata") +@XmlAccessorType(XmlAccessType.FIELD) +public class ValueMetadata +{ + private CommentsDeterminingExclusion CommentsDeterminingExclusion; + + @XmlElement(name = "TestName") + private String TestName; + + @XmlElement(name = "LowofHighValue") + private String LowofHighValue; + + @XmlElement(name = "Oktousevalues") + private String Oktousevalues = ""; + + @XmlElement(name = "UnitValues") + private UnitValues UnitValues; + + @XmlElement(name = "HighofToxicValue") + private String HighofToxicValue; + + @XmlElement(name = "HighofHighValue") + private String HighofHighValue; + + @XmlElement(name = "EnumValues") + private EnumValues EnumValues; + + @XmlElement(name = "LowofToxicValue") + private String LowofToxicValue; + + @XmlElement(name = "TestID") + private String TestID; + + @XmlElement(name = "MaxStringLength") + private String MaxStringLength =""; + + @XmlElement(name = "HighofLowValue") + private String HighofLowValue; + + @XmlElement(name = "CreationDateTime") + private String CreationDateTime; + + @XmlElement(name = "Version") + private String version; + + @XmlElement(name = "Analysis") + private Analysis Analysis; + + @XmlElement(name = "LowofLowValue") + private String LowofLowValue; + + @XmlElement(name = "Loinc") + private String Loinc; + + @XmlElement(name = "DataType") + private String DataType; + + @XmlElement(name = "CodeType") + private String CodeType; + + @XmlElement(name = "Flagstouse") + private String Flagstouse =""; + + public CommentsDeterminingExclusion getCommentsDeterminingExclusion () + { + return CommentsDeterminingExclusion; + } + + public void setCommentsDeterminingExclusion (CommentsDeterminingExclusion CommentsDeterminingExclusion) + { + this.CommentsDeterminingExclusion = CommentsDeterminingExclusion; + } + + public String getTestName () + { + return TestName; + } + + public void setTestName (String TestName) + { + this.TestName = TestName; + } + + public String getLowofHighValue () + { + return LowofHighValue; + } + + public void setLowofHighValue (String LowofHighValue) + { + this.LowofHighValue = LowofHighValue; + } + + public String getOktousevalues () + { + return Oktousevalues; + } + + public void setOktousevalues (String Oktousevalues) + { + this.Oktousevalues = Oktousevalues; + } + + public UnitValues getUnitValues () + { + return UnitValues; + } + + public void setUnitValues (UnitValues UnitValues) + { + this.UnitValues = UnitValues; + } + + public String getHighofToxicValue () + { + return HighofToxicValue; + } + + public void setHighofToxicValue (String HighofToxicValue) + { + this.HighofToxicValue = HighofToxicValue; + } + + public String getHighofHighValue () + { + return HighofHighValue; + } + + public void setHighofHighValue (String HighofHighValue) + { + this.HighofHighValue = HighofHighValue; + } + + public EnumValues getEnumValues () + { + return EnumValues; + } + + public void setEnumValues (EnumValues EnumValues) + { + this.EnumValues = EnumValues; + } + + public String getLowofToxicValue () + { + return LowofToxicValue; + } + + public void setLowofToxicValue (String LowofToxicValue) + { + this.LowofToxicValue = LowofToxicValue; + } + + public String getTestID () + { + return TestID; + } + + public void setTestID (String TestID) + { + this.TestID = TestID; + } + + public String getMaxStringLength () + { + return MaxStringLength; + } + + public void setMaxStringLength (String MaxStringLength) + { + this.MaxStringLength = MaxStringLength; + } + + public String getHighofLowValue () + { + return HighofLowValue; + } + + public void setHighofLowValue (String HighofLowValue) + { + this.HighofLowValue = HighofLowValue; + } + + public String getCreationDateTime () + { + return CreationDateTime; + } + + public void setCreationDateTime (String CreationDateTime) + { + this.CreationDateTime = CreationDateTime; + } + + public String getVersion () + { + return version; + } + + public void setVersion (String Version) + { + this.version = Version; + } + + public Analysis getAnalysis () + { + return Analysis; + } + + public void setAnalysis (Analysis Analysis) + { + this.Analysis = Analysis; + } + + public String getLowofLowValue () + { + return LowofLowValue; + } + + public void setLowofLowValue (String LowofLowValue) + { + this.LowofLowValue = LowofLowValue; + } + + public String getLoinc () + { + return Loinc; + } + + public void setLoinc (String Loinc) + { + this.Loinc = Loinc; + } + + public String getDataType () + { + return DataType; + } + + public void setDataType (String DataType) + { + this.DataType = DataType; + } + + public String getCodeType () + { + return CodeType; + } + + public void setCodeType (String CodeType) + { + this.CodeType = CodeType; + } + + public String getFlagstouse () + { + return Flagstouse; + } + + public void setFlagstouse (String Flagstouse) + { + this.Flagstouse = Flagstouse; + } + + @Override + public String toString() + { + return "ClassPojo [CommentsDeterminingExclusion = "+CommentsDeterminingExclusion+", TestName = "+TestName+", LowofHighValue = "+LowofHighValue+", Oktousevalues = "+Oktousevalues+", UnitValues = "+UnitValues+", HighofToxicValue = "+HighofToxicValue+", HighofHighValue = "+HighofHighValue+", EnumValues = "+EnumValues+", LowofToxicValue = "+LowofToxicValue+", TestID = "+TestID+", MaxStringLength = "+MaxStringLength+", HighofLowValue = "+HighofLowValue+", CreationDateTime = "+CreationDateTime+", Version = "+version+", Analysis = "+Analysis+", LowofLowValue = "+LowofLowValue+", Loinc = "+Loinc+", DataType = "+DataType+", CodeType = "+CodeType+", Flagstouse = "+Flagstouse+"]"; + } +} + \ No newline at end of file diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/role/IPriviledgeDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/role/IPriviledgeDao.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/role/IPriviledgeDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/role/IPriviledgeDao.java index cf8b3626..437d5013 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/role/IPriviledgeDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/role/IPriviledgeDao.java @@ -1,22 +1,22 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.role; - -import java.util.List; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.crc.datavo.db.QtPriviledge; - -public interface IPriviledgeDao { - public QtPriviledge getPriviledgeByProtectionLabel(String protectionLabel) - throws I2B2DAOException; - - public List getPriviledgeByPluginId(String pluginId) - throws I2B2DAOException; -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.role; + +import java.util.List; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.crc.datavo.db.QtPriviledge; + +public interface IPriviledgeDao { + public QtPriviledge getPriviledgeByProtectionLabel(String protectionLabel) + throws I2B2DAOException; + + public List getPriviledgeByPluginId(String pluginId) + throws I2B2DAOException; +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/role/PriviledgeSpringDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/role/PriviledgeSpringDao.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/role/PriviledgeSpringDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/role/PriviledgeSpringDao.java index 6c263bfd..1915fd0d --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/role/PriviledgeSpringDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/role/PriviledgeSpringDao.java @@ -1,80 +1,80 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.role; - -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.List; - -import javax.sql.DataSource; - -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.RowMapper; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.db.QtPriviledge; - -public class PriviledgeSpringDao extends CRCDAO implements IPriviledgeDao { - - JdbcTemplate jdbcTemplate = null; - - QtPriviledgeRowMapper priviledgeMapper = new QtPriviledgeRowMapper(); - - private DataSourceLookup dataSourceLookup = null; - - public PriviledgeSpringDao(DataSource dataSource, - DataSourceLookup dataSourceLookup) { - setDataSource(dataSource); - setDbSchemaName(dataSourceLookup.getFullSchema()); - jdbcTemplate = new JdbcTemplate(dataSource); - this.dataSourceLookup = dataSourceLookup; - - } - - @Override - public QtPriviledge getPriviledgeByProtectionLabel(String protectionLabel) - throws I2B2DAOException { - String lookupSql = "select * from " - + getDbSchemaName() - + "qt_privilege where protection_label_cd = ? and plugin_id is NULL"; - QtPriviledge priviledgeRow = (QtPriviledge) jdbcTemplate - .queryForObject(lookupSql, new Object[] { protectionLabel }, - priviledgeMapper); - return priviledgeRow; - - } - - @Override - public List getPriviledgeByPluginId(String pluginId) - throws I2B2DAOException { - String lookupSql = "select * from " - + getDbSchemaName() - + "qt_privilege where plugin_id = ? and protection_label_cd is NULL"; - List priviledgeRow = jdbcTemplate.query(lookupSql, - new Object[] { pluginId }, priviledgeMapper); - return priviledgeRow; - } - - private static class QtPriviledgeRowMapper implements RowMapper { - - @Override - public Object mapRow(ResultSet rs, int rowNum) throws SQLException { - QtPriviledge priviledge = new QtPriviledge(); - priviledge - .setProtectionLabelCd(rs.getString("PROTECTION_LABEL_CD")); - priviledge.setDataProtCd(rs.getString("DATAPROT_CD")); - priviledge.setHivemgmtCd(rs.getString("HIVEMGMT_CD")); - priviledge.setPluginId(rs.getString("PLUGIN_ID")); - return priviledge; - } - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.role; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.List; + +import javax.sql.DataSource; + +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.RowMapper; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.db.QtPriviledge; + +public class PriviledgeSpringDao extends CRCDAO implements IPriviledgeDao { + + JdbcTemplate jdbcTemplate = null; + + QtPriviledgeRowMapper priviledgeMapper = new QtPriviledgeRowMapper(); + + private DataSourceLookup dataSourceLookup = null; + + public PriviledgeSpringDao(DataSource dataSource, + DataSourceLookup dataSourceLookup) { + setDataSource(dataSource); + setDbSchemaName(dataSourceLookup.getFullSchema()); + jdbcTemplate = new JdbcTemplate(dataSource); + this.dataSourceLookup = dataSourceLookup; + + } + + @Override + public QtPriviledge getPriviledgeByProtectionLabel(String protectionLabel) + throws I2B2DAOException { + String lookupSql = "select * from " + + getDbSchemaName() + + "qt_privilege where protection_label_cd = ? and plugin_id is NULL"; + QtPriviledge priviledgeRow = (QtPriviledge) jdbcTemplate + .queryForObject(lookupSql, new Object[] { protectionLabel }, + priviledgeMapper); + return priviledgeRow; + + } + + @Override + public List getPriviledgeByPluginId(String pluginId) + throws I2B2DAOException { + String lookupSql = "select * from " + + getDbSchemaName() + + "qt_privilege where plugin_id = ? and protection_label_cd is NULL"; + List priviledgeRow = jdbcTemplate.query(lookupSql, + new Object[] { pluginId }, priviledgeMapper); + return priviledgeRow; + } + + private static class QtPriviledgeRowMapper implements RowMapper { + + @Override + public Object mapRow(ResultSet rs, int rowNum) throws SQLException { + QtPriviledge priviledge = new QtPriviledge(); + priviledge + .setProtectionLabelCd(rs.getString("PROTECTION_LABEL_CD")); + priviledge.setDataProtCd(rs.getString("DATAPROT_CD")); + priviledge.setHivemgmtCd(rs.getString("HIVEMGMT_CD")); + priviledge.setPluginId(rs.getString("PLUGIN_ID")); + return priviledge; + } + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/AnalysisPluginSpringDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/AnalysisPluginSpringDao.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/AnalysisPluginSpringDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/AnalysisPluginSpringDao.java index bc94a307..fcd3d301 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/AnalysisPluginSpringDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/AnalysisPluginSpringDao.java @@ -1,187 +1,187 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder; - -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.List; - -import javax.sql.DataSource; - -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.RowMapper; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.db.QtAnalysisPlugin; - -public class AnalysisPluginSpringDao extends CRCDAO implements - IAnalysisPluginDao { - - JdbcTemplate jdbcTemplate = null; - - QtAnalysisPluginRowMapper analysisPluginMapper = new QtAnalysisPluginRowMapper(); - - private DataSourceLookup dataSourceLookup = null; - - public AnalysisPluginSpringDao(DataSource dataSource, - DataSourceLookup dataSourceLookup) { - setDataSource(dataSource); - setDbSchemaName(dataSourceLookup.getFullSchema()); - jdbcTemplate = new JdbcTemplate(dataSource); - this.dataSourceLookup = dataSourceLookup; - - } - - /** - * Return plugin metadata - * - * @param analysisName - * @param projectId - * @return - */ - @Override - public List getAnalysisPluginMetadata( - String analysisName, String projectId) { - List analysisPluginList = null; - - // if the analysis name is ALL, then return all the plugin - if (analysisName != null && analysisName.equalsIgnoreCase("ALL")) { - String lookupSql = "select * from " + getDbSchemaName() - + "qt_analysis_plugin where group_id = ? or group_id = '@'"; - analysisPluginList = jdbcTemplate.query(lookupSql, - new Object[] { projectId }, analysisPluginMapper); - } else { - // if not get analysisname and the project = projectId or - // project='@' - String lookupSql = "select * from " - + getDbSchemaName() - + "qt_analysis_plugin where plugin_name = ? and (group_id = ? or group_id = '@')"; - analysisPluginList = jdbcTemplate.query(lookupSql, new Object[] { - analysisName, projectId }, analysisPluginMapper); - } - return analysisPluginList; - } - - @Override - public QtAnalysisPlugin lookupAnalysisPluginByNameVersionProject( - String analysisName, String version, String projectId) - throws I2B2DAOException { - List analysisPluginList = null; - boolean getMaxVersionFlag = false; - String maxVersionCd = null, errorMsg = ""; - QtAnalysisPlugin analysisPlugin = null; - - if (version == null) { - getMaxVersionFlag = true; - } - analysisPluginList = getAnalysisPluginByNameAndProject(analysisName, - projectId); - // if the list is empty, then try with group_id = @s - if (analysisPluginList.size() < 1) { - projectId = "@"; - analysisPluginList = getAnalysisPluginByNameAndProject( - analysisName, projectId); - } - if (analysisPluginList.size() > 0) { - if (getMaxVersionFlag) { - maxVersionCd = getMaxAnalysisPluginVersion(analysisName, - projectId); - version = maxVersionCd; - } - if (version == null) { - analysisPluginList = getAnalysisPluginByNameAndProject( - analysisName, projectId); - } else { - analysisPluginList = getAnalysisPluginByNameVersionProject( - analysisName, version, projectId); - } - } - if (analysisPluginList.size() > 0) { - analysisPlugin = analysisPluginList.get(0); - } else { - errorMsg = "Could not match plugin by name[" + analysisName - + "] + version [" + version + "] and group [" + projectId - + "]"; - throw new I2B2DAOException(errorMsg); - } - - return analysisPlugin; - - } - - private List getAnalysisPluginByNameAndProject( - String analysisName, String projectId) { - String lookupSql = "select * from " + getDbSchemaName() - + "qt_analysis_plugin where plugin_name = ? and group_id = ?"; - List analysisPluginList = jdbcTemplate.query( - lookupSql, new Object[] { analysisName, projectId }, - analysisPluginMapper); - return analysisPluginList; - } - - private String getMaxAnalysisPluginVersion(String analysisName, - String projectId) { - String lookupSql = "select max(version_cd) as maxversion from " - + getDbSchemaName() - + "qt_analysis_plugin where plugin_name = ? and group_id = ?"; - String maxVersion = (String) jdbcTemplate.queryForObject(lookupSql, - new Object[] { analysisName, projectId }, String.class); - return maxVersion; - } - - private List getAnalysisPluginByNameVersionProject( - String analysisName, String version, String projectId) { - String lookupSql = "select * from " - + getDbSchemaName() - + "qt_analysis_plugin where plugin_name = ? and version_cd = ? and group_id = ?"; - List analysisPluginList = jdbcTemplate.query( - lookupSql, new Object[] { analysisName, version, projectId }, - analysisPluginMapper); - return analysisPluginList; - } - - @Override - public QtAnalysisPlugin getAnalysisPluginById(int analysisId) - throws I2B2DAOException { - String lookupSql = "select * from " + getDbSchemaName() - + "qt_analysis_plugin where plugin_id = ?"; - QtAnalysisPlugin analysisPlugin = (QtAnalysisPlugin) jdbcTemplate - .queryForObject(lookupSql, new Object[] { analysisId }, - analysisPluginMapper); - return analysisPlugin; - } - - private static class QtAnalysisPluginRowMapper implements RowMapper { - - @Override - public Object mapRow(ResultSet rs, int rowNum) throws SQLException { - QtAnalysisPlugin analysisPlugin = new QtAnalysisPlugin(); - analysisPlugin.setPluginId(rs.getString("PLUGIN_ID")); - analysisPlugin.setPluginName(rs.getString("PLUGIN_NAME")); - analysisPlugin.setDescription(rs.getString("DESCRIPTION")); - analysisPlugin.setVersion(rs.getString("VERSION_CD")); - analysisPlugin.setCommandOptionCd(rs.getString("COMMANDOPTION_CD")); - analysisPlugin.setParameterInfo(rs.getString("PARAMETER_INFO")); - analysisPlugin.setParameterInfoXsd(rs - .getString("PARAMETER_INFO_XSD")); - analysisPlugin.setCommandLine(rs.getString("COMMAND_LINE")); - analysisPlugin.setWorkingFolder(rs.getString("WORKING_FOLDER")); - analysisPlugin.setPluginIcon(rs.getString("PLUGIN_ICON")); - analysisPlugin.setStatusId(rs.getString("STATUS_CD")); - analysisPlugin.setUserId(rs.getString("USER_ID")); - analysisPlugin.setGroupId(rs.getString("GROUP_ID")); - analysisPlugin.setCreateDate(rs.getTimestamp("CREATE_DATE")); - analysisPlugin.setUpdateDate(rs.getTimestamp("UPDATE_DATE")); - return analysisPlugin; - } - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.List; + +import javax.sql.DataSource; + +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.RowMapper; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.db.QtAnalysisPlugin; + +public class AnalysisPluginSpringDao extends CRCDAO implements + IAnalysisPluginDao { + + JdbcTemplate jdbcTemplate = null; + + QtAnalysisPluginRowMapper analysisPluginMapper = new QtAnalysisPluginRowMapper(); + + private DataSourceLookup dataSourceLookup = null; + + public AnalysisPluginSpringDao(DataSource dataSource, + DataSourceLookup dataSourceLookup) { + setDataSource(dataSource); + setDbSchemaName(dataSourceLookup.getFullSchema()); + jdbcTemplate = new JdbcTemplate(dataSource); + this.dataSourceLookup = dataSourceLookup; + + } + + /** + * Return plugin metadata + * + * @param analysisName + * @param projectId + * @return + */ + @Override + public List getAnalysisPluginMetadata( + String analysisName, String projectId) { + List analysisPluginList = null; + + // if the analysis name is ALL, then return all the plugin + if (analysisName != null && analysisName.equalsIgnoreCase("ALL")) { + String lookupSql = "select * from " + getDbSchemaName() + + "qt_analysis_plugin where group_id = ? or group_id = '@'"; + analysisPluginList = jdbcTemplate.query(lookupSql, + new Object[] { projectId }, analysisPluginMapper); + } else { + // if not get analysisname and the project = projectId or + // project='@' + String lookupSql = "select * from " + + getDbSchemaName() + + "qt_analysis_plugin where plugin_name = ? and (group_id = ? or group_id = '@')"; + analysisPluginList = jdbcTemplate.query(lookupSql, new Object[] { + analysisName, projectId }, analysisPluginMapper); + } + return analysisPluginList; + } + + @Override + public QtAnalysisPlugin lookupAnalysisPluginByNameVersionProject( + String analysisName, String version, String projectId) + throws I2B2DAOException { + List analysisPluginList = null; + boolean getMaxVersionFlag = false; + String maxVersionCd = null, errorMsg = ""; + QtAnalysisPlugin analysisPlugin = null; + + if (version == null) { + getMaxVersionFlag = true; + } + analysisPluginList = getAnalysisPluginByNameAndProject(analysisName, + projectId); + // if the list is empty, then try with group_id = @s + if (analysisPluginList.size() < 1) { + projectId = "@"; + analysisPluginList = getAnalysisPluginByNameAndProject( + analysisName, projectId); + } + if (analysisPluginList.size() > 0) { + if (getMaxVersionFlag) { + maxVersionCd = getMaxAnalysisPluginVersion(analysisName, + projectId); + version = maxVersionCd; + } + if (version == null) { + analysisPluginList = getAnalysisPluginByNameAndProject( + analysisName, projectId); + } else { + analysisPluginList = getAnalysisPluginByNameVersionProject( + analysisName, version, projectId); + } + } + if (analysisPluginList.size() > 0) { + analysisPlugin = analysisPluginList.get(0); + } else { + errorMsg = "Could not match plugin by name[" + analysisName + + "] + version [" + version + "] and group [" + projectId + + "]"; + throw new I2B2DAOException(errorMsg); + } + + return analysisPlugin; + + } + + private List getAnalysisPluginByNameAndProject( + String analysisName, String projectId) { + String lookupSql = "select * from " + getDbSchemaName() + + "qt_analysis_plugin where plugin_name = ? and group_id = ?"; + List analysisPluginList = jdbcTemplate.query( + lookupSql, new Object[] { analysisName, projectId }, + analysisPluginMapper); + return analysisPluginList; + } + + private String getMaxAnalysisPluginVersion(String analysisName, + String projectId) { + String lookupSql = "select max(version_cd) as maxversion from " + + getDbSchemaName() + + "qt_analysis_plugin where plugin_name = ? and group_id = ?"; + String maxVersion = (String) jdbcTemplate.queryForObject(lookupSql, + new Object[] { analysisName, projectId }, String.class); + return maxVersion; + } + + private List getAnalysisPluginByNameVersionProject( + String analysisName, String version, String projectId) { + String lookupSql = "select * from " + + getDbSchemaName() + + "qt_analysis_plugin where plugin_name = ? and version_cd = ? and group_id = ?"; + List analysisPluginList = jdbcTemplate.query( + lookupSql, new Object[] { analysisName, version, projectId }, + analysisPluginMapper); + return analysisPluginList; + } + + @Override + public QtAnalysisPlugin getAnalysisPluginById(int analysisId) + throws I2B2DAOException { + String lookupSql = "select * from " + getDbSchemaName() + + "qt_analysis_plugin where plugin_id = ?"; + QtAnalysisPlugin analysisPlugin = (QtAnalysisPlugin) jdbcTemplate + .queryForObject(lookupSql, new Object[] { analysisId }, + analysisPluginMapper); + return analysisPlugin; + } + + private static class QtAnalysisPluginRowMapper implements RowMapper { + + @Override + public Object mapRow(ResultSet rs, int rowNum) throws SQLException { + QtAnalysisPlugin analysisPlugin = new QtAnalysisPlugin(); + analysisPlugin.setPluginId(rs.getString("PLUGIN_ID")); + analysisPlugin.setPluginName(rs.getString("PLUGIN_NAME")); + analysisPlugin.setDescription(rs.getString("DESCRIPTION")); + analysisPlugin.setVersion(rs.getString("VERSION_CD")); + analysisPlugin.setCommandOptionCd(rs.getString("COMMANDOPTION_CD")); + analysisPlugin.setParameterInfo(rs.getString("PARAMETER_INFO")); + analysisPlugin.setParameterInfoXsd(rs + .getString("PARAMETER_INFO_XSD")); + analysisPlugin.setCommandLine(rs.getString("COMMAND_LINE")); + analysisPlugin.setWorkingFolder(rs.getString("WORKING_FOLDER")); + analysisPlugin.setPluginIcon(rs.getString("PLUGIN_ICON")); + analysisPlugin.setStatusId(rs.getString("STATUS_CD")); + analysisPlugin.setUserId(rs.getString("USER_ID")); + analysisPlugin.setGroupId(rs.getString("GROUP_ID")); + analysisPlugin.setCreateDate(rs.getTimestamp("CREATE_DATE")); + analysisPlugin.setUpdateDate(rs.getTimestamp("UPDATE_DATE")); + return analysisPlugin; + } + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/CRCTimeOutException.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/CRCTimeOutException.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/CRCTimeOutException.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/CRCTimeOutException.java index 5580dd7c..d752e6e2 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/CRCTimeOutException.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/CRCTimeOutException.java @@ -1,41 +1,41 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; - -public class CRCTimeOutException extends I2B2DAOException { - - /** - * - */ - private static final long serialVersionUID = 1L; - - - public CRCTimeOutException() { - } - - /** - * Constructor that takes message and the exception as inputs. - * @param message - * @param e - */ - public CRCTimeOutException(String message, Exception e) { - super(message, e); - } - - /** - * Constructor that takes message as input. - * @param message - */ - public CRCTimeOutException(String message) { - super(message); - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; + +public class CRCTimeOutException extends I2B2DAOException { + + /** + * + */ + private static final long serialVersionUID = 1L; + + + public CRCTimeOutException() { + } + + /** + * Constructor that takes message and the exception as inputs. + * @param message + * @param e + */ + public CRCTimeOutException(String message, Exception e) { + super(message, e); + } + + /** + * Constructor that takes message as input. + * @param message + */ + public CRCTimeOutException(String message) { + super(message); + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/CancelStatementRunner.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/CancelStatementRunner.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/CancelStatementRunner.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/CancelStatementRunner.java index 45a1f2c1..925defa5 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/CancelStatementRunner.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/CancelStatementRunner.java @@ -1,74 +1,74 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder; - -import java.sql.SQLException; -import java.sql.Statement; - -/** - * Thread class to cancel the long running sql. - */ -public class CancelStatementRunner implements Runnable { - - // default timeout three minutes - int transactionTimeout = 0; - Statement stmt = null; - boolean sqlFinishedFlag = false; - - /** - * Constructor - * - * @param stmt - * @param transactionTimeout - */ - public CancelStatementRunner(Statement stmt, int transactionTimeout) { - this.stmt = stmt; - this.transactionTimeout = transactionTimeout; - - } - - public boolean getSqlFinishedFlag() { - return this.sqlFinishedFlag; - } - - public void setSqlFinishedFlag() { - this.sqlFinishedFlag = true; - } - - @Override - public void run() { - long currentTime = System.currentTimeMillis(); - long finalTime = currentTime + transactionTimeout * 1000L; - while (currentTime < finalTime) { - currentTime = System.currentTimeMillis(); - // t.wait(transactionTimeout); - - try { - // wait for sec before checking - Thread.sleep(1000); - } catch (InterruptedException e) { - // ignore this interrupted message - ; - } - } - try { - // cancel the stmt if the sql did not complete - if (this.sqlFinishedFlag == false && stmt != null) { - stmt.cancel(); - } - } catch (SQLException e) { - - // if (e.getMessage().indexOf("The query was canceled.") > -1) { - // timeoutFlag = true; - // } - } - - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder; + +import java.sql.SQLException; +import java.sql.Statement; + +/** + * Thread class to cancel the long running sql. + */ +public class CancelStatementRunner implements Runnable { + + // default timeout three minutes + int transactionTimeout = 0; + Statement stmt = null; + boolean sqlFinishedFlag = false; + + /** + * Constructor + * + * @param stmt + * @param transactionTimeout + */ + public CancelStatementRunner(Statement stmt, int transactionTimeout) { + this.stmt = stmt; + this.transactionTimeout = transactionTimeout; + + } + + public boolean getSqlFinishedFlag() { + return this.sqlFinishedFlag; + } + + public void setSqlFinishedFlag() { + this.sqlFinishedFlag = true; + } + + @Override + public void run() { + long currentTime = System.currentTimeMillis(); + long finalTime = currentTime + transactionTimeout * 1000L; + while (currentTime < finalTime) { + currentTime = System.currentTimeMillis(); + // t.wait(transactionTimeout); + + try { + // wait for sec before checking + Thread.sleep(1000); + } catch (InterruptedException e) { + // ignore this interrupted message + ; + } + } + try { + // cancel the stmt if the sql did not complete + if (this.sqlFinishedFlag == false && stmt != null) { + stmt.cancel(); + } + } catch (SQLException e) { + + // if (e.getMessage().indexOf("The query was canceled.") > -1) { + // timeoutFlag = true; + // } + } + + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/CheckSkipTempTable.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/CheckSkipTempTable.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/CheckSkipTempTable.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/CheckSkipTempTable.java index 95075b1a..96980373 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/CheckSkipTempTable.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/CheckSkipTempTable.java @@ -1,164 +1,164 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder; - -import java.util.Iterator; -import java.util.List; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.crc.datavo.db.QtQueryResultType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ItemType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.PanelType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.PanelType.TotalItemOccurrences; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionRequestType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultOutputOptionListType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultOutputOptionType; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - -public class CheckSkipTempTable { - - private static Log log = LogFactory.getLog(CheckSkipTempTable.class); - - public CheckSkipTempTable() { - - } - - public boolean getSkipTempTable(QueryDefinitionRequestType queryDefRequestType, ResultOutputOptionListType resultOutputList ) { - boolean patientCountResultTypeFlag = false; - boolean notMorethanOneResultType = false, samePanelTiming = true, itemWithStandardConcept = true; - boolean totOccurencesMoreThanOne = false, accuracyScaleFlag = false; - boolean totConceptCount = true, panelInvert = false; - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - int maxConceptCount = 40; - - try { - String maxConceptCountStr = qpUtil.getCRCPropertyValue(QueryProcessorUtil.SINGLEPANEL_SKIPTEMPTABLE_MAXCONCEPT_PROPERTIES); - if (maxConceptCountStr != null) { - maxConceptCount = Integer.parseInt(maxConceptCountStr); - } else { - log.info("Setfinder query without temp table defaulting [" + QueryProcessorUtil.SINGLEPANEL_SKIPTEMPTABLE_MAXCONCEPT_PROPERTIES + "] to 40 "); - } - } catch (I2B2Exception i2b2Ex) { - log.info("Setfinder query without temp table defaulting [" + QueryProcessorUtil.SINGLEPANEL_SKIPTEMPTABLE_MAXCONCEPT_PROPERTIES + "] to 40 "); - } - - //skip table disabled in version 1.7 - try { - String queryGeneratorVersion = qpUtil - .getCRCPropertyValue("edu.harvard.i2b2.crc.setfinder.querygenerator.version"); - if (queryGeneratorVersion==null||queryGeneratorVersion.equalsIgnoreCase("1.7")) - return false; - } catch (I2B2Exception e) { - return false; - } - - //check query def query timing - if (queryDefRequestType.getQueryDefinition().getQueryTiming() != null) { - if (queryDefRequestType.getQueryDefinition().getQueryTiming().trim().length()>0) { - if (!queryDefRequestType.getQueryDefinition().getQueryTiming().equalsIgnoreCase("ANY")) { - log.debug("Setfinder query without temp table [Querydefinition's query timing is not ANY]"); - return false; - } - } - } - - //check if all panel are same timing and the concept in the panel are regular concepts - String prevPanelTiming = null, currPanelTiming = null; - List panelList = queryDefRequestType.getQueryDefinition().getPanel(); - int conceptCount = 0; - for (Iterator iterator = panelList.iterator(); iterator.hasNext();) { - PanelType panelType = iterator.next(); - TotalItemOccurrences totOcc = panelType.getTotalItemOccurrences(); - - if (totOcc != null && totOcc.getValue()>1) { - totOccurencesMoreThanOne = true; - log.debug("Setfinder query without temp table panel's total occurences greater than 1 [ " + totOcc.getValue() + " ]"); - break; - } - - - /*int accuracyScale = panelType.getPanelAccuracyScale(); - if (accuracyScale > 0) { - accuracyScaleFlag = true; - log.debug("Setfinder query without temp table panel's accuracy scale greater than 1 [ " + accuracyScale + " ]"); - break; - }*/ - - //check if the panel timing is ANY - currPanelTiming = panelType.getPanelTiming(); - if (currPanelTiming != null && currPanelTiming.trim().length()>0) { - if (!currPanelTiming.equalsIgnoreCase("ANY")) { - log.debug("Setfinder query without temp table the panel timing not ANY, it is [" + currPanelTiming + "]"); - samePanelTiming = false; - break; - } - } - - int invert = panelType.getInvert(); - if (invert > 0 ) { - log.debug("Setfinder query without temp table the panel invert is ON"); - panelInvert = true; - break; - } - - - - //check if the item in the panel is not special item - if (panelType.getItem() != null) { - List itemList = panelType.getItem(); - for (Iterator itemIterator = itemList.iterator();itemIterator.hasNext();) { - conceptCount++; - ItemType item = itemIterator.next(); - if (!item.getItemKey().trim().startsWith("\\")) { - log.debug("Setfinder query without temp table special item check [" + item.getItemKey() + "]"); - itemWithStandardConcept = false; - break; - } - - //check if the max concept count is reached - if (conceptCount>maxConceptCount) { - totConceptCount = false; - log.debug("Setfinder query without temp table reached the max concept count maxCount [" + maxConceptCount + " ]"); - } - } - } - - - - } - - //check if the result list has only the patient count xml - if (resultOutputList != null && resultOutputList.getResultOutput() != null) { - if (resultOutputList.getResultOutput().size()<=1) { - notMorethanOneResultType = true; - } - - for (Iterator iterator = resultOutputList.getResultOutput().iterator();iterator.hasNext();) { - ResultOutputOptionType resultOutputType = iterator.next(); - if (resultOutputType.getName().equalsIgnoreCase(QtQueryResultType.PATIENT_COUNT_XML)) { - patientCountResultTypeFlag = true; - break; - } - } - } - - - if (patientCountResultTypeFlag && notMorethanOneResultType && itemWithStandardConcept && samePanelTiming && totConceptCount && - !totOccurencesMoreThanOne && !panelInvert && !accuracyScaleFlag) { - log.info("Setfinder query without temp table is [true]"); - return true; - } else { - log.debug("Setfinder query without temp table [false]"); - return false; - } - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder; + +import java.util.Iterator; +import java.util.List; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.crc.datavo.db.QtQueryResultType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ItemType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.PanelType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.PanelType.TotalItemOccurrences; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionRequestType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultOutputOptionListType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultOutputOptionType; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + +public class CheckSkipTempTable { + + private static Log log = LogFactory.getLog(CheckSkipTempTable.class); + + public CheckSkipTempTable() { + + } + + public boolean getSkipTempTable(QueryDefinitionRequestType queryDefRequestType, ResultOutputOptionListType resultOutputList ) { + boolean patientCountResultTypeFlag = false; + boolean notMorethanOneResultType = false, samePanelTiming = true, itemWithStandardConcept = true; + boolean totOccurencesMoreThanOne = false, accuracyScaleFlag = false; + boolean totConceptCount = true, panelInvert = false; + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + int maxConceptCount = 40; + + try { + String maxConceptCountStr = qpUtil.getCRCPropertyValue(QueryProcessorUtil.SINGLEPANEL_SKIPTEMPTABLE_MAXCONCEPT_PROPERTIES); + if (maxConceptCountStr != null) { + maxConceptCount = Integer.parseInt(maxConceptCountStr); + } else { + log.info("Setfinder query without temp table defaulting [" + QueryProcessorUtil.SINGLEPANEL_SKIPTEMPTABLE_MAXCONCEPT_PROPERTIES + "] to 40 "); + } + } catch (I2B2Exception i2b2Ex) { + log.info("Setfinder query without temp table defaulting [" + QueryProcessorUtil.SINGLEPANEL_SKIPTEMPTABLE_MAXCONCEPT_PROPERTIES + "] to 40 "); + } + + //skip table disabled in version 1.7 + try { + String queryGeneratorVersion = qpUtil + .getCRCPropertyValue("edu.harvard.i2b2.crc.setfinder.querygenerator.version"); + if (queryGeneratorVersion==null||queryGeneratorVersion.equalsIgnoreCase("1.7")) + return false; + } catch (I2B2Exception e) { + return false; + } + + //check query def query timing + if (queryDefRequestType.getQueryDefinition().getQueryTiming() != null) { + if (queryDefRequestType.getQueryDefinition().getQueryTiming().trim().length()>0) { + if (!queryDefRequestType.getQueryDefinition().getQueryTiming().equalsIgnoreCase("ANY")) { + log.debug("Setfinder query without temp table [Querydefinition's query timing is not ANY]"); + return false; + } + } + } + + //check if all panel are same timing and the concept in the panel are regular concepts + String prevPanelTiming = null, currPanelTiming = null; + List panelList = queryDefRequestType.getQueryDefinition().getPanel(); + int conceptCount = 0; + for (Iterator iterator = panelList.iterator(); iterator.hasNext();) { + PanelType panelType = iterator.next(); + TotalItemOccurrences totOcc = panelType.getTotalItemOccurrences(); + + if (totOcc != null && totOcc.getValue()>1) { + totOccurencesMoreThanOne = true; + log.debug("Setfinder query without temp table panel's total occurences greater than 1 [ " + totOcc.getValue() + " ]"); + break; + } + + + /*int accuracyScale = panelType.getPanelAccuracyScale(); + if (accuracyScale > 0) { + accuracyScaleFlag = true; + log.debug("Setfinder query without temp table panel's accuracy scale greater than 1 [ " + accuracyScale + " ]"); + break; + }*/ + + //check if the panel timing is ANY + currPanelTiming = panelType.getPanelTiming(); + if (currPanelTiming != null && currPanelTiming.trim().length()>0) { + if (!currPanelTiming.equalsIgnoreCase("ANY")) { + log.debug("Setfinder query without temp table the panel timing not ANY, it is [" + currPanelTiming + "]"); + samePanelTiming = false; + break; + } + } + + int invert = panelType.getInvert(); + if (invert > 0 ) { + log.debug("Setfinder query without temp table the panel invert is ON"); + panelInvert = true; + break; + } + + + + //check if the item in the panel is not special item + if (panelType.getItem() != null) { + List itemList = panelType.getItem(); + for (Iterator itemIterator = itemList.iterator();itemIterator.hasNext();) { + conceptCount++; + ItemType item = itemIterator.next(); + if (!item.getItemKey().trim().startsWith("\\")) { + log.debug("Setfinder query without temp table special item check [" + item.getItemKey() + "]"); + itemWithStandardConcept = false; + break; + } + + //check if the max concept count is reached + if (conceptCount>maxConceptCount) { + totConceptCount = false; + log.debug("Setfinder query without temp table reached the max concept count maxCount [" + maxConceptCount + " ]"); + } + } + } + + + + } + + //check if the result list has only the patient count xml + if (resultOutputList != null && resultOutputList.getResultOutput() != null) { + if (resultOutputList.getResultOutput().size()<=1) { + notMorethanOneResultType = true; + } + + for (Iterator iterator = resultOutputList.getResultOutput().iterator();iterator.hasNext();) { + ResultOutputOptionType resultOutputType = iterator.next(); + if (resultOutputType.getName().equalsIgnoreCase(QtQueryResultType.PATIENT_COUNT_XML)) { + patientCountResultTypeFlag = true; + break; + } + } + } + + + if (patientCountResultTypeFlag && notMorethanOneResultType && itemWithStandardConcept && samePanelTiming && totConceptCount && + !totOccurencesMoreThanOne && !panelInvert && !accuracyScaleFlag) { + log.info("Setfinder query without temp table is [true]"); + return true; + } else { + log.debug("Setfinder query without temp table [false]"); + return false; + } + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/EncounterSetCollectionSpringDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/EncounterSetCollectionSpringDao.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/EncounterSetCollectionSpringDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/EncounterSetCollectionSpringDao.java index f88604d3..95035a55 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/EncounterSetCollectionSpringDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/EncounterSetCollectionSpringDao.java @@ -1,179 +1,179 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao.setfinder; - -import java.sql.PreparedStatement; -import java.sql.SQLException; -import java.util.Arrays; - -import javax.sql.DataSource; - -import org.springframework.jdbc.core.BatchPreparedStatementSetter; -import org.springframework.jdbc.core.JdbcTemplate; - -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.db.QtPatientEncCollection; -import edu.harvard.i2b2.crc.datavo.db.QtPatientSetCollection; -import edu.harvard.i2b2.crc.datavo.db.QtQueryResultInstance; - -/** - * Class to support batch inserts of patients to PatientSetCollection This class - * uses single Session to persist all the patients to collection. To have - * limited memory usage, it will flush and clear the session manually for every - * 1000 inserts. $Id: PatientSetCollectionDao.java,v 1.4 2007/08/31 14:44:26 - * rk903 Exp $ - * - * @author rkuttan - * @see QtPatientSetCollection - */ -public class EncounterSetCollectionSpringDao extends CRCDAO implements - IEncounterSetCollectionDao { - /** patient set collection index * */ - private long setIndex = 0; - private int batchDataIndex = 0; - private JdbcTemplate jdbcTemplate = null; - private String insert_sql = ""; - - QtPatientEncCollection[] patientEncColl = null; - /** master table for patient set collection * */ - QtQueryResultInstance resultInstance = null; - String resultInstanceId = null; - private static final int INITIAL_ARRAY_SIZE = 1100; - private DataSourceLookup dataSourceLookup = null; - - private SQLServerSequenceDAO sqlServerSequenceDao = null; - - /** - * Construc with patientset id Initialize hibernate session and creates - * Query reuslt instance class - * - * @param patientSetId - */ - public EncounterSetCollectionSpringDao(DataSource dataSource, - DataSourceLookup dataSourceLookup) { - setDataSource(dataSource); - setDbSchemaName(dataSourceLookup.getFullSchema()); - jdbcTemplate = new JdbcTemplate(dataSource); - this.dataSourceLookup = dataSourceLookup; - - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE)) { - insert_sql = "insert into " - + getDbSchemaName() - + "qt_patient_enc_collection(patient_enc_coll_id,result_instance_id,set_index,patient_num,encounter_num) values (" - + getDbSchemaName() + "QT_SQ_QPER_PECID.nextval,?,?,?,?)"; - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER) || dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) { - insert_sql = "insert into " - + getDbSchemaName() - + "qt_patient_enc_collection(result_instance_id,set_index,patient_num,encounter_num) values (?,?,?,?)"; - } - sqlServerSequenceDao = new SQLServerSequenceDAO(dataSource, - dataSourceLookup); - resultInstance = new QtQueryResultInstance(); - patientEncColl = new QtPatientEncCollection[INITIAL_ARRAY_SIZE]; - - } - - @Override - public void createPatientEncCollection(String resultInstanceId) { - resultInstance = new QtQueryResultInstance(); - resultInstance.setResultInstanceId(resultInstanceId); - - } - - @Override - public String getResultInstanceId() { - return resultInstance.getResultInstanceId(); - } - - /** - * function to add patient to patient set without out creating new db - * session - * - * @param patientId - */ - @Override - public void addEncounter(long encounterId, long patientId) { - setIndex++; - - QtPatientEncCollection collElement = new QtPatientEncCollection(); - int patientSetCollId = 0; - collElement.setPatientId(patientId); - collElement.setEncounterId(encounterId); - collElement.setQtQueryResultInstance(resultInstance); - collElement.setSetIndex(setIndex); - - patientEncColl[batchDataIndex++] = collElement; - - if ((setIndex % 1000) == 0) { - InsertStatementSetter batchSetter = new InsertStatementSetter( - patientEncColl, batchDataIndex); - jdbcTemplate.batchUpdate(insert_sql, batchSetter); - - Arrays.fill(patientEncColl, null); - batchDataIndex = 0; - } - } - - /** - * Call this function at the end. i.e. after loading all patient with - * addPatient function, finally call this function to clear session - */ - @Override - public void flush() { - InsertStatementSetter batchSetter = new InsertStatementSetter( - patientEncColl, batchDataIndex); - jdbcTemplate.batchUpdate(insert_sql, batchSetter); - Arrays.fill(patientEncColl, null); - batchDataIndex = 0; - setIndex = 0; - } - - class InsertStatementSetter implements BatchPreparedStatementSetter { - - private QtPatientEncCollection[] data; - private int batchSize = 0; - - public InsertStatementSetter(QtPatientEncCollection[] data, - int batchSize) { - this.data = data; - this.batchSize = batchSize; - } - - @Override - public int getBatchSize() { - return batchSize; - } - - // this is called for each row - @Override - public void setValues(PreparedStatement ps, int i) throws SQLException { - - // ps.setLong(1, data[i].getPatientSetCollId()); // set first value - ps.setInt(1, Integer.parseInt(data[i].getQtQueryResultInstance() - .getResultInstanceId())); - ps.setLong(2, data[i].getSetIndex()); - ps.setLong(3, data[i].getPatientId()); - ps.setLong(4, data[i].getEncounterId()); - - } - - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao.setfinder; + +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.Arrays; + +import javax.sql.DataSource; + +import org.springframework.jdbc.core.BatchPreparedStatementSetter; +import org.springframework.jdbc.core.JdbcTemplate; + +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.db.QtPatientEncCollection; +import edu.harvard.i2b2.crc.datavo.db.QtPatientSetCollection; +import edu.harvard.i2b2.crc.datavo.db.QtQueryResultInstance; + +/** + * Class to support batch inserts of patients to PatientSetCollection This class + * uses single Session to persist all the patients to collection. To have + * limited memory usage, it will flush and clear the session manually for every + * 1000 inserts. $Id: PatientSetCollectionDao.java,v 1.4 2007/08/31 14:44:26 + * rk903 Exp $ + * + * @author rkuttan + * @see QtPatientSetCollection + */ +public class EncounterSetCollectionSpringDao extends CRCDAO implements + IEncounterSetCollectionDao { + /** patient set collection index * */ + private long setIndex = 0; + private int batchDataIndex = 0; + private JdbcTemplate jdbcTemplate = null; + private String insert_sql = ""; + + QtPatientEncCollection[] patientEncColl = null; + /** master table for patient set collection * */ + QtQueryResultInstance resultInstance = null; + String resultInstanceId = null; + private static final int INITIAL_ARRAY_SIZE = 1100; + private DataSourceLookup dataSourceLookup = null; + + private SQLServerSequenceDAO sqlServerSequenceDao = null; + + /** + * Construc with patientset id Initialize hibernate session and creates + * Query reuslt instance class + * + * @param patientSetId + */ + public EncounterSetCollectionSpringDao(DataSource dataSource, + DataSourceLookup dataSourceLookup) { + setDataSource(dataSource); + setDbSchemaName(dataSourceLookup.getFullSchema()); + jdbcTemplate = new JdbcTemplate(dataSource); + this.dataSourceLookup = dataSourceLookup; + + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.ORACLE)) { + insert_sql = "insert into " + + getDbSchemaName() + + "qt_patient_enc_collection(patient_enc_coll_id,result_instance_id,set_index,patient_num,encounter_num) values (" + + getDbSchemaName() + "QT_SQ_QPER_PECID.nextval,?,?,?,?)"; + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER) || dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) { + insert_sql = "insert into " + + getDbSchemaName() + + "qt_patient_enc_collection(result_instance_id,set_index,patient_num,encounter_num) values (?,?,?,?)"; + } + sqlServerSequenceDao = new SQLServerSequenceDAO(dataSource, + dataSourceLookup); + resultInstance = new QtQueryResultInstance(); + patientEncColl = new QtPatientEncCollection[INITIAL_ARRAY_SIZE]; + + } + + @Override + public void createPatientEncCollection(String resultInstanceId) { + resultInstance = new QtQueryResultInstance(); + resultInstance.setResultInstanceId(resultInstanceId); + + } + + @Override + public String getResultInstanceId() { + return resultInstance.getResultInstanceId(); + } + + /** + * function to add patient to patient set without out creating new db + * session + * + * @param patientId + */ + @Override + public void addEncounter(long encounterId, long patientId) { + setIndex++; + + QtPatientEncCollection collElement = new QtPatientEncCollection(); + int patientSetCollId = 0; + collElement.setPatientId(patientId); + collElement.setEncounterId(encounterId); + collElement.setQtQueryResultInstance(resultInstance); + collElement.setSetIndex(setIndex); + + patientEncColl[batchDataIndex++] = collElement; + + if ((setIndex % 1000) == 0) { + InsertStatementSetter batchSetter = new InsertStatementSetter( + patientEncColl, batchDataIndex); + jdbcTemplate.batchUpdate(insert_sql, batchSetter); + + Arrays.fill(patientEncColl, null); + batchDataIndex = 0; + } + } + + /** + * Call this function at the end. i.e. after loading all patient with + * addPatient function, finally call this function to clear session + */ + @Override + public void flush() { + InsertStatementSetter batchSetter = new InsertStatementSetter( + patientEncColl, batchDataIndex); + jdbcTemplate.batchUpdate(insert_sql, batchSetter); + Arrays.fill(patientEncColl, null); + batchDataIndex = 0; + setIndex = 0; + } + + class InsertStatementSetter implements BatchPreparedStatementSetter { + + private QtPatientEncCollection[] data; + private int batchSize = 0; + + public InsertStatementSetter(QtPatientEncCollection[] data, + int batchSize) { + this.data = data; + this.batchSize = batchSize; + } + + @Override + public int getBatchSize() { + return batchSize; + } + + // this is called for each row + @Override + public void setValues(PreparedStatement ps, int i) throws SQLException { + + // ps.setLong(1, data[i].getPatientSetCollId()); // set first value + ps.setInt(1, Integer.parseInt(data[i].getQtQueryResultInstance() + .getResultInstanceId())); + ps.setLong(2, data[i].getSetIndex()); + ps.setLong(3, data[i].getPatientId()); + ps.setLong(4, data[i].getEncounterId()); + + } + + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/GaussianBoxMuller.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/GaussianBoxMuller.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/GaussianBoxMuller.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/GaussianBoxMuller.java index db0b40ea..de8c189d --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/GaussianBoxMuller.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/GaussianBoxMuller.java @@ -1,127 +1,127 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder; - -import java.security.SecureRandom; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - -public class GaussianBoxMuller { - - public double getObsecationData(double originalValue, double totalValue, - double rangeValue) { - double obNum = 0.0; - - while ((obNum > rangeValue) || (obNum < (rangeValue * -1.0))) { - obNum = Math.round(boxMuller(true, rangeValue, 0)); - } - // if less than three, then return 0 - return originalValue + obNum; - - } - - public double boxMuller(boolean iset, double stdDev, double mean) { - double w = 0.0, x1 = 0.0, x2 = 0.0, y1 = 0.0, y2 = 0.0, obsData = 0.0; - if (iset) { - do { - SecureRandom random = new SecureRandom(); - - x1 = 2.0 * random.nextDouble() - 1.0; - x2 = 2.0 * random.nextDouble() - 1.0; - w = x1 * x1 + x2 * x2; - } while (w >= 1.0); - - w = Math.sqrt((-2.0 * Math.log(w)) / w); - - y1 = x1 * w; - y2 = x2 * w; - obsData = y1; - } else { - iset = false; - obsData = y2; - } - // System.out.println("obsData " + obsData); - obsData = (obsData * stdDev) + mean; - return obsData; - } - - public long getNormalizedValueForCount(double originalValue,double sigma,double obfuscatedMinimumValue ) { - double normalizedValue = 0.0; - // read property file for the minimum cutoff - double minimumCutoffValue = obfuscatedMinimumValue; - // check if original value <3 then return zero - if (originalValue <= minimumCutoffValue) { - return (long) normalizedValue; - } - // read standard deviation from property file - double stdDev = sigma; - // read mean from property file - double mean = 0; - double boxMullerValue = boxMuller(true, stdDev , mean); - - /* - while (normalizedValue <= 0.0) { - normalizedValue = Math.round(originalValue + boxMullerValue); - } - */ - - - normalizedValue = Math.round(originalValue + boxMullerValue); - if (normalizedValue <= 0) { - return 0; - } - return (long) normalizedValue; - } - - public static double getCountSigma() throws I2B2Exception { - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - String countSigmaStr = qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.setfinderquery.obfuscation.count.sigma"); - return Double.parseDouble(countSigmaStr); - } - - - - - public static double getBreakdownCountSigma() throws I2B2Exception { - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - String breakdownCountSigmaStr = qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.setfinderquery.obfuscation.breakdowncount.sigma"); - return Double.parseDouble(breakdownCountSigmaStr); - } - - public static double getObfuscatedMinimumVal() throws I2B2Exception { - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - String countSigmaStr = qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.setfinderquery.obfuscation.minimum.value"); - return Double.parseDouble(countSigmaStr); - } - - public static void main(String[] args) { - GaussianBoxMuller g = new GaussianBoxMuller(); - for (int i = 0; i < 400; i++) { - double finalVal = 0.0d, boxMullerVal = -0.1; - - while (finalVal + boxMullerVal <= 0.0) { - boxMullerVal = g.boxMuller(true, 1.3, 0); - } - finalVal = finalVal + boxMullerVal; - // Random random = new Random(3); - // double gaussianBlur = random.nextGaussian(); - // double finalObsData = g.getObsecationData(10, 3, 3); - } - // System.out.println(" value " + String.valueOf(finalVal)); - // double finalObsData = g.getObsecationData(10, 3, 3); - double testData = 0.42923558760362324 * 2.0; - // System.out.println(" test data :" + testData); - - // System.out.println(" value " + String.valueOf(finalObsData)); - } - - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder; + +import java.security.SecureRandom; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + +public class GaussianBoxMuller { + + public double getObsecationData(double originalValue, double totalValue, + double rangeValue) { + double obNum = 0.0; + + while ((obNum > rangeValue) || (obNum < (rangeValue * -1.0))) { + obNum = Math.round(boxMuller(true, rangeValue, 0)); + } + // if less than three, then return 0 + return originalValue + obNum; + + } + + public double boxMuller(boolean iset, double stdDev, double mean) { + double w = 0.0, x1 = 0.0, x2 = 0.0, y1 = 0.0, y2 = 0.0, obsData = 0.0; + if (iset) { + do { + SecureRandom random = new SecureRandom(); + + x1 = 2.0 * random.nextDouble() - 1.0; + x2 = 2.0 * random.nextDouble() - 1.0; + w = x1 * x1 + x2 * x2; + } while (w >= 1.0); + + w = Math.sqrt((-2.0 * Math.log(w)) / w); + + y1 = x1 * w; + y2 = x2 * w; + obsData = y1; + } else { + iset = false; + obsData = y2; + } + // System.out.println("obsData " + obsData); + obsData = (obsData * stdDev) + mean; + return obsData; + } + + public long getNormalizedValueForCount(double originalValue,double sigma,double obfuscatedMinimumValue ) { + double normalizedValue = 0.0; + // read property file for the minimum cutoff + double minimumCutoffValue = obfuscatedMinimumValue; + // check if original value <3 then return zero + if (originalValue <= minimumCutoffValue) { + return (long) normalizedValue; + } + // read standard deviation from property file + double stdDev = sigma; + // read mean from property file + double mean = 0; + double boxMullerValue = boxMuller(true, stdDev , mean); + + /* + while (normalizedValue <= 0.0) { + normalizedValue = Math.round(originalValue + boxMullerValue); + } + */ + + + normalizedValue = Math.round(originalValue + boxMullerValue); + if (normalizedValue <= 0) { + return 0; + } + return (long) normalizedValue; + } + + public static double getCountSigma() throws I2B2Exception { + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + String countSigmaStr = qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.setfinderquery.obfuscation.count.sigma"); + return Double.parseDouble(countSigmaStr); + } + + + + + public static double getBreakdownCountSigma() throws I2B2Exception { + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + String breakdownCountSigmaStr = qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.setfinderquery.obfuscation.breakdowncount.sigma"); + return Double.parseDouble(breakdownCountSigmaStr); + } + + public static double getObfuscatedMinimumVal() throws I2B2Exception { + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + String countSigmaStr = qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.setfinderquery.obfuscation.minimum.value"); + return Double.parseDouble(countSigmaStr); + } + + public static void main(String[] args) { + GaussianBoxMuller g = new GaussianBoxMuller(); + for (int i = 0; i < 400; i++) { + double finalVal = 0.0d, boxMullerVal = -0.1; + + while (finalVal + boxMullerVal <= 0.0) { + boxMullerVal = g.boxMuller(true, 1.3, 0); + } + finalVal = finalVal + boxMullerVal; + // Random random = new Random(3); + // double gaussianBlur = random.nextGaussian(); + // double finalObsData = g.getObsecationData(10, 3, 3); + } + // System.out.println(" value " + String.valueOf(finalVal)); + // double finalObsData = g.getObsecationData(10, 3, 3); + double testData = 0.42923558760362324 * 2.0; + // System.out.println(" test data :" + testData); + + // System.out.println(" value " + String.valueOf(finalObsData)); + } + + + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/IAnalysisPluginDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/IAnalysisPluginDao.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/IAnalysisPluginDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/IAnalysisPluginDao.java index bf49256a..6be75f73 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/IAnalysisPluginDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/IAnalysisPluginDao.java @@ -1,35 +1,35 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder; - -import java.util.List; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.crc.datavo.db.QtAnalysisPlugin; - -public interface IAnalysisPluginDao { - - /** - * Return plugin metadata - * - * @param analysisName - * @param projectId - * @return - */ - public List getAnalysisPluginMetadata( - String analysisName, String projectId); - - public QtAnalysisPlugin lookupAnalysisPluginByNameVersionProject( - String analysisName, String version, String projectId) - throws I2B2DAOException; - - public QtAnalysisPlugin getAnalysisPluginById(int analysisId) - throws I2B2DAOException; - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder; + +import java.util.List; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.crc.datavo.db.QtAnalysisPlugin; + +public interface IAnalysisPluginDao { + + /** + * Return plugin metadata + * + * @param analysisName + * @param projectId + * @return + */ + public List getAnalysisPluginMetadata( + String analysisName, String projectId); + + public QtAnalysisPlugin lookupAnalysisPluginByNameVersionProject( + String analysisName, String version, String projectId) + throws I2B2DAOException; + + public QtAnalysisPlugin getAnalysisPluginById(int analysisId) + throws I2B2DAOException; + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/IEncounterSetCollectionDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/IEncounterSetCollectionDao.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/IEncounterSetCollectionDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/IEncounterSetCollectionDao.java index d21975a9..86fa6dc8 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/IEncounterSetCollectionDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/IEncounterSetCollectionDao.java @@ -1,37 +1,37 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder; - - -public interface IEncounterSetCollectionDao { - - /** - * function to add encounter to encounter set without out creating new db - * session - * - * @param patientId - */ - public void addEncounter(long encounterId, long patientId); - - /** - * Set resultInstance before addEncounter - * - * @param resultInstanceId - */ - public void createPatientEncCollection(String resultInstanceId); - - public String getResultInstanceId(); - - /** - * Call this function at the end. i.e. after loading all patient with - * addPatient function, finally call this function to clear session - */ - public void flush(); - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder; + + +public interface IEncounterSetCollectionDao { + + /** + * function to add encounter to encounter set without out creating new db + * session + * + * @param patientId + */ + public void addEncounter(long encounterId, long patientId); + + /** + * Set resultInstance before addEncounter + * + * @param resultInstanceId + */ + public void createPatientEncCollection(String resultInstanceId); + + public String getResultInstanceId(); + + /** + * Call this function at the end. i.e. after loading all patient with + * addPatient function, finally call this function to clear session + */ + public void flush(); + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/IPatientSetCollectionDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/IPatientSetCollectionDao.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/IPatientSetCollectionDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/IPatientSetCollectionDao.java index 527d71ee..88ad3cc8 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/IPatientSetCollectionDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/IPatientSetCollectionDao.java @@ -1,36 +1,36 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder; - -public interface IPatientSetCollectionDao { - - /** - * function to add patient to patient set without out creating new db - * session - * - * @param patientId - */ - public void addPatient(long patientId); - - - /** - * Set resultInstance before addPatient - * @param resultInstanceId - */ - public void createPatientSetCollection(String resultInstanceId) ; - - public String getResultInstanceId() ; - - /** - * Call this function at the end. i.e. after loading all patient with - * addPatient function, finally call this function to clear session - */ - public void flush(); - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder; + +public interface IPatientSetCollectionDao { + + /** + * function to add patient to patient set without out creating new db + * session + * + * @param patientId + */ + public void addPatient(long patientId); + + + /** + * Set resultInstance before addPatient + * @param resultInstanceId + */ + public void createPatientSetCollection(String resultInstanceId) ; + + public String getResultInstanceId() ; + + /** + * Call this function at the end. i.e. after loading all patient with + * addPatient function, finally call this function to clear session + */ + public void flush(); + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/IQueryBreakdownTypeDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/IQueryBreakdownTypeDao.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/IQueryBreakdownTypeDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/IQueryBreakdownTypeDao.java index 147e7471..88bd6251 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/IQueryBreakdownTypeDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/IQueryBreakdownTypeDao.java @@ -1,17 +1,17 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder; - -import edu.harvard.i2b2.crc.datavo.db.QtQueryBreakdownType; - -public interface IQueryBreakdownTypeDao { - - public QtQueryBreakdownType getBreakdownTypeByName(String name); - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder; + +import edu.harvard.i2b2.crc.datavo.db.QtQueryBreakdownType; + +public interface IQueryBreakdownTypeDao { + + public QtQueryBreakdownType getBreakdownTypeByName(String name); + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/IQueryExecutorDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/IQueryExecutorDao.java old mode 100755 new mode 100644 similarity index 98% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/IQueryExecutorDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/IQueryExecutorDao.java index f6009e27..77bde551 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/IQueryExecutorDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/IQueryExecutorDao.java @@ -1,28 +1,28 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder; - - -import java.util.List; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultOutputOptionListType; - -public interface IQueryExecutorDao { - public String executeSQL( - int transactionTimeout, DataSourceLookup dsLookup, - SetFinderDAOFactory sfDAOFactory, String requestXml, - String sqlString, String queryInstanceId, String patientSetId, - ResultOutputOptionListType resultOutputList, boolean allowLargeTextValueConstrainFlag, String pmXMl, List userRoles) - throws CRCTimeOutException, I2B2DAOException, I2B2Exception, JAXBUtilException; -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder; + + +import java.util.List; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultOutputOptionListType; + +public interface IQueryExecutorDao { + public String executeSQL( + int transactionTimeout, DataSourceLookup dsLookup, + SetFinderDAOFactory sfDAOFactory, String requestXml, + String sqlString, String queryInstanceId, String patientSetId, + ResultOutputOptionListType resultOutputList, boolean allowLargeTextValueConstrainFlag, String pmXMl, List userRoles) + throws CRCTimeOutException, I2B2DAOException, I2B2Exception, JAXBUtilException; +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/IQueryInstanceDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/IQueryInstanceDao.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/IQueryInstanceDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/IQueryInstanceDao.java index 4ff790fa..3ed7432a --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/IQueryInstanceDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/IQueryInstanceDao.java @@ -1,69 +1,69 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder; - -import java.util.List; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.crc.datavo.db.QtQueryInstance; - -public interface IQueryInstanceDao { - - /** - * Function to create query instance - * - * @param queryMasterId - * @param userId - * @param groupId - * @param batchMode - * @param statusId - * @return query instance id - */ - public String createQueryInstance(String queryMasterId, String userId, - String groupId, String batchMode, int statusId); - - /** - * Returns list of query instance for the given master id - * - * @param queryMasterId - * @return List - */ - @SuppressWarnings("unchecked") - public List getQueryInstanceByMasterId(String queryMasterId); - - /** - * Find query instance by id - * - * @param queryInstanceId - * @return QtQueryInstance - */ - public QtQueryInstance getQueryInstanceByInstanceId(String queryInstanceId); - - /** - * Update query instance - * - * @param queryInstance - * @return QtQueryInstance - */ - public QtQueryInstance update(QtQueryInstance queryInstance, - boolean appendMessageFlag) throws I2B2DAOException; - - - /** - * Update query instance message - * - * @param queryInstanceId - * @param message - * @param appendMessageFlag - * @return - */ - public void updateMessage(String queryInstanceId, String message, - boolean appendMessageFlag) throws I2B2DAOException ; - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder; + +import java.util.List; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.crc.datavo.db.QtQueryInstance; + +public interface IQueryInstanceDao { + + /** + * Function to create query instance + * + * @param queryMasterId + * @param userId + * @param groupId + * @param batchMode + * @param statusId + * @return query instance id + */ + public String createQueryInstance(String queryMasterId, String userId, + String groupId, String batchMode, int statusId); + + /** + * Returns list of query instance for the given master id + * + * @param queryMasterId + * @return List + */ + @SuppressWarnings("unchecked") + public List getQueryInstanceByMasterId(String queryMasterId); + + /** + * Find query instance by id + * + * @param queryInstanceId + * @return QtQueryInstance + */ + public QtQueryInstance getQueryInstanceByInstanceId(String queryInstanceId); + + /** + * Update query instance + * + * @param queryInstance + * @return QtQueryInstance + */ + public QtQueryInstance update(QtQueryInstance queryInstance, + boolean appendMessageFlag) throws I2B2DAOException; + + + /** + * Update query instance message + * + * @param queryInstanceId + * @param message + * @param appendMessageFlag + * @return + */ + public void updateMessage(String queryInstanceId, String message, + boolean appendMessageFlag) throws I2B2DAOException ; + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/IQueryMasterDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/IQueryMasterDao.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/IQueryMasterDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/IQueryMasterDao.java index 0bb8e0b7..93d93742 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/IQueryMasterDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/IQueryMasterDao.java @@ -1,112 +1,112 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder; - -import java.util.List; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.crc.datavo.db.QtQueryMaster; -import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.FindByChildType; - -public interface IQueryMasterDao { - - /** - * Function to create query master By default sets delete flag to false - * - * @param queryMaster - * @return query master id - */ - public String createQueryMaster(QtQueryMaster queryMaster, - String i2b2RequestXml, String pmXml); - - /** - * Write query sql for the master id - * - * @param masterId - * @param generatedSql - */ - public void updateQueryAfterRun(String masterId, String generatedSql, String masterType); - - - /** - * Write query sql for the master id - * - * @param masterId - */ - public void updateMasterTypeAfterRun(String masterId, String masterType); - - /** - * Returns list of query master by user id - * - * @param userId - * @return List - */ - @SuppressWarnings("unchecked") - public List getQueryMasterByUserId(String userId, - int fetchSize, String masterTypeCd, boolean includeQueryInstance); - - /** - * Returns list of query master by find search - * - * @param groupId - * @return List - * @throws I2B2Exception - */ - @SuppressWarnings("unchecked") - public List getQueryMasterByNameInfo(SecurityType userRequestType, FindByChildType find) throws I2B2Exception; - - /** - * Returns list of query master by group id - * - * @param groupId - * @return List - */ - @SuppressWarnings("unchecked") - public List getQueryMasterByGroupId(String groupId, - int fetchSize, String masterTypeCd, boolean includeQueryInstance); - - /** - * Find Query master by id - * - * @param masterId - * @return QtQueryMaster - */ - public QtQueryMaster getQueryDefinition(String masterId); - - /** - * Find query by name - * @param queryName - * @return - */ - public List getQueryByName(String queryName); - - /** - * Function to rename query master - * - * @param masterId - * @param queryNewName - * @throws I2B2DAOException - */ - public void renameQuery(String masterId, String queryNewName) - throws I2B2DAOException; - - /** - * Function to delete query using user and master id This function will not - * delete permanently, it will set delete flag field in query master, query - * instance and result instance to true - * - * @param masterId - * @throws I2B2DAOException - */ - @SuppressWarnings("unchecked") - public void deleteQuery(String masterId) throws I2B2DAOException; - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder; + +import java.util.List; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.crc.datavo.db.QtQueryMaster; +import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.FindByChildType; + +public interface IQueryMasterDao { + + /** + * Function to create query master By default sets delete flag to false + * + * @param queryMaster + * @return query master id + */ + public String createQueryMaster(QtQueryMaster queryMaster, + String i2b2RequestXml, String pmXml); + + /** + * Write query sql for the master id + * + * @param masterId + * @param generatedSql + */ + public void updateQueryAfterRun(String masterId, String generatedSql, String masterType); + + + /** + * Write query sql for the master id + * + * @param masterId + */ + public void updateMasterTypeAfterRun(String masterId, String masterType); + + /** + * Returns list of query master by user id + * + * @param userId + * @return List + */ + @SuppressWarnings("unchecked") + public List getQueryMasterByUserId(String userId, + int fetchSize, String masterTypeCd, boolean includeQueryInstance); + + /** + * Returns list of query master by find search + * + * @param groupId + * @return List + * @throws I2B2Exception + */ + @SuppressWarnings("unchecked") + public List getQueryMasterByNameInfo(SecurityType userRequestType, FindByChildType find) throws I2B2Exception; + + /** + * Returns list of query master by group id + * + * @param groupId + * @return List + */ + @SuppressWarnings("unchecked") + public List getQueryMasterByGroupId(String groupId, + int fetchSize, String masterTypeCd, boolean includeQueryInstance); + + /** + * Find Query master by id + * + * @param masterId + * @return QtQueryMaster + */ + public QtQueryMaster getQueryDefinition(String masterId); + + /** + * Find query by name + * @param queryName + * @return + */ + public List getQueryByName(String queryName); + + /** + * Function to rename query master + * + * @param masterId + * @param queryNewName + * @throws I2B2DAOException + */ + public void renameQuery(String masterId, String queryNewName) + throws I2B2DAOException; + + /** + * Function to delete query using user and master id This function will not + * delete permanently, it will set delete flag field in query master, query + * instance and result instance to true + * + * @param masterId + * @throws I2B2DAOException + */ + @SuppressWarnings("unchecked") + public void deleteQuery(String masterId) throws I2B2DAOException; + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/IQueryPdoMasterDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/IQueryPdoMasterDao.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/IQueryPdoMasterDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/IQueryPdoMasterDao.java index cffa9afc..6f2cf945 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/IQueryPdoMasterDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/IQueryPdoMasterDao.java @@ -1,24 +1,24 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder; - -import edu.harvard.i2b2.crc.datavo.db.QtQueryMaster; - -public interface IQueryPdoMasterDao { - - /** - * Function to create query master By default sets delete flag to false - * - * @param queryMaster - * @return query master id - */ - public String createPdoQueryMaster(QtQueryMaster queryMaster, - String i2b2RequestXml); - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder; + +import edu.harvard.i2b2.crc.datavo.db.QtQueryMaster; + +public interface IQueryPdoMasterDao { + + /** + * Function to create query master By default sets delete flag to false + * + * @param queryMaster + * @return query master id + */ + public String createPdoQueryMaster(QtQueryMaster queryMaster, + String i2b2RequestXml); + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/IQueryRequestDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/IQueryRequestDao.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/IQueryRequestDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/IQueryRequestDao.java index 70ddfb61..c43acc69 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/IQueryRequestDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/IQueryRequestDao.java @@ -1,67 +1,67 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder; - -import java.util.List; -import java.util.Map; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; - -public interface IQueryRequestDao { - - /** - * Function to execute the given setfinder sql And creates query instance - * and query result instance - * - * @param generatedSql - * @param queryInstanceId - * @return query result instance id - * @throws I2B2DAOException - */ - // public String getPatientCount(String generatedSql, String - // queryInstanceId, - // String patientSetId) throws I2B2DAOException; - /** - * Function to build sql from given query definition This function uses - * QueryToolUtil class to build sql - * - * @param queryRequestXml - * @return sql string - * @throws I2B2DAOException - * @throws I2B2Exception - * @throws JAXBUtilException - */ - public String[] buildSql(String queryRequestXml, boolean encounterSetFlag) - throws I2B2DAOException, I2B2Exception, JAXBUtilException; - - - /** - * set the project param flag - * @param Map projectParamMap - */ - public void setProjectParam(Map projectParamMap) ; - - - /** - * set the large text value constrain - * @param allowLargeTextValueConstrainFlag - */ - public void setAllowLargeTextValueConstrainFlag(boolean allowLargeTextValueConstrainFlag) ; - - public void setUserRoles(List userRoles); - /** - * set query with temp table optimization - * @param allowLargeTextValueConstrainFlag - */ - public void setQueryWithoutTempTableFlag(boolean queryWithoutTempTableFlag) ; - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder; + +import java.util.List; +import java.util.Map; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; + +public interface IQueryRequestDao { + + /** + * Function to execute the given setfinder sql And creates query instance + * and query result instance + * + * @param generatedSql + * @param queryInstanceId + * @return query result instance id + * @throws I2B2DAOException + */ + // public String getPatientCount(String generatedSql, String + // queryInstanceId, + // String patientSetId) throws I2B2DAOException; + /** + * Function to build sql from given query definition This function uses + * QueryToolUtil class to build sql + * + * @param queryRequestXml + * @return sql string + * @throws I2B2DAOException + * @throws I2B2Exception + * @throws JAXBUtilException + */ + public String[] buildSql(String queryRequestXml, boolean encounterSetFlag) + throws I2B2DAOException, I2B2Exception, JAXBUtilException; + + + /** + * set the project param flag + * @param Map projectParamMap + */ + public void setProjectParam(Map projectParamMap) ; + + + /** + * set the large text value constrain + * @param allowLargeTextValueConstrainFlag + */ + public void setAllowLargeTextValueConstrainFlag(boolean allowLargeTextValueConstrainFlag) ; + + public void setUserRoles(List userRoles); + /** + * set query with temp table optimization + * @param allowLargeTextValueConstrainFlag + */ + public void setQueryWithoutTempTableFlag(boolean queryWithoutTempTableFlag) ; + + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/IQueryResultInstanceDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/IQueryResultInstanceDao.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/IQueryResultInstanceDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/IQueryResultInstanceDao.java index b18ca803..9f51a773 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/IQueryResultInstanceDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/IQueryResultInstanceDao.java @@ -1,125 +1,125 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder; - -import java.util.List; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.crc.datavo.db.QtQueryResultInstance; - -public interface IQueryResultInstanceDao { - - public final String OBTOTAL = "OBTOTAL"; - public final String OBSUBTOTAL = "OBSUBTOTAL"; - - /** - * Function to create result instance for given query instance id. The - * result instance status is set to running. Use updatePatientSet function - * to change the status to completed or error - * - * @param queryInstanceId - * @return - */ - public String createPatientSet(String queryInstanceId, String resultName) - throws I2B2DAOException; - - /** - * Function used to update result instance Particularly its status and size - * - * @param resultInstanceId - * @param statusTypeId - * @param setSize - */ - public void updatePatientSet(String resultInstanceId, int statusTypeId, - int setSize); - - /** - * Function used to update result instance Particularly its status and size - * - * @param resultInstanceId - * @param statusTypeId - * @param setSize - */ - public void updatePatientSet(String resultInstanceId, int statusTypeId, - String message, int setSize, int obsSetSize, String obsSizeType); - - /** - * Function used to update result instance description - * - * @param resultInstanceId - * @param description - */ - public void updateResultInstanceDescription(String resultInstanceId, - String description); - - /** - * Function used to update instance message - * - * @param InstanceId - * @param description - */ - public void updateInstanceMessage(String instanceId, - String message); - - - /** - * Return list of query result instance by query instance id - * - * @param queryInstanceId - * @return List - */ - @SuppressWarnings("unchecked") - public List getResultInstanceList( - String queryInstanceId); - - /** - * Return list of query result instance by query result id - * - * @param queryResultId - * @return QtQueryResultInstance - */ - public QtQueryResultInstance getResultInstanceById(String queryResultId) - throws I2B2DAOException; - - /** - * Return list of query result instance by query instance id and result name - * - * @param queryInstanceId - * @param resultName - * @return QtQueryResultInstance - */ - @SuppressWarnings("unchecked") - public QtQueryResultInstance getResultInstanceByQueryInstanceIdAndName( - String queryInstanceId, String resultName); - - /** - * Return a list of query result instance with waiting status - * - * @param queueName - * @param maxListSize - * @return - */ - public List getUnfinishedInstanceByQueue( - String queueName, int maxListSize); - - /** - * Get result instance count by set size - * - * @param userId - * @param compareDays - * @param setSize - * @param totalCount - * @return - * @throws I2B2DAOException - */ - public int getResultInstanceCountBySetSize(String userId, int compareDays, - int resultTypeId, int setSize, int totalCount) - throws I2B2DAOException; - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder; + +import java.util.List; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.crc.datavo.db.QtQueryResultInstance; + +public interface IQueryResultInstanceDao { + + public final String OBTOTAL = "OBTOTAL"; + public final String OBSUBTOTAL = "OBSUBTOTAL"; + + /** + * Function to create result instance for given query instance id. The + * result instance status is set to running. Use updatePatientSet function + * to change the status to completed or error + * + * @param queryInstanceId + * @return + */ + public String createPatientSet(String queryInstanceId, String resultName) + throws I2B2DAOException; + + /** + * Function used to update result instance Particularly its status and size + * + * @param resultInstanceId + * @param statusTypeId + * @param setSize + */ + public void updatePatientSet(String resultInstanceId, int statusTypeId, + int setSize); + + /** + * Function used to update result instance Particularly its status and size + * + * @param resultInstanceId + * @param statusTypeId + * @param setSize + */ + public void updatePatientSet(String resultInstanceId, int statusTypeId, + String message, int setSize, int obsSetSize, String obsSizeType); + + /** + * Function used to update result instance description + * + * @param resultInstanceId + * @param description + */ + public void updateResultInstanceDescription(String resultInstanceId, + String description); + + /** + * Function used to update instance message + * + * @param InstanceId + * @param description + */ + public void updateInstanceMessage(String instanceId, + String message); + + + /** + * Return list of query result instance by query instance id + * + * @param queryInstanceId + * @return List + */ + @SuppressWarnings("unchecked") + public List getResultInstanceList( + String queryInstanceId); + + /** + * Return list of query result instance by query result id + * + * @param queryResultId + * @return QtQueryResultInstance + */ + public QtQueryResultInstance getResultInstanceById(String queryResultId) + throws I2B2DAOException; + + /** + * Return list of query result instance by query instance id and result name + * + * @param queryInstanceId + * @param resultName + * @return QtQueryResultInstance + */ + @SuppressWarnings("unchecked") + public QtQueryResultInstance getResultInstanceByQueryInstanceIdAndName( + String queryInstanceId, String resultName); + + /** + * Return a list of query result instance with waiting status + * + * @param queueName + * @param maxListSize + * @return + */ + public List getUnfinishedInstanceByQueue( + String queueName, int maxListSize); + + /** + * Get result instance count by set size + * + * @param userId + * @param compareDays + * @param setSize + * @param totalCount + * @return + * @throws I2B2DAOException + */ + public int getResultInstanceCountBySetSize(String userId, int compareDays, + int resultTypeId, int setSize, int totalCount) + throws I2B2DAOException; + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/IQueryResultTypeDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/IQueryResultTypeDao.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/IQueryResultTypeDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/IQueryResultTypeDao.java index a50861c0..d7b6f115 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/IQueryResultTypeDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/IQueryResultTypeDao.java @@ -1,52 +1,52 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder; - -import java.util.List; - -import edu.harvard.i2b2.crc.datavo.db.QtQueryResultType; - -public interface IQueryResultTypeDao { - - - /** - * Returns list of query master by user id - * - * @param userId - * @return List - */ - @SuppressWarnings("unchecked") - public String getQueryResultTypeClassname(String resultName); - - /** - * Returns list of query master by user id - * - * @param userId - * @return List - */ - @SuppressWarnings("unchecked") - public QtQueryResultType getQueryResultTypeById(int resultTypeId); - - /** - * Returns list of query master by user id - * - * @param userId - * @return List - */ - @SuppressWarnings("unchecked") - public List getQueryResultTypeByName(String resultName, List roles); - - /** - * Get all result type - * - * @return List - */ - public List getAllQueryResultType(List roles); - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder; + +import java.util.List; + +import edu.harvard.i2b2.crc.datavo.db.QtQueryResultType; + +public interface IQueryResultTypeDao { + + + /** + * Returns list of query master by user id + * + * @param userId + * @return List + */ + @SuppressWarnings("unchecked") + public String getQueryResultTypeClassname(String resultName); + + /** + * Returns list of query master by user id + * + * @param userId + * @return List + */ + @SuppressWarnings("unchecked") + public QtQueryResultType getQueryResultTypeById(int resultTypeId); + + /** + * Returns list of query master by user id + * + * @param userId + * @return List + */ + @SuppressWarnings("unchecked") + public List getQueryResultTypeByName(String resultName, List roles); + + /** + * Get all result type + * + * @return List + */ + public List getAllQueryResultType(List roles); + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/IQueryStatusTypeDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/IQueryStatusTypeDao.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/IQueryStatusTypeDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/IQueryStatusTypeDao.java index 56ca1e19..c37a0e4c --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/IQueryStatusTypeDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/IQueryStatusTypeDao.java @@ -1,23 +1,23 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder; - -import edu.harvard.i2b2.crc.datavo.db.QtQueryStatusType; - -public interface IQueryStatusTypeDao { - - /** - * Returns list of query master by user id - * @param userId - * @return List - */ - @SuppressWarnings("unchecked") - public QtQueryStatusType getQueryStatusTypeById(int statusTypeId); - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder; + +import edu.harvard.i2b2.crc.datavo.db.QtQueryStatusType; + +public interface IQueryStatusTypeDao { + + /** + * Returns list of query master by user id + * @param userId + * @return List + */ + @SuppressWarnings("unchecked") + public QtQueryStatusType getQueryStatusTypeById(int statusTypeId); + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/IResultGenerator.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/IResultGenerator.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/IResultGenerator.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/IResultGenerator.java index 2a0ad709..40ea90e3 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/IResultGenerator.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/IResultGenerator.java @@ -1,21 +1,21 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder; - -import java.util.Map; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; - -public interface IResultGenerator { - - public void generateResult(Map param) throws CRCTimeOutException, - I2B2DAOException; - - public String getResults(); -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder; + +import java.util.Map; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; + +public interface IResultGenerator { + + public void generateResult(Map param) throws CRCTimeOutException, + I2B2DAOException; + + public String getResults(); +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/IXmlResultDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/IXmlResultDao.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/IXmlResultDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/IXmlResultDao.java index 6eeb74be..198a4fa9 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/IXmlResultDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/IXmlResultDao.java @@ -1,38 +1,38 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.crc.datavo.db.QtXmlResult; - -public interface IXmlResultDao { - - /** - * Function to create query instance - * - * @param queryMasterId - * @param userId - * @param groupId - * @param batchMode - * @param statusId - * @return query instance id - */ - public String createQueryXmlResult(String resultInstanceId, String xmlValue); - - /** - * Returns list of query instance for the given master id - * - * @param queryMasterId - * @return List - */ - @SuppressWarnings("unchecked") - public QtXmlResult getXmlResultByResultInstanceId( - String resultInstanceId) throws I2B2DAOException; - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.crc.datavo.db.QtXmlResult; + +public interface IXmlResultDao { + + /** + * Function to create query instance + * + * @param queryMasterId + * @param userId + * @param groupId + * @param batchMode + * @param statusId + * @return query instance id + */ + public String createQueryXmlResult(String resultInstanceId, String xmlValue); + + /** + * Returns list of query instance for the given master id + * + * @param queryMasterId + * @return List + */ + @SuppressWarnings("unchecked") + public QtXmlResult getXmlResultByResultInstanceId( + String resultInstanceId) throws I2B2DAOException; + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/LockedoutException.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/LockedoutException.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/LockedoutException.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/LockedoutException.java index 5ea42ce8..a6634bf1 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/LockedoutException.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/LockedoutException.java @@ -1,41 +1,41 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; - -public class LockedoutException extends I2B2DAOException { - - /** - * - */ - private static final long serialVersionUID = 1L; - - - public LockedoutException() { - } - - /** - * Constructor that takes message and the exception as inputs. - * @param message - * @param e - */ - public LockedoutException(String message, Exception e) { - super(message, e); - } - - /** - * Constructor that takes message as input. - * @param message - */ - public LockedoutException(String message) { - super(message); - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; + +public class LockedoutException extends I2B2DAOException { + + /** + * + */ + private static final long serialVersionUID = 1L; + + + public LockedoutException() { + } + + /** + * Constructor that takes message and the exception as inputs. + * @param message + * @param e + */ + public LockedoutException(String message, Exception e) { + super(message, e); + } + + /** + * Constructor that takes message as input. + * @param message + */ + public LockedoutException(String message) { + super(message); + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/PatientSetCollectionSpringDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/PatientSetCollectionSpringDao.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/PatientSetCollectionSpringDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/PatientSetCollectionSpringDao.java index 80252f9b..0f3efac1 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/PatientSetCollectionSpringDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/PatientSetCollectionSpringDao.java @@ -1,177 +1,177 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao.setfinder; - -import java.sql.PreparedStatement; -import java.sql.SQLException; -import java.util.Arrays; - -import javax.sql.DataSource; - -import org.springframework.jdbc.core.BatchPreparedStatementSetter; -import org.springframework.jdbc.core.JdbcTemplate; - -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.db.QtPatientSetCollection; -import edu.harvard.i2b2.crc.datavo.db.QtQueryResultInstance; - -/** - * Class to support batch inserts of patients to PatientSetCollection This class - * uses single Session to persist all the patients to collection. To have - * limited memory usage, it will flush and clear the session manually for every - * 1000 inserts. $Id: PatientSetCollectionDao.java,v 1.4 2007/08/31 14:44:26 - * rk903 Exp $ - * - * @author rkuttan - * @see QtPatientSetCollection - */ -public class PatientSetCollectionSpringDao extends CRCDAO implements IPatientSetCollectionDao { - /** patient set collection index * */ - private int setIndex = 0, batchDataIndex = 0; - private JdbcTemplate jdbcTemplate = null; - private String insert_sql = ""; - - - QtPatientSetCollection[] patientSetColl = null; - /** master table for patient set collection * */ - QtQueryResultInstance resultInstance = null; - String resultInstanceId = null; - private static final int INITIAL_ARRAY_SIZE = 1100; - private DataSourceLookup dataSourceLookup = null; - - private SQLServerSequenceDAO sqlServerSequenceDao = null; - /** - * Construc with patientset id Initialize hibernate session and creates - * Query reuslt instance class - * - * @param patientSetId - */ - public PatientSetCollectionSpringDao(DataSource dataSource,DataSourceLookup dataSourceLookup) { - setDataSource(dataSource); - setDbSchemaName(dataSourceLookup.getFullSchema()); - jdbcTemplate = new JdbcTemplate(dataSource); - this.dataSourceLookup = dataSourceLookup; - if (dataSourceLookup.getServerType().equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { - insert_sql = "insert into " + getDbSchemaName() +"qt_patient_set_collection(patient_set_coll_id,result_instance_id,set_index,patient_num) values ("+getDbSchemaName()+"QT_SQ_QPR_PCID.nextval,?,?,?)"; - } else if (dataSourceLookup.getServerType().equalsIgnoreCase(DAOFactoryHelper.SQLSERVER) || dataSourceLookup.getServerType().equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { - insert_sql = "insert into " + getDbSchemaName() + "qt_patient_set_collection(result_instance_id,set_index,patient_num) values (?,?,?)"; - } - sqlServerSequenceDao = new SQLServerSequenceDAO(dataSource,dataSourceLookup) ; - resultInstance = new QtQueryResultInstance(); - patientSetColl = new QtPatientSetCollection[INITIAL_ARRAY_SIZE]; - - } - - - @Override - public void createPatientSetCollection(String resultInstanceId) { - resultInstance = new QtQueryResultInstance(); - resultInstance.setResultInstanceId(resultInstanceId); - - } - - - - - @Override - public String getResultInstanceId() { - return resultInstance.getResultInstanceId(); - } - - - - - - - - - - /** - * function to add patient to patient set without out creating new db - * session - * - * @param patientId - */ - @Override - public void addPatient(long patientId) { - setIndex++; - - QtPatientSetCollection collElement = new QtPatientSetCollection(); - int patientSetCollId = 0; - collElement.setPatientId(patientId); - collElement.setQtQueryResultInstance(resultInstance); - collElement.setSetIndex(setIndex); - patientSetColl[batchDataIndex++] = collElement; - - if ((setIndex % 1000) == 0) { - InsertStatementSetter batchSetter = new InsertStatementSetter( - patientSetColl, batchDataIndex); - jdbcTemplate.batchUpdate(insert_sql, batchSetter); - - Arrays.fill(patientSetColl, null); - batchDataIndex = 0; - } - } - - /** - * Call this function at the end. i.e. after loading all patient with - * addPatient function, finally call this function to clear session - */ - @Override - public void flush() { - InsertStatementSetter batchSetter = new InsertStatementSetter( - patientSetColl, batchDataIndex); - jdbcTemplate.batchUpdate(insert_sql, batchSetter); - Arrays.fill(patientSetColl, null); - batchDataIndex = 0; - setIndex = 0; - } - - class InsertStatementSetter implements BatchPreparedStatementSetter { - - private QtPatientSetCollection[] data; - private int batchSize = 0; - - public InsertStatementSetter(QtPatientSetCollection[] data, - int batchSize) { - this.data = data; - this.batchSize = batchSize; - } - - @Override - public int getBatchSize() { - return batchSize; - } - - // this is called for each row - @Override - public void setValues(PreparedStatement ps, int i) throws SQLException { - - //ps.setLong(1, data[i].getPatientSetCollId()); // set first value - ps.setInt(1, Integer.parseInt(data[i].getQtQueryResultInstance() - .getResultInstanceId())); - ps.setInt(2, data[i].getSetIndex()); - ps.setLong(3, data[i].getPatientId()); - - - } - - } - - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao.setfinder; + +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.Arrays; + +import javax.sql.DataSource; + +import org.springframework.jdbc.core.BatchPreparedStatementSetter; +import org.springframework.jdbc.core.JdbcTemplate; + +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.db.QtPatientSetCollection; +import edu.harvard.i2b2.crc.datavo.db.QtQueryResultInstance; + +/** + * Class to support batch inserts of patients to PatientSetCollection This class + * uses single Session to persist all the patients to collection. To have + * limited memory usage, it will flush and clear the session manually for every + * 1000 inserts. $Id: PatientSetCollectionDao.java,v 1.4 2007/08/31 14:44:26 + * rk903 Exp $ + * + * @author rkuttan + * @see QtPatientSetCollection + */ +public class PatientSetCollectionSpringDao extends CRCDAO implements IPatientSetCollectionDao { + /** patient set collection index * */ + private int setIndex = 0, batchDataIndex = 0; + private JdbcTemplate jdbcTemplate = null; + private String insert_sql = ""; + + + QtPatientSetCollection[] patientSetColl = null; + /** master table for patient set collection * */ + QtQueryResultInstance resultInstance = null; + String resultInstanceId = null; + private static final int INITIAL_ARRAY_SIZE = 1100; + private DataSourceLookup dataSourceLookup = null; + + private SQLServerSequenceDAO sqlServerSequenceDao = null; + /** + * Construc with patientset id Initialize hibernate session and creates + * Query reuslt instance class + * + * @param patientSetId + */ + public PatientSetCollectionSpringDao(DataSource dataSource,DataSourceLookup dataSourceLookup) { + setDataSource(dataSource); + setDbSchemaName(dataSourceLookup.getFullSchema()); + jdbcTemplate = new JdbcTemplate(dataSource); + this.dataSourceLookup = dataSourceLookup; + if (dataSourceLookup.getServerType().equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { + insert_sql = "insert into " + getDbSchemaName() +"qt_patient_set_collection(patient_set_coll_id,result_instance_id,set_index,patient_num) values ("+getDbSchemaName()+"QT_SQ_QPR_PCID.nextval,?,?,?)"; + } else if (dataSourceLookup.getServerType().equalsIgnoreCase(DAOFactoryHelper.SQLSERVER) || dataSourceLookup.getServerType().equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { + insert_sql = "insert into " + getDbSchemaName() + "qt_patient_set_collection(result_instance_id,set_index,patient_num) values (?,?,?)"; + } + sqlServerSequenceDao = new SQLServerSequenceDAO(dataSource,dataSourceLookup) ; + resultInstance = new QtQueryResultInstance(); + patientSetColl = new QtPatientSetCollection[INITIAL_ARRAY_SIZE]; + + } + + + @Override + public void createPatientSetCollection(String resultInstanceId) { + resultInstance = new QtQueryResultInstance(); + resultInstance.setResultInstanceId(resultInstanceId); + + } + + + + + @Override + public String getResultInstanceId() { + return resultInstance.getResultInstanceId(); + } + + + + + + + + + + /** + * function to add patient to patient set without out creating new db + * session + * + * @param patientId + */ + @Override + public void addPatient(long patientId) { + setIndex++; + + QtPatientSetCollection collElement = new QtPatientSetCollection(); + int patientSetCollId = 0; + collElement.setPatientId(patientId); + collElement.setQtQueryResultInstance(resultInstance); + collElement.setSetIndex(setIndex); + patientSetColl[batchDataIndex++] = collElement; + + if ((setIndex % 1000) == 0) { + InsertStatementSetter batchSetter = new InsertStatementSetter( + patientSetColl, batchDataIndex); + jdbcTemplate.batchUpdate(insert_sql, batchSetter); + + Arrays.fill(patientSetColl, null); + batchDataIndex = 0; + } + } + + /** + * Call this function at the end. i.e. after loading all patient with + * addPatient function, finally call this function to clear session + */ + @Override + public void flush() { + InsertStatementSetter batchSetter = new InsertStatementSetter( + patientSetColl, batchDataIndex); + jdbcTemplate.batchUpdate(insert_sql, batchSetter); + Arrays.fill(patientSetColl, null); + batchDataIndex = 0; + setIndex = 0; + } + + class InsertStatementSetter implements BatchPreparedStatementSetter { + + private QtPatientSetCollection[] data; + private int batchSize = 0; + + public InsertStatementSetter(QtPatientSetCollection[] data, + int batchSize) { + this.data = data; + this.batchSize = batchSize; + } + + @Override + public int getBatchSize() { + return batchSize; + } + + // this is called for each row + @Override + public void setValues(PreparedStatement ps, int i) throws SQLException { + + //ps.setLong(1, data[i].getPatientSetCollId()); // set first value + ps.setInt(1, Integer.parseInt(data[i].getQtQueryResultInstance() + .getResultInstanceId())); + ps.setInt(2, data[i].getSetIndex()); + ps.setLong(3, data[i].getPatientId()); + + + } + + } + + + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryBreakdownTypeSpringDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryBreakdownTypeSpringDao.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryBreakdownTypeSpringDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryBreakdownTypeSpringDao.java index 44eea74b..98b43f4d --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryBreakdownTypeSpringDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryBreakdownTypeSpringDao.java @@ -1,133 +1,133 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao.setfinder; - -import java.io.IOException; -import java.sql.Clob; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.List; - -import javax.sql.DataSource; - -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.RowMapper; - -import edu.harvard.i2b2.common.util.db.JDBCUtil; -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.db.QtQueryBreakdownType; -import edu.harvard.i2b2.crc.datavo.pdo.BlobType; - -/** - * Class to manager operation of QtBreakdownPath $Id: - * QueryBreakdownTypeSpringDao.java,v 1.3 2008/05/07 21:39:08 rk903 Exp $ - * - * @author rkuttan - * - */ -public class QueryBreakdownTypeSpringDao extends CRCDAO implements -IQueryBreakdownTypeDao { - - static JdbcTemplate jdbcTemplate = null; - - QtBreakdownTypeRowMapper queryBreakdownTypeMapper = new QtBreakdownTypeRowMapper(); - - static DataSourceLookup dataSourceLookup = null; - - public QueryBreakdownTypeSpringDao(DataSource dataSource, - DataSourceLookup dataSourceLookup) { - setDataSource(dataSource); - - setDbSchemaName(dataSourceLookup.getFullSchema()); - jdbcTemplate = new JdbcTemplate(dataSource); - this.dataSourceLookup = dataSourceLookup; - - } - - /** - * Returns list of query master by user id - * - * @param userId - * @return List - */ - @Override - @SuppressWarnings("unchecked") - public QtQueryBreakdownType getBreakdownTypeByName(String name) { - - String sql = "select b.VALUE, b.CREATE_DATE , b.UPDATE_DATE , b.USER_ID , a.name, a.user_role_cd, a.classname from " + getDbSchemaName() - + "qt_query_result_type a left join " + getDbSchemaName() - + "qt_breakdown_path b on a.name = b.name where a.name = ? "; - List queryStatusType = jdbcTemplate - .query(sql, new Object[] { name }, - queryBreakdownTypeMapper); - - if (queryStatusType.size() > 0) - return (QtQueryBreakdownType) queryStatusType.get(0); - else - return null; - } - - private static class QtBreakdownTypeRowMapper implements RowMapper { - @Override - public Object mapRow(ResultSet rs, int rowNum) throws SQLException { - QtQueryBreakdownType queryBreakdownType = new QtQueryBreakdownType(); - queryBreakdownType.setCreateDate(rs.getDate("CREATE_DATE")); - queryBreakdownType.setCreateDate(rs.getDate("UPDATE_DATE")); - queryBreakdownType.setName(rs.getString("NAME")); - queryBreakdownType.setValue(rs.getString("VALUE")); - /* - String dsLookup = dataSourceLookup.getServerType(); - //jdbcTemplate.getDataSource().getConnection().getMetaData().getDatabaseProductName(); - if (dsLookup.equalsIgnoreCase("POSTGRESQL"))// || dsLookup.equalsIgnoreCase("ORACLE")) - { - String clob = rs.getString("VALUE_BLOB"); - if (clob !=null) - { - BlobType blobType = new BlobType(); - blobType.getContent().add(clob); - queryBreakdownType.setValue(blobType); - - } - - } else { - String clob = rs.getString("VALUE_BLOB"); - Clob observationClob = rs.getClob("VALUE_BLOB"); - - if (observationClob != null) { - BlobType blobType = new BlobType(); - try { - blobType.getContent().add( - JDBCUtil.getClobStringWithLinebreak(observationClob)); - } catch (SQLException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - queryBreakdownType.setValue(blobType); - } - } - */ - - queryBreakdownType.setUserId(rs.getString("USER_ID")); - queryBreakdownType.setUserRoleCd(rs.getString("USER_ROLE_CD")); - queryBreakdownType.setClassname(rs.getString("CLASSNAME")); - return queryBreakdownType; - } - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao.setfinder; + +import java.io.IOException; +import java.sql.Clob; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.List; + +import javax.sql.DataSource; + +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.RowMapper; + +import edu.harvard.i2b2.common.util.db.JDBCUtil; +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.db.QtQueryBreakdownType; +import edu.harvard.i2b2.crc.datavo.pdo.BlobType; + +/** + * Class to manager operation of QtBreakdownPath $Id: + * QueryBreakdownTypeSpringDao.java,v 1.3 2008/05/07 21:39:08 rk903 Exp $ + * + * @author rkuttan + * + */ +public class QueryBreakdownTypeSpringDao extends CRCDAO implements +IQueryBreakdownTypeDao { + + static JdbcTemplate jdbcTemplate = null; + + QtBreakdownTypeRowMapper queryBreakdownTypeMapper = new QtBreakdownTypeRowMapper(); + + static DataSourceLookup dataSourceLookup = null; + + public QueryBreakdownTypeSpringDao(DataSource dataSource, + DataSourceLookup dataSourceLookup) { + setDataSource(dataSource); + + setDbSchemaName(dataSourceLookup.getFullSchema()); + jdbcTemplate = new JdbcTemplate(dataSource); + this.dataSourceLookup = dataSourceLookup; + + } + + /** + * Returns list of query master by user id + * + * @param userId + * @return List + */ + @Override + @SuppressWarnings("unchecked") + public QtQueryBreakdownType getBreakdownTypeByName(String name) { + + String sql = "select b.VALUE, b.CREATE_DATE , b.UPDATE_DATE , b.USER_ID , a.name, a.user_role_cd, a.classname from " + getDbSchemaName() + + "qt_query_result_type a left join " + getDbSchemaName() + + "qt_breakdown_path b on a.name = b.name where a.name = ? "; + List queryStatusType = jdbcTemplate + .query(sql, new Object[] { name }, + queryBreakdownTypeMapper); + + if (queryStatusType.size() > 0) + return (QtQueryBreakdownType) queryStatusType.get(0); + else + return null; + } + + private static class QtBreakdownTypeRowMapper implements RowMapper { + @Override + public Object mapRow(ResultSet rs, int rowNum) throws SQLException { + QtQueryBreakdownType queryBreakdownType = new QtQueryBreakdownType(); + queryBreakdownType.setCreateDate(rs.getDate("CREATE_DATE")); + queryBreakdownType.setCreateDate(rs.getDate("UPDATE_DATE")); + queryBreakdownType.setName(rs.getString("NAME")); + queryBreakdownType.setValue(rs.getString("VALUE")); + /* + String dsLookup = dataSourceLookup.getServerType(); + //jdbcTemplate.getDataSource().getConnection().getMetaData().getDatabaseProductName(); + if (dsLookup.equalsIgnoreCase("POSTGRESQL"))// || dsLookup.equalsIgnoreCase("ORACLE")) + { + String clob = rs.getString("VALUE_BLOB"); + if (clob !=null) + { + BlobType blobType = new BlobType(); + blobType.getContent().add(clob); + queryBreakdownType.setValue(blobType); + + } + + } else { + String clob = rs.getString("VALUE_BLOB"); + Clob observationClob = rs.getClob("VALUE_BLOB"); + + if (observationClob != null) { + BlobType blobType = new BlobType(); + try { + blobType.getContent().add( + JDBCUtil.getClobStringWithLinebreak(observationClob)); + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + queryBreakdownType.setValue(blobType); + } + } + */ + + queryBreakdownType.setUserId(rs.getString("USER_ID")); + queryBreakdownType.setUserRoleCd(rs.getString("USER_ROLE_CD")); + queryBreakdownType.setClassname(rs.getString("CLASSNAME")); + return queryBreakdownType; + } + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryExecutorDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryExecutorDao.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryExecutorDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryExecutorDao.java index 62c068ae..3b8a686c --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryExecutorDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryExecutorDao.java @@ -1,760 +1,760 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder; - -import java.io.StringWriter; -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.naming.InitialContext; -import javax.naming.NamingException; -import javax.sql.DataSource; -import jakarta.xml.bind.JAXBElement; - -import org.apache.axis2.AxisFault; -//import org.springframework.beans.factory.BeanFactory; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.exception.StackTraceUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.DirectQueryForSinglePanel; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.OntologyException; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.ProcessTimingReportUtil; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.db.QtQueryInstance; -import edu.harvard.i2b2.crc.datavo.db.QtQueryMaster; -import edu.harvard.i2b2.crc.datavo.db.QtQueryResultInstance; -import edu.harvard.i2b2.crc.datavo.db.QtQueryStatusType; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; -import edu.harvard.i2b2.crc.datavo.ontology.ConceptType; -import edu.harvard.i2b2.crc.datavo.ontology.DerivedFactColumnsType; -import edu.harvard.i2b2.crc.datavo.pm.RoleType; -import edu.harvard.i2b2.crc.datavo.pm.RolesType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ConstrainOperatorType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ConstrainValueType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ItemType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.PanelType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionRequestType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultOutputOptionListType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultOutputOptionType; -import edu.harvard.i2b2.crc.delegate.ejbpm.EJBPMUtil; -import edu.harvard.i2b2.crc.delegate.ontology.CallOntologyUtil; -import edu.harvard.i2b2.crc.ejb.ExecRunnable; -import edu.harvard.i2b2.crc.util.I2B2RequestMessageHelper; -import edu.harvard.i2b2.crc.util.LogTimingUtil; -import edu.harvard.i2b2.crc.util.PMServiceAccountUtil; -import edu.harvard.i2b2.crc.util.ParamUtil; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; -import edu.harvard.i2b2.crc.util.SqlClauseUtil; - -public class QueryExecutorDao extends CRCDAO implements IQueryExecutorDao { - - - protected static Log logesapi = LogFactory.getLog(ExecRunnable.class); - - - private DataSourceLookup dataSourceLookup = null, - originalDataSourceLookup = null; - // private static Map generatorMap = null; - // private static String defaultResultType = null; - private Map projectParamMap = new HashMap(); - private boolean queryWithoutTempTableFlag = false; - private boolean queryCountMinSketchFlag = false; - static { - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - // qpUtil.getManualConnection() - - // BeanFactory bf = qpUtil.getSpringBeanFactory(); - // generatorMap = (Map) bf.getBean("setFinderResultGeneratorMap"); - // defaultResultType = (String) bf.getBean("defaultSetfinderResultType"); - } - - public QueryExecutorDao(DataSource dataSource, - DataSourceLookup dataSourceLookup, - DataSourceLookup originalDataSourceLookup) { - setDataSource(dataSource); - setDbSchemaName(dataSourceLookup.getFullSchema()); - this.dataSourceLookup = dataSourceLookup; - this.originalDataSourceLookup = originalDataSourceLookup; - } - - // - public void setQueryWithoutTempTableFlag(boolean queryWithoutTempTableFlag) { - this.queryWithoutTempTableFlag = queryWithoutTempTableFlag; - } - - public void setQueryCountMinSketchFlag(boolean queryCountMinSketchFlag) { - this.queryCountMinSketchFlag = queryCountMinSketchFlag; - } - /** - * This function executes the given sql and create query result instance and - * its collection - * - * @param conn - * db connection - * @param sqlString - * @param queryInstanceId - * @param userRoles - * @return query result instance id - * @throws JAXBUtilException - * @throws I2B2Exception - */ - @Override - public String executeSQL( - int transactionTimeout, DataSourceLookup dsLookup, - SetFinderDAOFactory sfDAOFactory, String requestXml, - String sqlString, String queryInstanceId, String patientSetId, - ResultOutputOptionListType resultOutputList, boolean allowLargeTextValueConstrainFlag, String pmXml, List userRoles) - throws I2B2Exception, JAXBUtilException { - - String singleSql = null; - int recordCount = 0; - - boolean errorFlag = false, timeOutErrorFlag = false; - Statement stmt = null; - ResultSet resultSet = null; - Connection manualConnection = null; - /** Global temp table to store intermediate setfinder results* */ - String TEMP_TABLE = "#GLOBAL_TEMP_TABLE"; - - /** Global temp table to store intermediate patient list * */ - String TEMP_DX_TABLE = "#DX"; - if (dsLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER)) { - TEMP_TABLE = getDbSchemaName() + "#GLOBAL_TEMP_TABLE"; - TEMP_DX_TABLE = getDbSchemaName() + "#DX"; - - } else if (dsLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE) || dsLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) { - TEMP_TABLE = getDbSchemaName() + "QUERY_GLOBAL_TEMP"; - TEMP_DX_TABLE = getDbSchemaName() + "DX"; - } - Exception exception = null; - - InitialContext context; - try { - context = new InitialContext(); - - String processTimingFlag = LogTimingUtil.getPocessTiming(originalDataSourceLookup.getProjectPath(), originalDataSourceLookup.getOwnerId(), - originalDataSourceLookup.getDomainId()); - if (processTimingFlag == null) { - processTimingFlag = ProcessTimingReportUtil.NONE; - } - - projectParamMap.put(ParamUtil.PM_ENABLE_PROCESS_TIMING, processTimingFlag); - ParamUtil projectParamUtil = new ParamUtil(); - String unitConversionFlag = projectParamUtil.getParam(originalDataSourceLookup.getProjectPath(), originalDataSourceLookup.getOwnerId(), - originalDataSourceLookup.getDomainId(), ParamUtil.CRC_ENABLE_UNITCD_CONVERSION); - if (unitConversionFlag != null) { - projectParamMap.put(ParamUtil.CRC_ENABLE_UNITCD_CONVERSION, unitConversionFlag.trim()); - } - - - // change status of result instance to running - IQueryResultInstanceDao psResultDao = sfDAOFactory - .getPatientSetResultDAO(); - psResultDao.updatePatientSet(patientSetId, 2, 0); - - - // check if the sql is stored, else generate and store - IQueryMasterDao queryMasterDao = sfDAOFactory.getQueryMasterDAO(); - IQueryInstanceDao queryInstaneDao = sfDAOFactory - .getQueryInstanceDAO(); - QtQueryInstance queryInstance = queryInstaneDao - .getQueryInstanceByInstanceId(queryInstanceId); - String masterId = queryInstance.getQtQueryMaster() - .getQueryMasterId(); - QtQueryMaster queryMaster = queryMasterDao - .getQueryDefinition(masterId); - String generatedSql = queryMaster.getGeneratedSql(); - if (generatedSql == null) { - generatedSql = ""; - } - String missingItemMessage = "", processTimingMessage = ""; - boolean missingItemFlag = false; - String queryType = null; - - if (generatedSql.trim().length() == 0) { - // check if the sql is for patient set or encounter set - boolean encounterSetFlag = this - .getEncounterSetFlag(resultOutputList); - - // generate sql and store - IQueryRequestDao requestDao = sfDAOFactory.getQueryRequestDAO(); - requestDao.setProjectParam(projectParamMap) ; - requestDao.setAllowLargeTextValueConstrainFlag(allowLargeTextValueConstrainFlag); - //requestDao.setAllowProtectedQueryFlag(allowProtectedQueryFlag); - requestDao.setQueryWithoutTempTableFlag(queryWithoutTempTableFlag); - requestDao.setUserRoles(userRoles); - - String[] sqlResult = null; - if (this.queryCountMinSketchFlag) { - //generate sql for each panel - try { - RequestMessageType reqMsgType = this.getRequestMessageType(requestXml); - QueryDefinitionRequestType queryDefRequestType = this.getQueryDefinitionRequestType(reqMsgType); - PanelType[] panelList = queryDefRequestType.getQueryDefinition().getPanel().toArray(new PanelType[]{}); - String newRequestMsg = ""; - - /* - * create table qt_est_observation_fact - as - - select lower(c.concept_path) as concept_path, o.patient_num as patient_num, min(o.nval_num) as min_nval_num, max(o.nval_num) as max_nval_num, - count(patient_num) as instance_num, avg(o.nval_num) as avg_nval_num, - min(o.start_date) as first_start_date, max(o.start_date) as last_start_date - from observation_fact o, concept_dimension c - where - o.concept_cd = c.concept_cd - group by o.patient_num, c.concept_path - - - select concat('', count(nval_num),'', cast(nval_num as integer), '') - from observation_fact - where concept_cd = 'LOINC:14815-5' - and nval_num is not null - group by cast(nval_num as integer) - - SELECT cast(nval_num as integer) as a, - COUNT(*) AS Count - FROM - (SELECT - nval_num, - NTILE(70) OVER (ORDER BY m.nval_num) AS Buckets - FROM - observation_fact m - where concept_cd = 'LOINC:9830-1' - - ) m - WHERE - Buckets BETWEEN 2 AND 69 - GROUP BY cast(nval_num as integer) - - - - truncate table calc_qt_breakdown - GO - insert into calc_qt_breakdown - select 'sex_cd', sex_cd as patient_range, count(distinct patient_num) as patient_count - from patient_dimension group by sex_cd order by 1 - GO - insert into calc_qt_breakdown - select 'race_cd', b.c_name as patient_range, count(distinct a.patient_num) as patient_count - from patient_dimension a, i2b2 b where a.race_cd = b.c_dimcode group by a.race_cd, b.c_name order by 1 - GO - insert into calc_qt_breakdown - select 'total_counts', 'patients', count(distinct patient_num) from observation_fact - GO - insert into calc_qt_breakdown - select 'total_counts', 'encounters', count(distinct encounter_num) from observation_fact - GO - insert into calc_qt_breakdown - select 'total_counts', 'diagnosis', count( patient_num) from observation_fact where concept_cd IN (select concept_cd from public.concept_dimension where concept_path LIKE '\\i2b2\\Diagnoses\\%' ) - GO - insert into calc_qt_breakdown - select 'total_counts', 'Labtests', count( patient_num) from observation_fact where concept_cd IN (select concept_cd from public.concept_dimension where concept_path LIKE '\\i2b2\\Labtests\\%' ) - GO - insert into calc_qt_breakdown - select 'total_counts', 'medications', count( patient_num) from observation_fact where concept_cd IN (select concept_cd from public.concept_dimension where concept_path LIKE '\\i2b2\\Medications\\%' ) - GO - insert into calc_qt_breakdown - select 'top10diag', b.name_char as patient_range, count(distinct a.patient_num) as patient_count from observation_fact a, concept_dimension b where a.concept_cd = b.concept_cd and concept_path like '\\i2b2\\Diagnoses\\%' group by name_char order by patient_count desc limit 10 - GO - insert into calc_qt_breakdown - select 'age_cd', '>= 85 years old', count(distinct patient_num) from patient_dimension where birth_date <= (CURRENT_DATE - INTERVAL '31047.25 day') - GO - insert into calc_qt_breakdown - select 'age_cd', '35-44 years old', count(distinct patient_num) from patient_dimension where birth_date BETWEEN (CURRENT_DATE - INTERVAL '16437.25 day') AND (CURRENT_DATE - INTERVAL '12784.75 day') - GO - insert into calc_qt_breakdown - select 'age_cd', '>= 65 years old', count(distinct patient_num) from patient_dimension where birth_date <= (CURRENT_DATE - INTERVAL '23741.25 day') - GO - insert into calc_qt_breakdown - select 'age_cd', '75-84 years old', count(distinct patient_num) from patient_dimension where birth_date BETWEEN (CURRENT_DATE - INTERVAL '31047.25 day') AND (CURRENT_DATE - INTERVAL '27394.75 day') - GO - insert into calc_qt_breakdown - select 'age_cd', '55-64 years old', count(distinct patient_num) from patient_dimension where birth_date BETWEEN (CURRENT_DATE - INTERVAL '23742.25 day') AND (CURRENT_DATE - INTERVAL '20089.75 day') - GO - insert into calc_qt_breakdown - select 'age_cd', '45-54 years old', count(distinct patient_num) from patient_dimension where birth_date BETWEEN (CURRENT_DATE - INTERVAL '20089.75 day') AND (CURRENT_DATE - INTERVAL '16437.25 day') - GO - insert into calc_qt_breakdown - select 'age_cd', '0-9 years old', count(distinct patient_num) from patient_dimension where birth_date > (CURRENT_DATE - INTERVAL '3653.5 day') - GO - insert into calc_qt_breakdown - select 'age_cd', '18-34 years old', count(distinct patient_num) from patient_dimension where birth_date BETWEEN (CURRENT_DATE - INTERVAL '12784.75 day') AND (CURRENT_DATE - INTERVAL '6575.5 day') - GO - insert into calc_qt_breakdown - select 'age_cd', '10-17 years old', count(distinct patient_num) from patient_dimension where birth_date BETWEEN (CURRENT_DATE - INTERVAL '6575.5 day') AND (CURRENT_DATE - INTERVAL '3653.5 day') - GO - insert into calc_qt_breakdown - select 'age_cd', '65-74 years old', count(distinct patient_num) from patient_dimension where birth_date BETWEEN (CURRENT_DATE - INTERVAL '27394.75 day') AND (CURRENT_DATE - INTERVAL '23742.25 day') - GO - select * from calc_qt_breakdown - - */ - - generatedSql = ""; - for (int i =0; i < panelList.length; i++) { - //PanelType panelType = panelList[i]; - //buildRequestXml(panelType); - //queryDefRequestType.getQueryDefinition().getPanel().clear(); - log.debug("Setfinder query panel count " + panelList.length); - //queryDefRequestType.getQueryDefinition().getPanel().add(panelType); - //newRequestMsg = this.buildRequestMessage(reqMsgType, queryDefRequestType); - - log.debug("Single panel request message [" + newRequestMsg + "]"); - //send request xml for each panel - - - - - generatedSql += "select distinct patient_num from "+ this.getDbSchemaName() +"qt_est_observation_fact where " ; - - for (int j=0; j< panelList[i].getItem().size(); j++) - { - ItemType item = panelList[i].getItem().get(j); - String key = item.getItemKey(); - - - ConceptType conceptType = null; - try { - - - - SecurityType securityType = PMServiceAccountUtil - .getServiceSecurityType(dataSourceLookup.getDomainId()); - - - conceptType = CallOntologyUtil.callOntology(key, - securityType, dataSourceLookup.getProjectPath(), - QueryProcessorUtil.getInstance().getOntologyUrl()); - - } catch (Exception e) { - - log.error("Error while fetching metadata [" + key - + "] from ontology ", e); - throw new OntologyException("Error while fetching metadata [" - + key + "] from ontology " - + StackTraceUtil.getStackTrace(e)); - } - - key = key.substring(key.indexOf('\\', 3)).toLowerCase(); - if (dsLookup.getServerType().equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) - key = key.replace("\\", "\\\\"); - - generatedSql += " ( concept_path LIKE '" + key + "%'"; - if ( item.getConstrainByValue() != null) - { - for (ItemType.ConstrainByValue valueConstrain : item.getConstrainByValue()) { - - ConstrainValueType valueType = valueConstrain.getValueType(); - ConstrainOperatorType operatorType = valueConstrain - .getValueOperator(); - String value = valueConstrain.getValueConstraint(); - - if (valueType.equals(ConstrainValueType.NUMBER)) { - // check if operator and value not null - if (operatorType == null || value == null) { - continue; - } - - - if (operatorType.value().equalsIgnoreCase( - ConstrainOperatorType.GT.value())) { - generatedSql += - " and min_nval_num > " + value; - } else if (operatorType.value().equalsIgnoreCase( - ConstrainOperatorType.GE.value())) { - generatedSql += " and min_nval_num >= " + value; - } else if (operatorType.value().equalsIgnoreCase( - ConstrainOperatorType.LT.value())) { - generatedSql += " and min_nval_num < " + value; - } else if (operatorType.value().equalsIgnoreCase( - ConstrainOperatorType.LE.value())) { - generatedSql += " and min_nval_num <= " + value; - } else if (operatorType.value().equalsIgnoreCase( - ConstrainOperatorType.EQ.value())) { - generatedSql += " and min_nval_num = " + value - + " and max_nval_num = " + value; - } else if (operatorType.value().equalsIgnoreCase( - ConstrainOperatorType.BETWEEN.value())) { - generatedSql += " and min_nval_num > " + value - + " and max_nval_num < " + value; - } else if (operatorType.value().equalsIgnoreCase( - ConstrainOperatorType.NE.value())) { - generatedSql += " and min_nval_num < " + value; - } else { - throw new I2B2DAOException( - "Error NUMBER value constrain because operator(" - + operatorType.toString() + ")is invalid"); - } - - } - } - } - - if (panelList[i].getItem().size() != (j + 1)) - generatedSql += " ) or "; - else - generatedSql += " ) "; - - } - if (panelList.length != (i + 1)) - generatedSql += " union all "; - - } - - generatedSql = "select count(*) as patient_num_count from (select count( *) as mycount, patient_num from (" + - generatedSql + - " ) as a group by patient_num ) as b where mycount = " + panelList.length; - - log.debug("Setfinder converted sql without temp table " + generatedSql); - - } catch (JAXBUtilException e) { - e.printStackTrace(); - } catch (I2B2Exception e) { - e.printStackTrace(); - } - log.debug("Setfinder skip temp table generated sql " + generatedSql); - log.debug("Setfinder skip temp table missing item message " + missingItemMessage); - log.debug("Setfinder skip temp table process timing message " + processTimingMessage); - } - else if (this.queryWithoutTempTableFlag == false) { - sqlResult = requestDao.buildSql(requestXml, - encounterSetFlag); - generatedSql = sqlResult[0]; - missingItemMessage = sqlResult[1]; - processTimingMessage = sqlResult[2]; - if (sqlResult.length>3) - queryType = sqlResult[3]; - } else { - //generate sql for each panel - try { - RequestMessageType reqMsgType = this.getRequestMessageType(requestXml); - QueryDefinitionRequestType queryDefRequestType = this.getQueryDefinitionRequestType(reqMsgType); - PanelType[] panelList = queryDefRequestType.getQueryDefinition().getPanel().toArray(new PanelType[]{}); - String newRequestMsg = ""; - boolean buildSqlWithOR = true; - - boolean fullSqlGenerated = false; - while (!fullSqlGenerated) { - generatedSql = ""; - for (int i =0; i < panelList.length; i++) { - PanelType panelType = panelList[i]; - //buildRequestXml(panelType); - queryDefRequestType.getQueryDefinition().getPanel().clear(); - log.debug("Setfinder query panel count " + panelList.length); - queryDefRequestType.getQueryDefinition().getPanel().add(panelType); - newRequestMsg = this.buildRequestMessage(reqMsgType, queryDefRequestType); - - log.debug("Single panel request message [" + newRequestMsg + "]"); - //send request xml for each panel - sqlResult = requestDao.buildSql(newRequestMsg, - encounterSetFlag); - DirectQueryForSinglePanel directQuerySql = new DirectQueryForSinglePanel(); - if (buildSqlWithOR == false) { - generatedSql += "\n(" + directQuerySql.buildSqlWithUnion(sqlResult[0]) + ")\n"; - if (i+1 < panelList.length) { - generatedSql += " INTERSECT \n"; - } - } else if (buildSqlWithOR == true && (sqlResult[0].indexOf("patient_dimension where")>0 || - sqlResult[0].indexOf("visit_dimension where")>0)) { - buildSqlWithOR = false; - fullSqlGenerated = false; - break; - } else { - generatedSql += "\n(" + directQuerySql.buildSqlWithOR(sqlResult[0]) + ")\n"; - if (i+1 < panelList.length) { - generatedSql += " INTERSECT \n"; - generatedSql += "select patient_num from " + this.getDbSchemaName() +"observation_fact f where \n"; - } - } - - if (sqlResult[1] != null && sqlResult[1].trim().length()>0) { - missingItemMessage += sqlResult[1]; - } - if (sqlResult[2] != null && sqlResult[2].trim().length()>0) { - processTimingMessage += sqlResult[2]; - } - if (sqlResult[3] != null && sqlResult[3].trim().length()>0) { - queryType = sqlResult[3]; - } - fullSqlGenerated = true; - } - } - - if (buildSqlWithOR) { - generatedSql = "select patient_num from " + this.getDbSchemaName() +"observation_fact f where " + generatedSql; - } - generatedSql = "select count(distinct patient_num) as patient_num_count from ( \n" + generatedSql + " \n ) allitem "; - - logesapi.debug("Setfinder converted sql without temp table " + generatedSql); - - } catch (JAXBUtilException e) { - e.printStackTrace(); - } catch (I2B2Exception e) { - e.printStackTrace(); - } - logesapi.debug("Setfinder skip temp table generated sql " + generatedSql); - logesapi.debug("Setfinder skip temp table missing item message " + missingItemMessage); - logesapi.debug("Setfinder skip temp table process timing message " + processTimingMessage); - } - queryMasterDao.updateQueryAfterRun(masterId, generatedSql, queryType); - - if (missingItemMessage != null - && missingItemMessage.trim().length() > 1) { - logesapi.debug("Setfinder query missing item message not null" + missingItemMessage); - missingItemFlag = true; - - queryInstance.setEndDate(new Date(System - .currentTimeMillis())); - // queryInstance.setMessage(missingItemMessage); - setQueryInstanceStatus(sfDAOFactory, queryInstanceId, 4, - missingItemMessage); - // update the error status to result instance - setQueryResultInstanceStatus(sfDAOFactory, queryInstanceId, - 4, missingItemMessage); - throw new I2B2DAOException("Concept missing"); - - } - - if (processTimingMessage != null && processTimingMessage.trim().length()>0) { - - setQueryInstanceProcessTimingXml(sfDAOFactory, - queryInstanceId, processTimingMessage); - - } - - } - log.debug("Setfinder before executor helper dao missingItemFlag " + missingItemFlag); - if (missingItemFlag == false) { - QueryExecutorHelperDao helperDao = new QueryExecutorHelperDao( - dataSource, dataSourceLookup, originalDataSourceLookup); - helperDao.setProcessTimingFlag(processTimingFlag); - helperDao.setQueryWithoutTempTableFlag(this.queryWithoutTempTableFlag); - if (this.queryCountMinSketchFlag) - helperDao.setQueryWithoutTempTableFlag(this.queryCountMinSketchFlag); - helperDao.executeQuery( transactionTimeout, - dsLookup, sfDAOFactory, requestXml, sqlString, - queryInstanceId, patientSetId, resultOutputList, - generatedSql, pmXml); - - } - } catch (NamingException e) { - exception = e; - errorFlag = true; - } catch (SecurityException e) { - exception = e; - errorFlag = true; - } catch (IllegalStateException e) { - exception = e; - errorFlag = true; - } catch (CRCTimeOutException e) { - throw e; - } catch (I2B2DAOException e) { - - setQueryInstanceStatus(sfDAOFactory, queryInstanceId, 4, - e.getMessage()); - // update the error status to result instance - setQueryResultInstanceStatus(sfDAOFactory, queryInstanceId, - 4, e.getMessage()); - - log.debug("Error in QueryExecutorDAO Throwing: " + e.getMessage()); - exception = e; - errorFlag = true; - throw e; - } finally { - // close resultset and statement - try { - if (resultSet != null) { - resultSet.close(); - } - resultSet = null; - if (stmt != null) { - stmt.close(); - } - stmt = null; - if (manualConnection != null) { - manualConnection.close(); - } - manualConnection = null; - - } catch (SQLException sqle) { - log.error("Error closing statement/resultset ", sqle); - } - } - return patientSetId; - } - - private void setQueryInstanceStatus(SetFinderDAOFactory sfDAOFactory, - String queryInstanceId, int statusTypeId, String message) throws I2B2DAOException { - IQueryInstanceDao queryInstanceDao = sfDAOFactory.getQueryInstanceDAO(); - QtQueryInstance queryInstance = queryInstanceDao - .getQueryInstanceByInstanceId(queryInstanceId); - - QtQueryStatusType queryStatusType = new QtQueryStatusType(); - queryStatusType.setStatusTypeId(statusTypeId); - queryInstance.setQtQueryStatusType(queryStatusType); - queryInstance.setEndDate(new Date(System.currentTimeMillis())); - queryInstance.setMessage(queryInstance.getMessage() + "\n" + message); - queryInstanceDao.update(queryInstance, true); - } - - private void setQueryInstanceProcessTimingXml(SetFinderDAOFactory sfDAOFactory, - String queryInstanceId, String message) throws I2B2DAOException { - IQueryInstanceDao queryInstanceDao = sfDAOFactory.getQueryInstanceDAO(); - queryInstanceDao.updateMessage(queryInstanceId, message, true); - - } - - private void setQueryResultInstanceStatus(SetFinderDAOFactory sfDAOFactory, - String queryInstanceId, int statusTypeId, String message) { - IQueryResultInstanceDao queryResultInstanceDao = sfDAOFactory - .getPatientSetResultDAO(); - List resultInstanceList = queryResultInstanceDao - .getResultInstanceList(queryInstanceId); - for (QtQueryResultInstance queryResultInstance : resultInstanceList) { - queryResultInstanceDao.updatePatientSet(queryResultInstance - .getResultInstanceId(), statusTypeId, message, -1, -1, ""); - } - - } - - - - public boolean getEncounterSetFlag( - ResultOutputOptionListType resultOutputList) { - boolean encounterFoundFlag = false; - for (ResultOutputOptionType resultOutputOption : resultOutputList - .getResultOutput()) { - if (resultOutputOption.getName().equalsIgnoreCase( - "PATIENT_ENCOUNTER_SET")) { - encounterFoundFlag = true; - break; - } - } - return encounterFoundFlag; - } - - /** - * Call PM to get user roles. The security info is taken from the request - * xml - * - * @param requestXml - * @return - * @throws I2B2Exception - */ - public List getRoleFromPM(String requestXml) throws I2B2Exception { - - I2B2RequestMessageHelper reqMsgHelper = new I2B2RequestMessageHelper( - requestXml); - SecurityType origSecurityType = reqMsgHelper.getSecurityType(); - String projectId = reqMsgHelper.getProjectId(); - - SecurityType serviceSecurityType = PMServiceAccountUtil - .getServiceSecurityType(origSecurityType.getDomain()); - //EJBPMUtil callPMUtil = new EJBPMUtil(serviceSecurityType, projectId); - List roleList = new ArrayList(); - try { - //RolesType rolesType = callPMUtil.callGetRole(origSecurityType - // .getUsername(), projectId); - RolesType rolesType = EJBPMUtil.callGetRole(origSecurityType - .getUsername(), origSecurityType, projectId, QueryProcessorUtil.getInstance() - .getProjectManagementCellUrl()); - - - RoleType roleType = null; - for (java.util.Iterator iterator = rolesType.getRole() - .iterator(); iterator.hasNext();) { - roleType = iterator.next(); - roleList.add(roleType.getRole()); - } - - } catch (AxisFault e) { - throw new I2B2Exception(" Failed to get user role from PM " - + StackTraceUtil.getStackTrace(e)); - } - return roleList; - /* - * I2B2RequestMessageHelper reqMsgHelper = new I2B2RequestMessageHelper( - * requestXml); SecurityType securityType = - * reqMsgHelper.getSecurityType(); String projectId = - * reqMsgHelper.getProjectId(); // get roles from pm driver - * PMServiceDriver serviceDriver = new PMServiceDriver(); ProjectType - * projectType = null; - * - * try { projectType = serviceDriver.checkValidUser(securityType, - * projectId); } catch (AxisFault e) { e.printStackTrace(); throw new - * I2B2Exception(" Failed to get user role from PM " + - * StackTraceUtil.getStackTrace(e)); } catch (JAXBUtilException e) { - * e.printStackTrace(); throw new - * I2B2Exception(" Failed to get user role from PM " + - * StackTraceUtil.getStackTrace(e)); } return projectType.getRole(); - */ - } - - private RequestMessageType getRequestMessageType (String xmlRequest) throws I2B2Exception, JAXBUtilException { - JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); - JAXBElement jaxbElement = jaxbUtil.unMashallFromString(xmlRequest); - - if (jaxbElement == null) { - throw new I2B2Exception( - "null value in after unmarshalling request string "); - } - - RequestMessageType requestMessageType = (RequestMessageType) jaxbElement - .getValue(); - return requestMessageType; - } - - - public QueryDefinitionRequestType getQueryDefinitionRequestType(RequestMessageType requestMessageType) throws JAXBUtilException { - BodyType bodyType = requestMessageType.getMessageBody(); - JAXBUnWrapHelper unWrapHelper = new JAXBUnWrapHelper(); - QueryDefinitionRequestType queryDefReqType = (QueryDefinitionRequestType) unWrapHelper - .getObjectByClass(bodyType.getAny(), - QueryDefinitionRequestType.class); - return queryDefReqType; - - - } - - - private String buildRequestMessage(RequestMessageType requestMessageType , QueryDefinitionRequestType queryDefRequestType) throws JAXBUtilException{ - edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory setfinderOf = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); - requestMessageType.getMessageBody().getAny().add(setfinderOf.createRequest(queryDefRequestType)); - JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); - StringWriter strWriter = new StringWriter(); - ObjectFactory ob = new ObjectFactory(); - jaxbUtil.marshaller(ob.createRequest(requestMessageType), strWriter); - return strWriter.toString(); - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder; + +import java.io.StringWriter; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.naming.InitialContext; +import javax.naming.NamingException; +import javax.sql.DataSource; +import jakarta.xml.bind.JAXBElement; + +import org.apache.axis2.AxisFault; +//import org.springframework.beans.factory.BeanFactory; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.exception.StackTraceUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.DirectQueryForSinglePanel; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.OntologyException; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.ProcessTimingReportUtil; +import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.db.QtQueryInstance; +import edu.harvard.i2b2.crc.datavo.db.QtQueryMaster; +import edu.harvard.i2b2.crc.datavo.db.QtQueryResultInstance; +import edu.harvard.i2b2.crc.datavo.db.QtQueryStatusType; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; +import edu.harvard.i2b2.crc.datavo.ontology.ConceptType; +import edu.harvard.i2b2.crc.datavo.ontology.DerivedFactColumnsType; +import edu.harvard.i2b2.crc.datavo.pm.RoleType; +import edu.harvard.i2b2.crc.datavo.pm.RolesType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ConstrainOperatorType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ConstrainValueType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ItemType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.PanelType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionRequestType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultOutputOptionListType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultOutputOptionType; +import edu.harvard.i2b2.crc.delegate.ejbpm.EJBPMUtil; +import edu.harvard.i2b2.crc.delegate.ontology.CallOntologyUtil; +import edu.harvard.i2b2.crc.ejb.ExecRunnable; +import edu.harvard.i2b2.crc.util.I2B2RequestMessageHelper; +import edu.harvard.i2b2.crc.util.LogTimingUtil; +import edu.harvard.i2b2.crc.util.PMServiceAccountUtil; +import edu.harvard.i2b2.crc.util.ParamUtil; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; +import edu.harvard.i2b2.crc.util.SqlClauseUtil; + +public class QueryExecutorDao extends CRCDAO implements IQueryExecutorDao { + + + protected static Log logesapi = LogFactory.getLog(ExecRunnable.class); + + + private DataSourceLookup dataSourceLookup = null, + originalDataSourceLookup = null; + // private static Map generatorMap = null; + // private static String defaultResultType = null; + private Map projectParamMap = new HashMap(); + private boolean queryWithoutTempTableFlag = false; + private boolean queryCountMinSketchFlag = false; + static { + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + // qpUtil.getManualConnection() + + // BeanFactory bf = qpUtil.getSpringBeanFactory(); + // generatorMap = (Map) bf.getBean("setFinderResultGeneratorMap"); + // defaultResultType = (String) bf.getBean("defaultSetfinderResultType"); + } + + public QueryExecutorDao(DataSource dataSource, + DataSourceLookup dataSourceLookup, + DataSourceLookup originalDataSourceLookup) { + setDataSource(dataSource); + setDbSchemaName(dataSourceLookup.getFullSchema()); + this.dataSourceLookup = dataSourceLookup; + this.originalDataSourceLookup = originalDataSourceLookup; + } + + // + public void setQueryWithoutTempTableFlag(boolean queryWithoutTempTableFlag) { + this.queryWithoutTempTableFlag = queryWithoutTempTableFlag; + } + + public void setQueryCountMinSketchFlag(boolean queryCountMinSketchFlag) { + this.queryCountMinSketchFlag = queryCountMinSketchFlag; + } + /** + * This function executes the given sql and create query result instance and + * its collection + * + * @param conn + * db connection + * @param sqlString + * @param queryInstanceId + * @param userRoles + * @return query result instance id + * @throws JAXBUtilException + * @throws I2B2Exception + */ + @Override + public String executeSQL( + int transactionTimeout, DataSourceLookup dsLookup, + SetFinderDAOFactory sfDAOFactory, String requestXml, + String sqlString, String queryInstanceId, String patientSetId, + ResultOutputOptionListType resultOutputList, boolean allowLargeTextValueConstrainFlag, String pmXml, List userRoles) + throws I2B2Exception, JAXBUtilException { + + String singleSql = null; + int recordCount = 0; + + boolean errorFlag = false, timeOutErrorFlag = false; + Statement stmt = null; + ResultSet resultSet = null; + Connection manualConnection = null; + /** Global temp table to store intermediate setfinder results* */ + String TEMP_TABLE = "#GLOBAL_TEMP_TABLE"; + + /** Global temp table to store intermediate patient list * */ + String TEMP_DX_TABLE = "#DX"; + if (dsLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER)) { + TEMP_TABLE = getDbSchemaName() + "#GLOBAL_TEMP_TABLE"; + TEMP_DX_TABLE = getDbSchemaName() + "#DX"; + + } else if (dsLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.ORACLE) || dsLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) { + TEMP_TABLE = getDbSchemaName() + "QUERY_GLOBAL_TEMP"; + TEMP_DX_TABLE = getDbSchemaName() + "DX"; + } + Exception exception = null; + + InitialContext context; + try { + context = new InitialContext(); + + String processTimingFlag = LogTimingUtil.getPocessTiming(originalDataSourceLookup.getProjectPath(), originalDataSourceLookup.getOwnerId(), + originalDataSourceLookup.getDomainId()); + if (processTimingFlag == null) { + processTimingFlag = ProcessTimingReportUtil.NONE; + } + + projectParamMap.put(ParamUtil.PM_ENABLE_PROCESS_TIMING, processTimingFlag); + ParamUtil projectParamUtil = new ParamUtil(); + String unitConversionFlag = projectParamUtil.getParam(originalDataSourceLookup.getProjectPath(), originalDataSourceLookup.getOwnerId(), + originalDataSourceLookup.getDomainId(), ParamUtil.CRC_ENABLE_UNITCD_CONVERSION); + if (unitConversionFlag != null) { + projectParamMap.put(ParamUtil.CRC_ENABLE_UNITCD_CONVERSION, unitConversionFlag.trim()); + } + + + // change status of result instance to running + IQueryResultInstanceDao psResultDao = sfDAOFactory + .getPatientSetResultDAO(); + psResultDao.updatePatientSet(patientSetId, 2, 0); + + + // check if the sql is stored, else generate and store + IQueryMasterDao queryMasterDao = sfDAOFactory.getQueryMasterDAO(); + IQueryInstanceDao queryInstaneDao = sfDAOFactory + .getQueryInstanceDAO(); + QtQueryInstance queryInstance = queryInstaneDao + .getQueryInstanceByInstanceId(queryInstanceId); + String masterId = queryInstance.getQtQueryMaster() + .getQueryMasterId(); + QtQueryMaster queryMaster = queryMasterDao + .getQueryDefinition(masterId); + String generatedSql = queryMaster.getGeneratedSql(); + if (generatedSql == null) { + generatedSql = ""; + } + String missingItemMessage = "", processTimingMessage = ""; + boolean missingItemFlag = false; + String queryType = null; + + if (generatedSql.trim().length() == 0) { + // check if the sql is for patient set or encounter set + boolean encounterSetFlag = this + .getEncounterSetFlag(resultOutputList); + + // generate sql and store + IQueryRequestDao requestDao = sfDAOFactory.getQueryRequestDAO(); + requestDao.setProjectParam(projectParamMap) ; + requestDao.setAllowLargeTextValueConstrainFlag(allowLargeTextValueConstrainFlag); + //requestDao.setAllowProtectedQueryFlag(allowProtectedQueryFlag); + requestDao.setQueryWithoutTempTableFlag(queryWithoutTempTableFlag); + requestDao.setUserRoles(userRoles); + + String[] sqlResult = null; + if (this.queryCountMinSketchFlag) { + //generate sql for each panel + try { + RequestMessageType reqMsgType = this.getRequestMessageType(requestXml); + QueryDefinitionRequestType queryDefRequestType = this.getQueryDefinitionRequestType(reqMsgType); + PanelType[] panelList = queryDefRequestType.getQueryDefinition().getPanel().toArray(new PanelType[]{}); + String newRequestMsg = ""; + + /* + * create table qt_est_observation_fact + as + + select lower(c.concept_path) as concept_path, o.patient_num as patient_num, min(o.nval_num) as min_nval_num, max(o.nval_num) as max_nval_num, + count(patient_num) as instance_num, avg(o.nval_num) as avg_nval_num, + min(o.start_date) as first_start_date, max(o.start_date) as last_start_date + from observation_fact o, concept_dimension c + where + o.concept_cd = c.concept_cd + group by o.patient_num, c.concept_path + + + select concat('', count(nval_num),'', cast(nval_num as integer), '') + from observation_fact + where concept_cd = 'LOINC:14815-5' + and nval_num is not null + group by cast(nval_num as integer) + + SELECT cast(nval_num as integer) as a, + COUNT(*) AS Count + FROM + (SELECT + nval_num, + NTILE(70) OVER (ORDER BY m.nval_num) AS Buckets + FROM + observation_fact m + where concept_cd = 'LOINC:9830-1' + + ) m + WHERE + Buckets BETWEEN 2 AND 69 + GROUP BY cast(nval_num as integer) + + + + truncate table calc_qt_breakdown + GO + insert into calc_qt_breakdown + select 'sex_cd', sex_cd as patient_range, count(distinct patient_num) as patient_count + from patient_dimension group by sex_cd order by 1 + GO + insert into calc_qt_breakdown + select 'race_cd', b.c_name as patient_range, count(distinct a.patient_num) as patient_count + from patient_dimension a, i2b2 b where a.race_cd = b.c_dimcode group by a.race_cd, b.c_name order by 1 + GO + insert into calc_qt_breakdown + select 'total_counts', 'patients', count(distinct patient_num) from observation_fact + GO + insert into calc_qt_breakdown + select 'total_counts', 'encounters', count(distinct encounter_num) from observation_fact + GO + insert into calc_qt_breakdown + select 'total_counts', 'diagnosis', count( patient_num) from observation_fact where concept_cd IN (select concept_cd from public.concept_dimension where concept_path LIKE '\\i2b2\\Diagnoses\\%' ) + GO + insert into calc_qt_breakdown + select 'total_counts', 'Labtests', count( patient_num) from observation_fact where concept_cd IN (select concept_cd from public.concept_dimension where concept_path LIKE '\\i2b2\\Labtests\\%' ) + GO + insert into calc_qt_breakdown + select 'total_counts', 'medications', count( patient_num) from observation_fact where concept_cd IN (select concept_cd from public.concept_dimension where concept_path LIKE '\\i2b2\\Medications\\%' ) + GO + insert into calc_qt_breakdown + select 'top10diag', b.name_char as patient_range, count(distinct a.patient_num) as patient_count from observation_fact a, concept_dimension b where a.concept_cd = b.concept_cd and concept_path like '\\i2b2\\Diagnoses\\%' group by name_char order by patient_count desc limit 10 + GO + insert into calc_qt_breakdown + select 'age_cd', '>= 85 years old', count(distinct patient_num) from patient_dimension where birth_date <= (CURRENT_DATE - INTERVAL '31047.25 day') + GO + insert into calc_qt_breakdown + select 'age_cd', '35-44 years old', count(distinct patient_num) from patient_dimension where birth_date BETWEEN (CURRENT_DATE - INTERVAL '16437.25 day') AND (CURRENT_DATE - INTERVAL '12784.75 day') + GO + insert into calc_qt_breakdown + select 'age_cd', '>= 65 years old', count(distinct patient_num) from patient_dimension where birth_date <= (CURRENT_DATE - INTERVAL '23741.25 day') + GO + insert into calc_qt_breakdown + select 'age_cd', '75-84 years old', count(distinct patient_num) from patient_dimension where birth_date BETWEEN (CURRENT_DATE - INTERVAL '31047.25 day') AND (CURRENT_DATE - INTERVAL '27394.75 day') + GO + insert into calc_qt_breakdown + select 'age_cd', '55-64 years old', count(distinct patient_num) from patient_dimension where birth_date BETWEEN (CURRENT_DATE - INTERVAL '23742.25 day') AND (CURRENT_DATE - INTERVAL '20089.75 day') + GO + insert into calc_qt_breakdown + select 'age_cd', '45-54 years old', count(distinct patient_num) from patient_dimension where birth_date BETWEEN (CURRENT_DATE - INTERVAL '20089.75 day') AND (CURRENT_DATE - INTERVAL '16437.25 day') + GO + insert into calc_qt_breakdown + select 'age_cd', '0-9 years old', count(distinct patient_num) from patient_dimension where birth_date > (CURRENT_DATE - INTERVAL '3653.5 day') + GO + insert into calc_qt_breakdown + select 'age_cd', '18-34 years old', count(distinct patient_num) from patient_dimension where birth_date BETWEEN (CURRENT_DATE - INTERVAL '12784.75 day') AND (CURRENT_DATE - INTERVAL '6575.5 day') + GO + insert into calc_qt_breakdown + select 'age_cd', '10-17 years old', count(distinct patient_num) from patient_dimension where birth_date BETWEEN (CURRENT_DATE - INTERVAL '6575.5 day') AND (CURRENT_DATE - INTERVAL '3653.5 day') + GO + insert into calc_qt_breakdown + select 'age_cd', '65-74 years old', count(distinct patient_num) from patient_dimension where birth_date BETWEEN (CURRENT_DATE - INTERVAL '27394.75 day') AND (CURRENT_DATE - INTERVAL '23742.25 day') + GO + select * from calc_qt_breakdown + + */ + + generatedSql = ""; + for (int i =0; i < panelList.length; i++) { + //PanelType panelType = panelList[i]; + //buildRequestXml(panelType); + //queryDefRequestType.getQueryDefinition().getPanel().clear(); + log.debug("Setfinder query panel count " + panelList.length); + //queryDefRequestType.getQueryDefinition().getPanel().add(panelType); + //newRequestMsg = this.buildRequestMessage(reqMsgType, queryDefRequestType); + + log.debug("Single panel request message [" + newRequestMsg + "]"); + //send request xml for each panel + + + + + generatedSql += "select distinct patient_num from "+ this.getDbSchemaName() +"qt_est_observation_fact where " ; + + for (int j=0; j< panelList[i].getItem().size(); j++) + { + ItemType item = panelList[i].getItem().get(j); + String key = item.getItemKey(); + + + ConceptType conceptType = null; + try { + + + + SecurityType securityType = PMServiceAccountUtil + .getServiceSecurityType(dataSourceLookup.getDomainId()); + + + conceptType = CallOntologyUtil.callOntology(key, + securityType, dataSourceLookup.getProjectPath(), + QueryProcessorUtil.getInstance().getOntologyUrl()); + + } catch (Exception e) { + + log.error("Error while fetching metadata [" + key + + "] from ontology ", e); + throw new OntologyException("Error while fetching metadata [" + + key + "] from ontology " + + StackTraceUtil.getStackTrace(e)); + } + + key = key.substring(key.indexOf('\\', 3)).toLowerCase(); + if (dsLookup.getServerType().equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) + key = key.replace("\\", "\\\\"); + + generatedSql += " ( concept_path LIKE '" + key + "%'"; + if ( item.getConstrainByValue() != null) + { + for (ItemType.ConstrainByValue valueConstrain : item.getConstrainByValue()) { + + ConstrainValueType valueType = valueConstrain.getValueType(); + ConstrainOperatorType operatorType = valueConstrain + .getValueOperator(); + String value = valueConstrain.getValueConstraint(); + + if (valueType.equals(ConstrainValueType.NUMBER)) { + // check if operator and value not null + if (operatorType == null || value == null) { + continue; + } + + + if (operatorType.value().equalsIgnoreCase( + ConstrainOperatorType.GT.value())) { + generatedSql += + " and min_nval_num > " + value; + } else if (operatorType.value().equalsIgnoreCase( + ConstrainOperatorType.GE.value())) { + generatedSql += " and min_nval_num >= " + value; + } else if (operatorType.value().equalsIgnoreCase( + ConstrainOperatorType.LT.value())) { + generatedSql += " and min_nval_num < " + value; + } else if (operatorType.value().equalsIgnoreCase( + ConstrainOperatorType.LE.value())) { + generatedSql += " and min_nval_num <= " + value; + } else if (operatorType.value().equalsIgnoreCase( + ConstrainOperatorType.EQ.value())) { + generatedSql += " and min_nval_num = " + value + + " and max_nval_num = " + value; + } else if (operatorType.value().equalsIgnoreCase( + ConstrainOperatorType.BETWEEN.value())) { + generatedSql += " and min_nval_num > " + value + + " and max_nval_num < " + value; + } else if (operatorType.value().equalsIgnoreCase( + ConstrainOperatorType.NE.value())) { + generatedSql += " and min_nval_num < " + value; + } else { + throw new I2B2DAOException( + "Error NUMBER value constrain because operator(" + + operatorType.toString() + ")is invalid"); + } + + } + } + } + + if (panelList[i].getItem().size() != (j + 1)) + generatedSql += " ) or "; + else + generatedSql += " ) "; + + } + if (panelList.length != (i + 1)) + generatedSql += " union all "; + + } + + generatedSql = "select count(*) as patient_num_count from (select count( *) as mycount, patient_num from (" + + generatedSql + + " ) as a group by patient_num ) as b where mycount = " + panelList.length; + + log.debug("Setfinder converted sql without temp table " + generatedSql); + + } catch (JAXBUtilException e) { + e.printStackTrace(); + } catch (I2B2Exception e) { + e.printStackTrace(); + } + log.debug("Setfinder skip temp table generated sql " + generatedSql); + log.debug("Setfinder skip temp table missing item message " + missingItemMessage); + log.debug("Setfinder skip temp table process timing message " + processTimingMessage); + } + else if (this.queryWithoutTempTableFlag == false) { + sqlResult = requestDao.buildSql(requestXml, + encounterSetFlag); + generatedSql = sqlResult[0]; + missingItemMessage = sqlResult[1]; + processTimingMessage = sqlResult[2]; + if (sqlResult.length>3) + queryType = sqlResult[3]; + } else { + //generate sql for each panel + try { + RequestMessageType reqMsgType = this.getRequestMessageType(requestXml); + QueryDefinitionRequestType queryDefRequestType = this.getQueryDefinitionRequestType(reqMsgType); + PanelType[] panelList = queryDefRequestType.getQueryDefinition().getPanel().toArray(new PanelType[]{}); + String newRequestMsg = ""; + boolean buildSqlWithOR = true; + + boolean fullSqlGenerated = false; + while (!fullSqlGenerated) { + generatedSql = ""; + for (int i =0; i < panelList.length; i++) { + PanelType panelType = panelList[i]; + //buildRequestXml(panelType); + queryDefRequestType.getQueryDefinition().getPanel().clear(); + log.debug("Setfinder query panel count " + panelList.length); + queryDefRequestType.getQueryDefinition().getPanel().add(panelType); + newRequestMsg = this.buildRequestMessage(reqMsgType, queryDefRequestType); + + log.debug("Single panel request message [" + newRequestMsg + "]"); + //send request xml for each panel + sqlResult = requestDao.buildSql(newRequestMsg, + encounterSetFlag); + DirectQueryForSinglePanel directQuerySql = new DirectQueryForSinglePanel(); + if (buildSqlWithOR == false) { + generatedSql += "\n(" + directQuerySql.buildSqlWithUnion(sqlResult[0]) + ")\n"; + if (i+1 < panelList.length) { + generatedSql += " INTERSECT \n"; + } + } else if (buildSqlWithOR == true && (sqlResult[0].indexOf("patient_dimension where")>0 || + sqlResult[0].indexOf("visit_dimension where")>0)) { + buildSqlWithOR = false; + fullSqlGenerated = false; + break; + } else { + generatedSql += "\n(" + directQuerySql.buildSqlWithOR(sqlResult[0]) + ")\n"; + if (i+1 < panelList.length) { + generatedSql += " INTERSECT \n"; + generatedSql += "select patient_num from " + this.getDbSchemaName() +"observation_fact f where \n"; + } + } + + if (sqlResult[1] != null && sqlResult[1].trim().length()>0) { + missingItemMessage += sqlResult[1]; + } + if (sqlResult[2] != null && sqlResult[2].trim().length()>0) { + processTimingMessage += sqlResult[2]; + } + if (sqlResult[3] != null && sqlResult[3].trim().length()>0) { + queryType = sqlResult[3]; + } + fullSqlGenerated = true; + } + } + + if (buildSqlWithOR) { + generatedSql = "select patient_num from " + this.getDbSchemaName() +"observation_fact f where " + generatedSql; + } + generatedSql = "select count(distinct patient_num) as patient_num_count from ( \n" + generatedSql + " \n ) allitem "; + + logesapi.debug("Setfinder converted sql without temp table " + generatedSql); + + } catch (JAXBUtilException e) { + e.printStackTrace(); + } catch (I2B2Exception e) { + e.printStackTrace(); + } + logesapi.debug("Setfinder skip temp table generated sql " + generatedSql); + logesapi.debug("Setfinder skip temp table missing item message " + missingItemMessage); + logesapi.debug("Setfinder skip temp table process timing message " + processTimingMessage); + } + queryMasterDao.updateQueryAfterRun(masterId, generatedSql, queryType); + + if (missingItemMessage != null + && missingItemMessage.trim().length() > 1) { + logesapi.debug("Setfinder query missing item message not null" + missingItemMessage); + missingItemFlag = true; + + queryInstance.setEndDate(new Date(System + .currentTimeMillis())); + // queryInstance.setMessage(missingItemMessage); + setQueryInstanceStatus(sfDAOFactory, queryInstanceId, 4, + missingItemMessage); + // update the error status to result instance + setQueryResultInstanceStatus(sfDAOFactory, queryInstanceId, + 4, missingItemMessage); + throw new I2B2DAOException("Concept missing"); + + } + + if (processTimingMessage != null && processTimingMessage.trim().length()>0) { + + setQueryInstanceProcessTimingXml(sfDAOFactory, + queryInstanceId, processTimingMessage); + + } + + } + log.debug("Setfinder before executor helper dao missingItemFlag " + missingItemFlag); + if (missingItemFlag == false) { + QueryExecutorHelperDao helperDao = new QueryExecutorHelperDao( + dataSource, dataSourceLookup, originalDataSourceLookup); + helperDao.setProcessTimingFlag(processTimingFlag); + helperDao.setQueryWithoutTempTableFlag(this.queryWithoutTempTableFlag); + if (this.queryCountMinSketchFlag) + helperDao.setQueryWithoutTempTableFlag(this.queryCountMinSketchFlag); + helperDao.executeQuery( transactionTimeout, + dsLookup, sfDAOFactory, requestXml, sqlString, + queryInstanceId, patientSetId, resultOutputList, + generatedSql, pmXml); + + } + } catch (NamingException e) { + exception = e; + errorFlag = true; + } catch (SecurityException e) { + exception = e; + errorFlag = true; + } catch (IllegalStateException e) { + exception = e; + errorFlag = true; + } catch (CRCTimeOutException e) { + throw e; + } catch (I2B2DAOException e) { + + setQueryInstanceStatus(sfDAOFactory, queryInstanceId, 4, + e.getMessage()); + // update the error status to result instance + setQueryResultInstanceStatus(sfDAOFactory, queryInstanceId, + 4, e.getMessage()); + + log.debug("Error in QueryExecutorDAO Throwing: " + e.getMessage()); + exception = e; + errorFlag = true; + throw e; + } finally { + // close resultset and statement + try { + if (resultSet != null) { + resultSet.close(); + } + resultSet = null; + if (stmt != null) { + stmt.close(); + } + stmt = null; + if (manualConnection != null) { + manualConnection.close(); + } + manualConnection = null; + + } catch (SQLException sqle) { + log.error("Error closing statement/resultset ", sqle); + } + } + return patientSetId; + } + + private void setQueryInstanceStatus(SetFinderDAOFactory sfDAOFactory, + String queryInstanceId, int statusTypeId, String message) throws I2B2DAOException { + IQueryInstanceDao queryInstanceDao = sfDAOFactory.getQueryInstanceDAO(); + QtQueryInstance queryInstance = queryInstanceDao + .getQueryInstanceByInstanceId(queryInstanceId); + + QtQueryStatusType queryStatusType = new QtQueryStatusType(); + queryStatusType.setStatusTypeId(statusTypeId); + queryInstance.setQtQueryStatusType(queryStatusType); + queryInstance.setEndDate(new Date(System.currentTimeMillis())); + queryInstance.setMessage(queryInstance.getMessage() + "\n" + message); + queryInstanceDao.update(queryInstance, true); + } + + private void setQueryInstanceProcessTimingXml(SetFinderDAOFactory sfDAOFactory, + String queryInstanceId, String message) throws I2B2DAOException { + IQueryInstanceDao queryInstanceDao = sfDAOFactory.getQueryInstanceDAO(); + queryInstanceDao.updateMessage(queryInstanceId, message, true); + + } + + private void setQueryResultInstanceStatus(SetFinderDAOFactory sfDAOFactory, + String queryInstanceId, int statusTypeId, String message) { + IQueryResultInstanceDao queryResultInstanceDao = sfDAOFactory + .getPatientSetResultDAO(); + List resultInstanceList = queryResultInstanceDao + .getResultInstanceList(queryInstanceId); + for (QtQueryResultInstance queryResultInstance : resultInstanceList) { + queryResultInstanceDao.updatePatientSet(queryResultInstance + .getResultInstanceId(), statusTypeId, message, -1, -1, ""); + } + + } + + + + public boolean getEncounterSetFlag( + ResultOutputOptionListType resultOutputList) { + boolean encounterFoundFlag = false; + for (ResultOutputOptionType resultOutputOption : resultOutputList + .getResultOutput()) { + if (resultOutputOption.getName().equalsIgnoreCase( + "PATIENT_ENCOUNTER_SET")) { + encounterFoundFlag = true; + break; + } + } + return encounterFoundFlag; + } + + /** + * Call PM to get user roles. The security info is taken from the request + * xml + * + * @param requestXml + * @return + * @throws I2B2Exception + */ + public List getRoleFromPM(String requestXml) throws I2B2Exception { + + I2B2RequestMessageHelper reqMsgHelper = new I2B2RequestMessageHelper( + requestXml); + SecurityType origSecurityType = reqMsgHelper.getSecurityType(); + String projectId = reqMsgHelper.getProjectId(); + + SecurityType serviceSecurityType = PMServiceAccountUtil + .getServiceSecurityType(origSecurityType.getDomain()); + //EJBPMUtil callPMUtil = new EJBPMUtil(serviceSecurityType, projectId); + List roleList = new ArrayList(); + try { + //RolesType rolesType = callPMUtil.callGetRole(origSecurityType + // .getUsername(), projectId); + RolesType rolesType = EJBPMUtil.callGetRole(origSecurityType + .getUsername(), origSecurityType, projectId, QueryProcessorUtil.getInstance() + .getProjectManagementCellUrl()); + + + RoleType roleType = null; + for (java.util.Iterator iterator = rolesType.getRole() + .iterator(); iterator.hasNext();) { + roleType = iterator.next(); + roleList.add(roleType.getRole()); + } + + } catch (AxisFault e) { + throw new I2B2Exception(" Failed to get user role from PM " + + StackTraceUtil.getStackTrace(e)); + } + return roleList; + /* + * I2B2RequestMessageHelper reqMsgHelper = new I2B2RequestMessageHelper( + * requestXml); SecurityType securityType = + * reqMsgHelper.getSecurityType(); String projectId = + * reqMsgHelper.getProjectId(); // get roles from pm driver + * PMServiceDriver serviceDriver = new PMServiceDriver(); ProjectType + * projectType = null; + * + * try { projectType = serviceDriver.checkValidUser(securityType, + * projectId); } catch (AxisFault e) { e.printStackTrace(); throw new + * I2B2Exception(" Failed to get user role from PM " + + * StackTraceUtil.getStackTrace(e)); } catch (JAXBUtilException e) { + * e.printStackTrace(); throw new + * I2B2Exception(" Failed to get user role from PM " + + * StackTraceUtil.getStackTrace(e)); } return projectType.getRole(); + */ + } + + private RequestMessageType getRequestMessageType (String xmlRequest) throws I2B2Exception, JAXBUtilException { + JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); + JAXBElement jaxbElement = jaxbUtil.unMashallFromString(xmlRequest); + + if (jaxbElement == null) { + throw new I2B2Exception( + "null value in after unmarshalling request string "); + } + + RequestMessageType requestMessageType = (RequestMessageType) jaxbElement + .getValue(); + return requestMessageType; + } + + + public QueryDefinitionRequestType getQueryDefinitionRequestType(RequestMessageType requestMessageType) throws JAXBUtilException { + BodyType bodyType = requestMessageType.getMessageBody(); + JAXBUnWrapHelper unWrapHelper = new JAXBUnWrapHelper(); + QueryDefinitionRequestType queryDefReqType = (QueryDefinitionRequestType) unWrapHelper + .getObjectByClass(bodyType.getAny(), + QueryDefinitionRequestType.class); + return queryDefReqType; + + + } + + + private String buildRequestMessage(RequestMessageType requestMessageType , QueryDefinitionRequestType queryDefRequestType) throws JAXBUtilException{ + edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory setfinderOf = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); + requestMessageType.getMessageBody().getAny().add(setfinderOf.createRequest(queryDefRequestType)); + JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); + StringWriter strWriter = new StringWriter(); + ObjectFactory ob = new ObjectFactory(); + jaxbUtil.marshaller(ob.createRequest(requestMessageType), strWriter); + return strWriter.toString(); + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryExecutorHelperDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryExecutorHelperDao.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryExecutorHelperDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryExecutorHelperDao.java index 9bdf4469..973b7e80 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryExecutorHelperDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryExecutorHelperDao.java @@ -1,1034 +1,1034 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder; - -import java.security.SecureRandom; -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.time.LocalDate; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.sql.DataSource; -import jakarta.xml.bind.JAXBElement; - -import org.apache.axis2.AxisFault; -//import org.springframework.beans.factory.BeanFactory; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.exception.StackTraceUtil; -import edu.harvard.i2b2.common.util.ServiceLocator; -import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.dao.IDAOFactory; -import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.ProcessTimingReportUtil; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.db.QtQueryBreakdownType; -import edu.harvard.i2b2.crc.datavo.db.QtQueryInstance; -import edu.harvard.i2b2.crc.datavo.db.QtQueryResultInstance; -import edu.harvard.i2b2.crc.datavo.db.QtQueryStatusType; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; -import edu.harvard.i2b2.crc.datavo.pm.ProjectType; -import edu.harvard.i2b2.crc.datavo.pm.RoleType; -import edu.harvard.i2b2.crc.datavo.pm.RolesType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ItemType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.PanelType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionRequestType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultOutputOptionListType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultOutputOptionType; -import edu.harvard.i2b2.crc.delegate.ejbpm.EJBPMUtil; -import edu.harvard.i2b2.crc.delegate.pm.CallPMUtil; -import edu.harvard.i2b2.crc.ejb.ExecRunnable; -import edu.harvard.i2b2.crc.ejb.role.MissingRoleException; -import edu.harvard.i2b2.crc.role.AuthrizationHelper; -import edu.harvard.i2b2.crc.util.I2B2RequestMessageHelper; -import edu.harvard.i2b2.crc.util.LogTimingUtil; -import edu.harvard.i2b2.crc.util.PMServiceAccountUtil; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - -/** - * This class executes the setfinder query's panel sql. The temp table stores - * the patient/visits for the query and the temp table will be passed to rest of - * the result type generator class. - * - */ -public class QueryExecutorHelperDao extends CRCDAO { - - protected static Log logesapi = LogFactory.getLog(QueryExecutorHelperDao.class); - - private DataSourceLookup dataSourceLookup = null, - originalDataSourceLookup = null; - // private static Map generatorMap = null; - private static String defaultResultType = "PATIENT_COUNT_XML"; - private String processTimingFlag = ProcessTimingReportUtil.NONE; - private ProcessTimingReportUtil ptrUtil = null; - private boolean queryWithoutTempTableFlag = false; - - static { - // QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - // BeanFactory bf = qpUtil.getSpringBeanFactory(); - // generatorMap = (Map) bf.getBean("setFinderResultGeneratorMap"); - // defaultResultType = (String) bf.getBean("defaultSetfinderResultType"); - } - - public QueryExecutorHelperDao(DataSource dataSource, - DataSourceLookup dataSourceLookup, - DataSourceLookup originalDataSourceLookup) { - setDataSource(dataSource); - setDbSchemaName(dataSourceLookup.getFullSchema()); - this.dataSourceLookup = dataSourceLookup; - this.originalDataSourceLookup = originalDataSourceLookup; - - } - - public void setProcessTimingFlag(String processTimingFlag) { - this.processTimingFlag = processTimingFlag; - - try { - ptrUtil = new ProcessTimingReportUtil(dataSourceLookup); - } catch (I2B2DAOException e) { - log.error("Error trying to construct ProcessTimingReportUtil" + e.getMessage()); - } - } - - public void setQueryWithoutTempTableFlag(boolean queryWithoutTempTableFlag) { - this.queryWithoutTempTableFlag = queryWithoutTempTableFlag; - } - - - /** - * Execute the Panel's sql to write the patient/visit list into the temp - * table. - * - * And then pass this temp table data to rest of the result type generator. - * - * @param transaction - * @param transactionTimeout - * @param dsLookup - * @param sfDAOFactory - * @param requestXml - * @param sqlString - * @param queryInstanceId - * @param patientSetId - * @param resultOutputList - * @param generatedSql - * @param tm - * @param ut - * @throws CRCTimeOutException - * @throws I2B2DAOException - */ - public void executeQuery( - int transactionTimeout, DataSourceLookup dsLookup, - SetFinderDAOFactory sfDAOFactory, String requestXml, - String sqlString, String queryInstanceId, String patientSetId, - ResultOutputOptionListType resultOutputList, String generatedSql, String pmXml - ) - throws CRCTimeOutException, I2B2DAOException { - boolean errorFlag = false, timeOutErrorFlag = false; - Statement stmt = null; - ResultSet resultSet = null; - Connection manualConnection = null; - String singleSql = null; - int recordCount = 0, obfuscatedRecordCount = 0; - // WAS hard coded ... now passed int - // transactionTimeout = 7200; - //TRANSACTION - // log.info("Helper EXEC QUERY:TRANSACTION TIMEOUT IS " + transactionTimeout); - - /** Global temp table to store intermediate setfinder results* */ - String TEMP_TABLE = "#GLOBAL_TEMP_TABLE"; - - /** Global temp table to store intermediate patient list * */ - String TEMP_DX_TABLE = "#DX"; - String TEMP_MASTER_TABLE = "#MASTER_GLOBAL_TEMP_TABLE"; - - if (dsLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER)) { - TEMP_TABLE = getDbSchemaName() + "#GLOBAL_TEMP_TABLE"; - TEMP_DX_TABLE = getDbSchemaName() + "#DX"; - TEMP_MASTER_TABLE = getDbSchemaName() + "#MASTER_GLOBAL_TEMP_TABLE"; - } else if (dsLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE) ) { - TEMP_TABLE = getDbSchemaName() + "QUERY_GLOBAL_TEMP"; - TEMP_DX_TABLE = getDbSchemaName() + "DX"; - TEMP_MASTER_TABLE = getDbSchemaName() + "MASTER_QUERY_GLOBAL_TEMP"; - } else if (dsLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL) ) { - TEMP_TABLE = "QUERY_GLOBAL_TEMP"; - TEMP_DX_TABLE = "DX"; - TEMP_MASTER_TABLE = "MASTER_QUERY_GLOBAL_TEMP"; - } - Exception exception = null; - - try { - - manualConnection = ServiceLocator.getInstance() - .getAppServerDataSource(dsLookup.getDataSource()) - .getConnection(); - - stmt = manualConnection.createStatement(); - int count = 0; - - if (dsLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER) || dsLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) { - String checkDeleteGlobalTempTable = "drop table " + TEMP_TABLE; - String checkDeleteCountTable = "drop table " + TEMP_DX_TABLE; - String checkDeleteMasterTable = "drop table " + TEMP_MASTER_TABLE; - Statement clearTempStmt = manualConnection.createStatement(); - try { - clearTempStmt.executeUpdate(checkDeleteGlobalTempTable); - } catch (SQLException dEx) { - ; - } - try { - clearTempStmt.executeUpdate(checkDeleteCountTable); - } catch (SQLException dEx) { - ; - } - try { - clearTempStmt.executeUpdate(checkDeleteMasterTable); - } catch (SQLException dEx) { - ; - } - clearTempStmt.close(); - - String createSql = "CREATE TABLE " + TEMP_TABLE + " ( " - + " ENCOUNTER_NUM int, " + " PATIENT_NUM int, INSTANCE_NUM int, CONCEPT_CD varchar(50), START_DATE DATETIME, PROVIDER_ID varchar(50), " - + " PANEL_COUNT int, " + " fact_count int, " - + " fact_panels int " + ")"; - - if (dsLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) - createSql = "CREATE TEMP TABLE " + TEMP_TABLE + " ( " - + " ENCOUNTER_NUM int, " + " PATIENT_NUM int, INSTANCE_NUM int, CONCEPT_CD varchar(50), START_DATE TIMESTAMP, PROVIDER_ID varchar(50), " - + " PANEL_COUNT int, " + " fact_count int, " - + " fact_panels int " + ")"; - stmt.executeUpdate(createSql); - createSql = " CREATE TABLE " + TEMP_DX_TABLE + " ( " - + " ENCOUNTER_NUM int, " + " PATIENT_NUM int, INSTANCE_NUM int, CONCEPT_CD varchar(50), START_DATE DATETIME, PROVIDER_ID varchar(50), temporal_start_date datetime, temporal_end_date DATETIME ) "; - if (dsLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) - createSql = " CREATE TEMP TABLE " + TEMP_DX_TABLE + " ( " - + " ENCOUNTER_NUM int, " + " PATIENT_NUM int, INSTANCE_NUM int, CONCEPT_CD varchar(50), START_DATE TIMESTAMP, PROVIDER_ID varchar(50), temporal_start_date TIMESTAMP, temporal_end_date TIMESTAMP ) "; - - stmt.executeUpdate(createSql); - createSql = " CREATE TABLE " + TEMP_MASTER_TABLE + " ( " - + " ENCOUNTER_NUM int, PATIENT_NUM int , INSTANCE_NUM int, CONCEPT_CD varchar(50), START_DATE DATETIME, PROVIDER_ID varchar(50), MASTER_ID varchar(50), LEVEL_NO int, temporal_start_date DATETIME, temporal_end_date DATETIME ) "; - if (dsLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) - createSql = " CREATE TEMP TABLE " + TEMP_MASTER_TABLE + " ( " - + " ENCOUNTER_NUM int, PATIENT_NUM int , INSTANCE_NUM int, CONCEPT_CD varchar(50), START_DATE TIMESTAMP, PROVIDER_ID varchar(50), MASTER_ID varchar(50), LEVEL_NO int, temporal_start_date TIMESTAMP, temporal_end_date TIMESTAMP ) "; - stmt.executeUpdate(createSql); - - if (dsLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER)) { - String indexSql = "create index tempIndex on " - + getDbSchemaName() - + "#global_temp_table (patient_num,encounter_num,panel_count)"; - log.debug("Executing sql [ " + indexSql + " ]"); - stmt.executeUpdate(indexSql); - - indexSql = "CREATE NONCLUSTERED INDEX master_index_v1 " - + " ON " + TEMP_MASTER_TABLE + " (master_id, level_no, temporal_start_date, temporal_end_date) " - + " INCLUDE (patient_num) "; - log.debug("Executing sql [ " + indexSql + " ]"); - stmt.executeUpdate(indexSql); - - indexSql = "CREATE NONCLUSTERED INDEX master_index_v2 " - + " ON " + TEMP_MASTER_TABLE + " (patient_num, master_id) " - + " INCLUDE (temporal_start_date, temporal_end_date) "; - - log.debug("Executing sql [ " + indexSql + " ]"); - stmt.executeUpdate(indexSql); - - } - - } else if (dsLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE)) { - String clearGlobalTempTable = "delete from " + TEMP_TABLE; - String clearCountTable = "delete from " + TEMP_DX_TABLE; - String clearMasterTable = "delete from " + TEMP_MASTER_TABLE; - - Statement clearTempStmt = manualConnection.createStatement(); - try { - clearTempStmt.executeUpdate(clearGlobalTempTable); - clearTempStmt.executeUpdate(clearCountTable); - clearTempStmt.executeUpdate(clearMasterTable); - } catch (SQLException dEx) { - ; - } finally { - clearTempStmt.close(); - } - - } - // set transaction timeout - stmt.setQueryTimeout(transactionTimeout); - // start seperate thread to cancel the running sql if the - // stmt.setQueryTimeout did not work - CancelStatementRunner csr = new CancelStatementRunner(stmt, - transactionTimeout); - Thread csrThread = new Thread(csr); - csrThread.start(); - - // ut.commit(); - String[] sqls = null; - if (this.queryWithoutTempTableFlag == false) { - sqls = generatedSql.split("<\\*>"); - } else { - sqls = new String[] {generatedSql}; - } - - - log.info("Transaction timeout in sec " + transactionTimeout); - - - long startTime = System.currentTimeMillis(); - LogTimingUtil logTimingUtil = new LogTimingUtil(); - LogTimingUtil outerLogTimingUtil = new LogTimingUtil(); - outerLogTimingUtil.setStartTime(); - - // execute generated sql - while (count < sqls.length) { - singleSql = sqls[count++]; - if (singleSql != null && singleSql.trim().length() > 10) { - logesapi.info("Executing setfinder query sql [" + singleSql + "]" - + " for query instance= " + queryInstanceId); - logTimingUtil.setStartTime(); - if (this.queryWithoutTempTableFlag == false) { - int rows = stmt.executeUpdate(singleSql); - log.debug("Rows affected [" + rows + "] for query instance"); - // if the database is sqlserver, then updating the temp - // table statistics speed up the query - if (this.dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER)) { - - log.debug("UPDATE STATISTICS " - + getDbSchemaName() - + "#global_temp_table "); - - stmt.executeUpdate("UPDATE STATISTICS " - + getDbSchemaName() - + "#global_temp_table "); - } - } else { - resultSet = stmt.executeQuery(singleSql); - - } - logTimingUtil.setEndTime(); - - - - //log the time to the query instance - if (this.processTimingFlag.equalsIgnoreCase(ProcessTimingReportUtil.DEBUG)) { - ptrUtil.logProcessTimingMessage(queryInstanceId, ptrUtil.buildProcessTiming(logTimingUtil,"EXECUTE SQL - ITEM ","sql="+singleSql)); - } - } - } - - outerLogTimingUtil.setEndTime(); - long endTime = System.currentTimeMillis(); - long totalTime = endTime - startTime; - log.debug("Time to run the SETFINDER query query instance id [" - + queryInstanceId + "] is [" + totalTime + " ]"); - - //log the process timing to the query instance - if (this.processTimingFlag.equalsIgnoreCase(ProcessTimingReportUtil.INFO)) { - ptrUtil.logProcessTimingMessage(queryInstanceId, ptrUtil.buildProcessTiming(outerLogTimingUtil,"EXECUTE SQL",null)); - } - - // set the cancel thread the - csr.setSqlFinishedFlag(); - csrThread.interrupt(); - - String fetchSql = " select count(distinct patient_num) as patient_num_count from " - + TEMP_DX_TABLE; - Statement countStmt = manualConnection.createStatement(); - if (this.queryWithoutTempTableFlag == false) { - resultSet = countStmt.executeQuery(fetchSql); - } - - int i = 0; - //read count sigma from property file - double countSigma = GaussianBoxMuller.getCountSigma(); - double obfuscatedMinimumValue = GaussianBoxMuller.getObfuscatedMinimumVal(); - while (resultSet.next() && (i++ < 10)) { - recordCount = resultSet.getInt("patient_num_count"); - GaussianBoxMuller gaussianBoxMuller = new GaussianBoxMuller(); - obfuscatedRecordCount = (int) gaussianBoxMuller - .getNormalizedValueForCount(recordCount,countSigma,obfuscatedMinimumValue); - - log.debug("Calculated Patient set size :[" + recordCount - + "] for query instance= " + queryInstanceId); - } - resultSet.close(); - countStmt.close(); - - // tm.begin(); - // call the result generator with the db connection/temp table - callResultGenerator(resultOutputList, manualConnection, - sfDAOFactory, requestXml, patientSetId, queryInstanceId, - TEMP_DX_TABLE, recordCount, obfuscatedRecordCount, transactionTimeout, pmXml, totalTime/1000); - - - if (dsLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER) || dsLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) { - //Delete temp table for Sqlsever - String checkDeleteGlobalTempTable = "drop table " + TEMP_TABLE; - String checkDeleteCountTable = "drop table " + TEMP_DX_TABLE; - String checkDeleteMasterTable = "drop table " + TEMP_MASTER_TABLE; - Statement clearTempStmt = manualConnection.createStatement(); - try { - clearTempStmt.executeUpdate(checkDeleteGlobalTempTable); - } catch (SQLException dEx) { - ; - } - try { - clearTempStmt.executeUpdate(checkDeleteCountTable); - } catch (SQLException dEx) { - ; - } - try { - clearTempStmt.executeUpdate(checkDeleteMasterTable); - } catch (SQLException dEx) { - ; - } - clearTempStmt.close(); - } else if (dsLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE) ) { - String deleteGlobalTempTable = ""; - String deleteCountTable = "", deleteMasterTable = ""; - - deleteGlobalTempTable = "delete from " + TEMP_TABLE; - deleteCountTable = "delete from " + TEMP_DX_TABLE; - deleteMasterTable = "delete from " + TEMP_MASTER_TABLE; - - Statement deleteStmt = manualConnection.createStatement(); - Statement deleteStmt1 = manualConnection.createStatement(); - - log.debug("Executing Sql [" + deleteGlobalTempTable + "]"); - deleteStmt.executeUpdate(deleteGlobalTempTable); - log.debug("Executing Sql [" + deleteCountTable + "]"); - deleteStmt1.executeUpdate(deleteCountTable); - log.debug("Executing Sql [" + deleteMasterTable + "]"); - deleteStmt1.executeUpdate(deleteMasterTable); - deleteStmt.close(); - deleteStmt1.close(); - } - - // update query instance restult status - setQueryInstanceStatus(sfDAOFactory, queryInstanceId, 6, null); - log.debug("Query executor completed processing query instance[ " - + queryInstanceId + " ]"); - - } catch (CRCTimeOutException timeoutEx) { - //TRANSACTION timeout ... do nothing - // timeOutErrorFlag = true; - throw timeoutEx; - - } catch (SQLException sqlEx) { - if (sqlEx.toString().indexOf("ORA-01013") > -1) { - log.info("Query timed out"); - //TRANSACTION timeout - // timeOutErrorFlag = true; - throw new CRCTimeOutException(sqlEx.getMessage(), sqlEx); - } else if (sqlEx.getMessage().indexOf("The query was canceled.") > -1) { - log.info("Query timed out"); - //timeOutErrorFlag = true; - throw new CRCTimeOutException(sqlEx.getMessage(), - sqlEx); - } - else if (sqlEx.getMessage().indexOf("timed out") > -1) { - log.info("Query timed out"); - //TRANSACTION timeout . - - // timeOutErrorFlag = true; - throw new CRCTimeOutException(sqlEx.getMessage(), - sqlEx); - } - else if (sqlEx.getMessage().indexOf("canceling statement due to user request") > -1) { - log.info("Query timed out"); /// postgres timeout message - throw new CRCTimeOutException(sqlEx.getMessage(), - sqlEx); - } - else{ - errorFlag = true; - exception = sqlEx; - logesapi.error("Error while executing sql" + singleSql + sqlEx); - throw new I2B2DAOException("Error while executing sql", sqlEx); - } - } catch (LockedoutException crcDaoEx) { - // I2B2DAOException - errorFlag = true; - exception = crcDaoEx; - throw crcDaoEx; - } catch (I2B2Exception i2b2Ex) { - errorFlag = true; - exception = i2b2Ex; - log.error("Error executing " + i2b2Ex.getMessage(), i2b2Ex); - throw new I2B2DAOException("Error executing " - + i2b2Ex.getMessage(), i2b2Ex); - - } catch (IllegalStateException e) { - errorFlag = true; - exception = e; - e.printStackTrace(); - throw new I2B2DAOException("IllegalState exception", e); - } catch (SecurityException e) { - errorFlag = true; - exception = e; - e.printStackTrace(); - throw new I2B2DAOException("SecurityException", e); - } finally { - - // close resultset and statement - try { - if (resultSet != null) { - resultSet.close(); - } - if (stmt != null) { - stmt.close(); - } - if (manualConnection != null) { - manualConnection.close(); - } - - } catch (SQLException sqle) { - log.error("Error closing statement/resultset ", sqle); - } - - - } - - } - - private void setQueryInstanceStatus(SetFinderDAOFactory sfDAOFactory, - String queryInstanceId, int statusTypeId, String message) throws I2B2DAOException { - IQueryInstanceDao queryInstanceDao = sfDAOFactory.getQueryInstanceDAO(); - QtQueryInstance queryInstance = queryInstanceDao - .getQueryInstanceByInstanceId(queryInstanceId); - - QtQueryStatusType queryStatusType = new QtQueryStatusType(); - queryStatusType.setStatusTypeId(statusTypeId); - queryInstance.setQtQueryStatusType(queryStatusType); - queryInstance.setEndDate(new Date(System.currentTimeMillis())); - if (message != null) - queryInstance.setMessage(message); - queryInstanceDao.update(queryInstance, true); - } - - private void setQueryResultInstanceStatus(SetFinderDAOFactory sfDAOFactory, - String queryInstanceId, int statusTypeId, String message) { - IQueryResultInstanceDao queryResultInstanceDao = sfDAOFactory - .getPatientSetResultDAO(); - List resultInstanceList = queryResultInstanceDao - .getResultInstanceList(queryInstanceId); - for (QtQueryResultInstance queryResultInstance : resultInstanceList) { - queryResultInstanceDao.updatePatientSet(queryResultInstance - .getResultInstanceId(), statusTypeId, message, -1, -1, ""); - } - - } - - @SuppressWarnings("unchecked") - private void callResultGenerator( - ResultOutputOptionListType resultOutputList, - Connection manualConnection, SetFinderDAOFactory sfDAOFactory, - String requestXml, String patientSetId, String queryInstanceId, - String TEMP_DX_TABLE, int recordCount, int obfuscatedRecordCount, int transactionTimeout, String pmXml, long dxCreateTime) - throws CRCTimeOutException, LockedoutException, I2B2DAOException { - - log.debug("getting queryProcess instance"); - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - - //BeanFactory bf = qpUtil.getSpringBeanFactory(); - // Map ontologyKeyMap = (Map) - // bf.getBean("setFinderResultOntologyKeyMap"); - Map ontologyKeyMap = new HashMap(); - - - - QueryDefinitionType queryDef = getQueryDefinitionType(requestXml); - String queryTiming = queryDef.getQueryTiming(); - List panelList = queryDef.getPanel(); - for (PanelType singlePanel : panelList) { - List itemList = singlePanel.getItem(); - for (ItemType singleItem : itemList) { - ontologyKeyMap.put(singleItem.getItemName(), singleItem); - } - } - // CallOntologyUtil callOntologyUtil = null; - String ontologyGetChildrenUrl = null; - SecurityType securityType = null; - //String projectId = null; - try { - - String ontologyUrl = qpUtil - .getCRCPropertyValue("edu.harvard.i2b2.crc.delegate.ontology.url"); - String getChildrenOperationName = qpUtil - .getCRCPropertyValue("edu.harvard.i2b2.crc.delegate.ontology.operation.getchildren"); - ontologyGetChildrenUrl = ontologyUrl - + getChildrenOperationName; - log.debug("In callResultGenerator: Ontology getChildren url from property file [" - + ontologyGetChildrenUrl + "]"); - - - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil() - .unMashallFromString(requestXml); - RequestMessageType request = (RequestMessageType) responseJaxb - .getValue(); - //projectId = request.getMessageHeader().getProjectId(); - SecurityType tempSecurityType = request.getMessageHeader() - .getSecurity(); - securityType = PMServiceAccountUtil - .getServiceSecurityType(tempSecurityType.getDomain()); - - // callOntologyUtil = new CallOntologyUtil(ontologyGetChildrenUrl, - // requestXml); - } catch (JAXBUtilException e) { - e.printStackTrace(); - throw new I2B2DAOException(e.getMessage()); - } catch (I2B2Exception e) { - e.printStackTrace(); - throw new I2B2DAOException(e.getMessage()); - } - - // get roles either from cache or by calling PM - - List roles = new ArrayList(); - - try { - roles = getRoleFromPM(requestXml, pmXml); - } catch (I2B2Exception e) { - throw new I2B2DAOException(e.getMessage()); - } - int lockoutQueryCount = -1, lockoutQueryDay = -1, lockoutQueryZeroCount = -1; - boolean dataObfuscFlag = false; - String projectId = null; - try { - DataSourceLookup dataSourceLookup = sfDAOFactory - .getDataSourceLookup(); - - String domainId = dataSourceLookup.getDomainId(); - projectId = dataSourceLookup.getProjectPath(); - String userId = dataSourceLookup.getOwnerId(); - - DAOFactoryHelper helper = new DAOFactoryHelper(domainId, projectId, - userId); - IDAOFactory daoFactory = helper.getDAOFactory(); - AuthrizationHelper authHelper = new AuthrizationHelper(domainId, - projectId, userId, daoFactory); - boolean noDataAggFlag = false, noDataObfuscFlag = false; - try { - authHelper.checkRoleForProtectionLabel( - "SETFINDER_QRY_WITHOUT_DATAOBFSC", roles); - } catch (MissingRoleException noRoleEx) { - noDataAggFlag = true; - } catch (I2B2Exception e) { - throw e; - } - try { - authHelper.checkRoleForProtectionLabel( - "SETFINDER_QRY_WITH_DATAOBFSC", roles); - } catch (MissingRoleException noRoleEx) { - noDataObfuscFlag = true; - } catch (I2B2Exception e) { - throw e; - } - - if (noDataAggFlag && !noDataObfuscFlag) { - dataObfuscFlag = true; - } - String lockoutQueryCountStr = qpUtil - .getCRCPropertyValue("edu.harvard.i2b2.crc.lockout.setfinderquery.count"); - if (lockoutQueryCountStr != null) { - lockoutQueryCount = Integer.parseInt(lockoutQueryCountStr); - if (lockoutQueryCount>0) lockoutQueryCount--; - } - String lockoutQueryDayStr = qpUtil - .getCRCPropertyValue("edu.harvard.i2b2.crc.lockout.setfinderquery.day"); - if (lockoutQueryDayStr != null) { - lockoutQueryDay = Integer.parseInt(lockoutQueryDayStr); - } - String lockoutQueryZeroCountStr = null; - - lockoutQueryZeroCountStr = qpUtil - .getCRCPropertyValue("edu.harvard.i2b2.crc.lockout.setfinderquery.zero.count"); - if (lockoutQueryZeroCountStr != null) { - lockoutQueryZeroCount = Integer.parseInt(lockoutQueryZeroCountStr); - } - - } catch (I2B2Exception e) { - throw new I2B2DAOException(e.getMessage()); - } - Map param = new HashMap(); - log.debug("Creatiung hash map"); - SetFinderConnection sfConn = new SetFinderConnection(manualConnection); - param.put("SetFinderConnection", sfConn); - param.put("SetFinderDAOFactory", sfDAOFactory); - param.put("PatientSetId", patientSetId); - param.put("QueryInstanceId", queryInstanceId); - param.put("TEMP_DX_TABLE", TEMP_DX_TABLE); - param.put("setFinderResultOntologyKeyMap", ontologyKeyMap); - param.put("ServerType", this.dataSourceLookup.getServerType()); - // param.put("CallOntologyUtil", callOntologyUtil); - param.put("projectId", projectId); - param.put("ontologyGetChildrenUrl", ontologyGetChildrenUrl); - param.put("securityType", securityType); - param.put("OriginalDataSourceLookup", this.originalDataSourceLookup); - param.put("Roles", roles); - param.put("TransactionTimeout", transactionTimeout); - param.put("ProcessTimingFlag", processTimingFlag); - param.put("ObfuscatedRecordCount", obfuscatedRecordCount); - param.put("RecordCount", recordCount); - param.put("ObfuscatedRoleFlag", dataObfuscFlag); - param.put("panelList", panelList); - param.put("queryDef", queryDef); - param.put("DXCreateTime", dxCreateTime); - try { - //String fileName = ""; - String fileName = qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.filename"); - - // if (fileName.contains("{{{RANDOM_")) { - // int start = fileName.indexOf("{{{RANDOM_"); - // int end = fileName.indexOf("}}}", start); - // int size = Integer.parseInt(fileName.substring(start+10, end)); - - SecureRandom random = new SecureRandom(); - - param.put("ResultRandom", String.valueOf(random.nextInt())); - // } - - // if (fileName.contains("{{{DATE_")) { - // int start = fileName.indexOf("{{{DATE_"); - // int end = fileName.indexOf("}}}", start); - // String date = fileName.substring(start+8, end); - - // DateTimeFormatter formatter = DateTimeFormatter.ofPattern(date); - //fileName = fileName.replaceAll("\\{\\{\\{DATE_"+date+"\\}\\}\\}", LocalDate.now().format(formatter)); - //param.put("ResultDate", String.valueOf(LocalDate.now().format(formatter))); - param.put("ResultDate", LocalDate.now()); - //} - } catch (Exception e) {} - - - - if (resultOutputList != null) { - if (resultOutputList.getResultOutput() != null - && resultOutputList.getResultOutput().size() > 0) { - List resultOptionList = resultOutputList - .getResultOutput(); - param.put("resultOptionList", resultOptionList); - for (ResultOutputOptionType resultOutputOption : resultOptionList) { - String resultName = resultOutputOption.getName() - .toUpperCase(); - String resultInstanceId = getQueryResultInstanceId( - sfDAOFactory, queryInstanceId, resultName); - param.put("ResultInstanceId", resultInstanceId); - param.put("ResultOptionName", resultName); - if (resultOutputOption.getFullName() == null) - param.put("ResultFullName", null); - else - param.put("ResultFullName", resultOutputOption.getFullName().trim()); - param.put("ResultPriority", resultOutputOption.getPriorityIndex()); - - if (resultOutputOption.getPaths() != null) - param.put("ResultPath", resultOutputOption.getPaths().getPath()); - - IQueryBreakdownTypeDao queryBreakdownTypeDao = sfDAOFactory - .getQueryBreakdownTypeDao(); - QtQueryBreakdownType queryBreakdownType = queryBreakdownTypeDao - .getBreakdownTypeByName(resultName); - // ::TODO check if the result state is completed, before - // running the result - runGenerator(resultName, param, queryBreakdownType.getClassname()); - // check if the user need to be locked - // if the lockoutQueryCount = -1 skip lockout check - log.debug("check if the user need to be locked"); - if (lockoutQueryCount>-1) { - // resultInstanceId, userId - if (dataObfuscFlag) { - String userLockedDate = null; - try { - userLockedDate = processUserLock(sfDAOFactory, - requestXml, resultInstanceId, - lockoutQueryCount, lockoutQueryDay,lockoutQueryZeroCount); - } catch (I2B2Exception e) { - throw new I2B2DAOException(e.getMessage()); - } - if (userLockedDate != null) { - throw new LockedoutException(EJBPMUtil.LOCKEDOUT - + " error : User account locked on [" - + userLockedDate + "]"); - } - } - } else { - log.debug("Setfinder not doing the lockout check for instance ["+ queryInstanceId + "] " + - "the property value of query count is -1"); - } - } - } else { - log - .warn("No result output process to run, the is empty"); - } - - } else { - String resultType = defaultResultType; - // perform patient set - String resultInstanceId = getQueryResultInstanceId(sfDAOFactory, - queryInstanceId, defaultResultType); - param.put("ResultInstanceId", resultInstanceId); - - - IQueryBreakdownTypeDao queryBreakdownTypeDao = sfDAOFactory - .getQueryBreakdownTypeDao(); - QtQueryBreakdownType queryBreakdownType = queryBreakdownTypeDao - .getBreakdownTypeByName(resultType); - // ::TODO check if the result state is completed, before - // running the result - runGenerator(resultType, param, queryBreakdownType.getClassname()); - - // check if the user need to be locked - // if the lockoutQueryCount = -1 skip lockout check - if (lockoutQueryCount>-1) { - // resultInstanceId, userId - if (dataObfuscFlag) { - // do the check if the user need to be locked - String userLockedDate = null; - try { - userLockedDate = processUserLock(sfDAOFactory, requestXml, - resultInstanceId, lockoutQueryCount, lockoutQueryDay,lockoutQueryZeroCount); - } catch (I2B2Exception e) { - throw new I2B2DAOException(e.getMessage()); - } - if (userLockedDate != null) { - throw new LockedoutException(EJBPMUtil.LOCKEDOUT - + " error : User account locked on [" + userLockedDate - + "]"); - } - } - } else { - log.debug("Setfinder not doing the lockout check for instance ["+ queryInstanceId + "] " + - "the property value of query count is -1"); - } - } - } - - private void runGenerator(String resultName, Map param, String generatorClassName) - throws I2B2DAOException, CRCTimeOutException { - if (generatorClassName == null) { - throw new I2B2DAOException("Could not find result name [" - + resultName + "] in the config file"); - } - Class generatorClass; - IResultGenerator resultGenerator; - try { - generatorClass = Class.forName(generatorClassName, true, Thread - .currentThread().getContextClassLoader()); - if (generatorClass == null) { - throw new I2B2DAOException( - "Generator class not configured for result name[" - + resultName + "] "); - } - resultGenerator = (IResultGenerator) generatorClass.newInstance(); - log.debug("Running " + resultName + "'s class " - + generatorClassName); - resultGenerator.generateResult(param); - } catch (ClassNotFoundException e) { - throw new I2B2DAOException( - "Class not found for the generator class[" - + generatorClassName + "] ", e); - } catch (InstantiationException e) { - throw new I2B2DAOException("Could not initialize generator class[" - + generatorClassName + "] ", e); - } catch (IllegalAccessException e) { - throw new I2B2DAOException( - "Illegal Access Exception for generator class[" - + generatorClassName + "] ", e); - } - } - - private String getQueryResultInstanceId(SetFinderDAOFactory sfDAOFactory, - String queryInstanceId, String resultName) { - IQueryResultInstanceDao resultInstanceDao = sfDAOFactory - .getPatientSetResultDAO(); - QtQueryResultInstance resultInstance = resultInstanceDao - .getResultInstanceByQueryInstanceIdAndName(queryInstanceId, - resultName); - return resultInstance.getResultInstanceId(); - } - - private String processUserLock(SetFinderDAOFactory sfDAOFactory, - String requestXml, String resultInstanceId, int lockoutQueryCount, - int lockoutQueryDay, int lockoutQueryZeroCount) throws I2B2Exception { - String userLockedDate = null; - - I2B2RequestMessageHelper reqMsgHelper = new I2B2RequestMessageHelper( - requestXml); - SecurityType origSecurityType = reqMsgHelper.getSecurityType(); - String projectId = reqMsgHelper.getProjectId(); - String userId = origSecurityType.getUsername(); - - IQueryResultInstanceDao queryResultInstanceDao = sfDAOFactory - .getPatientSetResultDAO(); - QtQueryResultInstance resultInstance = queryResultInstanceDao - .getResultInstanceById(resultInstanceId); - int resultTypeId = resultInstance.getQtQueryResultType() - .getResultTypeId(); - int setSize = resultInstance.getRealSetSize(); - //if the lockout query zero count is -1, dont count zero - if (setSize == 0 ) { - if (lockoutQueryZeroCount == -1) { - logesapi.debug("Setfinder not doing the lockout check for result instance ["+ resultInstanceId + "] " + - "the zero count property value is -1"); - return userLockedDate; - } else { - //assign the lockout query zero count to lockout query count - logesapi.debug("Setfinder lockout query count value for result instance ["+ resultInstanceId + "] " + - "taken from zero count property value is ["+lockoutQueryZeroCount +"]"); - lockoutQueryCount = lockoutQueryZeroCount; - } - } - int queryCount = queryResultInstanceDao - .getResultInstanceCountBySetSize(userId, lockoutQueryDay, - resultTypeId, setSize, lockoutQueryCount); - if (queryCount > 0) { - userLockedDate = new Date(System.currentTimeMillis()).toString(); - SecurityType serviceSecurityType = PMServiceAccountUtil - .getServiceSecurityType(origSecurityType.getDomain()); - - // send pm message - //EJBPMUtil ejbPMUtil = new EJBPMUtil(serviceSecurityType, projectId); - - //ejbPMUtil.setUserLockedParam(userId, projectId, - // EJBPMUtil.LOCKEDOUT, userLockedDate); - EJBPMUtil.setUserLockedParam(userId, - EJBPMUtil.LOCKEDOUT, userLockedDate, serviceSecurityType, projectId, - QueryProcessorUtil.getInstance() - .getProjectManagementCellUrl()); - - } - - return userLockedDate; - } - - private QueryDefinitionType getQueryDefinitionType(String requestString) throws I2B2DAOException { - QueryDefinitionRequestType queryDefReqType = null; - JAXBElement responseJaxb; - try { - responseJaxb = CRCJAXBUtil.getJAXBUtil() - .unMashallFromString(requestString); - - RequestMessageType r = (RequestMessageType) responseJaxb.getValue(); - BodyType bodyType = r.getMessageBody(); - // get body and search for analysis definition - JAXBUnWrapHelper unWraphHelper = new JAXBUnWrapHelper(); - - - queryDefReqType = (QueryDefinitionRequestType) unWraphHelper - .getObjectByClass(bodyType.getAny(), - QueryDefinitionRequestType.class); - } catch (JAXBUtilException e) { - throw new I2B2DAOException(e.getMessage()); - } - - return queryDefReqType.getQueryDefinition(); - } - /** - * Call PM to get user roles. The security info is taken from the request - * xml - * - * @param requestXml - * @return - * @throws I2B2Exception - */ - public List getRoleFromPM(String requestXml, String pmXml) throws I2B2Exception { - - logesapi.debug("In getRoleFromPM, pmXml is " + pmXml); - I2B2RequestMessageHelper reqMsgHelper = new I2B2RequestMessageHelper( - requestXml); - SecurityType origSecurityType = reqMsgHelper.getSecurityType(); - String projectId = reqMsgHelper.getProjectId(); - - SecurityType serviceSecurityType = PMServiceAccountUtil - .getServiceSecurityType(origSecurityType.getDomain()); - //EJBPMUtil callPMUtil = new EJBPMUtil(serviceSecurityType, projectId); - List roleList = new ArrayList(); - try { - - - if (pmXml == null) { - //RolesType rolesType = callPMUtil.callGetRole(origSecurityType - // .getUsername(), projectId); - RolesType rolesType = EJBPMUtil.callGetRole(origSecurityType - .getUsername(), origSecurityType, projectId, - QueryProcessorUtil.getInstance() - .getProjectManagementCellUrl()); - - - RoleType roleType = null; - for (java.util.Iterator iterator = rolesType.getRole() - .iterator(); iterator.hasNext();) { - roleType = iterator.next(); - roleList.add(roleType.getRole()); - } - - } else { - ProjectType projectType = CallPMUtil.getUserProjectFromResponse(pmXml, origSecurityType, - projectId); - roleList = projectType.getRole(); - - } - - - } catch (AxisFault e) { - throw new I2B2Exception(" Failed to get user role from PM " - + StackTraceUtil.getStackTrace(e)); - } catch (JAXBUtilException e) { - // TODO Auto-generated catch block - throw new I2B2Exception(" Failed to Process PM Xml message " - + StackTraceUtil.getStackTrace(e)); - } - return roleList; - /* - * I2B2RequestMessageHelper reqMsgHelper = new I2B2RequestMessageHelper( - * requestXml); SecurityType securityType = - * reqMsgHelper.getSecurityType(); String projectId = - * reqMsgHelper.getProjectId(); // get roles from pm driver - * PMServiceDriver serviceDriver = new PMServiceDriver(); ProjectType - * projectType = null; - * - * try { projectType = serviceDriver.checkValidUser(securityType, - * projectId); } catch (AxisFault e) { e.printStackTrace(); throw new - * I2B2Exception(" Failed to get user role from PM " + - * StackTraceUtil.getStackTrace(e)); } catch (JAXBUtilException e) { - * e.printStackTrace(); throw new - * I2B2Exception(" Failed to get user role from PM " + - * StackTraceUtil.getStackTrace(e)); } return projectType.getRole(); - */ - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder; + +import java.security.SecureRandom; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.sql.DataSource; +import jakarta.xml.bind.JAXBElement; + +import org.apache.axis2.AxisFault; +//import org.springframework.beans.factory.BeanFactory; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.exception.StackTraceUtil; +import edu.harvard.i2b2.common.util.ServiceLocator; +import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.dao.IDAOFactory; +import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.ProcessTimingReportUtil; +import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.db.QtQueryBreakdownType; +import edu.harvard.i2b2.crc.datavo.db.QtQueryInstance; +import edu.harvard.i2b2.crc.datavo.db.QtQueryResultInstance; +import edu.harvard.i2b2.crc.datavo.db.QtQueryStatusType; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; +import edu.harvard.i2b2.crc.datavo.pm.ProjectType; +import edu.harvard.i2b2.crc.datavo.pm.RoleType; +import edu.harvard.i2b2.crc.datavo.pm.RolesType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ItemType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.PanelType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionRequestType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultOutputOptionListType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultOutputOptionType; +import edu.harvard.i2b2.crc.delegate.ejbpm.EJBPMUtil; +import edu.harvard.i2b2.crc.delegate.pm.CallPMUtil; +import edu.harvard.i2b2.crc.ejb.ExecRunnable; +import edu.harvard.i2b2.crc.ejb.role.MissingRoleException; +import edu.harvard.i2b2.crc.role.AuthrizationHelper; +import edu.harvard.i2b2.crc.util.I2B2RequestMessageHelper; +import edu.harvard.i2b2.crc.util.LogTimingUtil; +import edu.harvard.i2b2.crc.util.PMServiceAccountUtil; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + +/** + * This class executes the setfinder query's panel sql. The temp table stores + * the patient/visits for the query and the temp table will be passed to rest of + * the result type generator class. + * + */ +public class QueryExecutorHelperDao extends CRCDAO { + + protected static Log logesapi = LogFactory.getLog(QueryExecutorHelperDao.class); + + private DataSourceLookup dataSourceLookup = null, + originalDataSourceLookup = null; + // private static Map generatorMap = null; + private static String defaultResultType = "PATIENT_COUNT_XML"; + private String processTimingFlag = ProcessTimingReportUtil.NONE; + private ProcessTimingReportUtil ptrUtil = null; + private boolean queryWithoutTempTableFlag = false; + + static { + // QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + // BeanFactory bf = qpUtil.getSpringBeanFactory(); + // generatorMap = (Map) bf.getBean("setFinderResultGeneratorMap"); + // defaultResultType = (String) bf.getBean("defaultSetfinderResultType"); + } + + public QueryExecutorHelperDao(DataSource dataSource, + DataSourceLookup dataSourceLookup, + DataSourceLookup originalDataSourceLookup) { + setDataSource(dataSource); + setDbSchemaName(dataSourceLookup.getFullSchema()); + this.dataSourceLookup = dataSourceLookup; + this.originalDataSourceLookup = originalDataSourceLookup; + + } + + public void setProcessTimingFlag(String processTimingFlag) { + this.processTimingFlag = processTimingFlag; + + try { + ptrUtil = new ProcessTimingReportUtil(dataSourceLookup); + } catch (I2B2DAOException e) { + log.error("Error trying to construct ProcessTimingReportUtil" + e.getMessage()); + } + } + + public void setQueryWithoutTempTableFlag(boolean queryWithoutTempTableFlag) { + this.queryWithoutTempTableFlag = queryWithoutTempTableFlag; + } + + + /** + * Execute the Panel's sql to write the patient/visit list into the temp + * table. + * + * And then pass this temp table data to rest of the result type generator. + * + * @param transaction + * @param transactionTimeout + * @param dsLookup + * @param sfDAOFactory + * @param requestXml + * @param sqlString + * @param queryInstanceId + * @param patientSetId + * @param resultOutputList + * @param generatedSql + * @param tm + * @param ut + * @throws CRCTimeOutException + * @throws I2B2DAOException + */ + public void executeQuery( + int transactionTimeout, DataSourceLookup dsLookup, + SetFinderDAOFactory sfDAOFactory, String requestXml, + String sqlString, String queryInstanceId, String patientSetId, + ResultOutputOptionListType resultOutputList, String generatedSql, String pmXml + ) + throws CRCTimeOutException, I2B2DAOException { + boolean errorFlag = false, timeOutErrorFlag = false; + Statement stmt = null; + ResultSet resultSet = null; + Connection manualConnection = null; + String singleSql = null; + int recordCount = 0, obfuscatedRecordCount = 0; + // WAS hard coded ... now passed int + // transactionTimeout = 7200; + //TRANSACTION + // log.info("Helper EXEC QUERY:TRANSACTION TIMEOUT IS " + transactionTimeout); + + /** Global temp table to store intermediate setfinder results* */ + String TEMP_TABLE = "#GLOBAL_TEMP_TABLE"; + + /** Global temp table to store intermediate patient list * */ + String TEMP_DX_TABLE = "#DX"; + String TEMP_MASTER_TABLE = "#MASTER_GLOBAL_TEMP_TABLE"; + + if (dsLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER)) { + TEMP_TABLE = getDbSchemaName() + "#GLOBAL_TEMP_TABLE"; + TEMP_DX_TABLE = getDbSchemaName() + "#DX"; + TEMP_MASTER_TABLE = getDbSchemaName() + "#MASTER_GLOBAL_TEMP_TABLE"; + } else if (dsLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.ORACLE) ) { + TEMP_TABLE = getDbSchemaName() + "QUERY_GLOBAL_TEMP"; + TEMP_DX_TABLE = getDbSchemaName() + "DX"; + TEMP_MASTER_TABLE = getDbSchemaName() + "MASTER_QUERY_GLOBAL_TEMP"; + } else if (dsLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL) ) { + TEMP_TABLE = "QUERY_GLOBAL_TEMP"; + TEMP_DX_TABLE = "DX"; + TEMP_MASTER_TABLE = "MASTER_QUERY_GLOBAL_TEMP"; + } + Exception exception = null; + + try { + + manualConnection = ServiceLocator.getInstance() + .getAppServerDataSource(dsLookup.getDataSource()) + .getConnection(); + + stmt = manualConnection.createStatement(); + int count = 0; + + if (dsLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER) || dsLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) { + String checkDeleteGlobalTempTable = "drop table " + TEMP_TABLE; + String checkDeleteCountTable = "drop table " + TEMP_DX_TABLE; + String checkDeleteMasterTable = "drop table " + TEMP_MASTER_TABLE; + Statement clearTempStmt = manualConnection.createStatement(); + try { + clearTempStmt.executeUpdate(checkDeleteGlobalTempTable); + } catch (SQLException dEx) { + ; + } + try { + clearTempStmt.executeUpdate(checkDeleteCountTable); + } catch (SQLException dEx) { + ; + } + try { + clearTempStmt.executeUpdate(checkDeleteMasterTable); + } catch (SQLException dEx) { + ; + } + clearTempStmt.close(); + + String createSql = "CREATE TABLE " + TEMP_TABLE + " ( " + + " ENCOUNTER_NUM int, " + " PATIENT_NUM int, INSTANCE_NUM int, CONCEPT_CD varchar(50), START_DATE DATETIME, PROVIDER_ID varchar(50), " + + " PANEL_COUNT int, " + " fact_count int, " + + " fact_panels int " + ")"; + + if (dsLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) + createSql = "CREATE TEMP TABLE " + TEMP_TABLE + " ( " + + " ENCOUNTER_NUM int, " + " PATIENT_NUM int, INSTANCE_NUM int, CONCEPT_CD varchar(50), START_DATE TIMESTAMP, PROVIDER_ID varchar(50), " + + " PANEL_COUNT int, " + " fact_count int, " + + " fact_panels int " + ")"; + stmt.executeUpdate(createSql); + createSql = " CREATE TABLE " + TEMP_DX_TABLE + " ( " + + " ENCOUNTER_NUM int, " + " PATIENT_NUM int, INSTANCE_NUM int, CONCEPT_CD varchar(50), START_DATE DATETIME, PROVIDER_ID varchar(50), temporal_start_date datetime, temporal_end_date DATETIME ) "; + if (dsLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) + createSql = " CREATE TEMP TABLE " + TEMP_DX_TABLE + " ( " + + " ENCOUNTER_NUM int, " + " PATIENT_NUM int, INSTANCE_NUM int, CONCEPT_CD varchar(50), START_DATE TIMESTAMP, PROVIDER_ID varchar(50), temporal_start_date TIMESTAMP, temporal_end_date TIMESTAMP ) "; + + stmt.executeUpdate(createSql); + createSql = " CREATE TABLE " + TEMP_MASTER_TABLE + " ( " + + " ENCOUNTER_NUM int, PATIENT_NUM int , INSTANCE_NUM int, CONCEPT_CD varchar(50), START_DATE DATETIME, PROVIDER_ID varchar(50), MASTER_ID varchar(50), LEVEL_NO int, temporal_start_date DATETIME, temporal_end_date DATETIME ) "; + if (dsLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) + createSql = " CREATE TEMP TABLE " + TEMP_MASTER_TABLE + " ( " + + " ENCOUNTER_NUM int, PATIENT_NUM int , INSTANCE_NUM int, CONCEPT_CD varchar(50), START_DATE TIMESTAMP, PROVIDER_ID varchar(50), MASTER_ID varchar(50), LEVEL_NO int, temporal_start_date TIMESTAMP, temporal_end_date TIMESTAMP ) "; + stmt.executeUpdate(createSql); + + if (dsLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER)) { + String indexSql = "create index tempIndex on " + + getDbSchemaName() + + "#global_temp_table (patient_num,encounter_num,panel_count)"; + log.debug("Executing sql [ " + indexSql + " ]"); + stmt.executeUpdate(indexSql); + + indexSql = "CREATE NONCLUSTERED INDEX master_index_v1 " + + " ON " + TEMP_MASTER_TABLE + " (master_id, level_no, temporal_start_date, temporal_end_date) " + + " INCLUDE (patient_num) "; + log.debug("Executing sql [ " + indexSql + " ]"); + stmt.executeUpdate(indexSql); + + indexSql = "CREATE NONCLUSTERED INDEX master_index_v2 " + + " ON " + TEMP_MASTER_TABLE + " (patient_num, master_id) " + + " INCLUDE (temporal_start_date, temporal_end_date) "; + + log.debug("Executing sql [ " + indexSql + " ]"); + stmt.executeUpdate(indexSql); + + } + + } else if (dsLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.ORACLE)) { + String clearGlobalTempTable = "delete from " + TEMP_TABLE; + String clearCountTable = "delete from " + TEMP_DX_TABLE; + String clearMasterTable = "delete from " + TEMP_MASTER_TABLE; + + Statement clearTempStmt = manualConnection.createStatement(); + try { + clearTempStmt.executeUpdate(clearGlobalTempTable); + clearTempStmt.executeUpdate(clearCountTable); + clearTempStmt.executeUpdate(clearMasterTable); + } catch (SQLException dEx) { + ; + } finally { + clearTempStmt.close(); + } + + } + // set transaction timeout + stmt.setQueryTimeout(transactionTimeout); + // start seperate thread to cancel the running sql if the + // stmt.setQueryTimeout did not work + CancelStatementRunner csr = new CancelStatementRunner(stmt, + transactionTimeout); + Thread csrThread = new Thread(csr); + csrThread.start(); + + // ut.commit(); + String[] sqls = null; + if (this.queryWithoutTempTableFlag == false) { + sqls = generatedSql.split("<\\*>"); + } else { + sqls = new String[] {generatedSql}; + } + + + log.info("Transaction timeout in sec " + transactionTimeout); + + + long startTime = System.currentTimeMillis(); + LogTimingUtil logTimingUtil = new LogTimingUtil(); + LogTimingUtil outerLogTimingUtil = new LogTimingUtil(); + outerLogTimingUtil.setStartTime(); + + // execute generated sql + while (count < sqls.length) { + singleSql = sqls[count++]; + if (singleSql != null && singleSql.trim().length() > 10) { + logesapi.info("Executing setfinder query sql [" + singleSql + "]" + + " for query instance= " + queryInstanceId); + logTimingUtil.setStartTime(); + if (this.queryWithoutTempTableFlag == false) { + int rows = stmt.executeUpdate(singleSql); + log.debug("Rows affected [" + rows + "] for query instance"); + // if the database is sqlserver, then updating the temp + // table statistics speed up the query + if (this.dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER)) { + + log.debug("UPDATE STATISTICS " + + getDbSchemaName() + + "#global_temp_table "); + + stmt.executeUpdate("UPDATE STATISTICS " + + getDbSchemaName() + + "#global_temp_table "); + } + } else { + resultSet = stmt.executeQuery(singleSql); + + } + logTimingUtil.setEndTime(); + + + + //log the time to the query instance + if (this.processTimingFlag.equalsIgnoreCase(ProcessTimingReportUtil.DEBUG)) { + ptrUtil.logProcessTimingMessage(queryInstanceId, ptrUtil.buildProcessTiming(logTimingUtil,"EXECUTE SQL - ITEM ","sql="+singleSql)); + } + } + } + + outerLogTimingUtil.setEndTime(); + long endTime = System.currentTimeMillis(); + long totalTime = endTime - startTime; + log.debug("Time to run the SETFINDER query query instance id [" + + queryInstanceId + "] is [" + totalTime + " ]"); + + //log the process timing to the query instance + if (this.processTimingFlag.equalsIgnoreCase(ProcessTimingReportUtil.INFO)) { + ptrUtil.logProcessTimingMessage(queryInstanceId, ptrUtil.buildProcessTiming(outerLogTimingUtil,"EXECUTE SQL",null)); + } + + // set the cancel thread the + csr.setSqlFinishedFlag(); + csrThread.interrupt(); + + String fetchSql = " select count(distinct patient_num) as patient_num_count from " + + TEMP_DX_TABLE; + Statement countStmt = manualConnection.createStatement(); + if (this.queryWithoutTempTableFlag == false) { + resultSet = countStmt.executeQuery(fetchSql); + } + + int i = 0; + //read count sigma from property file + double countSigma = GaussianBoxMuller.getCountSigma(); + double obfuscatedMinimumValue = GaussianBoxMuller.getObfuscatedMinimumVal(); + while (resultSet.next() && (i++ < 10)) { + recordCount = resultSet.getInt("patient_num_count"); + GaussianBoxMuller gaussianBoxMuller = new GaussianBoxMuller(); + obfuscatedRecordCount = (int) gaussianBoxMuller + .getNormalizedValueForCount(recordCount,countSigma,obfuscatedMinimumValue); + + log.debug("Calculated Patient set size :[" + recordCount + + "] for query instance= " + queryInstanceId); + } + resultSet.close(); + countStmt.close(); + + // tm.begin(); + // call the result generator with the db connection/temp table + callResultGenerator(resultOutputList, manualConnection, + sfDAOFactory, requestXml, patientSetId, queryInstanceId, + TEMP_DX_TABLE, recordCount, obfuscatedRecordCount, transactionTimeout, pmXml, totalTime/1000); + + + if (dsLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER) || dsLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) { + //Delete temp table for Sqlsever + String checkDeleteGlobalTempTable = "drop table " + TEMP_TABLE; + String checkDeleteCountTable = "drop table " + TEMP_DX_TABLE; + String checkDeleteMasterTable = "drop table " + TEMP_MASTER_TABLE; + Statement clearTempStmt = manualConnection.createStatement(); + try { + clearTempStmt.executeUpdate(checkDeleteGlobalTempTable); + } catch (SQLException dEx) { + ; + } + try { + clearTempStmt.executeUpdate(checkDeleteCountTable); + } catch (SQLException dEx) { + ; + } + try { + clearTempStmt.executeUpdate(checkDeleteMasterTable); + } catch (SQLException dEx) { + ; + } + clearTempStmt.close(); + } else if (dsLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.ORACLE) ) { + String deleteGlobalTempTable = ""; + String deleteCountTable = "", deleteMasterTable = ""; + + deleteGlobalTempTable = "delete from " + TEMP_TABLE; + deleteCountTable = "delete from " + TEMP_DX_TABLE; + deleteMasterTable = "delete from " + TEMP_MASTER_TABLE; + + Statement deleteStmt = manualConnection.createStatement(); + Statement deleteStmt1 = manualConnection.createStatement(); + + log.debug("Executing Sql [" + deleteGlobalTempTable + "]"); + deleteStmt.executeUpdate(deleteGlobalTempTable); + log.debug("Executing Sql [" + deleteCountTable + "]"); + deleteStmt1.executeUpdate(deleteCountTable); + log.debug("Executing Sql [" + deleteMasterTable + "]"); + deleteStmt1.executeUpdate(deleteMasterTable); + deleteStmt.close(); + deleteStmt1.close(); + } + + // update query instance restult status + setQueryInstanceStatus(sfDAOFactory, queryInstanceId, 6, null); + log.debug("Query executor completed processing query instance[ " + + queryInstanceId + " ]"); + + } catch (CRCTimeOutException timeoutEx) { + //TRANSACTION timeout ... do nothing + // timeOutErrorFlag = true; + throw timeoutEx; + + } catch (SQLException sqlEx) { + if (sqlEx.toString().indexOf("ORA-01013") > -1) { + log.info("Query timed out"); + //TRANSACTION timeout + // timeOutErrorFlag = true; + throw new CRCTimeOutException(sqlEx.getMessage(), sqlEx); + } else if (sqlEx.getMessage().indexOf("The query was canceled.") > -1) { + log.info("Query timed out"); + //timeOutErrorFlag = true; + throw new CRCTimeOutException(sqlEx.getMessage(), + sqlEx); + } + else if (sqlEx.getMessage().indexOf("timed out") > -1) { + log.info("Query timed out"); + //TRANSACTION timeout . + + // timeOutErrorFlag = true; + throw new CRCTimeOutException(sqlEx.getMessage(), + sqlEx); + } + else if (sqlEx.getMessage().indexOf("canceling statement due to user request") > -1) { + log.info("Query timed out"); /// postgres timeout message + throw new CRCTimeOutException(sqlEx.getMessage(), + sqlEx); + } + else{ + errorFlag = true; + exception = sqlEx; + logesapi.error("Error while executing sql" + singleSql + sqlEx); + throw new I2B2DAOException("Error while executing sql", sqlEx); + } + } catch (LockedoutException crcDaoEx) { + // I2B2DAOException + errorFlag = true; + exception = crcDaoEx; + throw crcDaoEx; + } catch (I2B2Exception i2b2Ex) { + errorFlag = true; + exception = i2b2Ex; + log.error("Error executing " + i2b2Ex.getMessage(), i2b2Ex); + throw new I2B2DAOException("Error executing " + + i2b2Ex.getMessage(), i2b2Ex); + + } catch (IllegalStateException e) { + errorFlag = true; + exception = e; + e.printStackTrace(); + throw new I2B2DAOException("IllegalState exception", e); + } catch (SecurityException e) { + errorFlag = true; + exception = e; + e.printStackTrace(); + throw new I2B2DAOException("SecurityException", e); + } finally { + + // close resultset and statement + try { + if (resultSet != null) { + resultSet.close(); + } + if (stmt != null) { + stmt.close(); + } + if (manualConnection != null) { + manualConnection.close(); + } + + } catch (SQLException sqle) { + log.error("Error closing statement/resultset ", sqle); + } + + + } + + } + + private void setQueryInstanceStatus(SetFinderDAOFactory sfDAOFactory, + String queryInstanceId, int statusTypeId, String message) throws I2B2DAOException { + IQueryInstanceDao queryInstanceDao = sfDAOFactory.getQueryInstanceDAO(); + QtQueryInstance queryInstance = queryInstanceDao + .getQueryInstanceByInstanceId(queryInstanceId); + + QtQueryStatusType queryStatusType = new QtQueryStatusType(); + queryStatusType.setStatusTypeId(statusTypeId); + queryInstance.setQtQueryStatusType(queryStatusType); + queryInstance.setEndDate(new Date(System.currentTimeMillis())); + if (message != null) + queryInstance.setMessage(message); + queryInstanceDao.update(queryInstance, true); + } + + private void setQueryResultInstanceStatus(SetFinderDAOFactory sfDAOFactory, + String queryInstanceId, int statusTypeId, String message) { + IQueryResultInstanceDao queryResultInstanceDao = sfDAOFactory + .getPatientSetResultDAO(); + List resultInstanceList = queryResultInstanceDao + .getResultInstanceList(queryInstanceId); + for (QtQueryResultInstance queryResultInstance : resultInstanceList) { + queryResultInstanceDao.updatePatientSet(queryResultInstance + .getResultInstanceId(), statusTypeId, message, -1, -1, ""); + } + + } + + @SuppressWarnings("unchecked") + private void callResultGenerator( + ResultOutputOptionListType resultOutputList, + Connection manualConnection, SetFinderDAOFactory sfDAOFactory, + String requestXml, String patientSetId, String queryInstanceId, + String TEMP_DX_TABLE, int recordCount, int obfuscatedRecordCount, int transactionTimeout, String pmXml, long dxCreateTime) + throws CRCTimeOutException, LockedoutException, I2B2DAOException { + + log.debug("getting queryProcess instance"); + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + + //BeanFactory bf = qpUtil.getSpringBeanFactory(); + // Map ontologyKeyMap = (Map) + // bf.getBean("setFinderResultOntologyKeyMap"); + Map ontologyKeyMap = new HashMap(); + + + + QueryDefinitionType queryDef = getQueryDefinitionType(requestXml); + String queryTiming = queryDef.getQueryTiming(); + List panelList = queryDef.getPanel(); + for (PanelType singlePanel : panelList) { + List itemList = singlePanel.getItem(); + for (ItemType singleItem : itemList) { + ontologyKeyMap.put(singleItem.getItemName(), singleItem); + } + } + // CallOntologyUtil callOntologyUtil = null; + String ontologyGetChildrenUrl = null; + SecurityType securityType = null; + //String projectId = null; + try { + + String ontologyUrl = qpUtil + .getCRCPropertyValue("edu.harvard.i2b2.crc.delegate.ontology.url"); + String getChildrenOperationName = qpUtil + .getCRCPropertyValue("edu.harvard.i2b2.crc.delegate.ontology.operation.getchildren"); + ontologyGetChildrenUrl = ontologyUrl + + getChildrenOperationName; + log.debug("In callResultGenerator: Ontology getChildren url from property file [" + + ontologyGetChildrenUrl + "]"); + + + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil() + .unMashallFromString(requestXml); + RequestMessageType request = (RequestMessageType) responseJaxb + .getValue(); + //projectId = request.getMessageHeader().getProjectId(); + SecurityType tempSecurityType = request.getMessageHeader() + .getSecurity(); + securityType = PMServiceAccountUtil + .getServiceSecurityType(tempSecurityType.getDomain()); + + // callOntologyUtil = new CallOntologyUtil(ontologyGetChildrenUrl, + // requestXml); + } catch (JAXBUtilException e) { + e.printStackTrace(); + throw new I2B2DAOException(e.getMessage()); + } catch (I2B2Exception e) { + e.printStackTrace(); + throw new I2B2DAOException(e.getMessage()); + } + + // get roles either from cache or by calling PM + + List roles = new ArrayList(); + + try { + roles = getRoleFromPM(requestXml, pmXml); + } catch (I2B2Exception e) { + throw new I2B2DAOException(e.getMessage()); + } + int lockoutQueryCount = -1, lockoutQueryDay = -1, lockoutQueryZeroCount = -1; + boolean dataObfuscFlag = false; + String projectId = null; + try { + DataSourceLookup dataSourceLookup = sfDAOFactory + .getDataSourceLookup(); + + String domainId = dataSourceLookup.getDomainId(); + projectId = dataSourceLookup.getProjectPath(); + String userId = dataSourceLookup.getOwnerId(); + + DAOFactoryHelper helper = new DAOFactoryHelper(domainId, projectId, + userId); + IDAOFactory daoFactory = helper.getDAOFactory(); + AuthrizationHelper authHelper = new AuthrizationHelper(domainId, + projectId, userId, daoFactory); + boolean noDataAggFlag = false, noDataObfuscFlag = false; + try { + authHelper.checkRoleForProtectionLabel( + "SETFINDER_QRY_WITHOUT_DATAOBFSC", roles); + } catch (MissingRoleException noRoleEx) { + noDataAggFlag = true; + } catch (I2B2Exception e) { + throw e; + } + try { + authHelper.checkRoleForProtectionLabel( + "SETFINDER_QRY_WITH_DATAOBFSC", roles); + } catch (MissingRoleException noRoleEx) { + noDataObfuscFlag = true; + } catch (I2B2Exception e) { + throw e; + } + + if (noDataAggFlag && !noDataObfuscFlag) { + dataObfuscFlag = true; + } + String lockoutQueryCountStr = qpUtil + .getCRCPropertyValue("edu.harvard.i2b2.crc.lockout.setfinderquery.count"); + if (lockoutQueryCountStr != null) { + lockoutQueryCount = Integer.parseInt(lockoutQueryCountStr); + if (lockoutQueryCount>0) lockoutQueryCount--; + } + String lockoutQueryDayStr = qpUtil + .getCRCPropertyValue("edu.harvard.i2b2.crc.lockout.setfinderquery.day"); + if (lockoutQueryDayStr != null) { + lockoutQueryDay = Integer.parseInt(lockoutQueryDayStr); + } + String lockoutQueryZeroCountStr = null; + + lockoutQueryZeroCountStr = qpUtil + .getCRCPropertyValue("edu.harvard.i2b2.crc.lockout.setfinderquery.zero.count"); + if (lockoutQueryZeroCountStr != null) { + lockoutQueryZeroCount = Integer.parseInt(lockoutQueryZeroCountStr); + } + + } catch (I2B2Exception e) { + throw new I2B2DAOException(e.getMessage()); + } + Map param = new HashMap(); + log.debug("Creatiung hash map"); + SetFinderConnection sfConn = new SetFinderConnection(manualConnection); + param.put("SetFinderConnection", sfConn); + param.put("SetFinderDAOFactory", sfDAOFactory); + param.put("PatientSetId", patientSetId); + param.put("QueryInstanceId", queryInstanceId); + param.put("TEMP_DX_TABLE", TEMP_DX_TABLE); + param.put("setFinderResultOntologyKeyMap", ontologyKeyMap); + param.put("ServerType", this.dataSourceLookup.getServerType()); + // param.put("CallOntologyUtil", callOntologyUtil); + param.put("projectId", projectId); + param.put("ontologyGetChildrenUrl", ontologyGetChildrenUrl); + param.put("securityType", securityType); + param.put("OriginalDataSourceLookup", this.originalDataSourceLookup); + param.put("Roles", roles); + param.put("TransactionTimeout", transactionTimeout); + param.put("ProcessTimingFlag", processTimingFlag); + param.put("ObfuscatedRecordCount", obfuscatedRecordCount); + param.put("RecordCount", recordCount); + param.put("ObfuscatedRoleFlag", dataObfuscFlag); + param.put("panelList", panelList); + param.put("queryDef", queryDef); + param.put("DXCreateTime", dxCreateTime); + try { + //String fileName = ""; + String fileName = qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.filename"); + + // if (fileName.contains("{{{RANDOM_")) { + // int start = fileName.indexOf("{{{RANDOM_"); + // int end = fileName.indexOf("}}}", start); + // int size = Integer.parseInt(fileName.substring(start+10, end)); + + SecureRandom random = new SecureRandom(); + + param.put("ResultRandom", String.valueOf(random.nextInt())); + // } + + // if (fileName.contains("{{{DATE_")) { + // int start = fileName.indexOf("{{{DATE_"); + // int end = fileName.indexOf("}}}", start); + // String date = fileName.substring(start+8, end); + + // DateTimeFormatter formatter = DateTimeFormatter.ofPattern(date); + //fileName = fileName.replaceAll("\\{\\{\\{DATE_"+date+"\\}\\}\\}", LocalDate.now().format(formatter)); + //param.put("ResultDate", String.valueOf(LocalDate.now().format(formatter))); + param.put("ResultDate", LocalDate.now()); + //} + } catch (Exception e) {} + + + + if (resultOutputList != null) { + if (resultOutputList.getResultOutput() != null + && resultOutputList.getResultOutput().size() > 0) { + List resultOptionList = resultOutputList + .getResultOutput(); + param.put("resultOptionList", resultOptionList); + for (ResultOutputOptionType resultOutputOption : resultOptionList) { + String resultName = resultOutputOption.getName() + .toUpperCase(); + String resultInstanceId = getQueryResultInstanceId( + sfDAOFactory, queryInstanceId, resultName); + param.put("ResultInstanceId", resultInstanceId); + param.put("ResultOptionName", resultName); + if (resultOutputOption.getFullName() == null) + param.put("ResultFullName", null); + else + param.put("ResultFullName", resultOutputOption.getFullName().trim()); + param.put("ResultPriority", resultOutputOption.getPriorityIndex()); + + if (resultOutputOption.getPaths() != null) + param.put("ResultPath", resultOutputOption.getPaths().getPath()); + + IQueryBreakdownTypeDao queryBreakdownTypeDao = sfDAOFactory + .getQueryBreakdownTypeDao(); + QtQueryBreakdownType queryBreakdownType = queryBreakdownTypeDao + .getBreakdownTypeByName(resultName); + // ::TODO check if the result state is completed, before + // running the result + runGenerator(resultName, param, queryBreakdownType.getClassname()); + // check if the user need to be locked + // if the lockoutQueryCount = -1 skip lockout check + log.debug("check if the user need to be locked"); + if (lockoutQueryCount>-1) { + // resultInstanceId, userId + if (dataObfuscFlag) { + String userLockedDate = null; + try { + userLockedDate = processUserLock(sfDAOFactory, + requestXml, resultInstanceId, + lockoutQueryCount, lockoutQueryDay,lockoutQueryZeroCount); + } catch (I2B2Exception e) { + throw new I2B2DAOException(e.getMessage()); + } + if (userLockedDate != null) { + throw new LockedoutException(EJBPMUtil.LOCKEDOUT + + " error : User account locked on [" + + userLockedDate + "]"); + } + } + } else { + log.debug("Setfinder not doing the lockout check for instance ["+ queryInstanceId + "] " + + "the property value of query count is -1"); + } + } + } else { + log + .warn("No result output process to run, the is empty"); + } + + } else { + String resultType = defaultResultType; + // perform patient set + String resultInstanceId = getQueryResultInstanceId(sfDAOFactory, + queryInstanceId, defaultResultType); + param.put("ResultInstanceId", resultInstanceId); + + + IQueryBreakdownTypeDao queryBreakdownTypeDao = sfDAOFactory + .getQueryBreakdownTypeDao(); + QtQueryBreakdownType queryBreakdownType = queryBreakdownTypeDao + .getBreakdownTypeByName(resultType); + // ::TODO check if the result state is completed, before + // running the result + runGenerator(resultType, param, queryBreakdownType.getClassname()); + + // check if the user need to be locked + // if the lockoutQueryCount = -1 skip lockout check + if (lockoutQueryCount>-1) { + // resultInstanceId, userId + if (dataObfuscFlag) { + // do the check if the user need to be locked + String userLockedDate = null; + try { + userLockedDate = processUserLock(sfDAOFactory, requestXml, + resultInstanceId, lockoutQueryCount, lockoutQueryDay,lockoutQueryZeroCount); + } catch (I2B2Exception e) { + throw new I2B2DAOException(e.getMessage()); + } + if (userLockedDate != null) { + throw new LockedoutException(EJBPMUtil.LOCKEDOUT + + " error : User account locked on [" + userLockedDate + + "]"); + } + } + } else { + log.debug("Setfinder not doing the lockout check for instance ["+ queryInstanceId + "] " + + "the property value of query count is -1"); + } + } + } + + private void runGenerator(String resultName, Map param, String generatorClassName) + throws I2B2DAOException, CRCTimeOutException { + if (generatorClassName == null) { + throw new I2B2DAOException("Could not find result name [" + + resultName + "] in the config file"); + } + Class generatorClass; + IResultGenerator resultGenerator; + try { + generatorClass = Class.forName(generatorClassName, true, Thread + .currentThread().getContextClassLoader()); + if (generatorClass == null) { + throw new I2B2DAOException( + "Generator class not configured for result name[" + + resultName + "] "); + } + resultGenerator = (IResultGenerator) generatorClass.newInstance(); + log.debug("Running " + resultName + "'s class " + + generatorClassName); + resultGenerator.generateResult(param); + } catch (ClassNotFoundException e) { + throw new I2B2DAOException( + "Class not found for the generator class[" + + generatorClassName + "] ", e); + } catch (InstantiationException e) { + throw new I2B2DAOException("Could not initialize generator class[" + + generatorClassName + "] ", e); + } catch (IllegalAccessException e) { + throw new I2B2DAOException( + "Illegal Access Exception for generator class[" + + generatorClassName + "] ", e); + } + } + + private String getQueryResultInstanceId(SetFinderDAOFactory sfDAOFactory, + String queryInstanceId, String resultName) { + IQueryResultInstanceDao resultInstanceDao = sfDAOFactory + .getPatientSetResultDAO(); + QtQueryResultInstance resultInstance = resultInstanceDao + .getResultInstanceByQueryInstanceIdAndName(queryInstanceId, + resultName); + return resultInstance.getResultInstanceId(); + } + + private String processUserLock(SetFinderDAOFactory sfDAOFactory, + String requestXml, String resultInstanceId, int lockoutQueryCount, + int lockoutQueryDay, int lockoutQueryZeroCount) throws I2B2Exception { + String userLockedDate = null; + + I2B2RequestMessageHelper reqMsgHelper = new I2B2RequestMessageHelper( + requestXml); + SecurityType origSecurityType = reqMsgHelper.getSecurityType(); + String projectId = reqMsgHelper.getProjectId(); + String userId = origSecurityType.getUsername(); + + IQueryResultInstanceDao queryResultInstanceDao = sfDAOFactory + .getPatientSetResultDAO(); + QtQueryResultInstance resultInstance = queryResultInstanceDao + .getResultInstanceById(resultInstanceId); + int resultTypeId = resultInstance.getQtQueryResultType() + .getResultTypeId(); + int setSize = resultInstance.getRealSetSize(); + //if the lockout query zero count is -1, dont count zero + if (setSize == 0 ) { + if (lockoutQueryZeroCount == -1) { + logesapi.debug("Setfinder not doing the lockout check for result instance ["+ resultInstanceId + "] " + + "the zero count property value is -1"); + return userLockedDate; + } else { + //assign the lockout query zero count to lockout query count + logesapi.debug("Setfinder lockout query count value for result instance ["+ resultInstanceId + "] " + + "taken from zero count property value is ["+lockoutQueryZeroCount +"]"); + lockoutQueryCount = lockoutQueryZeroCount; + } + } + int queryCount = queryResultInstanceDao + .getResultInstanceCountBySetSize(userId, lockoutQueryDay, + resultTypeId, setSize, lockoutQueryCount); + if (queryCount > 0) { + userLockedDate = new Date(System.currentTimeMillis()).toString(); + SecurityType serviceSecurityType = PMServiceAccountUtil + .getServiceSecurityType(origSecurityType.getDomain()); + + // send pm message + //EJBPMUtil ejbPMUtil = new EJBPMUtil(serviceSecurityType, projectId); + + //ejbPMUtil.setUserLockedParam(userId, projectId, + // EJBPMUtil.LOCKEDOUT, userLockedDate); + EJBPMUtil.setUserLockedParam(userId, + EJBPMUtil.LOCKEDOUT, userLockedDate, serviceSecurityType, projectId, + QueryProcessorUtil.getInstance() + .getProjectManagementCellUrl()); + + } + + return userLockedDate; + } + + private QueryDefinitionType getQueryDefinitionType(String requestString) throws I2B2DAOException { + QueryDefinitionRequestType queryDefReqType = null; + JAXBElement responseJaxb; + try { + responseJaxb = CRCJAXBUtil.getJAXBUtil() + .unMashallFromString(requestString); + + RequestMessageType r = (RequestMessageType) responseJaxb.getValue(); + BodyType bodyType = r.getMessageBody(); + // get body and search for analysis definition + JAXBUnWrapHelper unWraphHelper = new JAXBUnWrapHelper(); + + + queryDefReqType = (QueryDefinitionRequestType) unWraphHelper + .getObjectByClass(bodyType.getAny(), + QueryDefinitionRequestType.class); + } catch (JAXBUtilException e) { + throw new I2B2DAOException(e.getMessage()); + } + + return queryDefReqType.getQueryDefinition(); + } + /** + * Call PM to get user roles. The security info is taken from the request + * xml + * + * @param requestXml + * @return + * @throws I2B2Exception + */ + public List getRoleFromPM(String requestXml, String pmXml) throws I2B2Exception { + + logesapi.debug("In getRoleFromPM, pmXml is " + pmXml); + I2B2RequestMessageHelper reqMsgHelper = new I2B2RequestMessageHelper( + requestXml); + SecurityType origSecurityType = reqMsgHelper.getSecurityType(); + String projectId = reqMsgHelper.getProjectId(); + + SecurityType serviceSecurityType = PMServiceAccountUtil + .getServiceSecurityType(origSecurityType.getDomain()); + //EJBPMUtil callPMUtil = new EJBPMUtil(serviceSecurityType, projectId); + List roleList = new ArrayList(); + try { + + + if (pmXml == null) { + //RolesType rolesType = callPMUtil.callGetRole(origSecurityType + // .getUsername(), projectId); + RolesType rolesType = EJBPMUtil.callGetRole(origSecurityType + .getUsername(), origSecurityType, projectId, + QueryProcessorUtil.getInstance() + .getProjectManagementCellUrl()); + + + RoleType roleType = null; + for (java.util.Iterator iterator = rolesType.getRole() + .iterator(); iterator.hasNext();) { + roleType = iterator.next(); + roleList.add(roleType.getRole()); + } + + } else { + ProjectType projectType = CallPMUtil.getUserProjectFromResponse(pmXml, origSecurityType, + projectId); + roleList = projectType.getRole(); + + } + + + } catch (AxisFault e) { + throw new I2B2Exception(" Failed to get user role from PM " + + StackTraceUtil.getStackTrace(e)); + } catch (JAXBUtilException e) { + // TODO Auto-generated catch block + throw new I2B2Exception(" Failed to Process PM Xml message " + + StackTraceUtil.getStackTrace(e)); + } + return roleList; + /* + * I2B2RequestMessageHelper reqMsgHelper = new I2B2RequestMessageHelper( + * requestXml); SecurityType securityType = + * reqMsgHelper.getSecurityType(); String projectId = + * reqMsgHelper.getProjectId(); // get roles from pm driver + * PMServiceDriver serviceDriver = new PMServiceDriver(); ProjectType + * projectType = null; + * + * try { projectType = serviceDriver.checkValidUser(securityType, + * projectId); } catch (AxisFault e) { e.printStackTrace(); throw new + * I2B2Exception(" Failed to get user role from PM " + + * StackTraceUtil.getStackTrace(e)); } catch (JAXBUtilException e) { + * e.printStackTrace(); throw new + * I2B2Exception(" Failed to get user role from PM " + + * StackTraceUtil.getStackTrace(e)); } return projectType.getRole(); + */ + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryInstanceSpringDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryInstanceSpringDao.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryInstanceSpringDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryInstanceSpringDao.java index 23fff141..9c02a59d --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryInstanceSpringDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryInstanceSpringDao.java @@ -1,486 +1,486 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao.setfinder; - -import java.sql.CallableStatement; -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Types; -import java.util.Date; -import java.util.List; - -import javax.sql.DataSource; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.RowMapper; -import org.springframework.jdbc.core.SqlParameter; -import org.springframework.jdbc.object.SqlUpdate; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.db.QtQueryInstance; -import edu.harvard.i2b2.crc.datavo.db.QtQueryMaster; -import edu.harvard.i2b2.crc.datavo.db.QtQueryStatusType; -import edu.harvard.i2b2.crc.ejb.analysis.QueryInstance; -import edu.harvard.i2b2.crc.dao.DataSourceLookupDAOFactory; - -/** - * Class to handle persistance operation of Query instance i.e. each run of - * query is called query instance $Id: QueryInstanceSpringDao.java,v 1.4 - * 2008/04/08 19:38:24 rk903 Exp $ - * - * @author rkuttan - * @see QtQueryInstance - */ -public class QueryInstanceSpringDao extends CRCDAO implements IQueryInstanceDao { - - JdbcTemplate jdbcTemplate = null; - SaveQueryInstance saveQueryInstance = null; - QtQueryInstanceRowMapper queryInstanceMapper = null; - private DataSourceLookup dataSourceLookup = null; - - /** log **/ - protected final Log log = LogFactory.getLog(getClass()); - - protected static Log logesapi = LogFactory.getLog(QueryInstanceSpringDao.class); - - - public QueryInstanceSpringDao(DataSource dataSource, - DataSourceLookup dataSourceLookup) { - setDataSource(dataSource); - setDbSchemaName(dataSourceLookup.getFullSchema()); - jdbcTemplate = new JdbcTemplate(dataSource); - this.dataSourceLookup = dataSourceLookup; - queryInstanceMapper = new QtQueryInstanceRowMapper(); - } - - /** - * Function to create query instance - * - * @param queryMasterId - * @param userId - * @param groupId - * @param batchMode - * @param statusId - * @return query instance id - */ - @Override - public String createQueryInstance(String queryMasterId, String userId, - String groupId, String batchMode, int statusId) { - QtQueryInstance queryInstance = new QtQueryInstance(); - queryInstance.setUserId(userId); - queryInstance.setGroupId(groupId); - queryInstance.setBatchMode(batchMode); - queryInstance.setDeleteFlag("N"); - - QtQueryMaster queryMaster = new QtQueryMaster(); - queryMaster.setQueryMasterId(queryMasterId); - queryInstance.setQtQueryMaster(queryMaster); - - QtQueryStatusType statusType = new QtQueryStatusType(); - statusType.setStatusTypeId(statusId); - queryInstance.setQtQueryStatusType(statusType); - - Date startDate = new Date(System.currentTimeMillis()); - queryInstance.setStartDate(startDate); - saveQueryInstance = new SaveQueryInstance(getDataSource(), - getDbSchemaName(), dataSourceLookup); - saveQueryInstance.save(queryInstance); - - return queryInstance.getQueryInstanceId(); - } - - /** - * Returns list of query instance for the given master id - * - * @param queryMasterId - * @return List - */ - @Override - @SuppressWarnings("unchecked") - public List getQueryInstanceByMasterId(String queryMasterId) { - String sql = "select * from " + getDbSchemaName() - + "qt_query_instance where query_master_id = ?"; - List queryInstanceList = jdbcTemplate.query(sql, - new Object[] { Integer.parseInt(queryMasterId) }, queryInstanceMapper); - return queryInstanceList; - } - - /** - * Find query instance by id - * - * @param queryInstanceId - * @return QtQueryInstance - */ - @Override - public QtQueryInstance getQueryInstanceByInstanceId(String queryInstanceId) { - String sql = "select * from " + getDbSchemaName() - + "qt_query_instance where query_instance_id =?"; - - QtQueryInstance queryInstance = (QtQueryInstance) jdbcTemplate - .queryForObject(sql, new Object[] { Integer.parseInt(queryInstanceId ) }, - queryInstanceMapper); - - return queryInstance; - } - - /** - * Update query instance - * - * @param queryInstance - * @return QtQueryInstance - * @throws I2B2DAOException - */ - @Override - public QtQueryInstance update(QtQueryInstance queryInstance, - boolean appendMessageFlag) throws I2B2DAOException { - - Integer statusTypeId = (queryInstance.getQtQueryStatusType() != null) ? queryInstance - .getQtQueryStatusType().getStatusTypeId() - : null; - String messageUpdate = ""; - if (appendMessageFlag) { - String concatOperator = ""; - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE)) { - concatOperator = "||"; - messageUpdate = " MESSAGE = nvl(MESSAGE,'') " + concatOperator - + " ? "; - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER) || dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) { - //concatOperator = "+"; - // messageUpdate = " MESSAGE = isnull(Cast(MESSAGE as nvarchar(4000)),'') " - // + concatOperator + " ? "; - // Cast(notes as nvarchar(4000)) - - //update message field - if (queryInstance.getMessage() != null) - updateMessage(queryInstance.getQueryInstanceId(),queryInstance.getMessage(),true); - - if (queryInstance.getEndDate() != null) { - //update rest of the fields - String sql = "UPDATE " - + getDbSchemaName() - + "QT_QUERY_INSTANCE set USER_ID = ?, GROUP_ID = ?,BATCH_MODE = ?,END_DATE = ? ,STATUS_TYPE_ID = ? " - + " where query_instance_id = ? "; - - jdbcTemplate.update(sql, new Object[] { - queryInstance.getUserId(), - queryInstance.getGroupId(), - queryInstance.getBatchMode(), - queryInstance.getEndDate(), - statusTypeId, - Integer.parseInt( queryInstance.getQueryInstanceId()) }); - } else { - //update rest of the fields - String sql = "UPDATE " - + getDbSchemaName() - + "QT_QUERY_INSTANCE set USER_ID = ?, GROUP_ID = ?,BATCH_MODE = ?,STATUS_TYPE_ID = ? " - + " where query_instance_id = ? "; - - jdbcTemplate.update(sql, new Object[] { - queryInstance.getUserId(), - queryInstance.getGroupId(), - queryInstance.getBatchMode(), - statusTypeId, - Integer.parseInt(queryInstance.getQueryInstanceId()) }); - } - return queryInstance; - } - - } else { - messageUpdate = " MESSAGE = ?"; - } - - if (queryInstance.getEndDate() != null) { - String sql = "UPDATE " - + getDbSchemaName() - + "QT_QUERY_INSTANCE set USER_ID = ?, GROUP_ID = ?,BATCH_MODE = ?,END_DATE = ? ,STATUS_TYPE_ID = ?, " - + messageUpdate + " where query_instance_id = ? "; - - jdbcTemplate.update(sql, new Object[] { - queryInstance.getUserId(), - queryInstance.getGroupId(), - queryInstance.getBatchMode(), - queryInstance.getEndDate(), - statusTypeId, - (queryInstance.getMessage() == null) ? "" : queryInstance - .getMessage(), Integer.parseInt(queryInstance.getQueryInstanceId()) }); - } else { - String sql = "UPDATE " - + getDbSchemaName() - + "QT_QUERY_INSTANCE set USER_ID = ?, GROUP_ID = ?,BATCH_MODE = ?,STATUS_TYPE_ID = ?, " - + messageUpdate + " where query_instance_id = ? "; - - jdbcTemplate.update(sql, new Object[] { - queryInstance.getUserId(), - queryInstance.getGroupId(), - queryInstance.getBatchMode(), - statusTypeId, - (queryInstance.getMessage() == null) ? "" : queryInstance - .getMessage(), Integer.parseInt(queryInstance.getQueryInstanceId()) }); - } - return queryInstance; - } - - - /** - * Update query instance message - * - * @param queryInstanceId - * @param message - * @param appendMessageFlag - * @return - */ - @Override - public void updateMessage(String queryInstanceId, String message, - boolean appendMessageFlag) throws I2B2DAOException { - - String messageUpdate = ""; - if (appendMessageFlag) { - String concatOperator = ""; - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE) ) { - concatOperator = "||"; - messageUpdate = " MESSAGE = nvl(MESSAGE,'') " + concatOperator - + " ? "; - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL) ) { - concatOperator = "||"; - messageUpdate = " MESSAGE = ? "; - - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER)) { - // Cast(notes as nvarchar(4000)) - //messageUpdate = " message.write (?, NULL, 0) "; - - Connection conn = null; - try { - conn = getDataSource().getConnection(); - CallableStatement callStmt = conn.prepareCall("{call " - + getDbSchemaName() + "UPDATE_QUERYINSTANCE_MESSAGE(?,?,?)}"); - callStmt.setString(1, message); - callStmt.setString(2, queryInstanceId); - callStmt.registerOutParameter(3, java.sql.Types.VARCHAR); - // callStmt.setString(2, tempPatientMappingTableName); - callStmt.execute(); - this.getSQLServerProcedureError(dataSourceLookup.getServerType(), - callStmt, 3); - callStmt.close(); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - throw new I2B2DAOException( - "SQLException occured" + sqlEx.getMessage(), sqlEx); - } catch (Exception ex) { - ex.printStackTrace(); - throw new I2B2DAOException("Exception occured" + ex.getMessage(), ex); - } finally { - if (conn != null) { - try { - conn.close(); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - log.error("Error while closing connection", sqlEx); - } - } - } - return ; - ////// - - } - - } else { - messageUpdate = " MESSAGE = ?"; - } - String sql = "UPDATE " - + getDbSchemaName() - + "QT_QUERY_INSTANCE set " - + messageUpdate + " where query_instance_id = ? "; - jdbcTemplate.update(sql, new Object[] { - - (message == null) ? "" : - message, Integer.parseInt(queryInstanceId) }); - - } - - private static class SaveQueryInstance extends SqlUpdate { - - private String INSERT_ORACLE = ""; - private String INSERT_SQLSERVER = ""; - private String SEQUENCE_ORACLE = ""; - private String SEQUENCE_POSTGRESQL = ""; - private String INSERT_POSTGRESQL = ""; - - - private DataSourceLookup dataSourceLookup = null; - - public SaveQueryInstance(DataSource dataSource, String dbSchemaName, - DataSourceLookup dataSourceLookup) { - super(); - this.dataSourceLookup = dataSourceLookup; - // sqlServerSequenceDao = new - // SQLServerSequenceDAO(dataSource,dataSourceLookup) ; - setDataSource(dataSource); - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE)) { - INSERT_ORACLE = "INSERT INTO " - + dbSchemaName - + "QT_QUERY_INSTANCE " - + "(QUERY_INSTANCE_ID, QUERY_MASTER_ID, USER_ID, GROUP_ID,BATCH_MODE,START_DATE,END_DATE,STATUS_TYPE_ID,DELETE_FLAG) " - + "VALUES (?,?,?,?,?,?,?,?,?)"; - setSql(INSERT_ORACLE); - SEQUENCE_ORACLE = "select " + dbSchemaName - + "QT_SQ_QI_QIID.nextval from dual"; - declareParameter(new SqlParameter(Types.INTEGER)); - - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER)) { - INSERT_SQLSERVER = "INSERT INTO " - + dbSchemaName - + "QT_QUERY_INSTANCE " - + "( QUERY_MASTER_ID, USER_ID, GROUP_ID,BATCH_MODE,START_DATE,END_DATE,STATUS_TYPE_ID,DELETE_FLAG) " - + "VALUES (?,?,?,?,?,?,?,?)"; - setSql(INSERT_SQLSERVER); - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) { - INSERT_POSTGRESQL = "INSERT INTO " - + dbSchemaName - + "QT_QUERY_INSTANCE " - + "(QUERY_INSTANCE_ID, QUERY_MASTER_ID, USER_ID, GROUP_ID,BATCH_MODE,START_DATE,END_DATE,STATUS_TYPE_ID,DELETE_FLAG) " - + "VALUES (?,?,?,?,?,?,?,?,?)"; - setSql(INSERT_POSTGRESQL); - SEQUENCE_POSTGRESQL = "select " // + dbSchemaName - + "nextval('qt_query_instance_query_instance_id_seq') "; - declareParameter(new SqlParameter(Types.INTEGER)); - - } - - declareParameter(new SqlParameter(Types.INTEGER)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.TIMESTAMP)); - declareParameter(new SqlParameter(Types.TIMESTAMP)); - declareParameter(new SqlParameter(Types.INTEGER)); - declareParameter(new SqlParameter(Types.VARCHAR)); - compile(); - } - - public void save(QtQueryInstance queryInstance) { - JdbcTemplate jdbc = getJdbcTemplate(); - int queryInstanceId = 0; - Object[] object = null; - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER) ) { - object = new Object[] { - - queryInstance.getQtQueryMaster().getQueryMasterId(), - queryInstance.getUserId(), queryInstance.getGroupId(), - queryInstance.getBatchMode(), - queryInstance.getStartDate(), - queryInstance.getEndDate(), - queryInstance.getQtQueryStatusType().getStatusTypeId(), - queryInstance.getDeleteFlag() }; - - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE)) { - queryInstanceId = jdbc.queryForObject(SEQUENCE_ORACLE, Integer.class); - queryInstance.setQueryInstanceId(String - .valueOf(queryInstanceId)); - object = new Object[] { queryInstance.getQueryInstanceId(), - queryInstance.getQtQueryMaster().getQueryMasterId(), - queryInstance.getUserId(), queryInstance.getGroupId(), - queryInstance.getBatchMode(), - queryInstance.getStartDate(), - queryInstance.getEndDate(), - queryInstance.getQtQueryStatusType().getStatusTypeId(), - queryInstance.getDeleteFlag() }; - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) { - queryInstanceId = jdbc.queryForObject(SEQUENCE_POSTGRESQL, Integer.class); - queryInstance.setQueryInstanceId(String - .valueOf(queryInstanceId)); - object = new Object[] { queryInstance.getQueryInstanceId(), - queryInstance.getQtQueryMaster().getQueryMasterId(), - queryInstance.getUserId(), queryInstance.getGroupId(), - queryInstance.getBatchMode(), - queryInstance.getStartDate(), - queryInstance.getEndDate(), - queryInstance.getQtQueryStatusType().getStatusTypeId(), - queryInstance.getDeleteFlag() }; - } - - update(object); - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER)) { - int queryInstanceIdentityId = jdbc - .queryForObject("SELECT @@IDENTITY", Integer.class); - - queryInstance.setQueryInstanceId(String - .valueOf(queryInstanceIdentityId)); - - } - } - } - - private class QtQueryInstanceRowMapper implements RowMapper { - QueryStatusTypeSpringDao statusTypeDao = new QueryStatusTypeSpringDao( - dataSource, dataSourceLookup); - - @Override - public Object mapRow(ResultSet rs, int rowNum) throws SQLException { - QtQueryInstance queryInstance = new QtQueryInstance(); - queryInstance.setQueryInstanceId(rs.getString("QUERY_INSTANCE_ID")); - QtQueryMaster queryMaster = new QtQueryMaster(); - queryMaster.setQueryMasterId(rs.getString("QUERY_MASTER_ID")); - queryInstance.setQtQueryMaster(queryMaster); - queryInstance.setUserId(rs.getString("USER_ID")); - queryInstance.setGroupId(rs.getString("GROUP_ID")); - queryInstance.setBatchMode(rs.getString("BATCH_MODE")); - queryInstance.setStartDate(rs.getTimestamp("START_DATE")); - queryInstance.setEndDate(rs.getTimestamp("END_DATE")); - queryInstance.setMessage(rs.getString("MESSAGE")); - int statusTypeId = rs.getInt("STATUS_TYPE_ID"); - queryInstance.setQtQueryStatusType(statusTypeDao - .getQueryStatusTypeById(statusTypeId)); - queryInstance.setDeleteFlag(rs.getString("DELETE_FLAG")); - return queryInstance; - } - } - - private void getSQLServerProcedureError(String serverType, - CallableStatement callStmt, int outParamIndex) throws SQLException, - I2B2Exception { - - if (serverType.equalsIgnoreCase(DataSourceLookupDAOFactory.SQLSERVER)) { - String errorMsg = callStmt.getString(outParamIndex); - if (errorMsg != null) { - logesapi.debug("error codde" + errorMsg); - throw new I2B2Exception("Error from stored procedure [" - + errorMsg + "]"); - } - } - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao.setfinder; + +import java.sql.CallableStatement; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Types; +import java.util.Date; +import java.util.List; + +import javax.sql.DataSource; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.RowMapper; +import org.springframework.jdbc.core.SqlParameter; +import org.springframework.jdbc.object.SqlUpdate; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.db.QtQueryInstance; +import edu.harvard.i2b2.crc.datavo.db.QtQueryMaster; +import edu.harvard.i2b2.crc.datavo.db.QtQueryStatusType; +import edu.harvard.i2b2.crc.ejb.analysis.QueryInstance; +import edu.harvard.i2b2.crc.dao.DataSourceLookupDAOFactory; + +/** + * Class to handle persistance operation of Query instance i.e. each run of + * query is called query instance $Id: QueryInstanceSpringDao.java,v 1.4 + * 2008/04/08 19:38:24 rk903 Exp $ + * + * @author rkuttan + * @see QtQueryInstance + */ +public class QueryInstanceSpringDao extends CRCDAO implements IQueryInstanceDao { + + JdbcTemplate jdbcTemplate = null; + SaveQueryInstance saveQueryInstance = null; + QtQueryInstanceRowMapper queryInstanceMapper = null; + private DataSourceLookup dataSourceLookup = null; + + /** log **/ + protected final Log log = LogFactory.getLog(getClass()); + + protected static Log logesapi = LogFactory.getLog(QueryInstanceSpringDao.class); + + + public QueryInstanceSpringDao(DataSource dataSource, + DataSourceLookup dataSourceLookup) { + setDataSource(dataSource); + setDbSchemaName(dataSourceLookup.getFullSchema()); + jdbcTemplate = new JdbcTemplate(dataSource); + this.dataSourceLookup = dataSourceLookup; + queryInstanceMapper = new QtQueryInstanceRowMapper(); + } + + /** + * Function to create query instance + * + * @param queryMasterId + * @param userId + * @param groupId + * @param batchMode + * @param statusId + * @return query instance id + */ + @Override + public String createQueryInstance(String queryMasterId, String userId, + String groupId, String batchMode, int statusId) { + QtQueryInstance queryInstance = new QtQueryInstance(); + queryInstance.setUserId(userId); + queryInstance.setGroupId(groupId); + queryInstance.setBatchMode(batchMode); + queryInstance.setDeleteFlag("N"); + + QtQueryMaster queryMaster = new QtQueryMaster(); + queryMaster.setQueryMasterId(queryMasterId); + queryInstance.setQtQueryMaster(queryMaster); + + QtQueryStatusType statusType = new QtQueryStatusType(); + statusType.setStatusTypeId(statusId); + queryInstance.setQtQueryStatusType(statusType); + + Date startDate = new Date(System.currentTimeMillis()); + queryInstance.setStartDate(startDate); + saveQueryInstance = new SaveQueryInstance(getDataSource(), + getDbSchemaName(), dataSourceLookup); + saveQueryInstance.save(queryInstance); + + return queryInstance.getQueryInstanceId(); + } + + /** + * Returns list of query instance for the given master id + * + * @param queryMasterId + * @return List + */ + @Override + @SuppressWarnings("unchecked") + public List getQueryInstanceByMasterId(String queryMasterId) { + String sql = "select * from " + getDbSchemaName() + + "qt_query_instance where query_master_id = ?"; + List queryInstanceList = jdbcTemplate.query(sql, + new Object[] { Integer.parseInt(queryMasterId) }, queryInstanceMapper); + return queryInstanceList; + } + + /** + * Find query instance by id + * + * @param queryInstanceId + * @return QtQueryInstance + */ + @Override + public QtQueryInstance getQueryInstanceByInstanceId(String queryInstanceId) { + String sql = "select * from " + getDbSchemaName() + + "qt_query_instance where query_instance_id =?"; + + QtQueryInstance queryInstance = (QtQueryInstance) jdbcTemplate + .queryForObject(sql, new Object[] { Integer.parseInt(queryInstanceId ) }, + queryInstanceMapper); + + return queryInstance; + } + + /** + * Update query instance + * + * @param queryInstance + * @return QtQueryInstance + * @throws I2B2DAOException + */ + @Override + public QtQueryInstance update(QtQueryInstance queryInstance, + boolean appendMessageFlag) throws I2B2DAOException { + + Integer statusTypeId = (queryInstance.getQtQueryStatusType() != null) ? queryInstance + .getQtQueryStatusType().getStatusTypeId() + : null; + String messageUpdate = ""; + if (appendMessageFlag) { + String concatOperator = ""; + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.ORACLE)) { + concatOperator = "||"; + messageUpdate = " MESSAGE = nvl(MESSAGE,'') " + concatOperator + + " ? "; + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER) || dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) { + //concatOperator = "+"; + // messageUpdate = " MESSAGE = isnull(Cast(MESSAGE as nvarchar(4000)),'') " + // + concatOperator + " ? "; + // Cast(notes as nvarchar(4000)) + + //update message field + if (queryInstance.getMessage() != null) + updateMessage(queryInstance.getQueryInstanceId(),queryInstance.getMessage(),true); + + if (queryInstance.getEndDate() != null) { + //update rest of the fields + String sql = "UPDATE " + + getDbSchemaName() + + "QT_QUERY_INSTANCE set USER_ID = ?, GROUP_ID = ?,BATCH_MODE = ?,END_DATE = ? ,STATUS_TYPE_ID = ? " + + " where query_instance_id = ? "; + + jdbcTemplate.update(sql, new Object[] { + queryInstance.getUserId(), + queryInstance.getGroupId(), + queryInstance.getBatchMode(), + queryInstance.getEndDate(), + statusTypeId, + Integer.parseInt( queryInstance.getQueryInstanceId()) }); + } else { + //update rest of the fields + String sql = "UPDATE " + + getDbSchemaName() + + "QT_QUERY_INSTANCE set USER_ID = ?, GROUP_ID = ?,BATCH_MODE = ?,STATUS_TYPE_ID = ? " + + " where query_instance_id = ? "; + + jdbcTemplate.update(sql, new Object[] { + queryInstance.getUserId(), + queryInstance.getGroupId(), + queryInstance.getBatchMode(), + statusTypeId, + Integer.parseInt(queryInstance.getQueryInstanceId()) }); + } + return queryInstance; + } + + } else { + messageUpdate = " MESSAGE = ?"; + } + + if (queryInstance.getEndDate() != null) { + String sql = "UPDATE " + + getDbSchemaName() + + "QT_QUERY_INSTANCE set USER_ID = ?, GROUP_ID = ?,BATCH_MODE = ?,END_DATE = ? ,STATUS_TYPE_ID = ?, " + + messageUpdate + " where query_instance_id = ? "; + + jdbcTemplate.update(sql, new Object[] { + queryInstance.getUserId(), + queryInstance.getGroupId(), + queryInstance.getBatchMode(), + queryInstance.getEndDate(), + statusTypeId, + (queryInstance.getMessage() == null) ? "" : queryInstance + .getMessage(), Integer.parseInt(queryInstance.getQueryInstanceId()) }); + } else { + String sql = "UPDATE " + + getDbSchemaName() + + "QT_QUERY_INSTANCE set USER_ID = ?, GROUP_ID = ?,BATCH_MODE = ?,STATUS_TYPE_ID = ?, " + + messageUpdate + " where query_instance_id = ? "; + + jdbcTemplate.update(sql, new Object[] { + queryInstance.getUserId(), + queryInstance.getGroupId(), + queryInstance.getBatchMode(), + statusTypeId, + (queryInstance.getMessage() == null) ? "" : queryInstance + .getMessage(), Integer.parseInt(queryInstance.getQueryInstanceId()) }); + } + return queryInstance; + } + + + /** + * Update query instance message + * + * @param queryInstanceId + * @param message + * @param appendMessageFlag + * @return + */ + @Override + public void updateMessage(String queryInstanceId, String message, + boolean appendMessageFlag) throws I2B2DAOException { + + String messageUpdate = ""; + if (appendMessageFlag) { + String concatOperator = ""; + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.ORACLE) ) { + concatOperator = "||"; + messageUpdate = " MESSAGE = nvl(MESSAGE,'') " + concatOperator + + " ? "; + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL) ) { + concatOperator = "||"; + messageUpdate = " MESSAGE = ? "; + + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER)) { + // Cast(notes as nvarchar(4000)) + //messageUpdate = " message.write (?, NULL, 0) "; + + Connection conn = null; + try { + conn = getDataSource().getConnection(); + CallableStatement callStmt = conn.prepareCall("{call " + + getDbSchemaName() + "UPDATE_QUERYINSTANCE_MESSAGE(?,?,?)}"); + callStmt.setString(1, message); + callStmt.setString(2, queryInstanceId); + callStmt.registerOutParameter(3, java.sql.Types.VARCHAR); + // callStmt.setString(2, tempPatientMappingTableName); + callStmt.execute(); + this.getSQLServerProcedureError(dataSourceLookup.getServerType(), + callStmt, 3); + callStmt.close(); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + throw new I2B2DAOException( + "SQLException occured" + sqlEx.getMessage(), sqlEx); + } catch (Exception ex) { + ex.printStackTrace(); + throw new I2B2DAOException("Exception occured" + ex.getMessage(), ex); + } finally { + if (conn != null) { + try { + conn.close(); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + log.error("Error while closing connection", sqlEx); + } + } + } + return ; + ////// + + } + + } else { + messageUpdate = " MESSAGE = ?"; + } + String sql = "UPDATE " + + getDbSchemaName() + + "QT_QUERY_INSTANCE set " + + messageUpdate + " where query_instance_id = ? "; + jdbcTemplate.update(sql, new Object[] { + + (message == null) ? "" : + message, Integer.parseInt(queryInstanceId) }); + + } + + private static class SaveQueryInstance extends SqlUpdate { + + private String INSERT_ORACLE = ""; + private String INSERT_SQLSERVER = ""; + private String SEQUENCE_ORACLE = ""; + private String SEQUENCE_POSTGRESQL = ""; + private String INSERT_POSTGRESQL = ""; + + + private DataSourceLookup dataSourceLookup = null; + + public SaveQueryInstance(DataSource dataSource, String dbSchemaName, + DataSourceLookup dataSourceLookup) { + super(); + this.dataSourceLookup = dataSourceLookup; + // sqlServerSequenceDao = new + // SQLServerSequenceDAO(dataSource,dataSourceLookup) ; + setDataSource(dataSource); + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.ORACLE)) { + INSERT_ORACLE = "INSERT INTO " + + dbSchemaName + + "QT_QUERY_INSTANCE " + + "(QUERY_INSTANCE_ID, QUERY_MASTER_ID, USER_ID, GROUP_ID,BATCH_MODE,START_DATE,END_DATE,STATUS_TYPE_ID,DELETE_FLAG) " + + "VALUES (?,?,?,?,?,?,?,?,?)"; + setSql(INSERT_ORACLE); + SEQUENCE_ORACLE = "select " + dbSchemaName + + "QT_SQ_QI_QIID.nextval from dual"; + declareParameter(new SqlParameter(Types.INTEGER)); + + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER)) { + INSERT_SQLSERVER = "INSERT INTO " + + dbSchemaName + + "QT_QUERY_INSTANCE " + + "( QUERY_MASTER_ID, USER_ID, GROUP_ID,BATCH_MODE,START_DATE,END_DATE,STATUS_TYPE_ID,DELETE_FLAG) " + + "VALUES (?,?,?,?,?,?,?,?)"; + setSql(INSERT_SQLSERVER); + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) { + INSERT_POSTGRESQL = "INSERT INTO " + + dbSchemaName + + "QT_QUERY_INSTANCE " + + "(QUERY_INSTANCE_ID, QUERY_MASTER_ID, USER_ID, GROUP_ID,BATCH_MODE,START_DATE,END_DATE,STATUS_TYPE_ID,DELETE_FLAG) " + + "VALUES (?,?,?,?,?,?,?,?,?)"; + setSql(INSERT_POSTGRESQL); + SEQUENCE_POSTGRESQL = "select " // + dbSchemaName + + "nextval('qt_query_instance_query_instance_id_seq') "; + declareParameter(new SqlParameter(Types.INTEGER)); + + } + + declareParameter(new SqlParameter(Types.INTEGER)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.TIMESTAMP)); + declareParameter(new SqlParameter(Types.TIMESTAMP)); + declareParameter(new SqlParameter(Types.INTEGER)); + declareParameter(new SqlParameter(Types.VARCHAR)); + compile(); + } + + public void save(QtQueryInstance queryInstance) { + JdbcTemplate jdbc = getJdbcTemplate(); + int queryInstanceId = 0; + Object[] object = null; + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER) ) { + object = new Object[] { + + queryInstance.getQtQueryMaster().getQueryMasterId(), + queryInstance.getUserId(), queryInstance.getGroupId(), + queryInstance.getBatchMode(), + queryInstance.getStartDate(), + queryInstance.getEndDate(), + queryInstance.getQtQueryStatusType().getStatusTypeId(), + queryInstance.getDeleteFlag() }; + + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.ORACLE)) { + queryInstanceId = jdbc.queryForObject(SEQUENCE_ORACLE, Integer.class); + queryInstance.setQueryInstanceId(String + .valueOf(queryInstanceId)); + object = new Object[] { queryInstance.getQueryInstanceId(), + queryInstance.getQtQueryMaster().getQueryMasterId(), + queryInstance.getUserId(), queryInstance.getGroupId(), + queryInstance.getBatchMode(), + queryInstance.getStartDate(), + queryInstance.getEndDate(), + queryInstance.getQtQueryStatusType().getStatusTypeId(), + queryInstance.getDeleteFlag() }; + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) { + queryInstanceId = jdbc.queryForObject(SEQUENCE_POSTGRESQL, Integer.class); + queryInstance.setQueryInstanceId(String + .valueOf(queryInstanceId)); + object = new Object[] { queryInstance.getQueryInstanceId(), + queryInstance.getQtQueryMaster().getQueryMasterId(), + queryInstance.getUserId(), queryInstance.getGroupId(), + queryInstance.getBatchMode(), + queryInstance.getStartDate(), + queryInstance.getEndDate(), + queryInstance.getQtQueryStatusType().getStatusTypeId(), + queryInstance.getDeleteFlag() }; + } + + update(object); + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER)) { + int queryInstanceIdentityId = jdbc + .queryForObject("SELECT @@IDENTITY", Integer.class); + + queryInstance.setQueryInstanceId(String + .valueOf(queryInstanceIdentityId)); + + } + } + } + + private class QtQueryInstanceRowMapper implements RowMapper { + QueryStatusTypeSpringDao statusTypeDao = new QueryStatusTypeSpringDao( + dataSource, dataSourceLookup); + + @Override + public Object mapRow(ResultSet rs, int rowNum) throws SQLException { + QtQueryInstance queryInstance = new QtQueryInstance(); + queryInstance.setQueryInstanceId(rs.getString("QUERY_INSTANCE_ID")); + QtQueryMaster queryMaster = new QtQueryMaster(); + queryMaster.setQueryMasterId(rs.getString("QUERY_MASTER_ID")); + queryInstance.setQtQueryMaster(queryMaster); + queryInstance.setUserId(rs.getString("USER_ID")); + queryInstance.setGroupId(rs.getString("GROUP_ID")); + queryInstance.setBatchMode(rs.getString("BATCH_MODE")); + queryInstance.setStartDate(rs.getTimestamp("START_DATE")); + queryInstance.setEndDate(rs.getTimestamp("END_DATE")); + queryInstance.setMessage(rs.getString("MESSAGE")); + int statusTypeId = rs.getInt("STATUS_TYPE_ID"); + queryInstance.setQtQueryStatusType(statusTypeDao + .getQueryStatusTypeById(statusTypeId)); + queryInstance.setDeleteFlag(rs.getString("DELETE_FLAG")); + return queryInstance; + } + } + + private void getSQLServerProcedureError(String serverType, + CallableStatement callStmt, int outParamIndex) throws SQLException, + I2B2Exception { + + if (serverType.equalsIgnoreCase(DataSourceLookupDAOFactory.SQLSERVER)) { + String errorMsg = callStmt.getString(outParamIndex); + if (errorMsg != null) { + logesapi.debug("error codde" + errorMsg); + throw new I2B2Exception("Error from stored procedure [" + + errorMsg + "]"); + } + } + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryMasterSpringDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryMasterSpringDao.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryMasterSpringDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryMasterSpringDao.java index 4cda428c..4832a3f9 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryMasterSpringDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryMasterSpringDao.java @@ -1,805 +1,805 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao.setfinder; - -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Types; -import java.util.Date; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import javax.sql.DataSource; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.dao.DataAccessException; -import org.springframework.dao.IncorrectResultSizeDataAccessException; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.RowMapper; -import org.springframework.jdbc.core.SqlParameter; -import org.springframework.jdbc.object.SqlUpdate; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.DateConstrainHandler; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.db.QtQueryInstance; -import edu.harvard.i2b2.crc.datavo.db.QtQueryMaster; -import edu.harvard.i2b2.crc.datavo.db.QtQueryResultInstance; -import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.FindByChildType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.InclusiveType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.MatchStrType; -import edu.harvard.i2b2.crc.ejb.analysis.QueryMaster; -import edu.harvard.i2b2.crc.util.CacheUtil; - -/** - * Class to manager persistance operation of QtQueryMaster $Id: - * QueryMasterSpringDao.java,v 1.3 2008/04/08 19:36:52 rk903 Exp $ - * - * @author rkuttan - * @see QtQueryMaster - */ -public class QueryMasterSpringDao extends CRCDAO implements IQueryMasterDao { - - - protected static Log logesapi = LogFactory.getLog(QueryMasterSpringDao.class); - - JdbcTemplate jdbcTemplate = null; - SaveQueryMaster saveQueryMaster = null; - QtQueryMasterRowMapper queryMasterMapper = new QtQueryMasterRowMapper(); - - public final String DELETE_YES_FLAG = "Y"; - public final String DELETE_NO_FLAG = "N"; - - private DataSourceLookup dataSourceLookup = null; - - public QueryMasterSpringDao(DataSource dataSource, - DataSourceLookup dataSourceLookup) { - setDataSource(dataSource); - setDbSchemaName(dataSourceLookup.getFullSchema()); - jdbcTemplate = new JdbcTemplate(dataSource); - this.dataSourceLookup = dataSourceLookup; - - } - - /** - * Function to create query master By default sets delete flag to false - * - * @param queryMaster - * @return query master id - */ - @Override - public String createQueryMaster(QtQueryMaster queryMaster, - String i2b2RequestXml, String pmXml) { - queryMaster.setDeleteFlag(DELETE_NO_FLAG); - saveQueryMaster = new SaveQueryMaster(getDataSource(), - getDbSchemaName(), dataSourceLookup); - saveQueryMaster.save(queryMaster, i2b2RequestXml, pmXml); - return queryMaster.getQueryMasterId(); - } - - /** - * Write query sql for the master id - * - * @param masterId - * @param generatedSql - */ - @Override - public void updateQueryAfterRun(String masterId, String generatedSql, String masterType) { - String sql = "UPDATE " - + getDbSchemaName() - + "QT_QUERY_MASTER set GENERATED_SQL = ?, MASTER_TYPE_CD = ? where query_master_id = ?"; - jdbcTemplate.update(sql, new Object[] { generatedSql, masterType, Integer.parseInt(masterId) }); - // jdbcTemplate.update(sql); - } - - /** - * Write query sql for the master id - * - * @param masterId - * @param generatedSql - */ - @Override - public void updateMasterTypeAfterRun(String masterId, String masterType) { - String sql = "UPDATE " - + getDbSchemaName() - + "QT_QUERY_MASTER set MASTER_TYPE_CD = ? where query_master_id = ?"; - jdbcTemplate.update(sql, new Object[] { masterType, Integer.parseInt(masterId) }); - // jdbcTemplate.update(sql); - } - - - /** - * Returns list of query master by find search - * - * @param userId - * @return List - * @throws I2B2Exception - */ - @Override - @SuppressWarnings("unchecked") - public List getQueryMasterByNameInfo(SecurityType userRequestType, FindByChildType findChildType) throws I2B2DAOException { - - - - String rolePath = dataSourceLookup.getDomainId() - + dataSourceLookup.getProjectPath() - + userRequestType.getUsername(); - - //List roles = (List) cache.getRoot().get(rolePath); - logesapi.debug("Roles from get " + rolePath); - List roles = (List) CacheUtil.get(rolePath); - - String sql = "select "; - - int fetchSize = findChildType.getMax(); - List queryMasterList = null; - - String str = ""; - MatchStrType matchStr = findChildType.getMatchStr(); - if (matchStr.getStrategy().toLowerCase().equals("right") || matchStr.getStrategy().toLowerCase().equals("contains")) - str = "%"; - str += matchStr.getValue(); - if (matchStr.getStrategy().toLowerCase().equals("left") || matchStr.getStrategy().toLowerCase().equals("contains")) - str += "%"; - - - if (fetchSize > 0 - && dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER)) { - sql += " top " + fetchSize; - } - if ((findChildType.getCategory().toLowerCase().equals("top")) || - (findChildType.getCategory().toLowerCase().equals("@"))) { - sql += " query_master_id,name,user_id,group_id,create_date,delete_date,null as pm_xml,null as request_xml,delete_flag,generated_sql, null as i2b2_request_xml, master_type_cd, null as plugin_id from " - + getDbSchemaName() - + "qt_query_master where "; - if (roles != null && !roles.contains("MANAGER")) - sql += " user_id = ? and "; - sql += " LOWER(name) like ? and delete_flag = ? "; //and master_type_cd is NULL"; - if (findChildType.getCreateDate() != null) - { - InclusiveType inclusive = InclusiveType.NO; - - DateConstrainHandler dateConstrainHandler = new DateConstrainHandler( - dataSourceLookup); - - if (findChildType.isAscending()) - sql +=" and " + dateConstrainHandler - .constructDateConstrainClause("create_date", - "create_date", inclusive, - inclusive, findChildType.getCreateDate() , - null); - else - sql += " and " + dateConstrainHandler - .constructDateConstrainClause("create_date", - "create_date", inclusive, - inclusive,null , - findChildType.getCreateDate()); - sql += " order by create_date "; - - } else { - sql += " order by create_date "; - } - - if (findChildType.isAscending() && findChildType.getCreateDate() != null) - sql += "asc"; - else - sql += "desc"; - /* if (findChildType.isAscending()) - sql += "desc"; - else - sql += "asc"; - */ - } - if ((findChildType.getCategory().equals("@"))) - { - if (fetchSize > 0) { - if ( dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE)) - sql = "select * from ( " + sql + " ) where " + " rownum <= " - + fetchSize; - else if ( dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) - sql += " limit " + fetchSize; - } - - if (roles != null && roles.contains("MANAGER")) - queryMasterList = jdbcTemplate.query(sql, - new Object[] { str.toLowerCase(), DELETE_NO_FLAG }, queryMasterMapper); - else - queryMasterList = jdbcTemplate.query(sql, - new Object[] { userRequestType.getUsername(), str.toLowerCase(), DELETE_NO_FLAG }, queryMasterMapper); - - - - - sql = "select "; - if (fetchSize > 0 - && dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER)) { - sql += " top " + fetchSize; - } - } - if ((findChildType.getCategory().toLowerCase().equals("results")) || - (findChildType.getCategory().equals("@"))) { - sql += " qm.query_master_id,qm.name,qm.user_id,qm.group_id,qm.create_date,qm.delete_date,null as pm_xml,null as request_xml,qm.delete_flag,qm.generated_sql, null as i2b2_request_xml, qm.master_type_cd, null as plugin_id from " - + getDbSchemaName() - + "qt_query_master qm, " - + getDbSchemaName() - + "qt_query_instance qi, " - + getDbSchemaName() - + "qt_query_result_instance qri where " - + "qm.QUERY_MASTER_ID = qi.QUERY_MASTER_ID and " - + "qi.QUERY_INSTANCE_ID = qri.QUERY_INSTANCE_ID and "; - if (roles != null && !roles.contains("MANAGER")) - sql += " qm.user_id = ? and"; - sql+= " LOWER(qri.DESCRIPTION) like ? and qm.delete_flag = ? "; //and qm.master_type_cd is NULL"; - if (findChildType.getCreateDate() != null) - { - DateConstrainHandler dateConstrainHandler = new DateConstrainHandler( - dataSourceLookup); - - if (!findChildType.isAscending()) - sql += " and " + dateConstrainHandler - .constructDateConstrainClause("create_date", - "create_date", null, - null, findChildType.getCreateDate() , - null); - else - sql += " and " + dateConstrainHandler - .constructDateConstrainClause("create_date", - "create_date", null, - null,null , - findChildType.getCreateDate()); - sql += " order by qm.create_date "; - - } - else { - sql += " order by qm.create_date "; - } - // if (findChildType.isAscending()) - sql += "desc"; - // else - // sql += "asc"; - } - if ((findChildType.getCategory().toLowerCase().equals("@"))) - { - - if (fetchSize > 0) { - if ( dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE)) - sql = "select * from ( " + sql + " ) where " + " rownum <= " - + fetchSize; - else if ( dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) - sql += " limit " + fetchSize; - - } - - if (roles != null && roles.contains("MANAGER")) - queryMasterList.addAll(jdbcTemplate.query(sql, - new Object[] { str.toLowerCase(), DELETE_NO_FLAG }, queryMasterMapper)); - else - queryMasterList.addAll(jdbcTemplate.query(sql, - new Object[] { userRequestType.getUsername(), str.toLowerCase(), DELETE_NO_FLAG }, queryMasterMapper)); - - sql = " select "; - if (fetchSize > 0 - && dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER)) { - sql += " distinct top " + fetchSize; - } else - { - sql += " distinct "; - } - } - if ((findChildType.getCategory().toLowerCase().equals("pdo")) || - (findChildType.getCategory().toLowerCase().equals("@"))) { - sql += " qm.query_master_id,qm.name,qm.user_id,qm.group_id,qm.create_date,qm.delete_date,null as pm_xml,null as request_xml,qm.delete_flag,null as generated_sql, null as i2b2_request_xml, qm.master_type_cd, null as plugin_id from " - + getDbSchemaName() - + "qt_query_master qm, " - + getDbSchemaName() - + "qt_query_instance qi, " - + getDbSchemaName() - + "QT_PATIENT_SET_COLLECTION qp, " - + getDbSchemaName() - + "qt_query_result_instance qri where " - + "qm.QUERY_MASTER_ID = qi.QUERY_MASTER_ID and " - + "qi.QUERY_INSTANCE_ID = qri.QUERY_INSTANCE_ID and " - + "qri.RESULT_INSTANCE_ID = qp.RESULT_INSTANCE_ID and "; - if (roles != null && !roles.contains("MANAGER")) - sql += " qm.user_id = ? and "; - if ( dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) - sql += " CAST(qp.patient_num AS TEXT) like ? and qm.delete_flag = ? "; - else - sql += " qp.patient_num like ? and qm.delete_flag = ? "; - - if (findChildType.getCreateDate() != null) - { - DateConstrainHandler dateConstrainHandler = new DateConstrainHandler( - dataSourceLookup); - - if (!findChildType.isAscending()) - sql += " and " + dateConstrainHandler - .constructDateConstrainClause("create_date", - "create_date", null, - null, findChildType.getCreateDate() , - null); - else - sql += " and " + dateConstrainHandler - .constructDateConstrainClause("create_date", - "create_date", null, - null,null , - findChildType.getCreateDate()); - - sql += " order by qm.create_date "; - } - else { - sql += " order by qm.create_date "; - } - // if (findChildType.isAscending()) - sql += "desc"; - // else - // sql += "asc"; - } - - if (fetchSize > 0) { - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE)) - sql = "select * from ( " + sql + " ) where " + " rownum <= " - + fetchSize; - else if ( dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) - sql += " limit " + fetchSize; - - } - - - - // if (findChildType.getCategory().toLowerCase().equals("@")) - // queryMasterList = jdbcTemplate.query(sql, - // new Object[] { userRequestType.getUsername(), str, DELETE_NO_FLAG, userRequestType.getUsername(), str, DELETE_NO_FLAG, userRequestType.getUsername(), str, DELETE_NO_FLAG }, queryMasterMapper); - // else - Object[] args = null; - String userid = userRequestType.getUsername(); - if (findChildType.getUserId() != null && roles != null && roles.contains("MANAGER")) - userid = findChildType.getUserId(); - // else if (findChildType.getUserId() != null) - // throw new I2B2DAOException ("Permisison denied"); - // if (findChildType.getCreateDate() != null) - // args = new Object[] { userid, str.toLowerCase(), DELETE_NO_FLAG,findChildType.getCreateDate() }; - // else - if (roles != null && roles.contains("MANAGER")) - args = new Object[] { str.toLowerCase(), DELETE_NO_FLAG }; - else - args = new Object[] { userid, str.toLowerCase(), DELETE_NO_FLAG }; - - if (!findChildType.getCategory().toLowerCase().equals("@")) - { - queryMasterList = jdbcTemplate.query(sql, - args, queryMasterMapper); - } else { - queryMasterList.addAll(jdbcTemplate.query(sql, - args, queryMasterMapper)); - } - return queryMasterList; - } - /** - * Returns list of query master by user id - * - * @param userId - * @return List - */ - @Override - @SuppressWarnings("unchecked") - public List getQueryMasterByUserId(String userId, - int fetchSize, String masterTypeCd, boolean includeQueryInstance) { - - String sql = "select "; - - if (fetchSize > 0 - && dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER)) { - sql += " top " + fetchSize; - } - sql += " query_master_id,name,user_id,group_id,create_date,delete_date,null as request_xml,null as pm_xml,delete_flag,generated_sql, null as i2b2_request_xml, master_type_cd, null as plugin_id from " - + getDbSchemaName() - + "qt_query_master " - + " where user_id = ? and delete_flag = ? ";// and master_type_cd is NULL"; - - Object[] obj = new Object[] { userId, DELETE_NO_FLAG }; - if (masterTypeCd != null) { - sql += " and master_type_cd = ?"; - obj = new Object[] { userId, DELETE_NO_FLAG, masterTypeCd }; - } - - sql += " order by create_date desc "; - - if (fetchSize > 0) { - if ( dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE)) - sql = "select * from ( " + sql + " ) where " + " rownum <= " - + fetchSize; - else if ( dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) - sql += " limit " + fetchSize; - - } - - List queryMasterList = jdbcTemplate.query(sql, - obj, queryMasterMapper); - - if (includeQueryInstance) { - QueryInstanceSpringDao instanceDao = new QueryInstanceSpringDao(dataSource, dataSourceLookup); - - for (QtQueryMaster qtMaster: queryMasterList) { - // create an empty set - Set set = new HashSet<>(); - - // Add each element of list into the set - for (QtQueryInstance t : instanceDao.getQueryInstanceByMasterId(qtMaster.getQueryMasterId())) - { - QueryResultInstanceSpringDao resultInstanceDao = new QueryResultInstanceSpringDao(dataSource, dataSourceLookup); - Set setResult = new HashSet<>(); - for (QtQueryResultInstance r : resultInstanceDao.getResultInstanceList(t.getQueryInstanceId())) - { - - setResult.add(r); - } - t.setQtQueryResultInstances(setResult); - set.add(t); - - } - - qtMaster.setQtQueryInstances(set); - } - } - return queryMasterList; - } - - /** - * Returns list of query master by group id - * - * @param groupId - * @return List - */ - @Override - @SuppressWarnings("unchecked") - public List getQueryMasterByGroupId(String groupId, - int fetchSize, String masterTypeCd, boolean includeQueryInstance) { - - String sql = "select "; - if (fetchSize > 0 - && dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER)) { - sql += " top " + fetchSize; - } - sql += " query_master_id,name,user_id,group_id,create_date,delete_date,null as request_xml,null as pm_xml,delete_flag,generated_sql,null as i2b2_request_xml, master_type_cd, null as plugin_id from " - + getDbSchemaName() - + "qt_query_master " - + " where group_id = ? and delete_flag = ? "; //and master_type_cd is NULL"; - - Object[] obj = new Object[] { groupId, DELETE_NO_FLAG }; - if (masterTypeCd != null) { - sql += " and master_type_cd = ?"; - obj = new Object[] { groupId, DELETE_NO_FLAG, masterTypeCd }; - } - - sql += " order by create_date desc "; - - if (fetchSize > 0) { - if ( dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE)) - sql = " select * from ( " + sql + " ) where rownum <= " - + fetchSize; - else if ( dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) - sql += " limit " + fetchSize; - - } - List queryMasterList = jdbcTemplate.query(sql, - obj, queryMasterMapper); - - - if (includeQueryInstance) { - QueryInstanceSpringDao instanceDao = new QueryInstanceSpringDao(dataSource, dataSourceLookup); - - for (QtQueryMaster qtMaster: queryMasterList) { - // create an empty set - Set set = new HashSet<>(); - - // Add each element of list into the set - for (QtQueryInstance t : instanceDao.getQueryInstanceByMasterId(qtMaster.getQueryMasterId())) - { - QueryResultInstanceSpringDao resultInstanceDao = new QueryResultInstanceSpringDao(dataSource, dataSourceLookup); - Set setResult = new HashSet<>(); - for (QtQueryResultInstance r : resultInstanceDao.getResultInstanceList(t.getQueryInstanceId())) - { - setResult.add(r); - } - t.setQtQueryResultInstances(setResult); - set.add(t); - - } - - qtMaster.setQtQueryInstances(set); - } - } - return queryMasterList; - } - - /** - * Find Query master by id - * - * @param masterId - * @return QtQueryMaster - */ - @Override - public QtQueryMaster getQueryDefinition(String masterId) { - String sql = "select * from " + getDbSchemaName() + "qt_query_master " - + " where query_master_id = ? and delete_flag = ? "; - QtQueryMaster queryMaster = null; - try { - queryMaster = (QtQueryMaster) jdbcTemplate.queryForObject(sql, - new Object[] { Integer.parseInt(masterId), DELETE_NO_FLAG }, - queryMasterMapper); - } catch (IncorrectResultSizeDataAccessException inResultEx) { - log.error("Query doesn't exists for masterId :[" + masterId + "]"); - } catch (DataAccessException e) { - log.error("Could not execute query master for masterId :[" - + masterId + "]"); - } - return queryMaster; - } - - - @Override - public List getQueryByName(String queryName) { - String sql = "select * from " + getDbSchemaName() + "qt_query_master " - + " where name = ? and delete_flag = ? "; - List queryMasterList = jdbcTemplate.query(sql, - new Object[] { queryName, DELETE_NO_FLAG }, queryMasterMapper); - return queryMasterList; - } - /** - * Function to rename query master - * - * @param masterId - * @param queryNewName - * @throws I2B2DAOException - */ - @Override - public void renameQuery(String masterId, String queryNewName) - throws I2B2DAOException { - log.debug("Rename masterId=" + masterId + " new query name" - + queryNewName); - - String sql = "update " - + getDbSchemaName() - + "qt_query_master set name = ? where query_master_id = ? and delete_flag = ?"; - int updatedRow = jdbcTemplate.update(sql, new Object[] { queryNewName, - Integer.parseInt(masterId), DELETE_NO_FLAG }); - if (updatedRow < 1) { - throw new I2B2DAOException("Query with master id " + masterId - + " not found"); - } - - } - - /** - * Function to delete query using user and master id This function will not - * delete permanently, it will set delete flag field in query master, query - * instance and result instance to true - * - * @param masterId - * @throws I2B2DAOException - */ - @Override - @SuppressWarnings("unchecked") - public void deleteQuery(String masterId) throws I2B2DAOException { - if (masterId==null){ - log.info("Null master id sent to deleteQuery method"); - } - else{ - log.info("Delete query for master id=" + masterId); - String resultInstanceSql = "update " + getDbSchemaName() - + "qt_query_result_instance set " - + " delete_flag=? where query_instance_id in (select " - + "query_instance_id from " + getDbSchemaName() - + "qt_query_instance where query_master_id=?) "; - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER)) { - resultInstanceSql = " update " + getDbSchemaName() - + "qt_query_result_instance set delete_flag=? " + " from " - + getDbSchemaName() - + "qt_query_result_instance qri inner join " - + getDbSchemaName() + "qt_query_instance qi " - + " on qri.query_instance_id = qi.query_instance_id " - + " where qi.query_master_id = ?"; - } - String queryInstanceSql = "update " - + getDbSchemaName() - + "qt_query_instance set delete_flag = ? where query_master_id = ? and delete_flag = ?"; - String queryMasterSql = "update " - + getDbSchemaName() - + "qt_query_master set delete_flag =?,delete_date=? where query_master_id = ? and delete_flag = ?"; - Date deleteDate = new Date(System.currentTimeMillis()); - int queryMasterCount = jdbcTemplate.update(queryMasterSql, - new Object[] { DELETE_YES_FLAG, deleteDate, Integer.parseInt(masterId), - DELETE_NO_FLAG }); - if (queryMasterCount < 1 && !dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) { - throw new I2B2DAOException("Query not found with masterid =[" - + masterId + "]"); - } - - int queryInstanceCount = jdbcTemplate.update(queryInstanceSql, - new Object[] { DELETE_YES_FLAG, Integer.parseInt(masterId), DELETE_NO_FLAG }); - log.debug("Total no. of query instance deleted" + queryInstanceCount); - int queryResultInstanceCount = jdbcTemplate.update(resultInstanceSql, - new Object[] { DELETE_YES_FLAG, Integer.parseInt(masterId) }); - log.debug("Total no. of query result deleted " - + queryResultInstanceCount); - } - } - - private static class SaveQueryMaster extends SqlUpdate { - - private String INSERT_ORACLE = ""; - private String INSERT_SQLSERVER = ""; - private String SEQUENCE_ORACLE = ""; - private String SEQUENCE_POSTGRESQL = ""; - private String INSERT_POSTGRESQL = ""; - - private DataSourceLookup dataSourceLookup = null; - - public SaveQueryMaster(DataSource dataSource, String dbSchemaName, - DataSourceLookup dataSourceLookup) { - super(); - this.setDataSource(dataSource); - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE)) { - this.setReturnGeneratedKeys(true); - INSERT_ORACLE = "INSERT INTO " - + dbSchemaName - + "QT_QUERY_MASTER " - + "(QUERY_MASTER_ID, NAME, USER_ID, GROUP_ID,MASTER_TYPE_CD,PLUGIN_ID,CREATE_DATE,DELETE_DATE,REQUEST_XML,DELETE_FLAG,GENERATED_SQL,I2B2_REQUEST_XML, PM_XML) " - + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)"; - setSql(INSERT_ORACLE); - SEQUENCE_ORACLE = "select " + dbSchemaName - + "QT_SQ_QM_QMID.nextval from dual"; - declareParameter(new SqlParameter(Types.INTEGER)); - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER)) { - INSERT_SQLSERVER = "INSERT INTO " - + dbSchemaName - + "QT_QUERY_MASTER " - + "( NAME, USER_ID, GROUP_ID,MASTER_TYPE_CD,PLUGIN_ID,CREATE_DATE,DELETE_DATE,REQUEST_XML,DELETE_FLAG,GENERATED_SQL,I2B2_REQUEST_XML,PM_XML) " - + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?)"; - this.setSql(INSERT_SQLSERVER); - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) { - this.setReturnGeneratedKeys(true); - INSERT_POSTGRESQL = "INSERT INTO " - + dbSchemaName - + "QT_QUERY_MASTER " - + "(QUERY_MASTER_ID, NAME, USER_ID, GROUP_ID,MASTER_TYPE_CD,PLUGIN_ID,CREATE_DATE,DELETE_DATE,REQUEST_XML,DELETE_FLAG,GENERATED_SQL,I2B2_REQUEST_XML, PM_XML) " - + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)"; - setSql(INSERT_POSTGRESQL); - SEQUENCE_POSTGRESQL = "select " //+ dbSchemaName - + " nextval('qt_query_master_query_master_id_seq') "; - declareParameter(new SqlParameter(Types.INTEGER)); - } - this.dataSourceLookup = dataSourceLookup; - - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.INTEGER)); - declareParameter(new SqlParameter(Types.TIMESTAMP)); - declareParameter(new SqlParameter(Types.TIMESTAMP)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - compile(); - - } - - public void save(QtQueryMaster queryMaster, String i2b2RequestXml, String pmXml) { - JdbcTemplate jdbc = getJdbcTemplate(); - int masterQueryId = 0; - Object[] object = null; - int queryMasterIdentityId = 0; - - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER)) { - object = new Object[] { queryMaster.getName(), - queryMaster.getUserId(), queryMaster.getGroupId(), - queryMaster.getMasterTypeCd(), - queryMaster.getPluginId(), queryMaster.getCreateDate(), - queryMaster.getDeleteDate(), - queryMaster.getRequestXml(), - queryMaster.getDeleteFlag(), - queryMaster.getGeneratedSql(), i2b2RequestXml, pmXml }; - update(object); - queryMasterIdentityId = jdbc.queryForObject("SELECT @@IDENTITY", Integer.class); - - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE)) { - queryMasterIdentityId = jdbc.queryForObject(SEQUENCE_ORACLE, Integer.class); - object = new Object[] { queryMasterIdentityId, - queryMaster.getName(), queryMaster.getUserId(), - queryMaster.getGroupId(), - queryMaster.getMasterTypeCd(), - queryMaster.getPluginId(), queryMaster.getCreateDate(), - queryMaster.getDeleteDate(), - queryMaster.getRequestXml(), - queryMaster.getDeleteFlag(), - queryMaster.getGeneratedSql(), i2b2RequestXml, pmXml }; - update(object); - - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) { - queryMasterIdentityId = jdbc.queryForObject(SEQUENCE_POSTGRESQL, Integer.class); - object = new Object[] { queryMasterIdentityId, - queryMaster.getName(), queryMaster.getUserId(), - queryMaster.getGroupId(), - queryMaster.getMasterTypeCd(), - queryMaster.getPluginId(), queryMaster.getCreateDate(), - queryMaster.getDeleteDate(), - queryMaster.getRequestXml(), - queryMaster.getDeleteFlag(), - queryMaster.getGeneratedSql(), i2b2RequestXml, pmXml }; - update(object); - } - - queryMaster.setQueryMasterId(String.valueOf(queryMasterIdentityId)); - - } - } - - private static class QtQueryMasterRowMapper implements RowMapper { - @Override - public Object mapRow(ResultSet rs, int rowNum) throws SQLException { - QtQueryMaster queryMaster = new QtQueryMaster(); - queryMaster.setQueryMasterId(String.valueOf(rs.getInt("QUERY_MASTER_ID"))); - queryMaster.setName(rs.getString("NAME")); - queryMaster.setUserId(rs.getString("USER_ID")); - queryMaster.setGroupId(rs.getString("GROUP_ID")); - queryMaster.setMasterTypeCd(rs.getString("MASTER_TYPE_CD")); - queryMaster.setPluginId(rs.getString("PLUGIN_ID")); - queryMaster.setCreateDate(rs.getTimestamp("CREATE_DATE")); - queryMaster.setDeleteDate(rs.getTimestamp("DELETE_DATE")); - queryMaster.setRequestXml(rs.getString("REQUEST_XML")); - queryMaster.setDeleteFlag(rs.getString("DELETE_FLAG")); - queryMaster.setGeneratedSql(rs.getString("GENERATED_SQL")); - queryMaster.setPmXml(rs.getString("PM_XML")); - queryMaster.setI2b2RequestXml(rs.getString("I2B2_REQUEST_XML")); - return queryMaster; - } - } - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao.setfinder; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Types; +import java.util.Date; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import javax.sql.DataSource; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.dao.DataAccessException; +import org.springframework.dao.IncorrectResultSizeDataAccessException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.RowMapper; +import org.springframework.jdbc.core.SqlParameter; +import org.springframework.jdbc.object.SqlUpdate; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.DateConstrainHandler; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.db.QtQueryInstance; +import edu.harvard.i2b2.crc.datavo.db.QtQueryMaster; +import edu.harvard.i2b2.crc.datavo.db.QtQueryResultInstance; +import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.FindByChildType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.InclusiveType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.MatchStrType; +import edu.harvard.i2b2.crc.ejb.analysis.QueryMaster; +import edu.harvard.i2b2.crc.util.CacheUtil; + +/** + * Class to manager persistance operation of QtQueryMaster $Id: + * QueryMasterSpringDao.java,v 1.3 2008/04/08 19:36:52 rk903 Exp $ + * + * @author rkuttan + * @see QtQueryMaster + */ +public class QueryMasterSpringDao extends CRCDAO implements IQueryMasterDao { + + + protected static Log logesapi = LogFactory.getLog(QueryMasterSpringDao.class); + + JdbcTemplate jdbcTemplate = null; + SaveQueryMaster saveQueryMaster = null; + QtQueryMasterRowMapper queryMasterMapper = new QtQueryMasterRowMapper(); + + public final String DELETE_YES_FLAG = "Y"; + public final String DELETE_NO_FLAG = "N"; + + private DataSourceLookup dataSourceLookup = null; + + public QueryMasterSpringDao(DataSource dataSource, + DataSourceLookup dataSourceLookup) { + setDataSource(dataSource); + setDbSchemaName(dataSourceLookup.getFullSchema()); + jdbcTemplate = new JdbcTemplate(dataSource); + this.dataSourceLookup = dataSourceLookup; + + } + + /** + * Function to create query master By default sets delete flag to false + * + * @param queryMaster + * @return query master id + */ + @Override + public String createQueryMaster(QtQueryMaster queryMaster, + String i2b2RequestXml, String pmXml) { + queryMaster.setDeleteFlag(DELETE_NO_FLAG); + saveQueryMaster = new SaveQueryMaster(getDataSource(), + getDbSchemaName(), dataSourceLookup); + saveQueryMaster.save(queryMaster, i2b2RequestXml, pmXml); + return queryMaster.getQueryMasterId(); + } + + /** + * Write query sql for the master id + * + * @param masterId + * @param generatedSql + */ + @Override + public void updateQueryAfterRun(String masterId, String generatedSql, String masterType) { + String sql = "UPDATE " + + getDbSchemaName() + + "QT_QUERY_MASTER set GENERATED_SQL = ?, MASTER_TYPE_CD = ? where query_master_id = ?"; + jdbcTemplate.update(sql, new Object[] { generatedSql, masterType, Integer.parseInt(masterId) }); + // jdbcTemplate.update(sql); + } + + /** + * Write query sql for the master id + * + * @param masterId + * @param generatedSql + */ + @Override + public void updateMasterTypeAfterRun(String masterId, String masterType) { + String sql = "UPDATE " + + getDbSchemaName() + + "QT_QUERY_MASTER set MASTER_TYPE_CD = ? where query_master_id = ?"; + jdbcTemplate.update(sql, new Object[] { masterType, Integer.parseInt(masterId) }); + // jdbcTemplate.update(sql); + } + + + /** + * Returns list of query master by find search + * + * @param userId + * @return List + * @throws I2B2Exception + */ + @Override + @SuppressWarnings("unchecked") + public List getQueryMasterByNameInfo(SecurityType userRequestType, FindByChildType findChildType) throws I2B2DAOException { + + + + String rolePath = dataSourceLookup.getDomainId() + + dataSourceLookup.getProjectPath() + + userRequestType.getUsername(); + + //List roles = (List) cache.getRoot().get(rolePath); + logesapi.debug("Roles from get " + rolePath); + List roles = (List) CacheUtil.get(rolePath); + + String sql = "select "; + + int fetchSize = findChildType.getMax(); + List queryMasterList = null; + + String str = ""; + MatchStrType matchStr = findChildType.getMatchStr(); + if (matchStr.getStrategy().toLowerCase().equals("right") || matchStr.getStrategy().toLowerCase().equals("contains")) + str = "%"; + str += matchStr.getValue(); + if (matchStr.getStrategy().toLowerCase().equals("left") || matchStr.getStrategy().toLowerCase().equals("contains")) + str += "%"; + + + if (fetchSize > 0 + && dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER)) { + sql += " top " + fetchSize; + } + if ((findChildType.getCategory().toLowerCase().equals("top")) || + (findChildType.getCategory().toLowerCase().equals("@"))) { + sql += " query_master_id,name,user_id,group_id,create_date,delete_date,null as pm_xml,null as request_xml,delete_flag,generated_sql, null as i2b2_request_xml, master_type_cd, null as plugin_id from " + + getDbSchemaName() + + "qt_query_master where "; + if (roles != null && !roles.contains("MANAGER")) + sql += " user_id = ? and "; + sql += " LOWER(name) like ? and delete_flag = ? "; //and master_type_cd is NULL"; + if (findChildType.getCreateDate() != null) + { + InclusiveType inclusive = InclusiveType.NO; + + DateConstrainHandler dateConstrainHandler = new DateConstrainHandler( + dataSourceLookup); + + if (findChildType.isAscending()) + sql +=" and " + dateConstrainHandler + .constructDateConstrainClause("create_date", + "create_date", inclusive, + inclusive, findChildType.getCreateDate() , + null); + else + sql += " and " + dateConstrainHandler + .constructDateConstrainClause("create_date", + "create_date", inclusive, + inclusive,null , + findChildType.getCreateDate()); + sql += " order by create_date "; + + } else { + sql += " order by create_date "; + } + + if (findChildType.isAscending() && findChildType.getCreateDate() != null) + sql += "asc"; + else + sql += "desc"; + /* if (findChildType.isAscending()) + sql += "desc"; + else + sql += "asc"; + */ + } + if ((findChildType.getCategory().equals("@"))) + { + if (fetchSize > 0) { + if ( dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.ORACLE)) + sql = "select * from ( " + sql + " ) where " + " rownum <= " + + fetchSize; + else if ( dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) + sql += " limit " + fetchSize; + } + + if (roles != null && roles.contains("MANAGER")) + queryMasterList = jdbcTemplate.query(sql, + new Object[] { str.toLowerCase(), DELETE_NO_FLAG }, queryMasterMapper); + else + queryMasterList = jdbcTemplate.query(sql, + new Object[] { userRequestType.getUsername(), str.toLowerCase(), DELETE_NO_FLAG }, queryMasterMapper); + + + + + sql = "select "; + if (fetchSize > 0 + && dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER)) { + sql += " top " + fetchSize; + } + } + if ((findChildType.getCategory().toLowerCase().equals("results")) || + (findChildType.getCategory().equals("@"))) { + sql += " qm.query_master_id,qm.name,qm.user_id,qm.group_id,qm.create_date,qm.delete_date,null as pm_xml,null as request_xml,qm.delete_flag,qm.generated_sql, null as i2b2_request_xml, qm.master_type_cd, null as plugin_id from " + + getDbSchemaName() + + "qt_query_master qm, " + + getDbSchemaName() + + "qt_query_instance qi, " + + getDbSchemaName() + + "qt_query_result_instance qri where " + + "qm.QUERY_MASTER_ID = qi.QUERY_MASTER_ID and " + + "qi.QUERY_INSTANCE_ID = qri.QUERY_INSTANCE_ID and "; + if (roles != null && !roles.contains("MANAGER")) + sql += " qm.user_id = ? and"; + sql+= " LOWER(qri.DESCRIPTION) like ? and qm.delete_flag = ? "; //and qm.master_type_cd is NULL"; + if (findChildType.getCreateDate() != null) + { + DateConstrainHandler dateConstrainHandler = new DateConstrainHandler( + dataSourceLookup); + + if (!findChildType.isAscending()) + sql += " and " + dateConstrainHandler + .constructDateConstrainClause("create_date", + "create_date", null, + null, findChildType.getCreateDate() , + null); + else + sql += " and " + dateConstrainHandler + .constructDateConstrainClause("create_date", + "create_date", null, + null,null , + findChildType.getCreateDate()); + sql += " order by qm.create_date "; + + } + else { + sql += " order by qm.create_date "; + } + // if (findChildType.isAscending()) + sql += "desc"; + // else + // sql += "asc"; + } + if ((findChildType.getCategory().toLowerCase().equals("@"))) + { + + if (fetchSize > 0) { + if ( dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.ORACLE)) + sql = "select * from ( " + sql + " ) where " + " rownum <= " + + fetchSize; + else if ( dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) + sql += " limit " + fetchSize; + + } + + if (roles != null && roles.contains("MANAGER")) + queryMasterList.addAll(jdbcTemplate.query(sql, + new Object[] { str.toLowerCase(), DELETE_NO_FLAG }, queryMasterMapper)); + else + queryMasterList.addAll(jdbcTemplate.query(sql, + new Object[] { userRequestType.getUsername(), str.toLowerCase(), DELETE_NO_FLAG }, queryMasterMapper)); + + sql = " select "; + if (fetchSize > 0 + && dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER)) { + sql += " distinct top " + fetchSize; + } else + { + sql += " distinct "; + } + } + if ((findChildType.getCategory().toLowerCase().equals("pdo")) || + (findChildType.getCategory().toLowerCase().equals("@"))) { + sql += " qm.query_master_id,qm.name,qm.user_id,qm.group_id,qm.create_date,qm.delete_date,null as pm_xml,null as request_xml,qm.delete_flag,null as generated_sql, null as i2b2_request_xml, qm.master_type_cd, null as plugin_id from " + + getDbSchemaName() + + "qt_query_master qm, " + + getDbSchemaName() + + "qt_query_instance qi, " + + getDbSchemaName() + + "QT_PATIENT_SET_COLLECTION qp, " + + getDbSchemaName() + + "qt_query_result_instance qri where " + + "qm.QUERY_MASTER_ID = qi.QUERY_MASTER_ID and " + + "qi.QUERY_INSTANCE_ID = qri.QUERY_INSTANCE_ID and " + + "qri.RESULT_INSTANCE_ID = qp.RESULT_INSTANCE_ID and "; + if (roles != null && !roles.contains("MANAGER")) + sql += " qm.user_id = ? and "; + if ( dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) + sql += " CAST(qp.patient_num AS TEXT) like ? and qm.delete_flag = ? "; + else + sql += " qp.patient_num like ? and qm.delete_flag = ? "; + + if (findChildType.getCreateDate() != null) + { + DateConstrainHandler dateConstrainHandler = new DateConstrainHandler( + dataSourceLookup); + + if (!findChildType.isAscending()) + sql += " and " + dateConstrainHandler + .constructDateConstrainClause("create_date", + "create_date", null, + null, findChildType.getCreateDate() , + null); + else + sql += " and " + dateConstrainHandler + .constructDateConstrainClause("create_date", + "create_date", null, + null,null , + findChildType.getCreateDate()); + + sql += " order by qm.create_date "; + } + else { + sql += " order by qm.create_date "; + } + // if (findChildType.isAscending()) + sql += "desc"; + // else + // sql += "asc"; + } + + if (fetchSize > 0) { + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.ORACLE)) + sql = "select * from ( " + sql + " ) where " + " rownum <= " + + fetchSize; + else if ( dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) + sql += " limit " + fetchSize; + + } + + + + // if (findChildType.getCategory().toLowerCase().equals("@")) + // queryMasterList = jdbcTemplate.query(sql, + // new Object[] { userRequestType.getUsername(), str, DELETE_NO_FLAG, userRequestType.getUsername(), str, DELETE_NO_FLAG, userRequestType.getUsername(), str, DELETE_NO_FLAG }, queryMasterMapper); + // else + Object[] args = null; + String userid = userRequestType.getUsername(); + if (findChildType.getUserId() != null && roles != null && roles.contains("MANAGER")) + userid = findChildType.getUserId(); + // else if (findChildType.getUserId() != null) + // throw new I2B2DAOException ("Permisison denied"); + // if (findChildType.getCreateDate() != null) + // args = new Object[] { userid, str.toLowerCase(), DELETE_NO_FLAG,findChildType.getCreateDate() }; + // else + if (roles != null && roles.contains("MANAGER")) + args = new Object[] { str.toLowerCase(), DELETE_NO_FLAG }; + else + args = new Object[] { userid, str.toLowerCase(), DELETE_NO_FLAG }; + + if (!findChildType.getCategory().toLowerCase().equals("@")) + { + queryMasterList = jdbcTemplate.query(sql, + args, queryMasterMapper); + } else { + queryMasterList.addAll(jdbcTemplate.query(sql, + args, queryMasterMapper)); + } + return queryMasterList; + } + /** + * Returns list of query master by user id + * + * @param userId + * @return List + */ + @Override + @SuppressWarnings("unchecked") + public List getQueryMasterByUserId(String userId, + int fetchSize, String masterTypeCd, boolean includeQueryInstance) { + + String sql = "select "; + + if (fetchSize > 0 + && dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER)) { + sql += " top " + fetchSize; + } + sql += " query_master_id,name,user_id,group_id,create_date,delete_date,null as request_xml,null as pm_xml,delete_flag,generated_sql, null as i2b2_request_xml, master_type_cd, null as plugin_id from " + + getDbSchemaName() + + "qt_query_master " + + " where user_id = ? and delete_flag = ? ";// and master_type_cd is NULL"; + + Object[] obj = new Object[] { userId, DELETE_NO_FLAG }; + if (masterTypeCd != null) { + sql += " and master_type_cd = ?"; + obj = new Object[] { userId, DELETE_NO_FLAG, masterTypeCd }; + } + + sql += " order by create_date desc "; + + if (fetchSize > 0) { + if ( dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.ORACLE)) + sql = "select * from ( " + sql + " ) where " + " rownum <= " + + fetchSize; + else if ( dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) + sql += " limit " + fetchSize; + + } + + List queryMasterList = jdbcTemplate.query(sql, + obj, queryMasterMapper); + + if (includeQueryInstance) { + QueryInstanceSpringDao instanceDao = new QueryInstanceSpringDao(dataSource, dataSourceLookup); + + for (QtQueryMaster qtMaster: queryMasterList) { + // create an empty set + Set set = new HashSet<>(); + + // Add each element of list into the set + for (QtQueryInstance t : instanceDao.getQueryInstanceByMasterId(qtMaster.getQueryMasterId())) + { + QueryResultInstanceSpringDao resultInstanceDao = new QueryResultInstanceSpringDao(dataSource, dataSourceLookup); + Set setResult = new HashSet<>(); + for (QtQueryResultInstance r : resultInstanceDao.getResultInstanceList(t.getQueryInstanceId())) + { + + setResult.add(r); + } + t.setQtQueryResultInstances(setResult); + set.add(t); + + } + + qtMaster.setQtQueryInstances(set); + } + } + return queryMasterList; + } + + /** + * Returns list of query master by group id + * + * @param groupId + * @return List + */ + @Override + @SuppressWarnings("unchecked") + public List getQueryMasterByGroupId(String groupId, + int fetchSize, String masterTypeCd, boolean includeQueryInstance) { + + String sql = "select "; + if (fetchSize > 0 + && dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER)) { + sql += " top " + fetchSize; + } + sql += " query_master_id,name,user_id,group_id,create_date,delete_date,null as request_xml,null as pm_xml,delete_flag,generated_sql,null as i2b2_request_xml, master_type_cd, null as plugin_id from " + + getDbSchemaName() + + "qt_query_master " + + " where group_id = ? and delete_flag = ? "; //and master_type_cd is NULL"; + + Object[] obj = new Object[] { groupId, DELETE_NO_FLAG }; + if (masterTypeCd != null) { + sql += " and master_type_cd = ?"; + obj = new Object[] { groupId, DELETE_NO_FLAG, masterTypeCd }; + } + + sql += " order by create_date desc "; + + if (fetchSize > 0) { + if ( dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.ORACLE)) + sql = " select * from ( " + sql + " ) where rownum <= " + + fetchSize; + else if ( dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) + sql += " limit " + fetchSize; + + } + List queryMasterList = jdbcTemplate.query(sql, + obj, queryMasterMapper); + + + if (includeQueryInstance) { + QueryInstanceSpringDao instanceDao = new QueryInstanceSpringDao(dataSource, dataSourceLookup); + + for (QtQueryMaster qtMaster: queryMasterList) { + // create an empty set + Set set = new HashSet<>(); + + // Add each element of list into the set + for (QtQueryInstance t : instanceDao.getQueryInstanceByMasterId(qtMaster.getQueryMasterId())) + { + QueryResultInstanceSpringDao resultInstanceDao = new QueryResultInstanceSpringDao(dataSource, dataSourceLookup); + Set setResult = new HashSet<>(); + for (QtQueryResultInstance r : resultInstanceDao.getResultInstanceList(t.getQueryInstanceId())) + { + setResult.add(r); + } + t.setQtQueryResultInstances(setResult); + set.add(t); + + } + + qtMaster.setQtQueryInstances(set); + } + } + return queryMasterList; + } + + /** + * Find Query master by id + * + * @param masterId + * @return QtQueryMaster + */ + @Override + public QtQueryMaster getQueryDefinition(String masterId) { + String sql = "select * from " + getDbSchemaName() + "qt_query_master " + + " where query_master_id = ? and delete_flag = ? "; + QtQueryMaster queryMaster = null; + try { + queryMaster = (QtQueryMaster) jdbcTemplate.queryForObject(sql, + new Object[] { Integer.parseInt(masterId), DELETE_NO_FLAG }, + queryMasterMapper); + } catch (IncorrectResultSizeDataAccessException inResultEx) { + log.error("Query doesn't exists for masterId :[" + masterId + "]"); + } catch (DataAccessException e) { + log.error("Could not execute query master for masterId :[" + + masterId + "]"); + } + return queryMaster; + } + + + @Override + public List getQueryByName(String queryName) { + String sql = "select * from " + getDbSchemaName() + "qt_query_master " + + " where name = ? and delete_flag = ? "; + List queryMasterList = jdbcTemplate.query(sql, + new Object[] { queryName, DELETE_NO_FLAG }, queryMasterMapper); + return queryMasterList; + } + /** + * Function to rename query master + * + * @param masterId + * @param queryNewName + * @throws I2B2DAOException + */ + @Override + public void renameQuery(String masterId, String queryNewName) + throws I2B2DAOException { + log.debug("Rename masterId=" + masterId + " new query name" + + queryNewName); + + String sql = "update " + + getDbSchemaName() + + "qt_query_master set name = ? where query_master_id = ? and delete_flag = ?"; + int updatedRow = jdbcTemplate.update(sql, new Object[] { queryNewName, + Integer.parseInt(masterId), DELETE_NO_FLAG }); + if (updatedRow < 1) { + throw new I2B2DAOException("Query with master id " + masterId + + " not found"); + } + + } + + /** + * Function to delete query using user and master id This function will not + * delete permanently, it will set delete flag field in query master, query + * instance and result instance to true + * + * @param masterId + * @throws I2B2DAOException + */ + @Override + @SuppressWarnings("unchecked") + public void deleteQuery(String masterId) throws I2B2DAOException { + if (masterId==null){ + log.info("Null master id sent to deleteQuery method"); + } + else{ + log.info("Delete query for master id=" + masterId); + String resultInstanceSql = "update " + getDbSchemaName() + + "qt_query_result_instance set " + + " delete_flag=? where query_instance_id in (select " + + "query_instance_id from " + getDbSchemaName() + + "qt_query_instance where query_master_id=?) "; + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER)) { + resultInstanceSql = " update " + getDbSchemaName() + + "qt_query_result_instance set delete_flag=? " + " from " + + getDbSchemaName() + + "qt_query_result_instance qri inner join " + + getDbSchemaName() + "qt_query_instance qi " + + " on qri.query_instance_id = qi.query_instance_id " + + " where qi.query_master_id = ?"; + } + String queryInstanceSql = "update " + + getDbSchemaName() + + "qt_query_instance set delete_flag = ? where query_master_id = ? and delete_flag = ?"; + String queryMasterSql = "update " + + getDbSchemaName() + + "qt_query_master set delete_flag =?,delete_date=? where query_master_id = ? and delete_flag = ?"; + Date deleteDate = new Date(System.currentTimeMillis()); + int queryMasterCount = jdbcTemplate.update(queryMasterSql, + new Object[] { DELETE_YES_FLAG, deleteDate, Integer.parseInt(masterId), + DELETE_NO_FLAG }); + if (queryMasterCount < 1 && !dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) { + throw new I2B2DAOException("Query not found with masterid =[" + + masterId + "]"); + } + + int queryInstanceCount = jdbcTemplate.update(queryInstanceSql, + new Object[] { DELETE_YES_FLAG, Integer.parseInt(masterId), DELETE_NO_FLAG }); + log.debug("Total no. of query instance deleted" + queryInstanceCount); + int queryResultInstanceCount = jdbcTemplate.update(resultInstanceSql, + new Object[] { DELETE_YES_FLAG, Integer.parseInt(masterId) }); + log.debug("Total no. of query result deleted " + + queryResultInstanceCount); + } + } + + private static class SaveQueryMaster extends SqlUpdate { + + private String INSERT_ORACLE = ""; + private String INSERT_SQLSERVER = ""; + private String SEQUENCE_ORACLE = ""; + private String SEQUENCE_POSTGRESQL = ""; + private String INSERT_POSTGRESQL = ""; + + private DataSourceLookup dataSourceLookup = null; + + public SaveQueryMaster(DataSource dataSource, String dbSchemaName, + DataSourceLookup dataSourceLookup) { + super(); + this.setDataSource(dataSource); + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.ORACLE)) { + this.setReturnGeneratedKeys(true); + INSERT_ORACLE = "INSERT INTO " + + dbSchemaName + + "QT_QUERY_MASTER " + + "(QUERY_MASTER_ID, NAME, USER_ID, GROUP_ID,MASTER_TYPE_CD,PLUGIN_ID,CREATE_DATE,DELETE_DATE,REQUEST_XML,DELETE_FLAG,GENERATED_SQL,I2B2_REQUEST_XML, PM_XML) " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)"; + setSql(INSERT_ORACLE); + SEQUENCE_ORACLE = "select " + dbSchemaName + + "QT_SQ_QM_QMID.nextval from dual"; + declareParameter(new SqlParameter(Types.INTEGER)); + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER)) { + INSERT_SQLSERVER = "INSERT INTO " + + dbSchemaName + + "QT_QUERY_MASTER " + + "( NAME, USER_ID, GROUP_ID,MASTER_TYPE_CD,PLUGIN_ID,CREATE_DATE,DELETE_DATE,REQUEST_XML,DELETE_FLAG,GENERATED_SQL,I2B2_REQUEST_XML,PM_XML) " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?)"; + this.setSql(INSERT_SQLSERVER); + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) { + this.setReturnGeneratedKeys(true); + INSERT_POSTGRESQL = "INSERT INTO " + + dbSchemaName + + "QT_QUERY_MASTER " + + "(QUERY_MASTER_ID, NAME, USER_ID, GROUP_ID,MASTER_TYPE_CD,PLUGIN_ID,CREATE_DATE,DELETE_DATE,REQUEST_XML,DELETE_FLAG,GENERATED_SQL,I2B2_REQUEST_XML, PM_XML) " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)"; + setSql(INSERT_POSTGRESQL); + SEQUENCE_POSTGRESQL = "select " //+ dbSchemaName + + " nextval('qt_query_master_query_master_id_seq') "; + declareParameter(new SqlParameter(Types.INTEGER)); + } + this.dataSourceLookup = dataSourceLookup; + + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.INTEGER)); + declareParameter(new SqlParameter(Types.TIMESTAMP)); + declareParameter(new SqlParameter(Types.TIMESTAMP)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + compile(); + + } + + public void save(QtQueryMaster queryMaster, String i2b2RequestXml, String pmXml) { + JdbcTemplate jdbc = getJdbcTemplate(); + int masterQueryId = 0; + Object[] object = null; + int queryMasterIdentityId = 0; + + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER)) { + object = new Object[] { queryMaster.getName(), + queryMaster.getUserId(), queryMaster.getGroupId(), + queryMaster.getMasterTypeCd(), + queryMaster.getPluginId(), queryMaster.getCreateDate(), + queryMaster.getDeleteDate(), + queryMaster.getRequestXml(), + queryMaster.getDeleteFlag(), + queryMaster.getGeneratedSql(), i2b2RequestXml, pmXml }; + update(object); + queryMasterIdentityId = jdbc.queryForObject("SELECT @@IDENTITY", Integer.class); + + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.ORACLE)) { + queryMasterIdentityId = jdbc.queryForObject(SEQUENCE_ORACLE, Integer.class); + object = new Object[] { queryMasterIdentityId, + queryMaster.getName(), queryMaster.getUserId(), + queryMaster.getGroupId(), + queryMaster.getMasterTypeCd(), + queryMaster.getPluginId(), queryMaster.getCreateDate(), + queryMaster.getDeleteDate(), + queryMaster.getRequestXml(), + queryMaster.getDeleteFlag(), + queryMaster.getGeneratedSql(), i2b2RequestXml, pmXml }; + update(object); + + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) { + queryMasterIdentityId = jdbc.queryForObject(SEQUENCE_POSTGRESQL, Integer.class); + object = new Object[] { queryMasterIdentityId, + queryMaster.getName(), queryMaster.getUserId(), + queryMaster.getGroupId(), + queryMaster.getMasterTypeCd(), + queryMaster.getPluginId(), queryMaster.getCreateDate(), + queryMaster.getDeleteDate(), + queryMaster.getRequestXml(), + queryMaster.getDeleteFlag(), + queryMaster.getGeneratedSql(), i2b2RequestXml, pmXml }; + update(object); + } + + queryMaster.setQueryMasterId(String.valueOf(queryMasterIdentityId)); + + } + } + + private static class QtQueryMasterRowMapper implements RowMapper { + @Override + public Object mapRow(ResultSet rs, int rowNum) throws SQLException { + QtQueryMaster queryMaster = new QtQueryMaster(); + queryMaster.setQueryMasterId(String.valueOf(rs.getInt("QUERY_MASTER_ID"))); + queryMaster.setName(rs.getString("NAME")); + queryMaster.setUserId(rs.getString("USER_ID")); + queryMaster.setGroupId(rs.getString("GROUP_ID")); + queryMaster.setMasterTypeCd(rs.getString("MASTER_TYPE_CD")); + queryMaster.setPluginId(rs.getString("PLUGIN_ID")); + queryMaster.setCreateDate(rs.getTimestamp("CREATE_DATE")); + queryMaster.setDeleteDate(rs.getTimestamp("DELETE_DATE")); + queryMaster.setRequestXml(rs.getString("REQUEST_XML")); + queryMaster.setDeleteFlag(rs.getString("DELETE_FLAG")); + queryMaster.setGeneratedSql(rs.getString("GENERATED_SQL")); + queryMaster.setPmXml(rs.getString("PM_XML")); + queryMaster.setI2b2RequestXml(rs.getString("I2B2_REQUEST_XML")); + return queryMaster; + } + } + + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryPdoMasterSpringDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryPdoMasterSpringDao.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryPdoMasterSpringDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryPdoMasterSpringDao.java index 25c44d6a..5c2e3449 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryPdoMasterSpringDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryPdoMasterSpringDao.java @@ -1,173 +1,173 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao.setfinder; - -import java.sql.Types; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.sql.DataSource; - -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.SqlParameter; -import org.springframework.jdbc.object.SqlUpdate; - -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.db.QtQueryMaster; - -/** - * Class to manager persistance operation of QtQueryMaster $Id: - * QueryMasterSpringDao.java,v 1.3 2008/04/08 19:36:52 rk903 Exp $ - * - * @author rkuttan - * @see QtQueryMaster - */ -public class QueryPdoMasterSpringDao extends CRCDAO implements - IQueryPdoMasterDao { - - JdbcTemplate jdbcTemplate = null; - SaveQueryMaster saveQueryMaster = null; - - private DataSourceLookup dataSourceLookup = null; - - public QueryPdoMasterSpringDao(DataSource dataSource, - DataSourceLookup dataSourceLookup) { - setDataSource(dataSource); - setDbSchemaName(dataSourceLookup.getFullSchema()); - jdbcTemplate = new JdbcTemplate(dataSource); - this.dataSourceLookup = dataSourceLookup; - - } - - /** - * Function to create query master By default sets delete flag to false - * - * @param queryMaster - * @return query master id - */ - @Override - public String createPdoQueryMaster(QtQueryMaster queryMaster, - String i2b2RequestXml) { - - saveQueryMaster = new SaveQueryMaster(getDataSource(), - getDbSchemaName(), dataSourceLookup); - saveQueryMaster.save(queryMaster, i2b2RequestXml); - return queryMaster.getQueryMasterId(); - } - - private static class SaveQueryMaster extends SqlUpdate { - - private String INSERT_ORACLE = ""; - private String INSERT_SQLSERVER = ""; - private String SEQUENCE_ORACLE = ""; - private String SEQUENCE_POSTGRESQL = ""; - private String INSERT_POSTGRESQL = ""; - - private DataSourceLookup dataSourceLookup = null; - - public SaveQueryMaster(DataSource dataSource, String dbSchemaName, - DataSourceLookup dataSourceLookup) { - super(); - this.setDataSource(dataSource); - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE)) { - this.setReturnGeneratedKeys(true); - INSERT_ORACLE = "INSERT INTO " - + dbSchemaName - + "QT_PDO_QUERY_MASTER " - + "(QUERY_MASTER_ID, USER_ID, GROUP_ID,CREATE_DATE,REQUEST_XML,I2B2_REQUEST_XML) " - + "VALUES (?,?,?,?,?,?)"; - setSql(INSERT_ORACLE); - SEQUENCE_ORACLE = "select " + dbSchemaName - + "QT_SQ_PQM_QMID.nextval from dual"; - declareParameter(new SqlParameter(Types.INTEGER)); - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER) ) { - INSERT_SQLSERVER = "INSERT INTO " - + dbSchemaName - + "QT_PDO_QUERY_MASTER " - + "( USER_ID, GROUP_ID,CREATE_DATE,REQUEST_XML,I2B2_REQUEST_XML) " - + "VALUES (?,?,?,?,?)"; - this.setSql(INSERT_SQLSERVER); - } else if ( dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) { - this.setReturnGeneratedKeys(true); - INSERT_POSTGRESQL = "INSERT INTO " - + dbSchemaName - + "QT_PDO_QUERY_MASTER " - + "(QUERY_MASTER_ID, USER_ID, GROUP_ID,CREATE_DATE,REQUEST_XML,I2B2_REQUEST_XML) " - + "VALUES (?,?,?,?,?,?)"; - setSql(INSERT_POSTGRESQL); - SEQUENCE_POSTGRESQL = "select "// + dbSchemaName - + "nextval('qt_pdo_query_master_query_master_id_seq') "; - declareParameter(new SqlParameter(Types.INTEGER)); - } - this.dataSourceLookup = dataSourceLookup; - - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.TIMESTAMP)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - compile(); - - } - - public void save(QtQueryMaster queryMaster, String i2b2RequestXml) { - JdbcTemplate jdbc = getJdbcTemplate(); - int masterQueryId = 0; - Object[] object = null; - int queryMasterIdentityId = 0; - - Pattern p = Pattern.compile(""); - Matcher m = p.matcher(queryMaster.getRequestXml()); - String getRequestXmlNoPass = m.replaceAll("*********"); - - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER)) { - object = new Object[] { queryMaster.getUserId(), - queryMaster.getGroupId(), queryMaster.getCreateDate(), - getRequestXmlNoPass, i2b2RequestXml }; - update(object); - queryMasterIdentityId = jdbc.queryForObject("SELECT @@IDENTITY", Integer.class); - - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE)) { - queryMasterIdentityId = jdbc.queryForObject(SEQUENCE_ORACLE, Integer.class); - object = new Object[] { queryMasterIdentityId, - queryMaster.getUserId(), queryMaster.getGroupId(), - queryMaster.getCreateDate(), - getRequestXmlNoPass, i2b2RequestXml }; - update(object); - - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) { - queryMasterIdentityId = jdbc.queryForObject(SEQUENCE_POSTGRESQL, Integer.class); - object = new Object[] { queryMasterIdentityId, - queryMaster.getUserId(), queryMaster.getGroupId(), - queryMaster.getCreateDate(), - getRequestXmlNoPass, i2b2RequestXml }; - update(object); - - } - - queryMaster.setQueryMasterId(String.valueOf(queryMasterIdentityId)); - - } - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao.setfinder; + +import java.sql.Types; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.sql.DataSource; + +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.SqlParameter; +import org.springframework.jdbc.object.SqlUpdate; + +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.db.QtQueryMaster; + +/** + * Class to manager persistance operation of QtQueryMaster $Id: + * QueryMasterSpringDao.java,v 1.3 2008/04/08 19:36:52 rk903 Exp $ + * + * @author rkuttan + * @see QtQueryMaster + */ +public class QueryPdoMasterSpringDao extends CRCDAO implements + IQueryPdoMasterDao { + + JdbcTemplate jdbcTemplate = null; + SaveQueryMaster saveQueryMaster = null; + + private DataSourceLookup dataSourceLookup = null; + + public QueryPdoMasterSpringDao(DataSource dataSource, + DataSourceLookup dataSourceLookup) { + setDataSource(dataSource); + setDbSchemaName(dataSourceLookup.getFullSchema()); + jdbcTemplate = new JdbcTemplate(dataSource); + this.dataSourceLookup = dataSourceLookup; + + } + + /** + * Function to create query master By default sets delete flag to false + * + * @param queryMaster + * @return query master id + */ + @Override + public String createPdoQueryMaster(QtQueryMaster queryMaster, + String i2b2RequestXml) { + + saveQueryMaster = new SaveQueryMaster(getDataSource(), + getDbSchemaName(), dataSourceLookup); + saveQueryMaster.save(queryMaster, i2b2RequestXml); + return queryMaster.getQueryMasterId(); + } + + private static class SaveQueryMaster extends SqlUpdate { + + private String INSERT_ORACLE = ""; + private String INSERT_SQLSERVER = ""; + private String SEQUENCE_ORACLE = ""; + private String SEQUENCE_POSTGRESQL = ""; + private String INSERT_POSTGRESQL = ""; + + private DataSourceLookup dataSourceLookup = null; + + public SaveQueryMaster(DataSource dataSource, String dbSchemaName, + DataSourceLookup dataSourceLookup) { + super(); + this.setDataSource(dataSource); + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.ORACLE)) { + this.setReturnGeneratedKeys(true); + INSERT_ORACLE = "INSERT INTO " + + dbSchemaName + + "QT_PDO_QUERY_MASTER " + + "(QUERY_MASTER_ID, USER_ID, GROUP_ID,CREATE_DATE,REQUEST_XML,I2B2_REQUEST_XML) " + + "VALUES (?,?,?,?,?,?)"; + setSql(INSERT_ORACLE); + SEQUENCE_ORACLE = "select " + dbSchemaName + + "QT_SQ_PQM_QMID.nextval from dual"; + declareParameter(new SqlParameter(Types.INTEGER)); + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER) ) { + INSERT_SQLSERVER = "INSERT INTO " + + dbSchemaName + + "QT_PDO_QUERY_MASTER " + + "( USER_ID, GROUP_ID,CREATE_DATE,REQUEST_XML,I2B2_REQUEST_XML) " + + "VALUES (?,?,?,?,?)"; + this.setSql(INSERT_SQLSERVER); + } else if ( dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) { + this.setReturnGeneratedKeys(true); + INSERT_POSTGRESQL = "INSERT INTO " + + dbSchemaName + + "QT_PDO_QUERY_MASTER " + + "(QUERY_MASTER_ID, USER_ID, GROUP_ID,CREATE_DATE,REQUEST_XML,I2B2_REQUEST_XML) " + + "VALUES (?,?,?,?,?,?)"; + setSql(INSERT_POSTGRESQL); + SEQUENCE_POSTGRESQL = "select "// + dbSchemaName + + "nextval('qt_pdo_query_master_query_master_id_seq') "; + declareParameter(new SqlParameter(Types.INTEGER)); + } + this.dataSourceLookup = dataSourceLookup; + + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.TIMESTAMP)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + compile(); + + } + + public void save(QtQueryMaster queryMaster, String i2b2RequestXml) { + JdbcTemplate jdbc = getJdbcTemplate(); + int masterQueryId = 0; + Object[] object = null; + int queryMasterIdentityId = 0; + + Pattern p = Pattern.compile(""); + Matcher m = p.matcher(queryMaster.getRequestXml()); + String getRequestXmlNoPass = m.replaceAll("*********"); + + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER)) { + object = new Object[] { queryMaster.getUserId(), + queryMaster.getGroupId(), queryMaster.getCreateDate(), + getRequestXmlNoPass, i2b2RequestXml }; + update(object); + queryMasterIdentityId = jdbc.queryForObject("SELECT @@IDENTITY", Integer.class); + + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.ORACLE)) { + queryMasterIdentityId = jdbc.queryForObject(SEQUENCE_ORACLE, Integer.class); + object = new Object[] { queryMasterIdentityId, + queryMaster.getUserId(), queryMaster.getGroupId(), + queryMaster.getCreateDate(), + getRequestXmlNoPass, i2b2RequestXml }; + update(object); + + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) { + queryMasterIdentityId = jdbc.queryForObject(SEQUENCE_POSTGRESQL, Integer.class); + object = new Object[] { queryMasterIdentityId, + queryMaster.getUserId(), queryMaster.getGroupId(), + queryMaster.getCreateDate(), + getRequestXmlNoPass, i2b2RequestXml }; + update(object); + + } + + queryMaster.setQueryMasterId(String.valueOf(queryMasterIdentityId)); + + } + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryRequestSpringDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryRequestSpringDao.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryRequestSpringDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryRequestSpringDao.java index 032836f0..943549f9 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryRequestSpringDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryRequestSpringDao.java @@ -1,205 +1,205 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao.setfinder; - -import java.sql.Connection; -import java.sql.SQLException; -import java.util.List; -import java.util.Map; - -import javax.sql.DataSource; - -import org.springframework.jdbc.core.JdbcTemplate; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.db.JDBCUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.QueryToolUtil; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.RecursiveBuild; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal.TemporalQueryBuilder; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.util.ParamUtil; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - -/** - * Helper class for setfinder operation. Builds sql from query definition, - * executes the generated sql and create query results instance $Id: - * QueryRequestSpringDao.java,v 1.5 2008/07/10 20:11:21 rk903 Exp $ - * - * @author rkuttan - */ -public class QueryRequestSpringDao extends CRCDAO implements IQueryRequestDao { - /** Global temp table to store intermediate setfinder results **/ - private String TEMP_TABLE = "QUERY_GLOBAL_TEMP"; - - /** Global temp table to store intermediate patient list **/ - private String TEMP_DX_TABLE = "DX"; - - JdbcTemplate jdbcTemplate = null; - DataSourceLookup dataSourceLookup = null; - String processTimingFlag = "NONE"; - Map projectParamMap = null; - boolean allowLargeTextValueConstrainFlag = true; - boolean queryWithoutTempTableFlag = false; - //boolean allowProtectedQueryFlag = false; - List userRoles = null; - - public QueryRequestSpringDao(DataSource dataSource, - DataSourceLookup dataSourceLookup) { - setDataSource(dataSource); - jdbcTemplate = new JdbcTemplate(dataSource); - this.dataSourceLookup = dataSourceLookup; - - } - - - - - @Override - public void setProjectParam(Map projectParamMap) { - this.projectParamMap = projectParamMap; - if (projectParamMap != null && projectParamMap.get(ParamUtil.PM_ENABLE_PROCESS_TIMING) != null) { - this.processTimingFlag = (String)projectParamMap.get(ParamUtil.PM_ENABLE_PROCESS_TIMING); - } - - } - - @Override - public void setAllowLargeTextValueConstrainFlag(boolean allowLargeTextValueConstrainFlag) { - this.allowLargeTextValueConstrainFlag = allowLargeTextValueConstrainFlag; - } - - //@Override -// public void setAllowProtectedQueryFlag(boolean allowProtectedQueryFlag) { -// this.allowProtectedQueryFlag = allowProtectedQueryFlag; -// } - - /** - * Function to build sql from given query definition This function uses - * QueryToolUtil class to build sql - * - * @param queryRequestXml - * @return sql string - * @throws I2B2Exception - * @throws JAXBUtilException - */ - @Override - public String[] buildSql(String queryRequestXml, boolean encounterSetFlag) throws I2B2Exception, JAXBUtilException { - String sql = null, ignoredItemMessage = null, processTimingMessage = null; - Connection conn = null; - - String queryType = null; - try { - // conn = getConnection(); - conn = dataSource.getConnection(); - - // check to switch between the old and new setfinder query - // generator. - String queryGeneratorVersion = "1.7"; - try { - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - queryGeneratorVersion = qpUtil - .getCRCPropertyValue("edu.harvard.i2b2.crc.setfinder.querygenerator.version"); - } catch (I2B2Exception e) { - // ignore this default will be 1.6 - } - if (queryGeneratorVersion.equals("1.7")) { - TemporalQueryBuilder temporalBuild = new TemporalQueryBuilder(dataSourceLookup,queryRequestXml); - temporalBuild.setProjectParamMap(this.projectParamMap); - temporalBuild.setAllowLargeTextValueConstrainFlag(allowLargeTextValueConstrainFlag); - temporalBuild.setQueryWithoutTempTableFlag(queryWithoutTempTableFlag); - temporalBuild.setUserRoles(userRoles); - - temporalBuild.startSqlBuild(); - sql = temporalBuild.getSql(); - ignoredItemMessage = temporalBuild.getIgnoredItemMessage(); - processTimingMessage = temporalBuild.getProcessTimingMessage(); - - //if (temporalBuild.isProtectedQuery() && allowProtectedQueryFlag==false) - // throw new I2B2DAOException("This query contains protected."); - //if (temporalBuild.isProtectedQuery() && allowProtectedQueryFlag==false) - // throw new I2B2DAOException("This query contains protected."); - if (temporalBuild.isTemporalQuery()) - queryType = "TEMPORAL"; - if (temporalBuild.isProtectedQuery()) - queryType = "PROT"; - if (temporalBuild.isProtectedQuery()&&temporalBuild.isTemporalQuery()) - queryType = "PROT_TEMPORAL"; - } - else if (queryGeneratorVersion.equals("1.6")) { - RecursiveBuild recursiveBuild = new RecursiveBuild(dataSourceLookup,queryRequestXml,encounterSetFlag); - recursiveBuild.setProjectParamMap(this.projectParamMap); - recursiveBuild.setAllowLargeTextValueConstrainFlag(allowLargeTextValueConstrainFlag); - - recursiveBuild.startSqlBuild(); - sql = recursiveBuild.getSql(); - ignoredItemMessage = recursiveBuild.getIgnoredItemMessage(); - processTimingMessage = recursiveBuild.getProcessTimingMessage(); - //QueryToolUtilNew queryUtil = new QueryToolUtilNew( - // dataSourceLookup, queryRequestXml, encounterSetFlag); - //sql = queryUtil.getSetfinderSqlForQueryDefinition(); - //ignoredItemMessage = queryUtil.getIgnoredItemMessage(); - } - /*else { - log - .warn("*** USING THE OLD QUERY GENERATOR *** QueryToolUtil.java"); - QueryToolUtil queryUtil = new QueryToolUtil(dataSourceLookup); - sql = queryUtil.generateSQL(conn, queryRequestXml, - encounterSetFlag); - ignoredItemMessage = queryUtil.getIgnoredItemMessage(); - } */ - - } catch (SQLException ex) { - log.error("Error while building sql", ex); - //throw new Exception("Error while building sql ", ex); - } catch (I2B2Exception e) { - log.error("QuieryRequestSptingDAO: Error while building sql I2b2 Error ", e); - // TODO Auto-generated catch block - throw e; - // e.printStackTrace(); - } catch (JAXBUtilException e) { - throw e; - } finally { - try { - JDBCUtil.closeJdbcResource(null, null, conn); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - return new String[] { sql, ignoredItemMessage, processTimingMessage, queryType}; - } - - - - - @Override - public void setQueryWithoutTempTableFlag(boolean queryWithoutTempTableFlag) { - this.queryWithoutTempTableFlag = queryWithoutTempTableFlag; - } - - - - - @Override - public void setUserRoles(List userRoles) { - this.userRoles = userRoles; - - } - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao.setfinder; + +import java.sql.Connection; +import java.sql.SQLException; +import java.util.List; +import java.util.Map; + +import javax.sql.DataSource; + +import org.springframework.jdbc.core.JdbcTemplate; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.db.JDBCUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.QueryToolUtil; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.RecursiveBuild; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal.TemporalQueryBuilder; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.util.ParamUtil; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + +/** + * Helper class for setfinder operation. Builds sql from query definition, + * executes the generated sql and create query results instance $Id: + * QueryRequestSpringDao.java,v 1.5 2008/07/10 20:11:21 rk903 Exp $ + * + * @author rkuttan + */ +public class QueryRequestSpringDao extends CRCDAO implements IQueryRequestDao { + /** Global temp table to store intermediate setfinder results **/ + private String TEMP_TABLE = "QUERY_GLOBAL_TEMP"; + + /** Global temp table to store intermediate patient list **/ + private String TEMP_DX_TABLE = "DX"; + + JdbcTemplate jdbcTemplate = null; + DataSourceLookup dataSourceLookup = null; + String processTimingFlag = "NONE"; + Map projectParamMap = null; + boolean allowLargeTextValueConstrainFlag = true; + boolean queryWithoutTempTableFlag = false; + //boolean allowProtectedQueryFlag = false; + List userRoles = null; + + public QueryRequestSpringDao(DataSource dataSource, + DataSourceLookup dataSourceLookup) { + setDataSource(dataSource); + jdbcTemplate = new JdbcTemplate(dataSource); + this.dataSourceLookup = dataSourceLookup; + + } + + + + + @Override + public void setProjectParam(Map projectParamMap) { + this.projectParamMap = projectParamMap; + if (projectParamMap != null && projectParamMap.get(ParamUtil.PM_ENABLE_PROCESS_TIMING) != null) { + this.processTimingFlag = (String)projectParamMap.get(ParamUtil.PM_ENABLE_PROCESS_TIMING); + } + + } + + @Override + public void setAllowLargeTextValueConstrainFlag(boolean allowLargeTextValueConstrainFlag) { + this.allowLargeTextValueConstrainFlag = allowLargeTextValueConstrainFlag; + } + + //@Override +// public void setAllowProtectedQueryFlag(boolean allowProtectedQueryFlag) { +// this.allowProtectedQueryFlag = allowProtectedQueryFlag; +// } + + /** + * Function to build sql from given query definition This function uses + * QueryToolUtil class to build sql + * + * @param queryRequestXml + * @return sql string + * @throws I2B2Exception + * @throws JAXBUtilException + */ + @Override + public String[] buildSql(String queryRequestXml, boolean encounterSetFlag) throws I2B2Exception, JAXBUtilException { + String sql = null, ignoredItemMessage = null, processTimingMessage = null; + Connection conn = null; + + String queryType = null; + try { + // conn = getConnection(); + conn = dataSource.getConnection(); + + // check to switch between the old and new setfinder query + // generator. + String queryGeneratorVersion = "1.7"; + try { + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + queryGeneratorVersion = qpUtil + .getCRCPropertyValue("edu.harvard.i2b2.crc.setfinder.querygenerator.version"); + } catch (I2B2Exception e) { + // ignore this default will be 1.6 + } + if (queryGeneratorVersion.equals("1.7")) { + TemporalQueryBuilder temporalBuild = new TemporalQueryBuilder(dataSourceLookup,queryRequestXml); + temporalBuild.setProjectParamMap(this.projectParamMap); + temporalBuild.setAllowLargeTextValueConstrainFlag(allowLargeTextValueConstrainFlag); + temporalBuild.setQueryWithoutTempTableFlag(queryWithoutTempTableFlag); + temporalBuild.setUserRoles(userRoles); + + temporalBuild.startSqlBuild(); + sql = temporalBuild.getSql(); + ignoredItemMessage = temporalBuild.getIgnoredItemMessage(); + processTimingMessage = temporalBuild.getProcessTimingMessage(); + + //if (temporalBuild.isProtectedQuery() && allowProtectedQueryFlag==false) + // throw new I2B2DAOException("This query contains protected."); + //if (temporalBuild.isProtectedQuery() && allowProtectedQueryFlag==false) + // throw new I2B2DAOException("This query contains protected."); + if (temporalBuild.isTemporalQuery()) + queryType = "TEMPORAL"; + if (temporalBuild.isProtectedQuery()) + queryType = "PROT"; + if (temporalBuild.isProtectedQuery()&&temporalBuild.isTemporalQuery()) + queryType = "PROT_TEMPORAL"; + } + else if (queryGeneratorVersion.equals("1.6")) { + RecursiveBuild recursiveBuild = new RecursiveBuild(dataSourceLookup,queryRequestXml,encounterSetFlag); + recursiveBuild.setProjectParamMap(this.projectParamMap); + recursiveBuild.setAllowLargeTextValueConstrainFlag(allowLargeTextValueConstrainFlag); + + recursiveBuild.startSqlBuild(); + sql = recursiveBuild.getSql(); + ignoredItemMessage = recursiveBuild.getIgnoredItemMessage(); + processTimingMessage = recursiveBuild.getProcessTimingMessage(); + //QueryToolUtilNew queryUtil = new QueryToolUtilNew( + // dataSourceLookup, queryRequestXml, encounterSetFlag); + //sql = queryUtil.getSetfinderSqlForQueryDefinition(); + //ignoredItemMessage = queryUtil.getIgnoredItemMessage(); + } + /*else { + log + .warn("*** USING THE OLD QUERY GENERATOR *** QueryToolUtil.java"); + QueryToolUtil queryUtil = new QueryToolUtil(dataSourceLookup); + sql = queryUtil.generateSQL(conn, queryRequestXml, + encounterSetFlag); + ignoredItemMessage = queryUtil.getIgnoredItemMessage(); + } */ + + } catch (SQLException ex) { + log.error("Error while building sql", ex); + //throw new Exception("Error while building sql ", ex); + } catch (I2B2Exception e) { + log.error("QuieryRequestSptingDAO: Error while building sql I2b2 Error ", e); + // TODO Auto-generated catch block + throw e; + // e.printStackTrace(); + } catch (JAXBUtilException e) { + throw e; + } finally { + try { + JDBCUtil.closeJdbcResource(null, null, conn); + } catch (SQLException e) { + e.printStackTrace(); + } + } + + return new String[] { sql, ignoredItemMessage, processTimingMessage, queryType}; + } + + + + + @Override + public void setQueryWithoutTempTableFlag(boolean queryWithoutTempTableFlag) { + this.queryWithoutTempTableFlag = queryWithoutTempTableFlag; + } + + + + + @Override + public void setUserRoles(List userRoles) { + this.userRoles = userRoles; + + } + + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryResultEncounterSetGenerator.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryResultEncounterSetGenerator.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryResultEncounterSetGenerator.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryResultEncounterSetGenerator.java index 452e39e3..5f5ad2a0 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryResultEncounterSetGenerator.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryResultEncounterSetGenerator.java @@ -1,216 +1,216 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder; - -import java.sql.PreparedStatement; -import java.sql.SQLException; -import java.util.List; -import java.util.Map; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.db.JDBCUtil; -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.ProcessTimingReportUtil; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.QueryDefinitionUnWrapUtil; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.QueryTimingHandler; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.db.QtQueryInstance; -import edu.harvard.i2b2.crc.datavo.db.QtQueryMaster; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionType; -import edu.harvard.i2b2.crc.util.LogTimingUtil; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - -public class QueryResultEncounterSetGenerator extends CRCDAO implements - IResultGenerator { - - protected final Log logesapi = LogFactory.getLog(getClass()); - - @Override - public String getResults() { - return xmlResult; - } - - private String xmlResult = null; - - @Override - public void generateResult(Map param) throws I2B2DAOException { - - SetFinderConnection sfConn = (SetFinderConnection) param - .get("SetFinderConnection"); - SetFinderDAOFactory sfDAOFactory = (SetFinderDAOFactory) param - .get("SetFinderDAOFactory"); - // String patientSetId = (String)param.get("PatientSetId"); - String queryInstanceId = (String) param.get("QueryInstanceId"); - String TEMP_DX_TABLE = (String) param.get("TEMP_DX_TABLE"); - String resultInstanceId = (String) param.get("ResultInstanceId"); - String resultTypeName = (String) param.get("ResultOptionName"); - DataSourceLookup originalDataSource = (DataSourceLookup) param - .get("OriginalDataSourceLookup"); - List roles = (List) param.get("Roles"); - String processTimingFlag = (String)param.get("ProcessTimingReportFlag"); - int obfucatedRecordCount = (Integer) param.get("ObfuscatedRecordCount"); - int recordCount = (Integer) param.get("RecordCount"); - boolean obfuscatedRoleFlag = (Boolean)param.get("ObfuscatedRoleFlag"); - this.setDbSchemaName(sfDAOFactory.getDataSourceLookup().getFullSchema()); - - - String queryGeneratorVersion = "1.6"; - try { - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - queryGeneratorVersion = qpUtil - .getCRCPropertyValue("edu.harvard.i2b2.crc.setfinder.querygenerator.version"); - } catch (I2B2Exception e) { - // ignore this default will be 1.6 - } - - boolean errorFlag = false; - Exception exception = null; - int loadCount = 0; - String obfuscationDescription = "", obfusMethod = ""; - - try { - - int i = 0; - IEncounterSetCollectionDao encounterSetCollectionDao = sfDAOFactory - .getEncounterSetCollectionDAO(); - encounterSetCollectionDao - .createPatientEncCollection(resultInstanceId); - - // build the encounter set sql using dx table - // if the querytiming is not SAMEVISIT, then join the - // visit_dimension table to get encountner num for the patients. - String encounterSql = buildEncounterSetSql(sfDAOFactory, - queryInstanceId, TEMP_DX_TABLE, queryGeneratorVersion); - logesapi.debug("Executing setfinder query result type encounter set sql [" + encounterSql + "]"); - ///////// - //JNix: refactored to no longer pull down records just to insert back. - String sql = null; - String dbSchemaName = this.getDbSchemaName(); - if (sfDAOFactory.getDataSourceLookup().getServerType().equals(DAOFactoryHelper.ORACLE)) { - sql = "INSERT INTO qt_patient_enc_collection" - + " (patient_enc_coll_id, result_instance_id, set_index, patient_num, encounter_num) " - + "SELECT QT_SQ_QPER_PECID.nextval AS patient_set_coll_id, ? AS result_instance_id, rownum AS set_index, t.patient_num, t.encounter_num " - + "FROM () t"; - } else if (sfDAOFactory.getDataSourceLookup().getServerType().equalsIgnoreCase(DAOFactoryHelper.SQLSERVER) || - sfDAOFactory.getDataSourceLookup().getServerType().equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { - sql = "INSERT INTO qt_patient_enc_collection" - + " (result_instance_id, set_index, patient_num, encounter_num) " - + "SELECT ? AS result_instance_id, ROW_NUMBER() OVER(ORDER BY patient_num) AS set_index, t.patient_num, t.encounter_num " - + "FROM () t order by t.patient_num,t.encounter_num"; - } - log.debug("Executing sql:\n" + sql); - LogTimingUtil logTimingUtil = new LogTimingUtil(); - logTimingUtil.setStartTime(); - - String sqlFinal = sql.replace("", dbSchemaName); - sqlFinal = sqlFinal.replace("", encounterSql); - - PreparedStatement ps = sfConn.prepareStatement(sqlFinal); - ps.setInt(1, Integer.parseInt(resultInstanceId)); - loadCount = ps.executeUpdate(); - ps.close(); - logTimingUtil.setEndTime(); - logesapi.debug("Total patients loaded for query instance =" - + queryInstanceId + " is [" + loadCount + "]"); - ///////// - if (processTimingFlag != null) { - ProcessTimingReportUtil ptrUtil = new ProcessTimingReportUtil(sfDAOFactory.getDataSourceLookup()); - ptrUtil.logProcessTimingMessage(queryInstanceId, ptrUtil.buildProcessTiming(logTimingUtil, "BUILD - ENCOUNTERSET", "")); - } - } catch (SQLException sqlEx) { - exception = sqlEx; - log.error("QueryResultEncounterSetGenerator.generateResult:" - + sqlEx.getMessage(), sqlEx); - throw new I2B2DAOException( - "QueryResultEncounterSetGenerator.generateResult:" - + sqlEx.getMessage(), sqlEx); - - } catch (Throwable throwable) { - throwable.printStackTrace(); - } finally { - IQueryResultInstanceDao resultInstanceDao = sfDAOFactory - .getPatientSetResultDAO(); - - if (errorFlag) { - resultInstanceDao.updatePatientSet(resultInstanceId, - QueryStatusTypeId.STATUSTYPE_ID_ERROR, 0); - } else { - - //set size for the encounter set = 0 - if (obfuscatedRoleFlag) { - loadCount = obfucatedRecordCount; - } else { - loadCount = recordCount; - } - - resultInstanceDao.updatePatientSet(resultInstanceId, - QueryStatusTypeId.STATUSTYPE_ID_FINISHED, "", - loadCount, recordCount, obfusMethod); - //String description = "Encounter Set - " - // + obfuscationDescription + loadCount + " encounters"; - String queryName = sfDAOFactory.getQueryMasterDAO().getQueryDefinition( - sfDAOFactory.getQueryInstanceDAO().getQueryInstanceByInstanceId(queryInstanceId).getQtQueryMaster().getQueryMasterId()).getName(); - String description = "Encounter Set for \"" + queryName +"\""; - resultInstanceDao.updateResultInstanceDescription( - resultInstanceId, description); - - } - } - } - - private String buildEncounterSetSql(SetFinderDAOFactory sfDAOFactory, - String queryInstanceId, String TEMP_DX_TABLE, - String queryGeneratorVersion) throws I2B2DAOException { - // get request xml from query instance id - // call timing helper to find if timing is samevisit - - String encounterSetSql = " select encounter_num,patient_num from " - + TEMP_DX_TABLE; - if (queryGeneratorVersion.equals("1.6")|| - queryGeneratorVersion.equals("1.7")) { - IQueryInstanceDao queryInstanceDao = sfDAOFactory - .getQueryInstanceDAO(); - QtQueryInstance queryInstance = queryInstanceDao - .getQueryInstanceByInstanceId(queryInstanceId); - String queryMasterId = queryInstance.getQtQueryMaster() - .getQueryMasterId(); - IQueryMasterDao queryMasterDao = sfDAOFactory.getQueryMasterDAO(); - QtQueryMaster queryMasterType = queryMasterDao - .getQueryDefinition(queryMasterId); - QueryDefinitionUnWrapUtil qpUnwrapUtil = new QueryDefinitionUnWrapUtil(); - QueryDefinitionType queryDefType = null; - try { - queryDefType = qpUnwrapUtil - .getQueryDefinitionType(queryMasterType - .getI2b2RequestXml()); - } catch (I2B2DAOException e) { - throw e; - } - QueryTimingHandler queryTimingHandler = new QueryTimingHandler(); - boolean sameVisitFlag = queryTimingHandler - .isSameVisit(queryDefType); - - if (sameVisitFlag == false) { - encounterSetSql = " select encounter_num, patient_num from " - + sfDAOFactory.getDataSourceLookup().getFullSchema() - + ".visit_dimension " - + " where patient_num in (select distinct patient_num from " - + TEMP_DX_TABLE - + ") "; - } - } - return encounterSetSql; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder; + +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.List; +import java.util.Map; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.db.JDBCUtil; +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.ProcessTimingReportUtil; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.QueryDefinitionUnWrapUtil; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.QueryTimingHandler; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.db.QtQueryInstance; +import edu.harvard.i2b2.crc.datavo.db.QtQueryMaster; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionType; +import edu.harvard.i2b2.crc.util.LogTimingUtil; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + +public class QueryResultEncounterSetGenerator extends CRCDAO implements + IResultGenerator { + + protected final Log logesapi = LogFactory.getLog(getClass()); + + @Override + public String getResults() { + return xmlResult; + } + + private String xmlResult = null; + + @Override + public void generateResult(Map param) throws I2B2DAOException { + + SetFinderConnection sfConn = (SetFinderConnection) param + .get("SetFinderConnection"); + SetFinderDAOFactory sfDAOFactory = (SetFinderDAOFactory) param + .get("SetFinderDAOFactory"); + // String patientSetId = (String)param.get("PatientSetId"); + String queryInstanceId = (String) param.get("QueryInstanceId"); + String TEMP_DX_TABLE = (String) param.get("TEMP_DX_TABLE"); + String resultInstanceId = (String) param.get("ResultInstanceId"); + String resultTypeName = (String) param.get("ResultOptionName"); + DataSourceLookup originalDataSource = (DataSourceLookup) param + .get("OriginalDataSourceLookup"); + List roles = (List) param.get("Roles"); + String processTimingFlag = (String)param.get("ProcessTimingReportFlag"); + int obfucatedRecordCount = (Integer) param.get("ObfuscatedRecordCount"); + int recordCount = (Integer) param.get("RecordCount"); + boolean obfuscatedRoleFlag = (Boolean)param.get("ObfuscatedRoleFlag"); + this.setDbSchemaName(sfDAOFactory.getDataSourceLookup().getFullSchema()); + + + String queryGeneratorVersion = "1.6"; + try { + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + queryGeneratorVersion = qpUtil + .getCRCPropertyValue("edu.harvard.i2b2.crc.setfinder.querygenerator.version"); + } catch (I2B2Exception e) { + // ignore this default will be 1.6 + } + + boolean errorFlag = false; + Exception exception = null; + int loadCount = 0; + String obfuscationDescription = "", obfusMethod = ""; + + try { + + int i = 0; + IEncounterSetCollectionDao encounterSetCollectionDao = sfDAOFactory + .getEncounterSetCollectionDAO(); + encounterSetCollectionDao + .createPatientEncCollection(resultInstanceId); + + // build the encounter set sql using dx table + // if the querytiming is not SAMEVISIT, then join the + // visit_dimension table to get encountner num for the patients. + String encounterSql = buildEncounterSetSql(sfDAOFactory, + queryInstanceId, TEMP_DX_TABLE, queryGeneratorVersion); + logesapi.debug("Executing setfinder query result type encounter set sql [" + encounterSql + "]"); + ///////// + //JNix: refactored to no longer pull down records just to insert back. + String sql = null; + String dbSchemaName = this.getDbSchemaName(); + if (sfDAOFactory.getDataSourceLookup().getServerType().equals(DAOFactoryHelper.ORACLE)) { + sql = "INSERT INTO qt_patient_enc_collection" + + " (patient_enc_coll_id, result_instance_id, set_index, patient_num, encounter_num) " + + "SELECT QT_SQ_QPER_PECID.nextval AS patient_set_coll_id, ? AS result_instance_id, rownum AS set_index, t.patient_num, t.encounter_num " + + "FROM () t"; + } else if (sfDAOFactory.getDataSourceLookup().getServerType().equalsIgnoreCase(DAOFactoryHelper.SQLSERVER) || + sfDAOFactory.getDataSourceLookup().getServerType().equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { + sql = "INSERT INTO qt_patient_enc_collection" + + " (result_instance_id, set_index, patient_num, encounter_num) " + + "SELECT ? AS result_instance_id, ROW_NUMBER() OVER(ORDER BY patient_num) AS set_index, t.patient_num, t.encounter_num " + + "FROM () t order by t.patient_num,t.encounter_num"; + } + log.debug("Executing sql:\n" + sql); + LogTimingUtil logTimingUtil = new LogTimingUtil(); + logTimingUtil.setStartTime(); + + String sqlFinal = sql.replace("", dbSchemaName); + sqlFinal = sqlFinal.replace("", encounterSql); + + PreparedStatement ps = sfConn.prepareStatement(sqlFinal); + ps.setInt(1, Integer.parseInt(resultInstanceId)); + loadCount = ps.executeUpdate(); + ps.close(); + logTimingUtil.setEndTime(); + logesapi.debug("Total patients loaded for query instance =" + + queryInstanceId + " is [" + loadCount + "]"); + ///////// + if (processTimingFlag != null) { + ProcessTimingReportUtil ptrUtil = new ProcessTimingReportUtil(sfDAOFactory.getDataSourceLookup()); + ptrUtil.logProcessTimingMessage(queryInstanceId, ptrUtil.buildProcessTiming(logTimingUtil, "BUILD - ENCOUNTERSET", "")); + } + } catch (SQLException sqlEx) { + exception = sqlEx; + log.error("QueryResultEncounterSetGenerator.generateResult:" + + sqlEx.getMessage(), sqlEx); + throw new I2B2DAOException( + "QueryResultEncounterSetGenerator.generateResult:" + + sqlEx.getMessage(), sqlEx); + + } catch (Throwable throwable) { + throwable.printStackTrace(); + } finally { + IQueryResultInstanceDao resultInstanceDao = sfDAOFactory + .getPatientSetResultDAO(); + + if (errorFlag) { + resultInstanceDao.updatePatientSet(resultInstanceId, + QueryStatusTypeId.STATUSTYPE_ID_ERROR, 0); + } else { + + //set size for the encounter set = 0 + if (obfuscatedRoleFlag) { + loadCount = obfucatedRecordCount; + } else { + loadCount = recordCount; + } + + resultInstanceDao.updatePatientSet(resultInstanceId, + QueryStatusTypeId.STATUSTYPE_ID_FINISHED, "", + loadCount, recordCount, obfusMethod); + //String description = "Encounter Set - " + // + obfuscationDescription + loadCount + " encounters"; + String queryName = sfDAOFactory.getQueryMasterDAO().getQueryDefinition( + sfDAOFactory.getQueryInstanceDAO().getQueryInstanceByInstanceId(queryInstanceId).getQtQueryMaster().getQueryMasterId()).getName(); + String description = "Encounter Set for \"" + queryName +"\""; + resultInstanceDao.updateResultInstanceDescription( + resultInstanceId, description); + + } + } + } + + private String buildEncounterSetSql(SetFinderDAOFactory sfDAOFactory, + String queryInstanceId, String TEMP_DX_TABLE, + String queryGeneratorVersion) throws I2B2DAOException { + // get request xml from query instance id + // call timing helper to find if timing is samevisit + + String encounterSetSql = " select encounter_num,patient_num from " + + TEMP_DX_TABLE; + if (queryGeneratorVersion.equals("1.6")|| + queryGeneratorVersion.equals("1.7")) { + IQueryInstanceDao queryInstanceDao = sfDAOFactory + .getQueryInstanceDAO(); + QtQueryInstance queryInstance = queryInstanceDao + .getQueryInstanceByInstanceId(queryInstanceId); + String queryMasterId = queryInstance.getQtQueryMaster() + .getQueryMasterId(); + IQueryMasterDao queryMasterDao = sfDAOFactory.getQueryMasterDAO(); + QtQueryMaster queryMasterType = queryMasterDao + .getQueryDefinition(queryMasterId); + QueryDefinitionUnWrapUtil qpUnwrapUtil = new QueryDefinitionUnWrapUtil(); + QueryDefinitionType queryDefType = null; + try { + queryDefType = qpUnwrapUtil + .getQueryDefinitionType(queryMasterType + .getI2b2RequestXml()); + } catch (I2B2DAOException e) { + throw e; + } + QueryTimingHandler queryTimingHandler = new QueryTimingHandler(); + boolean sameVisitFlag = queryTimingHandler + .isSameVisit(queryDefType); + + if (sameVisitFlag == false) { + encounterSetSql = " select encounter_num, patient_num from " + + sfDAOFactory.getDataSourceLookup().getFullSchema() + + ".visit_dimension " + + " where patient_num in (select distinct patient_num from " + + TEMP_DX_TABLE + + ") "; + } + } + return encounterSetSql; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryResultGenerator.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryResultGenerator.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryResultGenerator.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryResultGenerator.java index f96169d6..58cc5f67 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryResultGenerator.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryResultGenerator.java @@ -1,497 +1,497 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder; - -import java.io.StringWriter; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.List; -import java.util.Map; - -import javax.xml.stream.XMLStreamException; - -import org.apache.axis2.AxisFault; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.exception.StackTraceUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.ConceptNotFoundException; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.OntologyException; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.ProcessTimingReportUtil; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal.TemporalPanelCellQueryItem; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal.TemporalPanelConceptItem; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal.TemporalPanelItem; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.db.QtQueryBreakdownType; -import edu.harvard.i2b2.crc.datavo.db.QtQueryResultType; -import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; -import edu.harvard.i2b2.crc.datavo.i2b2result.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2result.DataType; -import edu.harvard.i2b2.crc.datavo.i2b2result.ResultEnvelopeType; -import edu.harvard.i2b2.crc.datavo.i2b2result.ResultType; -import edu.harvard.i2b2.crc.datavo.ontology.ConceptType; -import edu.harvard.i2b2.crc.datavo.ontology.ConceptsType; -import edu.harvard.i2b2.crc.delegate.ontology.CallOntologyUtil; -import edu.harvard.i2b2.crc.util.ItemKeyUtil; -import edu.harvard.i2b2.crc.util.LogTimingUtil; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; -import edu.harvard.i2b2.crc.util.SqlClauseUtil; -import edu.harvard.i2b2.crc.datavo.ontology.DerivedFactColumnsType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ItemType; - -/** - * Setfinder's result genertor class. This class calculates patient break down - * for the result type. - * - * Calls the ontology to get the children for the result type and then - * calculates the patient count for each child of the result type. - */ -public class QueryResultGenerator extends CRCDAO implements IResultGenerator { - - - @Override - public String getResults() { - return xmlResult; - } - - - protected DerivedFactColumnsType getFactColumnsFromOntologyCell(String itemKey, - SecurityType securityType, String projectId) - throws ConceptNotFoundException, OntologyException { - DerivedFactColumnsType factColumns = new DerivedFactColumnsType(); - try { - - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - String ontologyUrl = qpUtil - .getCRCPropertyValue(QueryProcessorUtil.ONTOLOGYCELL_ROOT_WS_URL_PROPERTIES); - - factColumns = CallOntologyUtil.callGetFactColumns(itemKey, - securityType, projectId, - ontologyUrl +"/getDerivedFactColumns"); - } catch (JAXBUtilException e) { - - log.error("Error while fetching metadata [" + itemKey - + "] from ontology ", e); - throw new OntologyException("Error while fetching metadata [" - + itemKey + "] from ontology " - + StackTraceUtil.getStackTrace(e)); - } catch (I2B2Exception e) { - log.error("Error while fetching metadata from ontology ", e); - throw new OntologyException("Error while fetching metadata [" - + itemKey + "] from ontology " - + StackTraceUtil.getStackTrace(e)); - } catch (AxisFault e) { - log.error("Error while fetching metadata from ontology ", e); - throw new OntologyException("Error while fetching metadata [" - + itemKey + "] from ontology " - + StackTraceUtil.getStackTrace(e)); - } catch (XMLStreamException e) { - log.error("Error while fetching metadata from ontology ", e); - throw new OntologyException("Error while fetching metadata [" - + itemKey + "] from ontology " - + StackTraceUtil.getStackTrace(e)); - } - - // if (factColumns.isEmpty()) { - // throw new ConceptNotFoundException("[" + itemKey + "] "); - - // } - - return factColumns; - } - private String xmlResult = null; - /** - * Function accepts parameter in Map. The patient count will be obfuscated - * if the user is OBFUS - */ - @Override - public void generateResult(Map param) throws CRCTimeOutException, - I2B2DAOException { - - SetFinderConnection sfConn = (SetFinderConnection) param - .get("SetFinderConnection"); - SetFinderDAOFactory sfDAOFactory = (SetFinderDAOFactory) param - .get("SetFinderDAOFactory"); - - // String patientSetId = (String)param.get("PatientSetId"); - String queryInstanceId = (String) param.get("QueryInstanceId"); - String TEMP_DX_TABLE = (String) param.get("TEMP_DX_TABLE"); - String resultInstanceId = (String) param.get("ResultInstanceId"); - // String itemKey = (String) param.get("ItemKey"); - String resultTypeName = (String) param.get("ResultOptionName"); - String processTimingFlag = (String) param.get("ProcessTimingFlag"); - int obfuscatedRecordCount = (Integer) param.get("ObfuscatedRecordCount"); - int recordCount = (Integer) param.get("RecordCount"); - int transactionTimeout = (Integer) param.get("TransactionTimeout"); - boolean obfscDataRoleFlag = (Boolean)param.get("ObfuscatedRoleFlag"); - - this - .setDbSchemaName(sfDAOFactory.getDataSourceLookup() - .getFullSchema()); - Map ontologyKeyMap = (Map) param.get("setFinderResultOntologyKeyMap"); - String serverType = (String) param.get("ServerType"); - // CallOntologyUtil ontologyUtil = (CallOntologyUtil) param - // .get("CallOntologyUtil"); - List roles = (List) param.get("Roles"); - String tempTableName = ""; - PreparedStatement stmt = null; - ResultSet resultSet = null; - boolean errorFlag = false, timeoutFlag = false; - String itemKey = ""; - - - try { - LogTimingUtil logTimingUtil = new LogTimingUtil(); - logTimingUtil.setStartTime(); - itemKey = getItemKeyFromResultType(sfDAOFactory, resultTypeName, roles); - - log.debug("Result type's " + resultTypeName + " item key value " - + itemKey); - - LogTimingUtil subLogTimingUtil = new LogTimingUtil(); - subLogTimingUtil.setStartTime(); - ConceptsType conceptsType = CallOntologyUtil.callGetChildren(itemKey, (SecurityType) param.get("securityType"), (String) param.get("projectId"), (String) param.get("ontologyGetChildrenUrl")); - if (conceptsType != null && conceptsType.getConcept().size()<1) { - throw new I2B2DAOException("Could not fetch children result type " + resultTypeName + " item key [ " + itemKey + " ]" ); - } - subLogTimingUtil.setEndTime(); - if (processTimingFlag != null) { - if (processTimingFlag.trim().equalsIgnoreCase(ProcessTimingReportUtil.DEBUG) ) { - ProcessTimingReportUtil ptrUtil = new ProcessTimingReportUtil(sfDAOFactory.getDataSourceLookup()); - ptrUtil.logProcessTimingMessage(queryInstanceId, ptrUtil.buildProcessTiming(subLogTimingUtil, "BUILD - " + resultTypeName + " : Ontology Call(GetChildren) ", "")); - } - } - - String itemCountSql = " select count(distinct PATIENT_NUM) as item_count from " - + this.getDbSchemaName() - + "observation_fact obs_fact " - + " where obs_fact.patient_num in (select patient_num from " - + TEMP_DX_TABLE - + " ) " - + " and obs_fact.concept_cd in (select concept_cd from " - + this.getDbSchemaName() - + "concept_dimension where concept_path like ?)"; - - //get break down count sigma from property file - - double breakdownCountSigma = GaussianBoxMuller.getBreakdownCountSigma(); - double obfuscatedMinimumValue = GaussianBoxMuller.getObfuscatedMinimumVal(); - - ResultType resultType = new ResultType(); - resultType.setName(resultTypeName); - /* - stmt = sfConn.prepareStatement(itemCountSql); - - CancelStatementRunner csr = new CancelStatementRunner(stmt, - transactionTimeout); - Thread csrThread = new Thread(csr); - csrThread.start(); - */ - - for (ConceptType conceptType : conceptsType.getConcept()) { - - // OMOP WAS... - // String joinTableName = "observation_fact"; - String factTable = "observation_fact"; - DerivedFactColumnsType columns = new DerivedFactColumnsType(); - columns.getDerivedFactTableColumn().add(conceptType.getFacttablecolumn()); - if( QueryProcessorUtil.getInstance().getDerivedFactTable() == true) { - - String baseItemFactColumn = conceptType.getFacttablecolumn(); - columns = getFactColumnsFromOntologyCell(conceptType.getKey(), (SecurityType) param.get("securityType"), (String) param.get("projectId")); - - if(columns.getDerivedFactTableColumn().size() > 1) { - for (String column : columns.getDerivedFactTableColumn()) { - // look for non-null fact table columns that are not equal to the base item's column - if((column != null) && !(column.equals(baseItemFactColumn))){ - if(!column.contains(".")){ - columns.getDerivedFactTableColumn().remove(column); - /* - TemporalPanelItem derivedPanelItem = new TemporalPanelConceptItem(this, itemType); - //if(conceptType == null) - // derivedPanelItem.getConceptType(); - - if (derivedPanelItem != null - && conceptType != null - && conceptType.getDimcode() != null - && conceptType.getDimcode() - .toLowerCase().trim() - .startsWith(ItemKeyUtil.ITEM_KEY_CELLID)) { - derivedPanelItem = new TemporalPanelCellQueryItem(this, itemType, - conceptType); - } - */ - log.debug("setting a new fact column: " + column); - /// derivedPanelItem.parseFactColumn(column); - // panelItemList.add(derivedPanelItem); - } - } - } - } - - - - } - int conceptWithCount = 0; - int actualTotal = 0; //, obsfcTotal = 0; - itemCountSql = " select count (distinct item_count) as item_count from ( "; - for (String column : columns.getDerivedFactTableColumn()) { - - String factColumnName = column; //conceptType.getFacttablecolumn(); - String factTableColumn = factColumnName; - - if (factColumnName!=null&&factColumnName.contains(".")){ - int lastIndex = factColumnName.lastIndexOf("."); - factTable= factColumnName.substring(0, lastIndex); - if ((lastIndex+1) -1) { - timeoutFlag = true; - throw new CRCTimeOutException(sqlEx.getMessage(), sqlEx); - } - if (sqlEx.getMessage().indexOf("The query was canceled.") > -1) { - timeoutFlag = true; - throw new CRCTimeOutException(sqlEx.getMessage(), sqlEx); - } - if (sqlEx.getMessage().indexOf("timed out") > -1) { - timeoutFlag = true; - throw new CRCTimeOutException(sqlEx.getMessage(), sqlEx); - } - errorFlag = true; - log.error("Error while executing sql", sqlEx); - throw new I2B2DAOException("Error while executing sql", sqlEx); - } catch (Exception sqlEx) { - - errorFlag = true; - log.error("QueryResultGenerator.generateResult:" - + sqlEx.getMessage(), sqlEx); - throw new I2B2DAOException( - "QueryResultGenerator.generateResult:" - + sqlEx.getMessage(), sqlEx); - } finally { - - IQueryResultInstanceDao resultInstanceDao = sfDAOFactory - .getPatientSetResultDAO(); - - if (errorFlag) { - resultInstanceDao.updatePatientSet(resultInstanceId, - QueryStatusTypeId.STATUSTYPE_ID_ERROR, 0); - } else { - // set the setsize and the description of the result instance if - // the user role is obfuscated - if (timeoutFlag == false) { // check if the query completed - try { - // tm.begin(); - - String obfusMethod = "", description = null; - if (obfscDataRoleFlag) { - obfusMethod = IQueryResultInstanceDao.OBSUBTOTAL; - // add () to the result type description - // read the description from result type - - } else { - obfuscatedRecordCount = recordCount; - } - IQueryResultTypeDao resultTypeDao = sfDAOFactory.getQueryResultTypeDao(); - List resultTypeList = resultTypeDao - .getQueryResultTypeByName(resultTypeName, roles); - - // add "(Obfuscated)" in the description - //description = resultTypeList.get(0) - // .getDescription() - // + " (Obfuscated) "; - String queryName = sfDAOFactory.getQueryMasterDAO().getQueryDefinition( - sfDAOFactory.getQueryInstanceDAO().getQueryInstanceByInstanceId(queryInstanceId).getQtQueryMaster().getQueryMasterId()).getName(); - - - - resultInstanceDao.updatePatientSet(resultInstanceId, - QueryStatusTypeId.STATUSTYPE_ID_FINISHED, null, - //obsfcTotal, - obfuscatedRecordCount, recordCount, obfusMethod); - - description = resultTypeList.get(0) - .getDescription() + " for \"" + queryName +"\""; - - // set the result instance description - resultInstanceDao.updateResultInstanceDescription( - resultInstanceId, description); - // tm.commit(); - } catch (SecurityException e) { - throw new I2B2DAOException( - "Failed to write obfuscated description " - + e.getMessage(), e); - } catch (IllegalStateException e) { - throw new I2B2DAOException( - "Failed to write obfuscated description " - + e.getMessage(), e); - } - } - } - } - - } - - private String getItemKeyFromResultType(SetFinderDAOFactory sfDAOFactory, - String resultTypeKey, List roles) throws I2B2Exception { - // - IQueryBreakdownTypeDao queryBreakdownTypeDao = sfDAOFactory - .getQueryBreakdownTypeDao(); - QtQueryBreakdownType queryBreakdownType = queryBreakdownTypeDao - .getBreakdownTypeByName(resultTypeKey); - String itemKey = queryBreakdownType.getValue(); - if (queryBreakdownType.getUserRoleCd() != null && !roles.contains(queryBreakdownType.getUserRoleCd())) - throw new I2B2Exception("User does not have permission to run this breakdown."); - return itemKey; - } - - - - private String getDimCodeInSqlFormat(ConceptType conceptType) { - String theData = null; - if (conceptType.getColumndatatype() != null - && conceptType.getColumndatatype().equalsIgnoreCase("T")) { - theData = SqlClauseUtil.handleMetaDataTextValue( - conceptType.getOperator(), conceptType.getDimcode()); - } else if (conceptType.getColumndatatype() != null - && conceptType.getColumndatatype().equalsIgnoreCase("N")) { - theData = SqlClauseUtil.handleMetaDataNumericValue( - conceptType.getOperator(), conceptType.getDimcode()); - } else if (conceptType.getColumndatatype() != null - && conceptType.getColumndatatype().equalsIgnoreCase("D")) { - theData = SqlClauseUtil.handleMetaDataDateValue( - conceptType.getOperator(), conceptType.getDimcode()); - } - return theData; - } +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder; + +import java.io.StringWriter; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.List; +import java.util.Map; + +import javax.xml.stream.XMLStreamException; + +import org.apache.axis2.AxisFault; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.exception.StackTraceUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.ConceptNotFoundException; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.OntologyException; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.ProcessTimingReportUtil; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal.TemporalPanelCellQueryItem; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal.TemporalPanelConceptItem; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal.TemporalPanelItem; +import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; +import edu.harvard.i2b2.crc.datavo.db.QtQueryBreakdownType; +import edu.harvard.i2b2.crc.datavo.db.QtQueryResultType; +import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; +import edu.harvard.i2b2.crc.datavo.i2b2result.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2result.DataType; +import edu.harvard.i2b2.crc.datavo.i2b2result.ResultEnvelopeType; +import edu.harvard.i2b2.crc.datavo.i2b2result.ResultType; +import edu.harvard.i2b2.crc.datavo.ontology.ConceptType; +import edu.harvard.i2b2.crc.datavo.ontology.ConceptsType; +import edu.harvard.i2b2.crc.delegate.ontology.CallOntologyUtil; +import edu.harvard.i2b2.crc.util.ItemKeyUtil; +import edu.harvard.i2b2.crc.util.LogTimingUtil; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; +import edu.harvard.i2b2.crc.util.SqlClauseUtil; +import edu.harvard.i2b2.crc.datavo.ontology.DerivedFactColumnsType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ItemType; + +/** + * Setfinder's result genertor class. This class calculates patient break down + * for the result type. + * + * Calls the ontology to get the children for the result type and then + * calculates the patient count for each child of the result type. + */ +public class QueryResultGenerator extends CRCDAO implements IResultGenerator { + + + @Override + public String getResults() { + return xmlResult; + } + + + protected DerivedFactColumnsType getFactColumnsFromOntologyCell(String itemKey, + SecurityType securityType, String projectId) + throws ConceptNotFoundException, OntologyException { + DerivedFactColumnsType factColumns = new DerivedFactColumnsType(); + try { + + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + String ontologyUrl = qpUtil + .getCRCPropertyValue(QueryProcessorUtil.ONTOLOGYCELL_ROOT_WS_URL_PROPERTIES); + + factColumns = CallOntologyUtil.callGetFactColumns(itemKey, + securityType, projectId, + ontologyUrl +"/getDerivedFactColumns"); + } catch (JAXBUtilException e) { + + log.error("Error while fetching metadata [" + itemKey + + "] from ontology ", e); + throw new OntologyException("Error while fetching metadata [" + + itemKey + "] from ontology " + + StackTraceUtil.getStackTrace(e)); + } catch (I2B2Exception e) { + log.error("Error while fetching metadata from ontology ", e); + throw new OntologyException("Error while fetching metadata [" + + itemKey + "] from ontology " + + StackTraceUtil.getStackTrace(e)); + } catch (AxisFault e) { + log.error("Error while fetching metadata from ontology ", e); + throw new OntologyException("Error while fetching metadata [" + + itemKey + "] from ontology " + + StackTraceUtil.getStackTrace(e)); + } catch (XMLStreamException e) { + log.error("Error while fetching metadata from ontology ", e); + throw new OntologyException("Error while fetching metadata [" + + itemKey + "] from ontology " + + StackTraceUtil.getStackTrace(e)); + } + + // if (factColumns.isEmpty()) { + // throw new ConceptNotFoundException("[" + itemKey + "] "); + + // } + + return factColumns; + } + private String xmlResult = null; + /** + * Function accepts parameter in Map. The patient count will be obfuscated + * if the user is OBFUS + */ + @Override + public void generateResult(Map param) throws CRCTimeOutException, + I2B2DAOException { + + SetFinderConnection sfConn = (SetFinderConnection) param + .get("SetFinderConnection"); + SetFinderDAOFactory sfDAOFactory = (SetFinderDAOFactory) param + .get("SetFinderDAOFactory"); + + // String patientSetId = (String)param.get("PatientSetId"); + String queryInstanceId = (String) param.get("QueryInstanceId"); + String TEMP_DX_TABLE = (String) param.get("TEMP_DX_TABLE"); + String resultInstanceId = (String) param.get("ResultInstanceId"); + // String itemKey = (String) param.get("ItemKey"); + String resultTypeName = (String) param.get("ResultOptionName"); + String processTimingFlag = (String) param.get("ProcessTimingFlag"); + int obfuscatedRecordCount = (Integer) param.get("ObfuscatedRecordCount"); + int recordCount = (Integer) param.get("RecordCount"); + int transactionTimeout = (Integer) param.get("TransactionTimeout"); + boolean obfscDataRoleFlag = (Boolean)param.get("ObfuscatedRoleFlag"); + + this + .setDbSchemaName(sfDAOFactory.getDataSourceLookup() + .getFullSchema()); + Map ontologyKeyMap = (Map) param.get("setFinderResultOntologyKeyMap"); + String serverType = (String) param.get("ServerType"); + // CallOntologyUtil ontologyUtil = (CallOntologyUtil) param + // .get("CallOntologyUtil"); + List roles = (List) param.get("Roles"); + String tempTableName = ""; + PreparedStatement stmt = null; + ResultSet resultSet = null; + boolean errorFlag = false, timeoutFlag = false; + String itemKey = ""; + + + try { + LogTimingUtil logTimingUtil = new LogTimingUtil(); + logTimingUtil.setStartTime(); + itemKey = getItemKeyFromResultType(sfDAOFactory, resultTypeName, roles); + + log.debug("Result type's " + resultTypeName + " item key value " + + itemKey); + + LogTimingUtil subLogTimingUtil = new LogTimingUtil(); + subLogTimingUtil.setStartTime(); + ConceptsType conceptsType = CallOntologyUtil.callGetChildren(itemKey, (SecurityType) param.get("securityType"), (String) param.get("projectId"), (String) param.get("ontologyGetChildrenUrl")); + if (conceptsType != null && conceptsType.getConcept().size()<1) { + throw new I2B2DAOException("Could not fetch children result type " + resultTypeName + " item key [ " + itemKey + " ]" ); + } + subLogTimingUtil.setEndTime(); + if (processTimingFlag != null) { + if (processTimingFlag.trim().equalsIgnoreCase(ProcessTimingReportUtil.DEBUG) ) { + ProcessTimingReportUtil ptrUtil = new ProcessTimingReportUtil(sfDAOFactory.getDataSourceLookup()); + ptrUtil.logProcessTimingMessage(queryInstanceId, ptrUtil.buildProcessTiming(subLogTimingUtil, "BUILD - " + resultTypeName + " : Ontology Call(GetChildren) ", "")); + } + } + + String itemCountSql = " select count(distinct PATIENT_NUM) as item_count from " + + this.getDbSchemaName() + + "observation_fact obs_fact " + + " where obs_fact.patient_num in (select patient_num from " + + TEMP_DX_TABLE + + " ) " + + " and obs_fact.concept_cd in (select concept_cd from " + + this.getDbSchemaName() + + "concept_dimension where concept_path like ?)"; + + //get break down count sigma from property file + + double breakdownCountSigma = GaussianBoxMuller.getBreakdownCountSigma(); + double obfuscatedMinimumValue = GaussianBoxMuller.getObfuscatedMinimumVal(); + + ResultType resultType = new ResultType(); + resultType.setName(resultTypeName); + /* + stmt = sfConn.prepareStatement(itemCountSql); + + CancelStatementRunner csr = new CancelStatementRunner(stmt, + transactionTimeout); + Thread csrThread = new Thread(csr); + csrThread.start(); + */ + + for (ConceptType conceptType : conceptsType.getConcept()) { + + // OMOP WAS... + // String joinTableName = "observation_fact"; + String factTable = "observation_fact"; + DerivedFactColumnsType columns = new DerivedFactColumnsType(); + columns.getDerivedFactTableColumn().add(conceptType.getFacttablecolumn()); + if( QueryProcessorUtil.getInstance().getDerivedFactTable() == true) { + + String baseItemFactColumn = conceptType.getFacttablecolumn(); + columns = getFactColumnsFromOntologyCell(conceptType.getKey(), (SecurityType) param.get("securityType"), (String) param.get("projectId")); + + if(columns.getDerivedFactTableColumn().size() > 1) { + for (String column : columns.getDerivedFactTableColumn()) { + // look for non-null fact table columns that are not equal to the base item's column + if((column != null) && !(column.equals(baseItemFactColumn))){ + if(!column.contains(".")){ + columns.getDerivedFactTableColumn().remove(column); + /* + TemporalPanelItem derivedPanelItem = new TemporalPanelConceptItem(this, itemType); + //if(conceptType == null) + // derivedPanelItem.getConceptType(); + + if (derivedPanelItem != null + && conceptType != null + && conceptType.getDimcode() != null + && conceptType.getDimcode() + .toLowerCase().trim() + .startsWith(ItemKeyUtil.ITEM_KEY_CELLID)) { + derivedPanelItem = new TemporalPanelCellQueryItem(this, itemType, + conceptType); + } + */ + log.debug("setting a new fact column: " + column); + /// derivedPanelItem.parseFactColumn(column); + // panelItemList.add(derivedPanelItem); + } + } + } + } + + + + } + int conceptWithCount = 0; + int actualTotal = 0; //, obsfcTotal = 0; + itemCountSql = " select count (distinct item_count) as item_count from ( "; + for (String column : columns.getDerivedFactTableColumn()) { + + String factColumnName = column; //conceptType.getFacttablecolumn(); + String factTableColumn = factColumnName; + + if (factColumnName!=null&&factColumnName.contains(".")){ + int lastIndex = factColumnName.lastIndexOf("."); + factTable= factColumnName.substring(0, lastIndex); + if ((lastIndex+1) -1) { + timeoutFlag = true; + throw new CRCTimeOutException(sqlEx.getMessage(), sqlEx); + } + if (sqlEx.getMessage().indexOf("The query was canceled.") > -1) { + timeoutFlag = true; + throw new CRCTimeOutException(sqlEx.getMessage(), sqlEx); + } + if (sqlEx.getMessage().indexOf("timed out") > -1) { + timeoutFlag = true; + throw new CRCTimeOutException(sqlEx.getMessage(), sqlEx); + } + errorFlag = true; + log.error("Error while executing sql", sqlEx); + throw new I2B2DAOException("Error while executing sql", sqlEx); + } catch (Exception sqlEx) { + + errorFlag = true; + log.error("QueryResultGenerator.generateResult:" + + sqlEx.getMessage(), sqlEx); + throw new I2B2DAOException( + "QueryResultGenerator.generateResult:" + + sqlEx.getMessage(), sqlEx); + } finally { + + IQueryResultInstanceDao resultInstanceDao = sfDAOFactory + .getPatientSetResultDAO(); + + if (errorFlag) { + resultInstanceDao.updatePatientSet(resultInstanceId, + QueryStatusTypeId.STATUSTYPE_ID_ERROR, 0); + } else { + // set the setsize and the description of the result instance if + // the user role is obfuscated + if (timeoutFlag == false) { // check if the query completed + try { + // tm.begin(); + + String obfusMethod = "", description = null; + if (obfscDataRoleFlag) { + obfusMethod = IQueryResultInstanceDao.OBSUBTOTAL; + // add () to the result type description + // read the description from result type + + } else { + obfuscatedRecordCount = recordCount; + } + IQueryResultTypeDao resultTypeDao = sfDAOFactory.getQueryResultTypeDao(); + List resultTypeList = resultTypeDao + .getQueryResultTypeByName(resultTypeName, roles); + + // add "(Obfuscated)" in the description + //description = resultTypeList.get(0) + // .getDescription() + // + " (Obfuscated) "; + String queryName = sfDAOFactory.getQueryMasterDAO().getQueryDefinition( + sfDAOFactory.getQueryInstanceDAO().getQueryInstanceByInstanceId(queryInstanceId).getQtQueryMaster().getQueryMasterId()).getName(); + + + + resultInstanceDao.updatePatientSet(resultInstanceId, + QueryStatusTypeId.STATUSTYPE_ID_FINISHED, null, + //obsfcTotal, + obfuscatedRecordCount, recordCount, obfusMethod); + + description = resultTypeList.get(0) + .getDescription() + " for \"" + queryName +"\""; + + // set the result instance description + resultInstanceDao.updateResultInstanceDescription( + resultInstanceId, description); + // tm.commit(); + } catch (SecurityException e) { + throw new I2B2DAOException( + "Failed to write obfuscated description " + + e.getMessage(), e); + } catch (IllegalStateException e) { + throw new I2B2DAOException( + "Failed to write obfuscated description " + + e.getMessage(), e); + } + } + } + } + + } + + private String getItemKeyFromResultType(SetFinderDAOFactory sfDAOFactory, + String resultTypeKey, List roles) throws I2B2Exception { + // + IQueryBreakdownTypeDao queryBreakdownTypeDao = sfDAOFactory + .getQueryBreakdownTypeDao(); + QtQueryBreakdownType queryBreakdownType = queryBreakdownTypeDao + .getBreakdownTypeByName(resultTypeKey); + String itemKey = queryBreakdownType.getValue(); + if (queryBreakdownType.getUserRoleCd() != null && !roles.contains(queryBreakdownType.getUserRoleCd())) + throw new I2B2Exception("User does not have permission to run this breakdown."); + return itemKey; + } + + + + private String getDimCodeInSqlFormat(ConceptType conceptType) { + String theData = null; + if (conceptType.getColumndatatype() != null + && conceptType.getColumndatatype().equalsIgnoreCase("T")) { + theData = SqlClauseUtil.handleMetaDataTextValue( + conceptType.getOperator(), conceptType.getDimcode()); + } else if (conceptType.getColumndatatype() != null + && conceptType.getColumndatatype().equalsIgnoreCase("N")) { + theData = SqlClauseUtil.handleMetaDataNumericValue( + conceptType.getOperator(), conceptType.getDimcode()); + } else if (conceptType.getColumndatatype() != null + && conceptType.getColumndatatype().equalsIgnoreCase("D")) { + theData = SqlClauseUtil.handleMetaDataDateValue( + conceptType.getOperator(), conceptType.getDimcode()); + } + return theData; + } } \ No newline at end of file diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryResultInstanceSpringDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryResultInstanceSpringDao.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryResultInstanceSpringDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryResultInstanceSpringDao.java index bfc76905..f43781d8 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryResultInstanceSpringDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryResultInstanceSpringDao.java @@ -1,555 +1,555 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao.setfinder; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Types; -import java.util.Date; -import java.util.List; - -import javax.sql.DataSource; - -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.RowMapper; -import org.springframework.jdbc.core.SqlParameter; -import org.springframework.jdbc.object.SqlUpdate; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.StackTraceUtil; -import edu.harvard.i2b2.common.util.db.JDBCUtil; -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.db.QtQueryInstance; -import edu.harvard.i2b2.crc.datavo.db.QtQueryResultInstance; -import edu.harvard.i2b2.crc.datavo.db.QtQueryResultType; -import edu.harvard.i2b2.crc.datavo.db.QtQueryStatusType; -import edu.harvard.i2b2.crc.datavo.db.StatusEnum; - -/** - * This is class handles persistance of result instance and its update operation - * $Id: QueryResultInstanceSpringDao.java,v 1.14 2010/07/22 18:54:51 rk903 Exp $ - * - * @author rkuttan - */ -public class QueryResultInstanceSpringDao extends CRCDAO implements -IQueryResultInstanceDao { - - JdbcTemplate jdbcTemplate = null; - SavePatientSetResult savePatientSetResult = null; - PatientSetResultRowMapper patientSetMapper = null; - DataSourceLookup dataSourceLookup = null; - List roles = null; - - - public QueryResultInstanceSpringDao(DataSource dataSource, - DataSourceLookup dataSourceLookup) { - setDataSource(dataSource); - setDbSchemaName(dataSourceLookup.getFullSchema()); - jdbcTemplate = new JdbcTemplate(dataSource); - this.dataSourceLookup = dataSourceLookup; - - patientSetMapper = new PatientSetResultRowMapper(); - } - - - public void setRoles(List roles) { - this.roles = roles; - } - - - /** - * Function to create result instance for given query instance id. The - * result instance status is set to running. Use updatePatientSet function - * to change the status to completed or error - * - * @param queryInstanceId - * @return - */ - @Override - public String createPatientSet(String queryInstanceId, String resultName) - throws I2B2DAOException { - QtQueryResultInstance resultInstance = new QtQueryResultInstance(); - resultInstance.setDeleteFlag("N"); - - QueryResultTypeSpringDao resultTypeDao = new QueryResultTypeSpringDao( - dataSource, dataSourceLookup); - List resultType = resultTypeDao - .getQueryResultTypeByName(resultName, roles); - if (resultType.size() < 1) { - throw new I2B2DAOException(" Result type [" + resultName - + "] not found"); - } - resultInstance.setQtQueryResultType(resultType.get(0)); - resultInstance.setDescription(resultType.get(0).getDescription()); - QtQueryInstance queryInstance = new QtQueryInstance(); - queryInstance.setQueryInstanceId(queryInstanceId); - resultInstance.setQtQueryInstance(queryInstance); - - QtQueryStatusType queryStatusType = new QtQueryStatusType(); - queryStatusType.setStatusTypeId(StatusEnum.QUEUED.ordinal()); // 1 - resultInstance.setQtQueryStatusType(queryStatusType); - - Date startDate = new Date(System.currentTimeMillis()); - resultInstance.setStartDate(startDate); - savePatientSetResult = new SavePatientSetResult(getDataSource(), - getDbSchemaName(), dataSourceLookup); - savePatientSetResult.save(resultInstance); - - return resultInstance.getResultInstanceId(); - } - - /** - * Function used to update result instance Particularly its status and size - * - * @param resultInstanceId - * @param statusTypeId - * @param setSize - */ - @Override - public void updatePatientSet(String resultInstanceId, int statusTypeId, - int setSize) { - updatePatientSet(resultInstanceId, statusTypeId, "", setSize, 0, ""); - } - - /** - * Function used to update result instance Particularly its status and size - * - * @param resultInstanceId - * @param statusTypeId - * @param setSize - */ - @Override - public void updatePatientSet(String resultInstanceId, int statusTypeId, - String message, int setSize, int realSetSize, String obsMethod) { - - Date endDate = new Date(System.currentTimeMillis()); - String sql = "update " - + getDbSchemaName() - + "qt_query_result_instance set set_size = ?, real_set_size = ? , obfusc_method = ?, status_type_id =?, end_date = ?, message = ? where result_instance_id = ?"; - jdbcTemplate.update(sql, new Object[] { setSize, realSetSize, - obsMethod, statusTypeId, endDate, message, resultInstanceId }, - new int[] { Types.INTEGER, Types.INTEGER, Types.VARCHAR, - Types.INTEGER, Types.TIMESTAMP, Types.VARCHAR, - Types.INTEGER }); - } - - /** - * Function used to update result instance description - * - * @param resultInstanceId - * @param description - */ - @Override - public void updateResultInstanceDescription(String resultInstanceId, - String description) { - String sql = "update " - + getDbSchemaName() - + "qt_query_result_instance set description = ? where result_instance_id = ?"; - jdbcTemplate.update(sql, - new Object[] { description, Integer.parseInt(resultInstanceId) }, new int[] { - Types.VARCHAR, Types.INTEGER }); - } - - - @Override - public void updateInstanceMessage(String instanceId, String message) { - String sql = "update " - + getDbSchemaName() - + "qt_query_instance set message = ? where query_instance_id = ?"; - jdbcTemplate.update(sql, - new Object[] { message, Integer.parseInt(instanceId) }, new int[] { - Types.VARCHAR, Types.INTEGER }); - - } - /** - * Return list of query result instance by query instance id - * - * @param queryInstanceId - * @return List - */ - @Override - @SuppressWarnings("unchecked") - public List getResultInstanceList( - String queryInstanceId) { - String sql = "select * from " + getDbSchemaName() - + "qt_query_result_instance where query_instance_id = ? "; - List queryResultInstanceList = jdbcTemplate - .query(sql, new Object[] { Integer.parseInt(queryInstanceId) }, patientSetMapper); - return queryResultInstanceList; - } - - /** - * Return list of query result instance by query result id - * - * @param queryResultId - * @return QtQueryResultInstance - */ - @Override - @SuppressWarnings("unchecked") - public QtQueryResultInstance getResultInstanceById(String queryResultId) - throws I2B2DAOException { - String sql = "select * from " + getDbSchemaName() - + "qt_query_result_instance where result_instance_id = ? "; - List queryResultInstanceList = jdbcTemplate - .query(sql, new Object[] { Integer.parseInt(queryResultId) }, patientSetMapper); - if (queryResultInstanceList.size() > 0) { - return queryResultInstanceList.get(0); - } else { - throw new I2B2DAOException("Query result id " + queryResultId - + " not found"); - } - - } - - /** - * Return list of query result instance by query instance id and result name - * - * @param queryInstanceId - * @param resultName - * @return QtQueryResultInstance - */ - @Override - @SuppressWarnings("unchecked") - public QtQueryResultInstance getResultInstanceByQueryInstanceIdAndName( - String queryInstanceId, String resultName) { - String sql = "select * from " - + getDbSchemaName() - + "qt_query_result_instance ri, " - + getDbSchemaName() - + "qt_query_result_type rt where ri.query_instance_id = ? and ri.result_type_id = rt.result_type_id and rt.name=?"; - QtQueryResultInstance queryResultInstanceList = (QtQueryResultInstance) jdbcTemplate - .queryForObject(sql, - new Object[] { Integer.parseInt(queryInstanceId), resultName }, - patientSetMapper); - return queryResultInstanceList; - } - - /** - * Return a list of query result instance with waiting status - * - * @param queueName - * @param maxListSize - * @return - */ - @Override - public List getUnfinishedInstanceByQueue( - String queueName, int maxListSize) { - List resultInstanceList = null; - int waitStatus = 1; - String sql = "select * from " - + getDbSchemaName() - + "qt_query_result_instance ri, " - + getDbSchemaName() - + "qt_query_result_type rt where status_type_id = ? and queue_name = ? and ri.result_type_id = rt.result_type_id order by start_date"; - resultInstanceList = jdbcTemplate.query(sql, new Object[] { waitStatus, - queueName }, patientSetMapper); - return resultInstanceList; - } - - /** - * Get result instance count by set size - * - * @param userId - * @param compareDays - * @param setSize - * @param totalCount - * @return - * @throws I2B2DAOException - */ - @Override - public int getResultInstanceCountBySetSize(String userId, int compareDays, - int resultTypeId, int setSize, int totalCount) - throws I2B2DAOException { - // int betweenDayValue = compareDays / 2; - int startBetweenDayValue = compareDays * -1; - int returnSetSize = 0; - String queryCountSql = ""; - - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE) ) { - queryCountSql = " select count(r1.result_instance_id) result_count,r1.real_set_size " - + " from " + this.getDbSchemaName() + "qt_query_result_instance r1 inner join " + this.getDbSchemaName()+ "qt_query_result_instance r2 on " - + " r1.real_set_size = r2.real_set_size, " - + this.getDbSchemaName() +"qt_query_instance qi " - + " where " - + " r1.start_date between sysdate- " - + compareDays - + " and sysdate " - + " and r2.start_date between sysdate- " - + compareDays - + " and sysdate " - + " and r1.result_type_id = ?" - + " and r2.result_type_id = ? " - + " and qi.user_id = ? " - + " and qi.query_instance_id = r1.query_instance_id " - + " and qi.query_instance_id = r2.query_instance_id " - + " and r1.real_set_size = ? " - + " group by r1.real_set_size " - + " having count(r1.result_instance_id) > ? "; - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL) ) { - queryCountSql = " select count(r1.result_instance_id) result_count,r1.real_set_size " - + " from " + this.getDbSchemaName() + "qt_query_result_instance r1 inner join " + this.getDbSchemaName()+ "qt_query_result_instance r2 on " - + " r1.real_set_size = r2.real_set_size, " - + this.getDbSchemaName() +"qt_query_instance qi " - + " where " - + " r1.start_date between LOCALTIMESTAMP - INTERVAL '" - + compareDays - + " days' and LOCALTIMESTAMP " - + " and r2.start_date between LOCALTIMESTAMP - INTERVAL '" - + compareDays - + " days' and LOCALTIMESTAMP " - + " and r1.result_type_id = ?" - + " and r2.result_type_id = ? " - + " and qi.user_id = ? " - + " and qi.query_instance_id = r1.query_instance_id " - + " and qi.query_instance_id = r2.query_instance_id " - + " and r1.real_set_size = ? " - + " group by r1.real_set_size " - + " having count(r1.result_instance_id) > ? "; - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER)) { - queryCountSql = " select count(r1.result_instance_id) result_count,r1.real_set_size " - + " from " + this.getDbSchemaName() + "qt_query_result_instance r1 inner join " + this.getDbSchemaName() + "qt_query_result_instance r2 on " - + " r1.real_set_size = r2.real_set_size, " - + this.getDbSchemaName() +"qt_query_instance qi " - + " where " - + " r1.start_date between DATEADD ( day , " - + startBetweenDayValue - + ", getDate()) and DATEADD ( day , " - + "1" - + ", getDate()) " - + " and r2.start_date between DATEADD ( day , " - + startBetweenDayValue - + ", getDate()) and DATEADD ( day , " - + "1" - + ", getDate()) " - + " and r1.result_type_id = ? " - + " and r2.result_type_id = ? " - + " and qi.user_id = ? " - + " and qi.query_instance_id = r1.query_instance_id " - + " and qi.query_instance_id = r2.query_instance_id " - + " and r1.real_set_size = ? " - + " group by r1.real_set_size " - + " having count(r1.result_instance_id) > ? "; - } - - Connection conn = null; - PreparedStatement preparedStmt = null; - try { - conn = dataSource.getConnection(); - - log.debug("Executing sql [" + queryCountSql + "]"); - preparedStmt = conn.prepareStatement(queryCountSql); - preparedStmt.setInt(1, resultTypeId); - preparedStmt.setInt(2, resultTypeId); - preparedStmt.setString(3, userId); - preparedStmt.setInt(4, setSize); - preparedStmt.setInt(5, totalCount); - - ResultSet resultSet = preparedStmt.executeQuery(); - if (resultSet.next()) { - returnSetSize = resultSet.getInt("result_count"); - } - } catch (SQLException e) { - e.printStackTrace(); - throw new I2B2DAOException( - "Error while calculating query count by set size" - + StackTraceUtil.getStackTrace(e)); - } finally { - try { - JDBCUtil.closeJdbcResource(null, preparedStmt, conn); - } catch (SQLException e) { - - e.printStackTrace(); - } - - } - return returnSetSize; - - } - - private static class SavePatientSetResult extends SqlUpdate { - - - private String INSERT_ORACLE = ""; - private String INSERT_SQLSERVER = ""; - private String SEQUENCE_ORACLE = ""; - private String SEQUENCE_POSTGRESQL = ""; - private String INSERT_POSTGRESQL = ""; - DataSourceLookup dataSourceLookup = null; - - public SavePatientSetResult(DataSource dataSource, String dbSchemaName, - DataSourceLookup dataSourceLookup) { - super(); - setDataSource(dataSource); - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE)) { - INSERT_ORACLE = "INSERT INTO " - + dbSchemaName - + "QT_QUERY_RESULT_INSTANCE " - + "(RESULT_INSTANCE_ID, QUERY_INSTANCE_ID, RESULT_TYPE_ID, SET_SIZE,START_DATE,END_DATE,STATUS_TYPE_ID,DELETE_FLAG) " - + "VALUES (?,?,?,?,?,?,?,?)"; - setSql(INSERT_ORACLE); - SEQUENCE_ORACLE = "select " + dbSchemaName - + "QT_SQ_QRI_QRIID.nextval from dual"; - declareParameter(new SqlParameter(Types.INTEGER)); - - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER)) { - INSERT_SQLSERVER = "INSERT INTO " - + dbSchemaName - + "QT_QUERY_RESULT_INSTANCE " - + "( QUERY_INSTANCE_ID, RESULT_TYPE_ID, SET_SIZE,START_DATE,END_DATE,STATUS_TYPE_ID,DELETE_FLAG) " - + "VALUES (?,?,?,?,?,?,?)"; - setSql(INSERT_SQLSERVER); - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) { - INSERT_POSTGRESQL = "INSERT INTO " - + dbSchemaName - + "QT_QUERY_RESULT_INSTANCE " - + "(RESULT_INSTANCE_ID, QUERY_INSTANCE_ID, RESULT_TYPE_ID, SET_SIZE,START_DATE,END_DATE,STATUS_TYPE_ID,DELETE_FLAG) " - + "VALUES (?,?,?,?,?,?,?,?)"; - setSql(INSERT_POSTGRESQL); - SEQUENCE_POSTGRESQL = "select " //+ dbSchemaName - + "nextval('qt_query_result_instance_result_instance_id_seq') "; - declareParameter(new SqlParameter(Types.INTEGER)); - - - } - - declareParameter(new SqlParameter(Types.INTEGER)); - declareParameter(new SqlParameter(Types.INTEGER)); - declareParameter(new SqlParameter(Types.INTEGER)); - declareParameter(new SqlParameter(Types.TIMESTAMP)); - declareParameter(new SqlParameter(Types.TIMESTAMP)); - declareParameter(new SqlParameter(Types.INTEGER)); - declareParameter(new SqlParameter(Types.VARCHAR)); - this.dataSourceLookup = dataSourceLookup; - - compile(); - } - - public void save(QtQueryResultInstance resultInstance) { - JdbcTemplate jdbc = getJdbcTemplate(); - int resultInstanceId = 0; - Object[] object = null; - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER)) { - - object = new Object[] { - resultInstance.getQtQueryInstance() - .getQueryInstanceId(), - - resultInstance.getQtQueryResultType().getResultTypeId(), - resultInstance.getSetSize(), - resultInstance.getStartDate(), - resultInstance.getEndDate(), - resultInstance.getQtQueryStatusType().getStatusTypeId(), - resultInstance.getDeleteFlag() - - }; - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE)) { - resultInstanceId = jdbc.queryForObject(SEQUENCE_ORACLE, Integer.class); - resultInstance.setResultInstanceId(String - .valueOf(resultInstanceId)); - object = new Object[] { - resultInstance.getResultInstanceId(), - resultInstance.getQtQueryInstance() - .getQueryInstanceId(), - resultInstance.getQtQueryResultType().getResultTypeId(), - resultInstance.getSetSize(), - resultInstance.getStartDate(), - resultInstance.getEndDate(), - resultInstance.getQtQueryStatusType().getStatusTypeId(), - resultInstance.getDeleteFlag() - - }; - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) { - resultInstanceId = jdbc.queryForObject(SEQUENCE_POSTGRESQL, Integer.class); - resultInstance.setResultInstanceId(String - .valueOf(resultInstanceId)); - object = new Object[] { - resultInstance.getResultInstanceId(), - resultInstance.getQtQueryInstance() - .getQueryInstanceId(), - resultInstance.getQtQueryResultType().getResultTypeId(), - resultInstance.getSetSize(), - resultInstance.getStartDate(), - resultInstance.getEndDate(), - resultInstance.getQtQueryStatusType().getStatusTypeId(), - resultInstance.getDeleteFlag() - - }; - } - - update(object); - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER)) { - int resultInstanceIdentityId = jdbc - .queryForObject("SELECT @@IDENTITY", Integer.class); - - resultInstance.setResultInstanceId(String - .valueOf(resultInstanceIdentityId)); - - } - - } - } - - private class PatientSetResultRowMapper implements RowMapper { - QueryStatusTypeSpringDao statusTypeDao = new QueryStatusTypeSpringDao( - dataSource, dataSourceLookup); - QueryResultTypeSpringDao resultTypeDao = new QueryResultTypeSpringDao( - dataSource, dataSourceLookup); - - @Override - public Object mapRow(ResultSet rs, int rowNum) throws SQLException { - QtQueryResultInstance resultInstance = new QtQueryResultInstance(); - resultInstance.setResultInstanceId(rs - .getString("RESULT_INSTANCE_ID")); - - QtQueryInstance queryInstance = new QtQueryInstance(); - queryInstance.setQueryInstanceId(rs.getString("QUERY_INSTANCE_ID")); - resultInstance.setQtQueryInstance(queryInstance); - resultInstance.setDescription(rs.getString("DESCRIPTION")); - - int resultTypeId = rs.getInt("RESULT_TYPE_ID"); - resultInstance.setQtQueryResultType(resultTypeDao - .getQueryResultTypeById(resultTypeId)); - resultInstance.setSetSize(rs.getInt("SET_SIZE")); - resultInstance.setRealSetSize(rs.getInt("REAL_SET_SIZE")); - resultInstance.setObfuscateMethod(rs.getString("OBFUSC_METHOD")); - resultInstance.setStartDate(rs.getTimestamp("START_DATE")); - resultInstance.setEndDate(rs.getTimestamp("END_DATE")); - resultInstance.setMessage(rs.getString("MESSAGE")); - // QtQueryStatusType queryStatusType = new QtQueryStatusType(); - int statusTypeId = rs.getInt("STATUS_TYPE_ID"); - resultInstance.setQtQueryStatusType(statusTypeDao - .getQueryStatusTypeById(statusTypeId)); - // resultInstance.setQtQueryStatusType(queryStatusType); - resultInstance.setDeleteFlag(rs.getString("DELETE_FLAG")); - return resultInstance; - } - } - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao.setfinder; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Types; +import java.util.Date; +import java.util.List; + +import javax.sql.DataSource; + +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.RowMapper; +import org.springframework.jdbc.core.SqlParameter; +import org.springframework.jdbc.object.SqlUpdate; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.StackTraceUtil; +import edu.harvard.i2b2.common.util.db.JDBCUtil; +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.db.QtQueryInstance; +import edu.harvard.i2b2.crc.datavo.db.QtQueryResultInstance; +import edu.harvard.i2b2.crc.datavo.db.QtQueryResultType; +import edu.harvard.i2b2.crc.datavo.db.QtQueryStatusType; +import edu.harvard.i2b2.crc.datavo.db.StatusEnum; + +/** + * This is class handles persistance of result instance and its update operation + * $Id: QueryResultInstanceSpringDao.java,v 1.14 2010/07/22 18:54:51 rk903 Exp $ + * + * @author rkuttan + */ +public class QueryResultInstanceSpringDao extends CRCDAO implements +IQueryResultInstanceDao { + + JdbcTemplate jdbcTemplate = null; + SavePatientSetResult savePatientSetResult = null; + PatientSetResultRowMapper patientSetMapper = null; + DataSourceLookup dataSourceLookup = null; + List roles = null; + + + public QueryResultInstanceSpringDao(DataSource dataSource, + DataSourceLookup dataSourceLookup) { + setDataSource(dataSource); + setDbSchemaName(dataSourceLookup.getFullSchema()); + jdbcTemplate = new JdbcTemplate(dataSource); + this.dataSourceLookup = dataSourceLookup; + + patientSetMapper = new PatientSetResultRowMapper(); + } + + + public void setRoles(List roles) { + this.roles = roles; + } + + + /** + * Function to create result instance for given query instance id. The + * result instance status is set to running. Use updatePatientSet function + * to change the status to completed or error + * + * @param queryInstanceId + * @return + */ + @Override + public String createPatientSet(String queryInstanceId, String resultName) + throws I2B2DAOException { + QtQueryResultInstance resultInstance = new QtQueryResultInstance(); + resultInstance.setDeleteFlag("N"); + + QueryResultTypeSpringDao resultTypeDao = new QueryResultTypeSpringDao( + dataSource, dataSourceLookup); + List resultType = resultTypeDao + .getQueryResultTypeByName(resultName, roles); + if (resultType.size() < 1) { + throw new I2B2DAOException(" Result type [" + resultName + + "] not found"); + } + resultInstance.setQtQueryResultType(resultType.get(0)); + resultInstance.setDescription(resultType.get(0).getDescription()); + QtQueryInstance queryInstance = new QtQueryInstance(); + queryInstance.setQueryInstanceId(queryInstanceId); + resultInstance.setQtQueryInstance(queryInstance); + + QtQueryStatusType queryStatusType = new QtQueryStatusType(); + queryStatusType.setStatusTypeId(StatusEnum.QUEUED.ordinal()); // 1 + resultInstance.setQtQueryStatusType(queryStatusType); + + Date startDate = new Date(System.currentTimeMillis()); + resultInstance.setStartDate(startDate); + savePatientSetResult = new SavePatientSetResult(getDataSource(), + getDbSchemaName(), dataSourceLookup); + savePatientSetResult.save(resultInstance); + + return resultInstance.getResultInstanceId(); + } + + /** + * Function used to update result instance Particularly its status and size + * + * @param resultInstanceId + * @param statusTypeId + * @param setSize + */ + @Override + public void updatePatientSet(String resultInstanceId, int statusTypeId, + int setSize) { + updatePatientSet(resultInstanceId, statusTypeId, "", setSize, 0, ""); + } + + /** + * Function used to update result instance Particularly its status and size + * + * @param resultInstanceId + * @param statusTypeId + * @param setSize + */ + @Override + public void updatePatientSet(String resultInstanceId, int statusTypeId, + String message, int setSize, int realSetSize, String obsMethod) { + + Date endDate = new Date(System.currentTimeMillis()); + String sql = "update " + + getDbSchemaName() + + "qt_query_result_instance set set_size = ?, real_set_size = ? , obfusc_method = ?, status_type_id =?, end_date = ?, message = ? where result_instance_id = ?"; + jdbcTemplate.update(sql, new Object[] { setSize, realSetSize, + obsMethod, statusTypeId, endDate, message, resultInstanceId }, + new int[] { Types.INTEGER, Types.INTEGER, Types.VARCHAR, + Types.INTEGER, Types.TIMESTAMP, Types.VARCHAR, + Types.INTEGER }); + } + + /** + * Function used to update result instance description + * + * @param resultInstanceId + * @param description + */ + @Override + public void updateResultInstanceDescription(String resultInstanceId, + String description) { + String sql = "update " + + getDbSchemaName() + + "qt_query_result_instance set description = ? where result_instance_id = ?"; + jdbcTemplate.update(sql, + new Object[] { description, Integer.parseInt(resultInstanceId) }, new int[] { + Types.VARCHAR, Types.INTEGER }); + } + + + @Override + public void updateInstanceMessage(String instanceId, String message) { + String sql = "update " + + getDbSchemaName() + + "qt_query_instance set message = ? where query_instance_id = ?"; + jdbcTemplate.update(sql, + new Object[] { message, Integer.parseInt(instanceId) }, new int[] { + Types.VARCHAR, Types.INTEGER }); + + } + /** + * Return list of query result instance by query instance id + * + * @param queryInstanceId + * @return List + */ + @Override + @SuppressWarnings("unchecked") + public List getResultInstanceList( + String queryInstanceId) { + String sql = "select * from " + getDbSchemaName() + + "qt_query_result_instance where query_instance_id = ? "; + List queryResultInstanceList = jdbcTemplate + .query(sql, new Object[] { Integer.parseInt(queryInstanceId) }, patientSetMapper); + return queryResultInstanceList; + } + + /** + * Return list of query result instance by query result id + * + * @param queryResultId + * @return QtQueryResultInstance + */ + @Override + @SuppressWarnings("unchecked") + public QtQueryResultInstance getResultInstanceById(String queryResultId) + throws I2B2DAOException { + String sql = "select * from " + getDbSchemaName() + + "qt_query_result_instance where result_instance_id = ? "; + List queryResultInstanceList = jdbcTemplate + .query(sql, new Object[] { Integer.parseInt(queryResultId) }, patientSetMapper); + if (queryResultInstanceList.size() > 0) { + return queryResultInstanceList.get(0); + } else { + throw new I2B2DAOException("Query result id " + queryResultId + + " not found"); + } + + } + + /** + * Return list of query result instance by query instance id and result name + * + * @param queryInstanceId + * @param resultName + * @return QtQueryResultInstance + */ + @Override + @SuppressWarnings("unchecked") + public QtQueryResultInstance getResultInstanceByQueryInstanceIdAndName( + String queryInstanceId, String resultName) { + String sql = "select * from " + + getDbSchemaName() + + "qt_query_result_instance ri, " + + getDbSchemaName() + + "qt_query_result_type rt where ri.query_instance_id = ? and ri.result_type_id = rt.result_type_id and rt.name=?"; + QtQueryResultInstance queryResultInstanceList = (QtQueryResultInstance) jdbcTemplate + .queryForObject(sql, + new Object[] { Integer.parseInt(queryInstanceId), resultName }, + patientSetMapper); + return queryResultInstanceList; + } + + /** + * Return a list of query result instance with waiting status + * + * @param queueName + * @param maxListSize + * @return + */ + @Override + public List getUnfinishedInstanceByQueue( + String queueName, int maxListSize) { + List resultInstanceList = null; + int waitStatus = 1; + String sql = "select * from " + + getDbSchemaName() + + "qt_query_result_instance ri, " + + getDbSchemaName() + + "qt_query_result_type rt where status_type_id = ? and queue_name = ? and ri.result_type_id = rt.result_type_id order by start_date"; + resultInstanceList = jdbcTemplate.query(sql, new Object[] { waitStatus, + queueName }, patientSetMapper); + return resultInstanceList; + } + + /** + * Get result instance count by set size + * + * @param userId + * @param compareDays + * @param setSize + * @param totalCount + * @return + * @throws I2B2DAOException + */ + @Override + public int getResultInstanceCountBySetSize(String userId, int compareDays, + int resultTypeId, int setSize, int totalCount) + throws I2B2DAOException { + // int betweenDayValue = compareDays / 2; + int startBetweenDayValue = compareDays * -1; + int returnSetSize = 0; + String queryCountSql = ""; + + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.ORACLE) ) { + queryCountSql = " select count(r1.result_instance_id) result_count,r1.real_set_size " + + " from " + this.getDbSchemaName() + "qt_query_result_instance r1 inner join " + this.getDbSchemaName()+ "qt_query_result_instance r2 on " + + " r1.real_set_size = r2.real_set_size, " + + this.getDbSchemaName() +"qt_query_instance qi " + + " where " + + " r1.start_date between sysdate- " + + compareDays + + " and sysdate " + + " and r2.start_date between sysdate- " + + compareDays + + " and sysdate " + + " and r1.result_type_id = ?" + + " and r2.result_type_id = ? " + + " and qi.user_id = ? " + + " and qi.query_instance_id = r1.query_instance_id " + + " and qi.query_instance_id = r2.query_instance_id " + + " and r1.real_set_size = ? " + + " group by r1.real_set_size " + + " having count(r1.result_instance_id) > ? "; + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL) ) { + queryCountSql = " select count(r1.result_instance_id) result_count,r1.real_set_size " + + " from " + this.getDbSchemaName() + "qt_query_result_instance r1 inner join " + this.getDbSchemaName()+ "qt_query_result_instance r2 on " + + " r1.real_set_size = r2.real_set_size, " + + this.getDbSchemaName() +"qt_query_instance qi " + + " where " + + " r1.start_date between LOCALTIMESTAMP - INTERVAL '" + + compareDays + + " days' and LOCALTIMESTAMP " + + " and r2.start_date between LOCALTIMESTAMP - INTERVAL '" + + compareDays + + " days' and LOCALTIMESTAMP " + + " and r1.result_type_id = ?" + + " and r2.result_type_id = ? " + + " and qi.user_id = ? " + + " and qi.query_instance_id = r1.query_instance_id " + + " and qi.query_instance_id = r2.query_instance_id " + + " and r1.real_set_size = ? " + + " group by r1.real_set_size " + + " having count(r1.result_instance_id) > ? "; + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER)) { + queryCountSql = " select count(r1.result_instance_id) result_count,r1.real_set_size " + + " from " + this.getDbSchemaName() + "qt_query_result_instance r1 inner join " + this.getDbSchemaName() + "qt_query_result_instance r2 on " + + " r1.real_set_size = r2.real_set_size, " + + this.getDbSchemaName() +"qt_query_instance qi " + + " where " + + " r1.start_date between DATEADD ( day , " + + startBetweenDayValue + + ", getDate()) and DATEADD ( day , " + + "1" + + ", getDate()) " + + " and r2.start_date between DATEADD ( day , " + + startBetweenDayValue + + ", getDate()) and DATEADD ( day , " + + "1" + + ", getDate()) " + + " and r1.result_type_id = ? " + + " and r2.result_type_id = ? " + + " and qi.user_id = ? " + + " and qi.query_instance_id = r1.query_instance_id " + + " and qi.query_instance_id = r2.query_instance_id " + + " and r1.real_set_size = ? " + + " group by r1.real_set_size " + + " having count(r1.result_instance_id) > ? "; + } + + Connection conn = null; + PreparedStatement preparedStmt = null; + try { + conn = dataSource.getConnection(); + + log.debug("Executing sql [" + queryCountSql + "]"); + preparedStmt = conn.prepareStatement(queryCountSql); + preparedStmt.setInt(1, resultTypeId); + preparedStmt.setInt(2, resultTypeId); + preparedStmt.setString(3, userId); + preparedStmt.setInt(4, setSize); + preparedStmt.setInt(5, totalCount); + + ResultSet resultSet = preparedStmt.executeQuery(); + if (resultSet.next()) { + returnSetSize = resultSet.getInt("result_count"); + } + } catch (SQLException e) { + e.printStackTrace(); + throw new I2B2DAOException( + "Error while calculating query count by set size" + + StackTraceUtil.getStackTrace(e)); + } finally { + try { + JDBCUtil.closeJdbcResource(null, preparedStmt, conn); + } catch (SQLException e) { + + e.printStackTrace(); + } + + } + return returnSetSize; + + } + + private static class SavePatientSetResult extends SqlUpdate { + + + private String INSERT_ORACLE = ""; + private String INSERT_SQLSERVER = ""; + private String SEQUENCE_ORACLE = ""; + private String SEQUENCE_POSTGRESQL = ""; + private String INSERT_POSTGRESQL = ""; + DataSourceLookup dataSourceLookup = null; + + public SavePatientSetResult(DataSource dataSource, String dbSchemaName, + DataSourceLookup dataSourceLookup) { + super(); + setDataSource(dataSource); + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.ORACLE)) { + INSERT_ORACLE = "INSERT INTO " + + dbSchemaName + + "QT_QUERY_RESULT_INSTANCE " + + "(RESULT_INSTANCE_ID, QUERY_INSTANCE_ID, RESULT_TYPE_ID, SET_SIZE,START_DATE,END_DATE,STATUS_TYPE_ID,DELETE_FLAG) " + + "VALUES (?,?,?,?,?,?,?,?)"; + setSql(INSERT_ORACLE); + SEQUENCE_ORACLE = "select " + dbSchemaName + + "QT_SQ_QRI_QRIID.nextval from dual"; + declareParameter(new SqlParameter(Types.INTEGER)); + + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER)) { + INSERT_SQLSERVER = "INSERT INTO " + + dbSchemaName + + "QT_QUERY_RESULT_INSTANCE " + + "( QUERY_INSTANCE_ID, RESULT_TYPE_ID, SET_SIZE,START_DATE,END_DATE,STATUS_TYPE_ID,DELETE_FLAG) " + + "VALUES (?,?,?,?,?,?,?)"; + setSql(INSERT_SQLSERVER); + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) { + INSERT_POSTGRESQL = "INSERT INTO " + + dbSchemaName + + "QT_QUERY_RESULT_INSTANCE " + + "(RESULT_INSTANCE_ID, QUERY_INSTANCE_ID, RESULT_TYPE_ID, SET_SIZE,START_DATE,END_DATE,STATUS_TYPE_ID,DELETE_FLAG) " + + "VALUES (?,?,?,?,?,?,?,?)"; + setSql(INSERT_POSTGRESQL); + SEQUENCE_POSTGRESQL = "select " //+ dbSchemaName + + "nextval('qt_query_result_instance_result_instance_id_seq') "; + declareParameter(new SqlParameter(Types.INTEGER)); + + + } + + declareParameter(new SqlParameter(Types.INTEGER)); + declareParameter(new SqlParameter(Types.INTEGER)); + declareParameter(new SqlParameter(Types.INTEGER)); + declareParameter(new SqlParameter(Types.TIMESTAMP)); + declareParameter(new SqlParameter(Types.TIMESTAMP)); + declareParameter(new SqlParameter(Types.INTEGER)); + declareParameter(new SqlParameter(Types.VARCHAR)); + this.dataSourceLookup = dataSourceLookup; + + compile(); + } + + public void save(QtQueryResultInstance resultInstance) { + JdbcTemplate jdbc = getJdbcTemplate(); + int resultInstanceId = 0; + Object[] object = null; + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER)) { + + object = new Object[] { + resultInstance.getQtQueryInstance() + .getQueryInstanceId(), + + resultInstance.getQtQueryResultType().getResultTypeId(), + resultInstance.getSetSize(), + resultInstance.getStartDate(), + resultInstance.getEndDate(), + resultInstance.getQtQueryStatusType().getStatusTypeId(), + resultInstance.getDeleteFlag() + + }; + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.ORACLE)) { + resultInstanceId = jdbc.queryForObject(SEQUENCE_ORACLE, Integer.class); + resultInstance.setResultInstanceId(String + .valueOf(resultInstanceId)); + object = new Object[] { + resultInstance.getResultInstanceId(), + resultInstance.getQtQueryInstance() + .getQueryInstanceId(), + resultInstance.getQtQueryResultType().getResultTypeId(), + resultInstance.getSetSize(), + resultInstance.getStartDate(), + resultInstance.getEndDate(), + resultInstance.getQtQueryStatusType().getStatusTypeId(), + resultInstance.getDeleteFlag() + + }; + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) { + resultInstanceId = jdbc.queryForObject(SEQUENCE_POSTGRESQL, Integer.class); + resultInstance.setResultInstanceId(String + .valueOf(resultInstanceId)); + object = new Object[] { + resultInstance.getResultInstanceId(), + resultInstance.getQtQueryInstance() + .getQueryInstanceId(), + resultInstance.getQtQueryResultType().getResultTypeId(), + resultInstance.getSetSize(), + resultInstance.getStartDate(), + resultInstance.getEndDate(), + resultInstance.getQtQueryStatusType().getStatusTypeId(), + resultInstance.getDeleteFlag() + + }; + } + + update(object); + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER)) { + int resultInstanceIdentityId = jdbc + .queryForObject("SELECT @@IDENTITY", Integer.class); + + resultInstance.setResultInstanceId(String + .valueOf(resultInstanceIdentityId)); + + } + + } + } + + private class PatientSetResultRowMapper implements RowMapper { + QueryStatusTypeSpringDao statusTypeDao = new QueryStatusTypeSpringDao( + dataSource, dataSourceLookup); + QueryResultTypeSpringDao resultTypeDao = new QueryResultTypeSpringDao( + dataSource, dataSourceLookup); + + @Override + public Object mapRow(ResultSet rs, int rowNum) throws SQLException { + QtQueryResultInstance resultInstance = new QtQueryResultInstance(); + resultInstance.setResultInstanceId(rs + .getString("RESULT_INSTANCE_ID")); + + QtQueryInstance queryInstance = new QtQueryInstance(); + queryInstance.setQueryInstanceId(rs.getString("QUERY_INSTANCE_ID")); + resultInstance.setQtQueryInstance(queryInstance); + resultInstance.setDescription(rs.getString("DESCRIPTION")); + + int resultTypeId = rs.getInt("RESULT_TYPE_ID"); + resultInstance.setQtQueryResultType(resultTypeDao + .getQueryResultTypeById(resultTypeId)); + resultInstance.setSetSize(rs.getInt("SET_SIZE")); + resultInstance.setRealSetSize(rs.getInt("REAL_SET_SIZE")); + resultInstance.setObfuscateMethod(rs.getString("OBFUSC_METHOD")); + resultInstance.setStartDate(rs.getTimestamp("START_DATE")); + resultInstance.setEndDate(rs.getTimestamp("END_DATE")); + resultInstance.setMessage(rs.getString("MESSAGE")); + // QtQueryStatusType queryStatusType = new QtQueryStatusType(); + int statusTypeId = rs.getInt("STATUS_TYPE_ID"); + resultInstance.setQtQueryStatusType(statusTypeDao + .getQueryStatusTypeById(statusTypeId)); + // resultInstance.setQtQueryStatusType(queryStatusType); + resultInstance.setDeleteFlag(rs.getString("DELETE_FLAG")); + return resultInstance; + } + } + + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientAgeCountGenerator.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientAgeCountGenerator.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientAgeCountGenerator.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientAgeCountGenerator.java index 80b92c90..976f89d0 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientAgeCountGenerator.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientAgeCountGenerator.java @@ -1,158 +1,158 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder; - -import java.io.StringWriter; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.util.Map; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.util.db.JDBCUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.i2b2result.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2result.DataType; -import edu.harvard.i2b2.crc.datavo.i2b2result.ResultEnvelopeType; -import edu.harvard.i2b2.crc.datavo.i2b2result.ResultType; - -public class QueryResultPatientAgeCountGenerator extends CRCDAO implements - IResultGenerator { - - @Override - public String getResults() { - return xmlResult; - } - - private String xmlResult = null; - - public static final String RESULT_NAME = "PATIENT_AGE_COUNT_XML"; - - @Override - public void generateResult(Map param) throws I2B2DAOException { - - SetFinderConnection sfConn = (SetFinderConnection) param - .get("SetFinderConnection"); - SetFinderDAOFactory sfDAOFactory = (SetFinderDAOFactory) param - .get("SetFinderDAOFactory"); - // String patientSetId = (String)param.get("PatientSetId"); - String queryInstanceId = (String) param.get("QueryInstanceId"); - String TEMP_DX_TABLE = (String) param.get("TEMP_DX_TABLE"); - String resultInstanceId = (String) param.get("ResultInstanceId"); - this - .setDbSchemaName(sfDAOFactory.getDataSourceLookup() - .getFullSchema()); - - String age1CountSql = "select count(distinct dx.patient_num) patient_count, '0-20' patient_range" - + " from " - + " " - + "patient_dimension pd ," - + " " - + " dx where pd.patient_num = dx.patient_num" - + " and pd.age_in_years_num between 0 and 20"; - - String age2CountSql = "select count(dx.patient_num) patient_count, '21-40' patient_range" - + " from " - + " " - + "patient_dimension pd ," - + " " - + " dx where pd.patient_num = dx.patient_num" - + " and pd.age_in_years_num between 21 and 40"; - - String age3CountSql = "select count(dx.patient_num) patient_count, '41-60' patient_range" - + " from " - + " " - + "patient_dimension pd ," - + " " - + " dx where pd.patient_num = dx.patient_num" - + " and pd.age_in_years_num between 41 and 60"; - - String age4CountSql = "select count(dx.patient_num) patient_count, '61-80' patient_range" - + " from " - + " " - + "patient_dimension pd ," - + " " - + " dx where pd.patient_num = dx.patient_num" - + " and pd.age_in_years_num between 61 and 80"; - - String age5CountSql = "select count(dx.patient_num) patient_count, '>80' patient_range" - + " from " - + " " - + "patient_dimension pd ," - + " " - + " dx where pd.patient_num = dx.patient_num" - + " and pd.age_in_years_num > 80"; - - String ageFinalCountSql = age1CountSql + "\n union all " + age2CountSql - + "\n union all " + age3CountSql + "\n union all " - + age4CountSql + "\n union all " + age5CountSql; - - boolean errorFlag = false; - int totalCount = 0; - try { - - String sqlFinal = ageFinalCountSql.replace("", this.getDbSchemaName() ); - sqlFinal = ageFinalCountSql.replace("", TEMP_DX_TABLE); - - log.debug("Executing[ " + ageFinalCountSql + " ]"); - PreparedStatement stmt = sfConn.prepareStatement(sqlFinal); - ResultSet resultSet = stmt.executeQuery(); - ResultType resultType = new ResultType(); - resultType.setName(RESULT_NAME); - while (resultSet.next()) { - String demoCount = resultSet.getString("patient_count"); - String raceCd = resultSet.getString("patient_range"); - DataType mdataType = new DataType(); - mdataType.setValue(demoCount); - mdataType.setColumn(raceCd); - mdataType.setType("int"); - resultType.getData().add(mdataType); - } - resultSet.close(); - stmt.close(); - edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory(); - BodyType bodyType = new BodyType(); - bodyType.getAny().add(of.createResult(resultType)); - ResultEnvelopeType resultEnvelop = new ResultEnvelopeType(); - resultEnvelop.setBody(bodyType); - - JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); - - StringWriter strWriter = new StringWriter(); - - jaxbUtil.marshaller(of.createI2B2ResultEnvelope(resultEnvelop), - strWriter); - - IXmlResultDao xmlResultDao = sfDAOFactory.getXmlResultDao(); - xmlResult = strWriter.toString(); - xmlResultDao.createQueryXmlResult(resultInstanceId, strWriter - .toString()); - - } catch (Exception sqlEx) { - log.error("QueryResultPatientAgeCountGenerator.generateResult:" - + sqlEx.getMessage(), sqlEx); - throw new I2B2DAOException( - "QueryResultPatientAgeCountGenerator.generateResult:" - + sqlEx.getMessage(), sqlEx); - } finally { - IQueryResultInstanceDao resultInstanceDao = sfDAOFactory - .getPatientSetResultDAO(); - - if (errorFlag) { - resultInstanceDao.updatePatientSet(resultInstanceId, - QueryStatusTypeId.STATUSTYPE_ID_ERROR, 0); - } else { - resultInstanceDao.updatePatientSet(resultInstanceId, - QueryStatusTypeId.STATUSTYPE_ID_FINISHED, totalCount); - } - } - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder; + +import java.io.StringWriter; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.Map; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.util.db.JDBCUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; +import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; +import edu.harvard.i2b2.crc.datavo.i2b2result.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2result.DataType; +import edu.harvard.i2b2.crc.datavo.i2b2result.ResultEnvelopeType; +import edu.harvard.i2b2.crc.datavo.i2b2result.ResultType; + +public class QueryResultPatientAgeCountGenerator extends CRCDAO implements + IResultGenerator { + + @Override + public String getResults() { + return xmlResult; + } + + private String xmlResult = null; + + public static final String RESULT_NAME = "PATIENT_AGE_COUNT_XML"; + + @Override + public void generateResult(Map param) throws I2B2DAOException { + + SetFinderConnection sfConn = (SetFinderConnection) param + .get("SetFinderConnection"); + SetFinderDAOFactory sfDAOFactory = (SetFinderDAOFactory) param + .get("SetFinderDAOFactory"); + // String patientSetId = (String)param.get("PatientSetId"); + String queryInstanceId = (String) param.get("QueryInstanceId"); + String TEMP_DX_TABLE = (String) param.get("TEMP_DX_TABLE"); + String resultInstanceId = (String) param.get("ResultInstanceId"); + this + .setDbSchemaName(sfDAOFactory.getDataSourceLookup() + .getFullSchema()); + + String age1CountSql = "select count(distinct dx.patient_num) patient_count, '0-20' patient_range" + + " from " + + " " + + "patient_dimension pd ," + + " " + + " dx where pd.patient_num = dx.patient_num" + + " and pd.age_in_years_num between 0 and 20"; + + String age2CountSql = "select count(dx.patient_num) patient_count, '21-40' patient_range" + + " from " + + " " + + "patient_dimension pd ," + + " " + + " dx where pd.patient_num = dx.patient_num" + + " and pd.age_in_years_num between 21 and 40"; + + String age3CountSql = "select count(dx.patient_num) patient_count, '41-60' patient_range" + + " from " + + " " + + "patient_dimension pd ," + + " " + + " dx where pd.patient_num = dx.patient_num" + + " and pd.age_in_years_num between 41 and 60"; + + String age4CountSql = "select count(dx.patient_num) patient_count, '61-80' patient_range" + + " from " + + " " + + "patient_dimension pd ," + + " " + + " dx where pd.patient_num = dx.patient_num" + + " and pd.age_in_years_num between 61 and 80"; + + String age5CountSql = "select count(dx.patient_num) patient_count, '>80' patient_range" + + " from " + + " " + + "patient_dimension pd ," + + " " + + " dx where pd.patient_num = dx.patient_num" + + " and pd.age_in_years_num > 80"; + + String ageFinalCountSql = age1CountSql + "\n union all " + age2CountSql + + "\n union all " + age3CountSql + "\n union all " + + age4CountSql + "\n union all " + age5CountSql; + + boolean errorFlag = false; + int totalCount = 0; + try { + + String sqlFinal = ageFinalCountSql.replace("", this.getDbSchemaName() ); + sqlFinal = ageFinalCountSql.replace("", TEMP_DX_TABLE); + + log.debug("Executing[ " + ageFinalCountSql + " ]"); + PreparedStatement stmt = sfConn.prepareStatement(sqlFinal); + ResultSet resultSet = stmt.executeQuery(); + ResultType resultType = new ResultType(); + resultType.setName(RESULT_NAME); + while (resultSet.next()) { + String demoCount = resultSet.getString("patient_count"); + String raceCd = resultSet.getString("patient_range"); + DataType mdataType = new DataType(); + mdataType.setValue(demoCount); + mdataType.setColumn(raceCd); + mdataType.setType("int"); + resultType.getData().add(mdataType); + } + resultSet.close(); + stmt.close(); + edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory(); + BodyType bodyType = new BodyType(); + bodyType.getAny().add(of.createResult(resultType)); + ResultEnvelopeType resultEnvelop = new ResultEnvelopeType(); + resultEnvelop.setBody(bodyType); + + JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); + + StringWriter strWriter = new StringWriter(); + + jaxbUtil.marshaller(of.createI2B2ResultEnvelope(resultEnvelop), + strWriter); + + IXmlResultDao xmlResultDao = sfDAOFactory.getXmlResultDao(); + xmlResult = strWriter.toString(); + xmlResultDao.createQueryXmlResult(resultInstanceId, strWriter + .toString()); + + } catch (Exception sqlEx) { + log.error("QueryResultPatientAgeCountGenerator.generateResult:" + + sqlEx.getMessage(), sqlEx); + throw new I2B2DAOException( + "QueryResultPatientAgeCountGenerator.generateResult:" + + sqlEx.getMessage(), sqlEx); + } finally { + IQueryResultInstanceDao resultInstanceDao = sfDAOFactory + .getPatientSetResultDAO(); + + if (errorFlag) { + resultInstanceDao.updatePatientSet(resultInstanceId, + QueryStatusTypeId.STATUSTYPE_ID_ERROR, 0); + } else { + resultInstanceDao.updatePatientSet(resultInstanceId, + QueryStatusTypeId.STATUSTYPE_ID_FINISHED, totalCount); + } + } + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientCountGenerator.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientCountGenerator.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientCountGenerator.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientCountGenerator.java index 4b045af5..76134c5b --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientCountGenerator.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientCountGenerator.java @@ -1,147 +1,147 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder; - -import java.io.StringWriter; -import java.util.List; -import java.util.Map; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.db.QtQueryResultType; -import edu.harvard.i2b2.crc.datavo.i2b2result.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2result.DataType; -import edu.harvard.i2b2.crc.datavo.i2b2result.ResultEnvelopeType; -import edu.harvard.i2b2.crc.datavo.i2b2result.ResultType; - -public class QueryResultPatientCountGenerator extends CRCDAO implements - IResultGenerator { - - @Override - public String getResults() { - return xmlResult; - } - - private String xmlResult = null; - - @Override - public void generateResult(Map param) throws I2B2DAOException { - - SetFinderConnection sfConn = (SetFinderConnection) param - .get("SetFinderConnection"); - SetFinderDAOFactory sfDAOFactory = (SetFinderDAOFactory) param - .get("SetFinderDAOFactory"); - // String patientSetId = (String)param.get("PatientSetId"); - String queryInstanceId = (String) param.get("QueryInstanceId"); - String TEMP_DX_TABLE = (String) param.get("TEMP_DX_TABLE"); - String resultInstanceId = (String) param.get("ResultInstanceId"); - List roles = (List) param.get("Roles"); - int obfucatedRecordCount = (Integer) param.get("ObfuscatedRecordCount"); - int recordCount = (Integer) param.get("RecordCount"); - String resultTypeName = (String) param.get("ResultOptionName"); - Boolean queryWithoutTempTableFlag = (Boolean) param - .get("QueryWithoutTempTableFlag"); - boolean dataObfusRole = (Boolean)param.get("ObfuscatedRoleFlag"); - - this.setDbSchemaName(sfDAOFactory.getDataSourceLookup().getFullSchema()); - - boolean errorFlag = false; - int patientCount = 0, realPatientCount = 0; - - try { - - if (dataObfusRole) { - patientCount = obfucatedRecordCount; - realPatientCount = recordCount; - } else { - patientCount = recordCount; - realPatientCount = recordCount; - obfucatedRecordCount = recordCount; - } - - int i = 0; - ResultType resultType = new ResultType(); - resultType.setName("PATIENT_COUNT_XML"); - DataType mdataType = new DataType(); - mdataType.setValue(String.valueOf(patientCount)); - mdataType.setColumn("patient_count"); - mdataType.setType("int"); - resultType.getData().add(mdataType); - - edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory(); - BodyType bodyType = new BodyType(); - bodyType.getAny().add(of.createResult(resultType)); - ResultEnvelopeType resultEnvelope = new ResultEnvelopeType(); - resultEnvelope.setBody(bodyType); - - JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); - - StringWriter strWriter = new StringWriter(); - - jaxbUtil.marshaller(of.createI2B2ResultEnvelope(resultEnvelope), - strWriter); - - IXmlResultDao xmlResultDao = sfDAOFactory.getXmlResultDao(); - xmlResult = strWriter.toString(); - xmlResultDao.createQueryXmlResult(resultInstanceId, - strWriter.toString()); - } catch (Exception sqlEx) { - log.error( - "QueryResultPatientCountGenerator.generateResult:" - + sqlEx.getMessage(), sqlEx); - throw new I2B2DAOException( - "QueryResultPatientCountGenerator.generateResult:" - + sqlEx.getMessage(), sqlEx); - } finally { - IQueryResultInstanceDao resultInstanceDao = sfDAOFactory - .getPatientSetResultDAO(); - - if (errorFlag) { - resultInstanceDao.updatePatientSet(resultInstanceId, - QueryStatusTypeId.STATUSTYPE_ID_ERROR, 0); - } else { - String obfusMethod = "", description = null; - if (dataObfusRole) { - obfusMethod = IQueryResultInstanceDao.OBSUBTOTAL; - // add () to the result type description - // read the description from result type - } - - IQueryResultTypeDao resultTypeDao = sfDAOFactory - .getQueryResultTypeDao(); - List resultTypeList = resultTypeDao - .getQueryResultTypeByName(resultTypeName, roles); - - String queryName = sfDAOFactory - .getQueryMasterDAO() - .getQueryDefinition( - sfDAOFactory - .getQueryInstanceDAO() - .getQueryInstanceByInstanceId( - queryInstanceId) - .getQtQueryMaster().getQueryMasterId()) - .getName(); - description = resultTypeList.get(0).getDescription() - + " for \"" + queryName + "\""; - - resultInstanceDao.updatePatientSet(resultInstanceId, - QueryStatusTypeId.STATUSTYPE_ID_FINISHED, "", - obfucatedRecordCount, realPatientCount, obfusMethod); - - resultInstanceDao.updateResultInstanceDescription( - resultInstanceId, description); - } - } - } - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder; + +import java.io.StringWriter; +import java.util.List; +import java.util.Map; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; +import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; +import edu.harvard.i2b2.crc.datavo.db.QtQueryResultType; +import edu.harvard.i2b2.crc.datavo.i2b2result.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2result.DataType; +import edu.harvard.i2b2.crc.datavo.i2b2result.ResultEnvelopeType; +import edu.harvard.i2b2.crc.datavo.i2b2result.ResultType; + +public class QueryResultPatientCountGenerator extends CRCDAO implements + IResultGenerator { + + @Override + public String getResults() { + return xmlResult; + } + + private String xmlResult = null; + + @Override + public void generateResult(Map param) throws I2B2DAOException { + + SetFinderConnection sfConn = (SetFinderConnection) param + .get("SetFinderConnection"); + SetFinderDAOFactory sfDAOFactory = (SetFinderDAOFactory) param + .get("SetFinderDAOFactory"); + // String patientSetId = (String)param.get("PatientSetId"); + String queryInstanceId = (String) param.get("QueryInstanceId"); + String TEMP_DX_TABLE = (String) param.get("TEMP_DX_TABLE"); + String resultInstanceId = (String) param.get("ResultInstanceId"); + List roles = (List) param.get("Roles"); + int obfucatedRecordCount = (Integer) param.get("ObfuscatedRecordCount"); + int recordCount = (Integer) param.get("RecordCount"); + String resultTypeName = (String) param.get("ResultOptionName"); + Boolean queryWithoutTempTableFlag = (Boolean) param + .get("QueryWithoutTempTableFlag"); + boolean dataObfusRole = (Boolean)param.get("ObfuscatedRoleFlag"); + + this.setDbSchemaName(sfDAOFactory.getDataSourceLookup().getFullSchema()); + + boolean errorFlag = false; + int patientCount = 0, realPatientCount = 0; + + try { + + if (dataObfusRole) { + patientCount = obfucatedRecordCount; + realPatientCount = recordCount; + } else { + patientCount = recordCount; + realPatientCount = recordCount; + obfucatedRecordCount = recordCount; + } + + int i = 0; + ResultType resultType = new ResultType(); + resultType.setName("PATIENT_COUNT_XML"); + DataType mdataType = new DataType(); + mdataType.setValue(String.valueOf(patientCount)); + mdataType.setColumn("patient_count"); + mdataType.setType("int"); + resultType.getData().add(mdataType); + + edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory(); + BodyType bodyType = new BodyType(); + bodyType.getAny().add(of.createResult(resultType)); + ResultEnvelopeType resultEnvelope = new ResultEnvelopeType(); + resultEnvelope.setBody(bodyType); + + JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); + + StringWriter strWriter = new StringWriter(); + + jaxbUtil.marshaller(of.createI2B2ResultEnvelope(resultEnvelope), + strWriter); + + IXmlResultDao xmlResultDao = sfDAOFactory.getXmlResultDao(); + xmlResult = strWriter.toString(); + xmlResultDao.createQueryXmlResult(resultInstanceId, + strWriter.toString()); + } catch (Exception sqlEx) { + log.error( + "QueryResultPatientCountGenerator.generateResult:" + + sqlEx.getMessage(), sqlEx); + throw new I2B2DAOException( + "QueryResultPatientCountGenerator.generateResult:" + + sqlEx.getMessage(), sqlEx); + } finally { + IQueryResultInstanceDao resultInstanceDao = sfDAOFactory + .getPatientSetResultDAO(); + + if (errorFlag) { + resultInstanceDao.updatePatientSet(resultInstanceId, + QueryStatusTypeId.STATUSTYPE_ID_ERROR, 0); + } else { + String obfusMethod = "", description = null; + if (dataObfusRole) { + obfusMethod = IQueryResultInstanceDao.OBSUBTOTAL; + // add () to the result type description + // read the description from result type + } + + IQueryResultTypeDao resultTypeDao = sfDAOFactory + .getQueryResultTypeDao(); + List resultTypeList = resultTypeDao + .getQueryResultTypeByName(resultTypeName, roles); + + String queryName = sfDAOFactory + .getQueryMasterDAO() + .getQueryDefinition( + sfDAOFactory + .getQueryInstanceDAO() + .getQueryInstanceByInstanceId( + queryInstanceId) + .getQtQueryMaster().getQueryMasterId()) + .getName(); + description = resultTypeList.get(0).getDescription() + + " for \"" + queryName + "\""; + + resultInstanceDao.updatePatientSet(resultInstanceId, + QueryStatusTypeId.STATUSTYPE_ID_FINISHED, "", + obfucatedRecordCount, realPatientCount, obfusMethod); + + resultInstanceDao.updateResultInstanceDescription( + resultInstanceId, description); + } + } + } + + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientDownload.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientDownload.java similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientDownload.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientDownload.java index 7114898f..2b6d3268 100644 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientDownload.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientDownload.java @@ -1,852 +1,852 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder; - -import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; -import java.io.File; -import java.io.FileOutputStream; -import edu.harvard.i2b2.crc.dao.xml.ValueExporter; -/** - * To add Length of Stay (This is for Oracle and Postgresl) For Sql Server change the sql statement from (DX to #DX) - * - * Add a entry to QT_BREAKDOWN_PATH - * NAME = LENGTH_OF_STAY - * VALUE = select length_of_stay as patient_range, count(distinct a.PATIENT_num) as patient_count from visit_dimension a, DX b where a.patient_num = b.patient_num group by a.length_of_stay order by 1 - * - * Add a entry to QT_QUERY_RESULT_TYPE - * RESULT_TYPE_ID = 13 (Or any unused number) - * NAME = LENGTH_OF_STAY - * DESCRIPTION = Length of Dtay Brealdown - * DISPLAY_TYPE_ID = CATNUM - * VISUAL_ATTRIBUTE_TYPE_ID = LA - * - * Add a new in CRCApplicationContext.xml - * - * - * LENGTH_OF_STAY - * - * edu.harvard.i2b2.crc.dao.setfinder.QueryResultPatientSQLCountGenerator - * - * - */ - -import java.io.PrintWriter; -import java.io.StringWriter; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.security.SecureRandom; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.text.DateFormat; -import java.time.LocalDate; -import java.time.ZonedDateTime; -import java.time.format.DateTimeFormatter; -import java.time.format.FormatStyle; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import jakarta.xml.bind.JAXBContext; -import jakarta.xml.bind.JAXBException; -import jakarta.xml.bind.Unmarshaller; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.util.db.JDBCUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.dao.EmailUtil; -import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.ProcessTimingReportUtil; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.db.QtQueryBreakdownType; -import edu.harvard.i2b2.crc.datavo.db.QtQueryMaster; -import edu.harvard.i2b2.crc.datavo.db.QtQueryResultType; -import edu.harvard.i2b2.crc.datavo.i2b2result.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2result.DataType; -import edu.harvard.i2b2.crc.datavo.i2b2result.ResultEnvelopeType; -import edu.harvard.i2b2.crc.datavo.i2b2result.ResultType; -import edu.harvard.i2b2.crc.datavo.pm.UserType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.PanelType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultOutputOptionType; -import edu.harvard.i2b2.crc.delegate.pm.CallPMUtil; -import edu.harvard.i2b2.crc.opencsv.CSVWriter; -import edu.harvard.i2b2.crc.opencsv.ResultSetHelperService; -import edu.harvard.i2b2.crc.util.LogTimingUtil; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; -import edu.harvard.i2b2.crc.dao.xml.Item_orig; -import edu.harvard.i2b2.crc.dao.xml.Items; -import edu.harvard.i2b2.crc.dao.xml.ValueExport; -import net.lingala.zip4j.ZipFile; -//mport net.lingala.zip4j.ZipFile; -import net.lingala.zip4j.io.outputstream.ZipOutputStream; -import net.lingala.zip4j.model.ZipParameters; -import net.lingala.zip4j.model.enums.CompressionLevel; -import net.lingala.zip4j.model.enums.EncryptionMethod; -import java.io.StringReader; - -/** - * Setfinder's result genertor class. This class calculates patient break down - * for the result type. - * - * Calls the ontology to get the children for the result type and then - * calculates the patient count for each child of the result type. - */ -public class QueryResultPatientDownload extends CRCDAO implements IResultGenerator { - - protected final Log logesapi = LogFactory.getLog(getClass()); - - @Override - public String getResults() { - return xmlResult; - } - - private String xmlResult = null; - /** - * Function accepts parameter in Map. The patient count will be obfuscated - * if the user is OBFUS - */ - @Override - public void generateResult(Map param) throws CRCTimeOutException, - I2B2DAOException { - - - // mm create a csv in a folder - - - SetFinderConnection sfConn = (SetFinderConnection) param - .get("SetFinderConnection"); - SetFinderDAOFactory sfDAOFactory = (SetFinderDAOFactory) param - .get("SetFinderDAOFactory"); - - // String patientSetId = (String)param.get("PatientSetId"); - String queryInstanceId = (String) param.get("QueryInstanceId"); - String TEMP_DX_TABLE = (String) param.get("TEMP_DX_TABLE"); - String resultInstanceId = (String) param.get("ResultInstanceId"); - // String itemKey = (String) param.get("ItemKey"); - String resultTypeName = (String) param.get("ResultOptionName"); - - - //ZipOutputStream zipStream; - - //List filesToAdd = new List; - //(String) param.get("ResultFullName"); - - String processTimingFlag = (String) param.get("ProcessTimingFlag"); - String projectId = (String) param.get("projectId"); - int obfuscatedRecordCount = (Integer) param.get("ObfuscatedRecordCount"); - int recordCount = (Integer) param.get("RecordCount"); - int resultPriority = (Integer) param.get("ResultPriority"); - int transactionTimeout = (Integer) param.get("TransactionTimeout"); - boolean obfscDataRoleFlag = (Boolean)param.get("ObfuscatedRoleFlag"); - QueryDefinitionType queryDef = (QueryDefinitionType)param.get("queryDef"); - List panelList = (List)param.get("panelList"); - List resultOptionList = (List) param.get("resultOptionList"); - - boolean skipCSV = false; - if ((Boolean)param.get("SkipCSV") != null) - skipCSV = (Boolean)param.get("SkipCSV"); - ValueExporter valueExport ; - this - .setDbSchemaName(sfDAOFactory.getDataSourceLookup() - .getFullSchema()); - Map ontologyKeyMap = (Map) param.get("setFinderResultOntologyKeyMap"); - String serverType = (String) param.get("ServerType"); - // CallOntologyUtil ontologyUtil = (CallOntologyUtil) param - // .get("CallOntologyUtil"); - List roles = (List) param.get("Roles"); - String tempTableName = ""; - PreparedStatement stmt = null; - boolean errorFlag = false, timeoutFlag = false; - //String itemKey = ""; - - String letter = ""; - int actualTotal = 0, obsfcTotal = 0; - - String logFile = ""; - int rowCount = 0; - QtQueryMaster queryMaster = sfDAOFactory.getQueryMasterDAO().getQueryDefinition(sfDAOFactory.getQueryInstanceDAO().getQueryInstanceByInstanceId(queryInstanceId).getQtQueryMaster().getQueryMasterId()); - UserType user = null; - //zip up if priority is 999 - if (resultPriority == 999) - { - - - } else { - - try { - LogTimingUtil logTimingUtil = new LogTimingUtil(); - logTimingUtil.setStartTime(); - - LogTimingUtil subLogTimingUtil = new LogTimingUtil(); - subLogTimingUtil.setStartTime(); - - user = CallPMUtil.getUserFromResponse(queryMaster.getPmXml()); - - param.put("QueryStartDate", queryMaster.getCreateDate()); - param.put("FullName", user.getFullName()); - param.put("UserName", user.getUserName()); - param.put("resultInstanceId", resultInstanceId); - String exportItemXml = getItemKeyFromResultType(sfDAOFactory, resultTypeName); - - //get break down count sigma from property file - - ResultType resultType = new ResultType(); - resultType.setName(resultTypeName); - //stmt = sfConn.prepareStatement(itemCountSql); - - CancelStatementRunner csr = new CancelStatementRunner(stmt, - transactionTimeout); - Thread csrThread = new Thread(csr); - csrThread.start(); - - //String sqlFinal = ""; - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - - valueExport = new ValueExporter(); - - - String workDir = ""; - - String workDirStr = qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.workfolder"); - if (workDirStr != null) { - workDir = workDirStr; // + File.separatorChar + (String) param.get("ResultRandom") + File.separatorChar; - } - - try { - valueExport = JaxbXmlToObj(exportItemXml); - } catch (Exception e) - { - edu.harvard.i2b2.crc.dao.xml.File item = new edu.harvard.i2b2.crc.dao.xml.File(); - if (qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.filename").endsWith(".zip")) { - item.setFilename(workDir+qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.filename").replace(".zip", ".csv")); - item.setFilename(processFilename(item.getFilename(), param)); - - valueExport.setZipFilename(processFilename(workDir+qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.filename"), param)); - }else { - item.setFilename(workDir+qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.filename")); - item.setFilename(processFilename(item.getFilename(), param)); - } - item.setQuery(exportItemXml); - item.setSeperatorCharacter(qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.defaultseperator")); - valueExport.setFile(new edu.harvard.i2b2.crc.dao.xml.File[] {item}); - valueExport.setZipEncryptMethod(qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.zipencryptmethod")); - - } - JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); - //ValueExport valueExport = (ValueExport) jaxbUtil - // .unMashallFromString(exportItemXml).getValue(); - - letter = valueExport.getDataManagerEmailMessage(); - - - String letterFilenameStr = valueExport.getDataManagerEmailMessage(); - String letterFilename = null; - - String zipFileNameStr = valueExport.getZipFilename();//.getZipFilename(); - String zipFileName = null; - if (zipFileNameStr != null) { - - zipFileName = workDirStr + zipFileNameStr; - - zipFileName = processFilename(zipFileName, param); - - - } - - for (edu.harvard.i2b2.crc.dao.xml.File item: valueExport.getFile()) { - /* - * JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); - RequestMessageType reqMsgType = (RequestMessageType) jaxbUtil - .unMashallFromString(xml).getValue(); - System.out.println(reqMsgType.getMessageHeader().getMessageControlId()); - JAXBUnWrapHelper unWrapHelper = new JAXBUnWrapHelper(); - QueryDefinitionRequestType queryDefinitionType = (QueryDefinitionRequestType) unWrapHelper - .getObjectByClass( - reqMsgType.getMessageBody().getAny(), - edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionRequestType.class); - System.out.println("query namef" - + queryDefinitionType.getQueryDefinition().getQueryName()); - */ - - Path p = Paths.get(item.getFilename()); - letterFilename = workDirStr + p.getParent() + File.separator + "Letter.txt"; - - letterFilename = processFilename(letterFilename, param); - - - - if (item.getQuery().contains("{{{DX}}}")) - item.setQuery(item.getQuery().replaceAll("\\{\\{\\{DX\\}\\}\\}", TEMP_DX_TABLE)); - if (item.getQuery().contains("{{{FULL_SCHEMA}}}")) - item.setQuery(item.getQuery().replaceAll("\\{\\{\\{FULL_SCHEMA\\}\\}\\}", this.getDbSchemaName())); - - stmt = sfConn.prepareStatement(item.getQuery()); - stmt.setQueryTimeout(transactionTimeout); - logesapi.debug("Executing count sql [" + item.getQuery() + "]"); - - // - subLogTimingUtil.setStartTime(); - ResultSet resultSet = stmt.executeQuery(); - - //String fileName = "/tmp/"+ projectId +"output"+resultInstanceId + ".csv"; - //automatically compression if destination file extension is ".zip" or ".gz" - - char separator = ','; - char escapechar = '"'; - char lineEnd = '\n'; - String userName = ""; - char quotechar = '"'; - String fileName = ""; - int fetchSize = 50000; - int maxFetchRows = -1; - String separatorStr = qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.defaultseperator"); - if (separatorStr != null) { - separator = getChar(separatorStr); - } - if (item.getSeperatorCharacter() != null) - separator = getChar(item.getSeperatorCharacter()); - - String quotecharStr = qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.defaultquotechar"); - if (quotecharStr != null) { - quotechar = getChar(quotecharStr); - } - String escapecharStr = qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.defaultescapecharacter"); - if (escapecharStr != null) { - escapechar = getChar(escapecharStr); - } - String lineEndStr = qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.defaultlineend"); - if (lineEndStr != null) { - lineEnd = getChar(lineEndStr); - } - - String fileNameStr = qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.filename"); - if (fileNameStr != null) { - fileName = fileNameStr; - } - if (item.getFilename() != null) - fileName = workDir + item.getFilename(); - - String fetchSizeStr = qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.resultfetchsize"); - if (fetchSizeStr != null) { - fetchSize = Integer.parseInt(fetchSizeStr); - } - String maxFetchRowsStr = qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.maxfetchrows"); - if (maxFetchRowsStr != null) { - maxFetchRows = Integer.parseInt(maxFetchRowsStr); - } - - fileName = processFilename(fileName, param); - - /*fileName = fileName.replaceAll("\\{\\{\\{USER_NAME\\}\\}\\}", userName); - fileName = fileName.replaceAll("\\{\\{\\{FULL_NAME\\}\\}\\}", resultFullName); - fileName = fileName.replaceAll("\\{\\{\\{PROJECT_ID\\}\\}\\}", projectId.substring(1, projectId.length()-1)); - //fileName = fileName.replaceAll("\\{\\{\\{RESULT_INSTANCE_ID\\}\\}\\}", resultInstanceId); - fileName = fileName.replaceAll("\\{\\{\\{QUERY_NAME\\}\\}\\}", sanitizeFilename(queryDef.getQueryName())); - fileName = fileName.replaceAll("\\{\\{\\{QUERY_MASTER_ID\\}\\}\\}", sanitizeFilename(queryDef.getQueryId())); - - while (fileName.contains("{{{RANDOM_")) - { - - try { - int start = fileName.indexOf("{{{RANDOM_"); - int end = fileName.indexOf("}}}", start); - int size = Integer.parseInt(fileName.substring(start+10, end)); - - //SecureRandom random = new SecureRandom(); - //fileName = fileName.replaceAll("\\{\\{\\{RANDOM_"+size+"\\}\\}\\}", String.valueOf(random.nextInt(size))); - fileName = fileName.replaceAll("\\{\\{\\{RANDOM_"+size+"\\}\\}\\}", (String) param.get("ResultRandom")); - - } catch (Exception e) {} - - } - // Deal with dates - while (fileName.contains("{{{DATE_")) - { - - try { - int start = fileName.indexOf("{{{DATE_"); - int end = fileName.indexOf("}}}", start); - String date = fileName.substring(start+8, end); - - //DateTimeFormatter formatter = DateTimeFormatter.ofPattern(date); - //fileName = fileName.replaceAll("\\{\\{\\{DATE_"+date+"\\}\\}\\}", LocalDate.now().format(formatter)); - - DateTimeFormatter formatter = DateTimeFormatter.ofPattern(date); - fileName = fileName.replaceAll("\\{\\{\\{DATE_"+date+"\\}\\}\\}", ((LocalDate) param.get("ResultDate")).format(formatter)); - //(String) param.get("ResultDate")); - - } catch (Exception e) {} - - } - */ - - - - if (skipCSV == false) { - boolean async = true; - - File file = new File(fileName); - file.getParentFile().mkdirs(); - try (CSVWriter writer = new CSVWriter(fileName, separator, quotechar, escapechar, Character.toString(lineEnd), recordCount)) { - //CSVWriter(fileName)) { - - - //Define fetch size(default as 30000 rows), higher to be faster performance but takes more memory - ResultSetHelperService.RESULT_FETCH_SIZE=fetchSize; - //Define MAX extract rows, -1 means unlimited. - ResultSetHelperService.MAX_FETCH_ROWS=maxFetchRows; - - - - //String lockoutQueryCountStr = qpUtil - // .getCRCPropertyValue("edu.harvard.i2b2.crc.lockout.setfinderquery.count"); - writer.setAsyncMode(async); - rowCount = writer.writeAll(resultSet, true); - - logFile += writer.getLog(); - resultSet.close(); - } - if (csr.getSqlFinishedFlag()) { - timeoutFlag = true; - throw new CRCTimeOutException("The query was canceled."); - } - - } - } - - edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory(); - BodyType bodyType = new BodyType(); - bodyType.getAny().add(of.createResult(resultType)); - ResultEnvelopeType resultEnvelop = new ResultEnvelopeType(); - resultEnvelop.setBody(bodyType); - - //JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); - - StringWriter strWriter = new StringWriter(); - subLogTimingUtil.setStartTime(); - jaxbUtil.marshaller(of.createI2B2ResultEnvelope(resultEnvelop), - strWriter); - subLogTimingUtil.setEndTime(); - //tm.begin(); - /* - IXmlResultDao xmlResultDao = sfDAOFactory.getXmlResultDao(); - xmlResult = strWriter.toString(); - if (resultInstanceId != null) - xmlResultDao.createQueryXmlResult(resultInstanceId, strWriter - .toString()); - */ - // - if (processTimingFlag != null) { - if (!processTimingFlag.trim().equalsIgnoreCase(ProcessTimingReportUtil.NONE) ) { - ProcessTimingReportUtil ptrUtil = new ProcessTimingReportUtil(sfDAOFactory.getDataSourceLookup()); - if (processTimingFlag.trim().equalsIgnoreCase(ProcessTimingReportUtil.DEBUG) ) { - ptrUtil.logProcessTimingMessage(queryInstanceId, ptrUtil.buildProcessTiming(subLogTimingUtil, "JAXB - " + resultTypeName , "")); - } - logTimingUtil.setEndTime(); - ptrUtil.logProcessTimingMessage(queryInstanceId, ptrUtil.buildProcessTiming(logTimingUtil, "BUILD - " + resultTypeName , "")); - } - } - //} - //tm.commit(); - - //Process XIP File - if (letter != null && letterFilename != null) { - - File path = new File(letterFilename); - path.getParentFile().mkdirs(); - // Declaring the print writer with path - PrintWriter pw = new PrintWriter(path); - - - //queryMaster. - if (zipFileName != null) { - letter = letter.replaceAll("\\{\\{\\{ZIP_FILENAME_WIN\\}\\}\\}", zipFileName.replaceAll("/", "\\\\")); - letter = letter.replaceAll("\\{\\{\\{ZIP_FILENAME_MAC\\}\\}\\}", zipFileName.replaceAll("\\\\", "/")); - letter = letter.replaceAll("\\{\\{\\{ZIP_PASSWORD\\}\\}\\}", valueExport.getZipPassword()); - } - // Now calling writer() method with string - pw.write(processFilename(letter, param )); - - // Flushing the print writer - pw.flush(); - - // Lastly closing the printwriter - // using the close() method - pw.close(); - } - - - //String requesterLetter = valueExport.getDataManagerEmailMessage(); - - - if (letter != null && qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.datamanageremail") != null) { - - letter = processFilename(letter, param); - - //Send out email letter - EmailUtil email = new EmailUtil(); - IQueryResultTypeDao resultTypeDao = sfDAOFactory.getQueryResultTypeDao(); - String requestedData = "\n"; - String finalResultOutput = ""; - - for (ResultOutputOptionType resultOutputOption : resultOptionList) { - String resultName = resultOutputOption.getName() - .toUpperCase(); - List resultTypeList = resultTypeDao - .getQueryResultTypeByName(resultName, null); - if (resultTypeList.size() > 0) { - requestedData += resultTypeList.get(0).getDescription() + ", "; - finalResultOutput = resultTypeList.get(0).getName().toUpperCase(); - } - } - letter = letter.replaceAll("\\{\\{\\{REQUESTED_DATA_TYPE\\}\\}\\}",requestedData); - if (zipFileName != null && skipCSV == false && resultTypeName.equals(finalResultOutput)) { - - File file = new File(zipFileName); - file.getParentFile().mkdirs(); - String zipencryptMethod = "NONE"; - if ( valueExport.getZipEncryptMethod() != null) { - zipencryptMethod = valueExport.getZipEncryptMethod(); - } - - ZipParameters zipParameters = new ZipParameters(); - if (!zipencryptMethod.equals("NONE")) { - zipParameters.setEncryptFiles(true); - zipParameters.setCompressionLevel(CompressionLevel.MAXIMUM); - if (zipencryptMethod.equals("AES")) - zipParameters.setEncryptionMethod(EncryptionMethod.AES); - else if (zipencryptMethod.equals("STANARD")) - zipParameters.setEncryptionMethod(EncryptionMethod.ZIP_STANDARD); - else - zipParameters.setEncryptionMethod(EncryptionMethod.NONE); - - } - //zipParameters.setFileNameInZip( workDir + "*.*" ); - //zipParameters.setPassword("password"); - - //zipStream = new ZipOutputStream(buff); - //zip. - //ZipFile zipfile = new ZipFile(fileName + (extName.equals(null) ? "" : "." + default_ext), "password".toCharArray()); - - - if (zipParameters.getEncryptionMethod().equals(EncryptionMethod.NONE)) - new ZipFile(zipFileName).addFolder(new File(workDir),zipParameters); - //zipStream = new ZipOutputStream(new FileOutputStream(new File(zipFileName))); - else - new ZipFile(zipFileName,valueExport.getZipPassword().toCharArray()).addFolder(new File(workDir),zipParameters); - - - // zipStream = new ZipOutputStream(new FileOutputStream(new File(zipFileName)) - // , valueExport.getZip_password().toCharArray()); - - //zipStream.putNextEntry(zipParameters); - } - - if ((resultTypeName.equals(finalResultOutput)) - && (qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.smtp.enabled").equalsIgnoreCase("true")) ) - - email.email(qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.datamanageremail"), qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.datamanageremail"), "i2b2 Data Export - " + queryDef.getQueryName(), letter); - } - } catch (SQLException sqlEx) { - // catch oracle query timeout error ORA-01013 - if (sqlEx.toString().indexOf("ORA-01013") > -1) { - timeoutFlag = true; - throw new CRCTimeOutException(sqlEx.getMessage(), sqlEx); - } - if (sqlEx.getMessage().indexOf("The query was canceled.") > -1) { - timeoutFlag = true; - throw new CRCTimeOutException(sqlEx.getMessage(), sqlEx); - } - if (sqlEx.getMessage().indexOf("timed out") > -1) { - timeoutFlag = true; - throw new CRCTimeOutException(sqlEx.getMessage(), sqlEx); - } - errorFlag = true; - log.error("Error while executing sql", sqlEx); - throw new I2B2DAOException("Error while executing sql", sqlEx); - } catch (Exception sqlEx) { - - errorFlag = true; - log.error("QueryResultPatientSetGenerator.generateResult:" - + sqlEx.getMessage(), sqlEx); - throw new I2B2DAOException( - "QueryResultPatientSetGenerator.generateResult:" - + sqlEx.getMessage(), sqlEx); - } finally { - - if (resultInstanceId != null) { - IQueryResultInstanceDao resultInstanceDao = sfDAOFactory - .getPatientSetResultDAO(); - - if (errorFlag) { - resultInstanceDao.updatePatientSet(resultInstanceId, - QueryStatusTypeId.STATUSTYPE_ID_ERROR, 0); - } else { - // set the setsize and the description of the result instance if - // the user role is obfuscated - if (timeoutFlag == false) { // check if the query completed - try { - // tm.begin(); - - String obfusMethod = "", description = null; - if (obfscDataRoleFlag) { - obfusMethod = IQueryResultInstanceDao.OBSUBTOTAL; - // add () to the result type description - // read the description from result type - - } else { - obfuscatedRecordCount = recordCount; - } - IQueryResultTypeDao resultTypeDao = sfDAOFactory.getQueryResultTypeDao(); - List resultTypeList = resultTypeDao - .getQueryResultTypeByName(resultTypeName, roles); - - // add "(Obfuscated)" in the description - //description = resultTypeList.get(0) - // .getDescription() - // + " (Obfuscated) "; - String queryName = sfDAOFactory.getQueryMasterDAO().getQueryDefinition( - sfDAOFactory.getQueryInstanceDAO().getQueryInstanceByInstanceId(queryInstanceId).getQtQueryMaster().getQueryMasterId()).getName(); - - - - resultInstanceDao.updatePatientSet(resultInstanceId, - QueryStatusTypeId.STATUSTYPE_ID_FINISHED, null, - //obsfcTotal, - obfuscatedRecordCount, recordCount, obfusMethod); - - - ResultType resultType = new ResultType(); - resultType.setName(resultTypeName); - DataType mdataType = new DataType(); - mdataType.setValue(String.valueOf(recordCount)); - mdataType.setColumn("PatientCount"); - mdataType.setType("int"); - resultType.setName(resultTypeName); - mdataType = new DataType(); - mdataType.setValue(String.valueOf(rowCount)); - mdataType.setColumn("RowCount"); - mdataType.setType("int"); - resultType.getData().add(mdataType); - mdataType = new DataType(); - mdataType.setValue(letter); - mdataType.setColumn("RequestLetter"); - mdataType.setType("string"); - mdataType = new DataType(); - mdataType.setValue(String.valueOf(logFile)); - mdataType.setColumn("Log"); - mdataType.setType("string"); - - resultType.getData().add(mdataType); - mdataType = new DataType(); - mdataType.setValue(sfDAOFactory.getQueryInstanceDAO().getQueryInstanceByInstanceId(queryInstanceId).getQtQueryMaster().getQueryMasterId()); - mdataType.setColumn("QueryMasterID"); - mdataType.setType("string"); - resultType.getData().add(mdataType); - mdataType = new DataType(); - - edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory(); - BodyType bodyType = new BodyType(); - bodyType.getAny().add(of.createResult(resultType)); - ResultEnvelopeType resultEnvelop = new ResultEnvelopeType(); - resultEnvelop.setBody(bodyType); - - //JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); - - StringWriter strWriter = new StringWriter(); - - //subLogTimingUtil.setStartTime(); - JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); - jaxbUtil.marshaller(of.createI2B2ResultEnvelope(resultEnvelop), - strWriter); - - IXmlResultDao xmlResultDao = sfDAOFactory.getXmlResultDao(); - xmlResult = strWriter.toString(); - if (resultInstanceId != null) - xmlResultDao.createQueryXmlResult(resultInstanceId, strWriter - .toString()); - - description = resultTypeList.get(0) - .getDescription() + " for \"" + queryName +"\""; - - // set the result instance description - resultInstanceDao.updateResultInstanceDescription( - resultInstanceId, description); - // tm.commit(); - - - } catch (SecurityException e) { - throw new I2B2DAOException( - "Failed to write obfuscated description " - + e.getMessage(), e); - } catch (IllegalStateException e) { - throw new I2B2DAOException( - "Failed to write obfuscated description " - + e.getMessage(), e); - } catch (JAXBUtilException e) { - throw new I2B2DAOException( - "Failed to write jaxb " - + e.getMessage(), e); - } - } - } - } - } - } - - } - - - public static ValueExporter JaxbXmlToObj(String xmlString) { - - ValueExporter val = new ValueExporter(); - ValueExporter resultDataSet = null ; - JAXBContext jaxbContext; - try { - jaxbContext = JAXBContext.newInstance(val.getClass()); - - Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); - - resultDataSet = (ValueExporter) jaxbUnmarshaller.unmarshal(new StringReader(xmlString)); - - //System.out.println(resultDataSet); - } - catch (JAXBException e) { - e.printStackTrace(); - } - return resultDataSet; - } - private String sanitizeFilename(String filename) - { - - return filename.replaceAll("[^a-zA-Z0-9.-]", "_"); - } - /* - private static final Pattern TAG_REGEX = Pattern.compile("{{{(.+?)}}}", Pattern.DOTALL); - - - private static List getTagValues(final String str) { - final List tagValues = new ArrayList(); - final Matcher matcher = TAG_REGEX.matcher(str); - while (matcher.find()) { - tagValues.add(matcher.group(1)); - } - return tagValues; - } - */ - private char getChar(String sTerminatedBy) - { - if ("\\t".equals(sTerminatedBy)) { - return ( '\t'); - } else if ("\\n".equals(sTerminatedBy)) { - return ( '\n'); - } else if ("\\r".equals(sTerminatedBy)) { - return ( '\r'); - } else if ("\\f".equals(sTerminatedBy)) { - return ( '\f'); - } else if (null == sTerminatedBy || "".equals(sTerminatedBy) || "\\0".equals(sTerminatedBy)) { - return ('\0'); - } else { - return ( sTerminatedBy.charAt(0)); - } - - } - - private String processFilename(String fileName, Map param) - { - - - // SetFinderDAOFactory sfDAOFactory = (SetFinderDAOFactory) param - // .get("SetFinderDAOFactory"); - - String projectId = (String) param.get("projectId"); - String queryInstanceId = (String) param.get("QueryInstanceId"); - QueryDefinitionType queryDef = (QueryDefinitionType)param.get("queryDef"); - String resultFullName = queryDef.getQueryName(); - //queryDef.getQueryId() - - // String resultFullName = sfDAOFactory.getQueryMasterDAO().getQueryDefinition( - // sfDAOFactory.getQueryInstanceDAO().getQueryInstanceByInstanceId(queryInstanceId).getQtQueryMaster().getQueryMasterId()).getName(); - // QtQueryMaster qtMaster = sfDAOFactory.getQueryInstanceDAO().getQueryInstanceByInstanceId(queryInstanceId).getQtQueryMaster(); - - fileName = fileName.replaceAll("\\{\\{\\{USER_NAME\\}\\}\\}",(String) param.get("UserName"));//queryDef.getUserId()); - fileName = fileName.replaceAll("\\{\\{\\{QUERY_STARTDATE\\}\\}\\}", ((java.sql.Timestamp) param.get("QueryStartDate")).toLocaleString());//sfDAOFactory.getQueryInstanceDAO().getQueryInstanceByInstanceId(queryInstanceId).getStartDate().toLocaleString()); - fileName = fileName.replaceAll("\\{\\{\\{QUERY_ENDDATE\\}\\}\\}", new Date().toLocaleString()); - fileName = fileName.replaceAll("\\{\\{\\{QUERY_RUNTIME\\}\\}\\}", Integer.toString(Math.toIntExact(new Date().getTime() - ((java.sql.Timestamp) param.get("QueryStartDate")).getTime())/1000)); - - fileName = fileName.replaceAll("\\{\\{\\{PATIENT_COUNT\\}\\}\\}", param.get("RecordCount").toString()); - fileName = fileName.replaceAll("\\{\\{\\{FULL_NAME\\}\\}\\}", (String) param.get("FullName")); - fileName = fileName.replaceAll("\\{\\{\\{PROJECT_ID\\}\\}\\}", projectId.substring(1, projectId.length()-1)); - fileName = fileName.replaceAll("\\{\\{\\{RESULT_INSTANCE_ID\\}\\}\\}", (String) param.get("resultFullName")); - fileName = fileName.replaceAll("\\{\\{\\{QUERY_NAME\\}\\}\\}", sanitizeFilename(resultFullName)); - fileName = fileName.replaceAll("\\{\\{\\{QUERY_MASTER_ID\\}\\}\\}", sanitizeFilename(queryInstanceId)); //qtMaster.getQueryMasterId())); - - while (fileName.contains("{{{RANDOM_")) - { - - try { - int start = fileName.indexOf("{{{RANDOM_"); - int end = fileName.indexOf("}}}", start); - int size = Integer.parseInt(fileName.substring(start+10, end)); - - //SecureRandom random = new SecureRandom(); - //fileName = fileName.replaceAll("\\{\\{\\{RANDOM_"+size+"\\}\\}\\}", String.valueOf(random.nextInt(size))); - fileName = fileName.replaceAll("\\{\\{\\{RANDOM_"+size+"\\}\\}\\}", (String) param.get("ResultRandom")); - - } catch (Exception e) {} - - } - // Deal with dates - while (fileName.contains("{{{DATE_")) - { - - try { - int start = fileName.indexOf("{{{DATE_"); - int end = fileName.indexOf("}}}", start); - String date = fileName.substring(start+8, end); - - //DateTimeFormatter formatter = DateTimeFormatter.ofPattern(date); - //fileName = fileName.replaceAll("\\{\\{\\{DATE_"+date+"\\}\\}\\}", LocalDate.now().format(formatter)); - - DateTimeFormatter formatter = DateTimeFormatter.ofPattern(date); - fileName = fileName.replaceAll("\\{\\{\\{DATE_"+date+"\\}\\}\\}", ((LocalDate) param.get("ResultDate")).format(formatter)); - //(String) param.get("ResultDate")); - - } catch (Exception e) {} - - } - - - return fileName; - } - - private String getItemKeyFromResultType(SetFinderDAOFactory sfDAOFactory, - String resultTypeKey) { - // - IQueryBreakdownTypeDao queryBreakdownTypeDao = sfDAOFactory - .getQueryBreakdownTypeDao(); - QtQueryBreakdownType queryBreakdownType = queryBreakdownTypeDao - .getBreakdownTypeByName(resultTypeKey); - String itemKey = queryBreakdownType.getValue(); - return itemKey; - } - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder; + +import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; +import java.io.File; +import java.io.FileOutputStream; +import edu.harvard.i2b2.crc.dao.xml.ValueExporter; +/** + * To add Length of Stay (This is for Oracle and Postgresl) For Sql Server change the sql statement from (DX to #DX) + * + * Add a entry to QT_BREAKDOWN_PATH + * NAME = LENGTH_OF_STAY + * VALUE = select length_of_stay as patient_range, count(distinct a.PATIENT_num) as patient_count from visit_dimension a, DX b where a.patient_num = b.patient_num group by a.length_of_stay order by 1 + * + * Add a entry to QT_QUERY_RESULT_TYPE + * RESULT_TYPE_ID = 13 (Or any unused number) + * NAME = LENGTH_OF_STAY + * DESCRIPTION = Length of Dtay Brealdown + * DISPLAY_TYPE_ID = CATNUM + * VISUAL_ATTRIBUTE_TYPE_ID = LA + * + * Add a new in CRCApplicationContext.xml + * + * + * LENGTH_OF_STAY + * + * edu.harvard.i2b2.crc.dao.setfinder.QueryResultPatientSQLCountGenerator + * + * + */ + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.security.SecureRandom; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.text.DateFormat; +import java.time.LocalDate; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.FormatStyle; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import jakarta.xml.bind.JAXBContext; +import jakarta.xml.bind.JAXBException; +import jakarta.xml.bind.Unmarshaller; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.util.db.JDBCUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.dao.EmailUtil; +import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.ProcessTimingReportUtil; +import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; +import edu.harvard.i2b2.crc.datavo.db.QtQueryBreakdownType; +import edu.harvard.i2b2.crc.datavo.db.QtQueryMaster; +import edu.harvard.i2b2.crc.datavo.db.QtQueryResultType; +import edu.harvard.i2b2.crc.datavo.i2b2result.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2result.DataType; +import edu.harvard.i2b2.crc.datavo.i2b2result.ResultEnvelopeType; +import edu.harvard.i2b2.crc.datavo.i2b2result.ResultType; +import edu.harvard.i2b2.crc.datavo.pm.UserType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.PanelType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultOutputOptionType; +import edu.harvard.i2b2.crc.delegate.pm.CallPMUtil; +import edu.harvard.i2b2.crc.opencsv.CSVWriter; +import edu.harvard.i2b2.crc.opencsv.ResultSetHelperService; +import edu.harvard.i2b2.crc.util.LogTimingUtil; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; +import edu.harvard.i2b2.crc.dao.xml.Item_orig; +import edu.harvard.i2b2.crc.dao.xml.Items; +import edu.harvard.i2b2.crc.dao.xml.ValueExport; +import net.lingala.zip4j.ZipFile; +//mport net.lingala.zip4j.ZipFile; +import net.lingala.zip4j.io.outputstream.ZipOutputStream; +import net.lingala.zip4j.model.ZipParameters; +import net.lingala.zip4j.model.enums.CompressionLevel; +import net.lingala.zip4j.model.enums.EncryptionMethod; +import java.io.StringReader; + +/** + * Setfinder's result genertor class. This class calculates patient break down + * for the result type. + * + * Calls the ontology to get the children for the result type and then + * calculates the patient count for each child of the result type. + */ +public class QueryResultPatientDownload extends CRCDAO implements IResultGenerator { + + protected final Log logesapi = LogFactory.getLog(getClass()); + + @Override + public String getResults() { + return xmlResult; + } + + private String xmlResult = null; + /** + * Function accepts parameter in Map. The patient count will be obfuscated + * if the user is OBFUS + */ + @Override + public void generateResult(Map param) throws CRCTimeOutException, + I2B2DAOException { + + + // mm create a csv in a folder + + + SetFinderConnection sfConn = (SetFinderConnection) param + .get("SetFinderConnection"); + SetFinderDAOFactory sfDAOFactory = (SetFinderDAOFactory) param + .get("SetFinderDAOFactory"); + + // String patientSetId = (String)param.get("PatientSetId"); + String queryInstanceId = (String) param.get("QueryInstanceId"); + String TEMP_DX_TABLE = (String) param.get("TEMP_DX_TABLE"); + String resultInstanceId = (String) param.get("ResultInstanceId"); + // String itemKey = (String) param.get("ItemKey"); + String resultTypeName = (String) param.get("ResultOptionName"); + + + //ZipOutputStream zipStream; + + //List filesToAdd = new List; + //(String) param.get("ResultFullName"); + + String processTimingFlag = (String) param.get("ProcessTimingFlag"); + String projectId = (String) param.get("projectId"); + int obfuscatedRecordCount = (Integer) param.get("ObfuscatedRecordCount"); + int recordCount = (Integer) param.get("RecordCount"); + int resultPriority = (Integer) param.get("ResultPriority"); + int transactionTimeout = (Integer) param.get("TransactionTimeout"); + boolean obfscDataRoleFlag = (Boolean)param.get("ObfuscatedRoleFlag"); + QueryDefinitionType queryDef = (QueryDefinitionType)param.get("queryDef"); + List panelList = (List)param.get("panelList"); + List resultOptionList = (List) param.get("resultOptionList"); + + boolean skipCSV = false; + if ((Boolean)param.get("SkipCSV") != null) + skipCSV = (Boolean)param.get("SkipCSV"); + ValueExporter valueExport ; + this + .setDbSchemaName(sfDAOFactory.getDataSourceLookup() + .getFullSchema()); + Map ontologyKeyMap = (Map) param.get("setFinderResultOntologyKeyMap"); + String serverType = (String) param.get("ServerType"); + // CallOntologyUtil ontologyUtil = (CallOntologyUtil) param + // .get("CallOntologyUtil"); + List roles = (List) param.get("Roles"); + String tempTableName = ""; + PreparedStatement stmt = null; + boolean errorFlag = false, timeoutFlag = false; + //String itemKey = ""; + + String letter = ""; + int actualTotal = 0, obsfcTotal = 0; + + String logFile = ""; + int rowCount = 0; + QtQueryMaster queryMaster = sfDAOFactory.getQueryMasterDAO().getQueryDefinition(sfDAOFactory.getQueryInstanceDAO().getQueryInstanceByInstanceId(queryInstanceId).getQtQueryMaster().getQueryMasterId()); + UserType user = null; + //zip up if priority is 999 + if (resultPriority == 999) + { + + + } else { + + try { + LogTimingUtil logTimingUtil = new LogTimingUtil(); + logTimingUtil.setStartTime(); + + LogTimingUtil subLogTimingUtil = new LogTimingUtil(); + subLogTimingUtil.setStartTime(); + + user = CallPMUtil.getUserFromResponse(queryMaster.getPmXml()); + + param.put("QueryStartDate", queryMaster.getCreateDate()); + param.put("FullName", user.getFullName()); + param.put("UserName", user.getUserName()); + param.put("resultInstanceId", resultInstanceId); + String exportItemXml = getItemKeyFromResultType(sfDAOFactory, resultTypeName); + + //get break down count sigma from property file + + ResultType resultType = new ResultType(); + resultType.setName(resultTypeName); + //stmt = sfConn.prepareStatement(itemCountSql); + + CancelStatementRunner csr = new CancelStatementRunner(stmt, + transactionTimeout); + Thread csrThread = new Thread(csr); + csrThread.start(); + + //String sqlFinal = ""; + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + + valueExport = new ValueExporter(); + + + String workDir = ""; + + String workDirStr = qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.workfolder"); + if (workDirStr != null) { + workDir = workDirStr; // + File.separatorChar + (String) param.get("ResultRandom") + File.separatorChar; + } + + try { + valueExport = JaxbXmlToObj(exportItemXml); + } catch (Exception e) + { + edu.harvard.i2b2.crc.dao.xml.File item = new edu.harvard.i2b2.crc.dao.xml.File(); + if (qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.filename").endsWith(".zip")) { + item.setFilename(workDir+qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.filename").replace(".zip", ".csv")); + item.setFilename(processFilename(item.getFilename(), param)); + + valueExport.setZipFilename(processFilename(workDir+qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.filename"), param)); + }else { + item.setFilename(workDir+qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.filename")); + item.setFilename(processFilename(item.getFilename(), param)); + } + item.setQuery(exportItemXml); + item.setSeperatorCharacter(qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.defaultseperator")); + valueExport.setFile(new edu.harvard.i2b2.crc.dao.xml.File[] {item}); + valueExport.setZipEncryptMethod(qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.zipencryptmethod")); + + } + JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); + //ValueExport valueExport = (ValueExport) jaxbUtil + // .unMashallFromString(exportItemXml).getValue(); + + letter = valueExport.getDataManagerEmailMessage(); + + + String letterFilenameStr = valueExport.getDataManagerEmailMessage(); + String letterFilename = null; + + String zipFileNameStr = valueExport.getZipFilename();//.getZipFilename(); + String zipFileName = null; + if (zipFileNameStr != null) { + + zipFileName = workDirStr + zipFileNameStr; + + zipFileName = processFilename(zipFileName, param); + + + } + + for (edu.harvard.i2b2.crc.dao.xml.File item: valueExport.getFile()) { + /* + * JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); + RequestMessageType reqMsgType = (RequestMessageType) jaxbUtil + .unMashallFromString(xml).getValue(); + System.out.println(reqMsgType.getMessageHeader().getMessageControlId()); + JAXBUnWrapHelper unWrapHelper = new JAXBUnWrapHelper(); + QueryDefinitionRequestType queryDefinitionType = (QueryDefinitionRequestType) unWrapHelper + .getObjectByClass( + reqMsgType.getMessageBody().getAny(), + edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionRequestType.class); + System.out.println("query namef" + + queryDefinitionType.getQueryDefinition().getQueryName()); + */ + + Path p = Paths.get(item.getFilename()); + letterFilename = workDirStr + p.getParent() + File.separator + "Letter.txt"; + + letterFilename = processFilename(letterFilename, param); + + + + if (item.getQuery().contains("{{{DX}}}")) + item.setQuery(item.getQuery().replaceAll("\\{\\{\\{DX\\}\\}\\}", TEMP_DX_TABLE)); + if (item.getQuery().contains("{{{FULL_SCHEMA}}}")) + item.setQuery(item.getQuery().replaceAll("\\{\\{\\{FULL_SCHEMA\\}\\}\\}", this.getDbSchemaName())); + + stmt = sfConn.prepareStatement(item.getQuery()); + stmt.setQueryTimeout(transactionTimeout); + logesapi.debug("Executing count sql [" + item.getQuery() + "]"); + + // + subLogTimingUtil.setStartTime(); + ResultSet resultSet = stmt.executeQuery(); + + //String fileName = "/tmp/"+ projectId +"output"+resultInstanceId + ".csv"; + //automatically compression if destination file extension is ".zip" or ".gz" + + char separator = ','; + char escapechar = '"'; + char lineEnd = '\n'; + String userName = ""; + char quotechar = '"'; + String fileName = ""; + int fetchSize = 50000; + int maxFetchRows = -1; + String separatorStr = qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.defaultseperator"); + if (separatorStr != null) { + separator = getChar(separatorStr); + } + if (item.getSeperatorCharacter() != null) + separator = getChar(item.getSeperatorCharacter()); + + String quotecharStr = qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.defaultquotechar"); + if (quotecharStr != null) { + quotechar = getChar(quotecharStr); + } + String escapecharStr = qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.defaultescapecharacter"); + if (escapecharStr != null) { + escapechar = getChar(escapecharStr); + } + String lineEndStr = qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.defaultlineend"); + if (lineEndStr != null) { + lineEnd = getChar(lineEndStr); + } + + String fileNameStr = qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.filename"); + if (fileNameStr != null) { + fileName = fileNameStr; + } + if (item.getFilename() != null) + fileName = workDir + item.getFilename(); + + String fetchSizeStr = qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.resultfetchsize"); + if (fetchSizeStr != null) { + fetchSize = Integer.parseInt(fetchSizeStr); + } + String maxFetchRowsStr = qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.maxfetchrows"); + if (maxFetchRowsStr != null) { + maxFetchRows = Integer.parseInt(maxFetchRowsStr); + } + + fileName = processFilename(fileName, param); + + /*fileName = fileName.replaceAll("\\{\\{\\{USER_NAME\\}\\}\\}", userName); + fileName = fileName.replaceAll("\\{\\{\\{FULL_NAME\\}\\}\\}", resultFullName); + fileName = fileName.replaceAll("\\{\\{\\{PROJECT_ID\\}\\}\\}", projectId.substring(1, projectId.length()-1)); + //fileName = fileName.replaceAll("\\{\\{\\{RESULT_INSTANCE_ID\\}\\}\\}", resultInstanceId); + fileName = fileName.replaceAll("\\{\\{\\{QUERY_NAME\\}\\}\\}", sanitizeFilename(queryDef.getQueryName())); + fileName = fileName.replaceAll("\\{\\{\\{QUERY_MASTER_ID\\}\\}\\}", sanitizeFilename(queryDef.getQueryId())); + + while (fileName.contains("{{{RANDOM_")) + { + + try { + int start = fileName.indexOf("{{{RANDOM_"); + int end = fileName.indexOf("}}}", start); + int size = Integer.parseInt(fileName.substring(start+10, end)); + + //SecureRandom random = new SecureRandom(); + //fileName = fileName.replaceAll("\\{\\{\\{RANDOM_"+size+"\\}\\}\\}", String.valueOf(random.nextInt(size))); + fileName = fileName.replaceAll("\\{\\{\\{RANDOM_"+size+"\\}\\}\\}", (String) param.get("ResultRandom")); + + } catch (Exception e) {} + + } + // Deal with dates + while (fileName.contains("{{{DATE_")) + { + + try { + int start = fileName.indexOf("{{{DATE_"); + int end = fileName.indexOf("}}}", start); + String date = fileName.substring(start+8, end); + + //DateTimeFormatter formatter = DateTimeFormatter.ofPattern(date); + //fileName = fileName.replaceAll("\\{\\{\\{DATE_"+date+"\\}\\}\\}", LocalDate.now().format(formatter)); + + DateTimeFormatter formatter = DateTimeFormatter.ofPattern(date); + fileName = fileName.replaceAll("\\{\\{\\{DATE_"+date+"\\}\\}\\}", ((LocalDate) param.get("ResultDate")).format(formatter)); + //(String) param.get("ResultDate")); + + } catch (Exception e) {} + + } + */ + + + + if (skipCSV == false) { + boolean async = true; + + File file = new File(fileName); + file.getParentFile().mkdirs(); + try (CSVWriter writer = new CSVWriter(fileName, separator, quotechar, escapechar, Character.toString(lineEnd), recordCount)) { + //CSVWriter(fileName)) { + + + //Define fetch size(default as 30000 rows), higher to be faster performance but takes more memory + ResultSetHelperService.RESULT_FETCH_SIZE=fetchSize; + //Define MAX extract rows, -1 means unlimited. + ResultSetHelperService.MAX_FETCH_ROWS=maxFetchRows; + + + + //String lockoutQueryCountStr = qpUtil + // .getCRCPropertyValue("edu.harvard.i2b2.crc.lockout.setfinderquery.count"); + writer.setAsyncMode(async); + rowCount = writer.writeAll(resultSet, true); + + logFile += writer.getLog(); + resultSet.close(); + } + if (csr.getSqlFinishedFlag()) { + timeoutFlag = true; + throw new CRCTimeOutException("The query was canceled."); + } + + } + } + + edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory(); + BodyType bodyType = new BodyType(); + bodyType.getAny().add(of.createResult(resultType)); + ResultEnvelopeType resultEnvelop = new ResultEnvelopeType(); + resultEnvelop.setBody(bodyType); + + //JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); + + StringWriter strWriter = new StringWriter(); + subLogTimingUtil.setStartTime(); + jaxbUtil.marshaller(of.createI2B2ResultEnvelope(resultEnvelop), + strWriter); + subLogTimingUtil.setEndTime(); + //tm.begin(); + /* + IXmlResultDao xmlResultDao = sfDAOFactory.getXmlResultDao(); + xmlResult = strWriter.toString(); + if (resultInstanceId != null) + xmlResultDao.createQueryXmlResult(resultInstanceId, strWriter + .toString()); + */ + // + if (processTimingFlag != null) { + if (!processTimingFlag.trim().equalsIgnoreCase(ProcessTimingReportUtil.NONE) ) { + ProcessTimingReportUtil ptrUtil = new ProcessTimingReportUtil(sfDAOFactory.getDataSourceLookup()); + if (processTimingFlag.trim().equalsIgnoreCase(ProcessTimingReportUtil.DEBUG) ) { + ptrUtil.logProcessTimingMessage(queryInstanceId, ptrUtil.buildProcessTiming(subLogTimingUtil, "JAXB - " + resultTypeName , "")); + } + logTimingUtil.setEndTime(); + ptrUtil.logProcessTimingMessage(queryInstanceId, ptrUtil.buildProcessTiming(logTimingUtil, "BUILD - " + resultTypeName , "")); + } + } + //} + //tm.commit(); + + //Process XIP File + if (letter != null && letterFilename != null) { + + File path = new File(letterFilename); + path.getParentFile().mkdirs(); + // Declaring the print writer with path + PrintWriter pw = new PrintWriter(path); + + + //queryMaster. + if (zipFileName != null) { + letter = letter.replaceAll("\\{\\{\\{ZIP_FILENAME_WIN\\}\\}\\}", zipFileName.replaceAll("/", "\\\\")); + letter = letter.replaceAll("\\{\\{\\{ZIP_FILENAME_MAC\\}\\}\\}", zipFileName.replaceAll("\\\\", "/")); + letter = letter.replaceAll("\\{\\{\\{ZIP_PASSWORD\\}\\}\\}", valueExport.getZipPassword()); + } + // Now calling writer() method with string + pw.write(processFilename(letter, param )); + + // Flushing the print writer + pw.flush(); + + // Lastly closing the printwriter + // using the close() method + pw.close(); + } + + + //String requesterLetter = valueExport.getDataManagerEmailMessage(); + + + if (letter != null && qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.datamanageremail") != null) { + + letter = processFilename(letter, param); + + //Send out email letter + EmailUtil email = new EmailUtil(); + IQueryResultTypeDao resultTypeDao = sfDAOFactory.getQueryResultTypeDao(); + String requestedData = "\n"; + String finalResultOutput = ""; + + for (ResultOutputOptionType resultOutputOption : resultOptionList) { + String resultName = resultOutputOption.getName() + .toUpperCase(); + List resultTypeList = resultTypeDao + .getQueryResultTypeByName(resultName, null); + if (resultTypeList.size() > 0) { + requestedData += resultTypeList.get(0).getDescription() + ", "; + finalResultOutput = resultTypeList.get(0).getName().toUpperCase(); + } + } + letter = letter.replaceAll("\\{\\{\\{REQUESTED_DATA_TYPE\\}\\}\\}",requestedData); + if (zipFileName != null && skipCSV == false && resultTypeName.equals(finalResultOutput)) { + + File file = new File(zipFileName); + file.getParentFile().mkdirs(); + String zipencryptMethod = "NONE"; + if ( valueExport.getZipEncryptMethod() != null) { + zipencryptMethod = valueExport.getZipEncryptMethod(); + } + + ZipParameters zipParameters = new ZipParameters(); + if (!zipencryptMethod.equals("NONE")) { + zipParameters.setEncryptFiles(true); + zipParameters.setCompressionLevel(CompressionLevel.MAXIMUM); + if (zipencryptMethod.equals("AES")) + zipParameters.setEncryptionMethod(EncryptionMethod.AES); + else if (zipencryptMethod.equals("STANARD")) + zipParameters.setEncryptionMethod(EncryptionMethod.ZIP_STANDARD); + else + zipParameters.setEncryptionMethod(EncryptionMethod.NONE); + + } + //zipParameters.setFileNameInZip( workDir + "*.*" ); + //zipParameters.setPassword("password"); + + //zipStream = new ZipOutputStream(buff); + //zip. + //ZipFile zipfile = new ZipFile(fileName + (extName.equals(null) ? "" : "." + default_ext), "password".toCharArray()); + + + if (zipParameters.getEncryptionMethod().equals(EncryptionMethod.NONE)) + new ZipFile(zipFileName).addFolder(new File(workDir),zipParameters); + //zipStream = new ZipOutputStream(new FileOutputStream(new File(zipFileName))); + else + new ZipFile(zipFileName,valueExport.getZipPassword().toCharArray()).addFolder(new File(workDir),zipParameters); + + + // zipStream = new ZipOutputStream(new FileOutputStream(new File(zipFileName)) + // , valueExport.getZip_password().toCharArray()); + + //zipStream.putNextEntry(zipParameters); + } + + if ((resultTypeName.equals(finalResultOutput)) + && (qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.smtp.enabled").equalsIgnoreCase("true")) ) + + email.email(qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.datamanageremail"), qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.datamanageremail"), "i2b2 Data Export - " + queryDef.getQueryName(), letter); + } + } catch (SQLException sqlEx) { + // catch oracle query timeout error ORA-01013 + if (sqlEx.toString().indexOf("ORA-01013") > -1) { + timeoutFlag = true; + throw new CRCTimeOutException(sqlEx.getMessage(), sqlEx); + } + if (sqlEx.getMessage().indexOf("The query was canceled.") > -1) { + timeoutFlag = true; + throw new CRCTimeOutException(sqlEx.getMessage(), sqlEx); + } + if (sqlEx.getMessage().indexOf("timed out") > -1) { + timeoutFlag = true; + throw new CRCTimeOutException(sqlEx.getMessage(), sqlEx); + } + errorFlag = true; + log.error("Error while executing sql", sqlEx); + throw new I2B2DAOException("Error while executing sql", sqlEx); + } catch (Exception sqlEx) { + + errorFlag = true; + log.error("QueryResultPatientSetGenerator.generateResult:" + + sqlEx.getMessage(), sqlEx); + throw new I2B2DAOException( + "QueryResultPatientSetGenerator.generateResult:" + + sqlEx.getMessage(), sqlEx); + } finally { + + if (resultInstanceId != null) { + IQueryResultInstanceDao resultInstanceDao = sfDAOFactory + .getPatientSetResultDAO(); + + if (errorFlag) { + resultInstanceDao.updatePatientSet(resultInstanceId, + QueryStatusTypeId.STATUSTYPE_ID_ERROR, 0); + } else { + // set the setsize and the description of the result instance if + // the user role is obfuscated + if (timeoutFlag == false) { // check if the query completed + try { + // tm.begin(); + + String obfusMethod = "", description = null; + if (obfscDataRoleFlag) { + obfusMethod = IQueryResultInstanceDao.OBSUBTOTAL; + // add () to the result type description + // read the description from result type + + } else { + obfuscatedRecordCount = recordCount; + } + IQueryResultTypeDao resultTypeDao = sfDAOFactory.getQueryResultTypeDao(); + List resultTypeList = resultTypeDao + .getQueryResultTypeByName(resultTypeName, roles); + + // add "(Obfuscated)" in the description + //description = resultTypeList.get(0) + // .getDescription() + // + " (Obfuscated) "; + String queryName = sfDAOFactory.getQueryMasterDAO().getQueryDefinition( + sfDAOFactory.getQueryInstanceDAO().getQueryInstanceByInstanceId(queryInstanceId).getQtQueryMaster().getQueryMasterId()).getName(); + + + + resultInstanceDao.updatePatientSet(resultInstanceId, + QueryStatusTypeId.STATUSTYPE_ID_FINISHED, null, + //obsfcTotal, + obfuscatedRecordCount, recordCount, obfusMethod); + + + ResultType resultType = new ResultType(); + resultType.setName(resultTypeName); + DataType mdataType = new DataType(); + mdataType.setValue(String.valueOf(recordCount)); + mdataType.setColumn("PatientCount"); + mdataType.setType("int"); + resultType.setName(resultTypeName); + mdataType = new DataType(); + mdataType.setValue(String.valueOf(rowCount)); + mdataType.setColumn("RowCount"); + mdataType.setType("int"); + resultType.getData().add(mdataType); + mdataType = new DataType(); + mdataType.setValue(letter); + mdataType.setColumn("RequestLetter"); + mdataType.setType("string"); + mdataType = new DataType(); + mdataType.setValue(String.valueOf(logFile)); + mdataType.setColumn("Log"); + mdataType.setType("string"); + + resultType.getData().add(mdataType); + mdataType = new DataType(); + mdataType.setValue(sfDAOFactory.getQueryInstanceDAO().getQueryInstanceByInstanceId(queryInstanceId).getQtQueryMaster().getQueryMasterId()); + mdataType.setColumn("QueryMasterID"); + mdataType.setType("string"); + resultType.getData().add(mdataType); + mdataType = new DataType(); + + edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory(); + BodyType bodyType = new BodyType(); + bodyType.getAny().add(of.createResult(resultType)); + ResultEnvelopeType resultEnvelop = new ResultEnvelopeType(); + resultEnvelop.setBody(bodyType); + + //JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); + + StringWriter strWriter = new StringWriter(); + + //subLogTimingUtil.setStartTime(); + JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); + jaxbUtil.marshaller(of.createI2B2ResultEnvelope(resultEnvelop), + strWriter); + + IXmlResultDao xmlResultDao = sfDAOFactory.getXmlResultDao(); + xmlResult = strWriter.toString(); + if (resultInstanceId != null) + xmlResultDao.createQueryXmlResult(resultInstanceId, strWriter + .toString()); + + description = resultTypeList.get(0) + .getDescription() + " for \"" + queryName +"\""; + + // set the result instance description + resultInstanceDao.updateResultInstanceDescription( + resultInstanceId, description); + // tm.commit(); + + + } catch (SecurityException e) { + throw new I2B2DAOException( + "Failed to write obfuscated description " + + e.getMessage(), e); + } catch (IllegalStateException e) { + throw new I2B2DAOException( + "Failed to write obfuscated description " + + e.getMessage(), e); + } catch (JAXBUtilException e) { + throw new I2B2DAOException( + "Failed to write jaxb " + + e.getMessage(), e); + } + } + } + } + } + } + + } + + + public static ValueExporter JaxbXmlToObj(String xmlString) { + + ValueExporter val = new ValueExporter(); + ValueExporter resultDataSet = null ; + JAXBContext jaxbContext; + try { + jaxbContext = JAXBContext.newInstance(val.getClass()); + + Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); + + resultDataSet = (ValueExporter) jaxbUnmarshaller.unmarshal(new StringReader(xmlString)); + + //System.out.println(resultDataSet); + } + catch (JAXBException e) { + e.printStackTrace(); + } + return resultDataSet; + } + private String sanitizeFilename(String filename) + { + + return filename.replaceAll("[^a-zA-Z0-9.-]", "_"); + } + /* + private static final Pattern TAG_REGEX = Pattern.compile("{{{(.+?)}}}", Pattern.DOTALL); + + + private static List getTagValues(final String str) { + final List tagValues = new ArrayList(); + final Matcher matcher = TAG_REGEX.matcher(str); + while (matcher.find()) { + tagValues.add(matcher.group(1)); + } + return tagValues; + } + */ + private char getChar(String sTerminatedBy) + { + if ("\\t".equals(sTerminatedBy)) { + return ( '\t'); + } else if ("\\n".equals(sTerminatedBy)) { + return ( '\n'); + } else if ("\\r".equals(sTerminatedBy)) { + return ( '\r'); + } else if ("\\f".equals(sTerminatedBy)) { + return ( '\f'); + } else if (null == sTerminatedBy || "".equals(sTerminatedBy) || "\\0".equals(sTerminatedBy)) { + return ('\0'); + } else { + return ( sTerminatedBy.charAt(0)); + } + + } + + private String processFilename(String fileName, Map param) + { + + + // SetFinderDAOFactory sfDAOFactory = (SetFinderDAOFactory) param + // .get("SetFinderDAOFactory"); + + String projectId = (String) param.get("projectId"); + String queryInstanceId = (String) param.get("QueryInstanceId"); + QueryDefinitionType queryDef = (QueryDefinitionType)param.get("queryDef"); + String resultFullName = queryDef.getQueryName(); + //queryDef.getQueryId() + + // String resultFullName = sfDAOFactory.getQueryMasterDAO().getQueryDefinition( + // sfDAOFactory.getQueryInstanceDAO().getQueryInstanceByInstanceId(queryInstanceId).getQtQueryMaster().getQueryMasterId()).getName(); + // QtQueryMaster qtMaster = sfDAOFactory.getQueryInstanceDAO().getQueryInstanceByInstanceId(queryInstanceId).getQtQueryMaster(); + + fileName = fileName.replaceAll("\\{\\{\\{USER_NAME\\}\\}\\}",(String) param.get("UserName"));//queryDef.getUserId()); + fileName = fileName.replaceAll("\\{\\{\\{QUERY_STARTDATE\\}\\}\\}", ((java.sql.Timestamp) param.get("QueryStartDate")).toLocaleString());//sfDAOFactory.getQueryInstanceDAO().getQueryInstanceByInstanceId(queryInstanceId).getStartDate().toLocaleString()); + fileName = fileName.replaceAll("\\{\\{\\{QUERY_ENDDATE\\}\\}\\}", new Date().toLocaleString()); + fileName = fileName.replaceAll("\\{\\{\\{QUERY_RUNTIME\\}\\}\\}", Integer.toString(Math.toIntExact(new Date().getTime() - ((java.sql.Timestamp) param.get("QueryStartDate")).getTime())/1000)); + + fileName = fileName.replaceAll("\\{\\{\\{PATIENT_COUNT\\}\\}\\}", param.get("RecordCount").toString()); + fileName = fileName.replaceAll("\\{\\{\\{FULL_NAME\\}\\}\\}", (String) param.get("FullName")); + fileName = fileName.replaceAll("\\{\\{\\{PROJECT_ID\\}\\}\\}", projectId.substring(1, projectId.length()-1)); + fileName = fileName.replaceAll("\\{\\{\\{RESULT_INSTANCE_ID\\}\\}\\}", (String) param.get("resultFullName")); + fileName = fileName.replaceAll("\\{\\{\\{QUERY_NAME\\}\\}\\}", sanitizeFilename(resultFullName)); + fileName = fileName.replaceAll("\\{\\{\\{QUERY_MASTER_ID\\}\\}\\}", sanitizeFilename(queryInstanceId)); //qtMaster.getQueryMasterId())); + + while (fileName.contains("{{{RANDOM_")) + { + + try { + int start = fileName.indexOf("{{{RANDOM_"); + int end = fileName.indexOf("}}}", start); + int size = Integer.parseInt(fileName.substring(start+10, end)); + + //SecureRandom random = new SecureRandom(); + //fileName = fileName.replaceAll("\\{\\{\\{RANDOM_"+size+"\\}\\}\\}", String.valueOf(random.nextInt(size))); + fileName = fileName.replaceAll("\\{\\{\\{RANDOM_"+size+"\\}\\}\\}", (String) param.get("ResultRandom")); + + } catch (Exception e) {} + + } + // Deal with dates + while (fileName.contains("{{{DATE_")) + { + + try { + int start = fileName.indexOf("{{{DATE_"); + int end = fileName.indexOf("}}}", start); + String date = fileName.substring(start+8, end); + + //DateTimeFormatter formatter = DateTimeFormatter.ofPattern(date); + //fileName = fileName.replaceAll("\\{\\{\\{DATE_"+date+"\\}\\}\\}", LocalDate.now().format(formatter)); + + DateTimeFormatter formatter = DateTimeFormatter.ofPattern(date); + fileName = fileName.replaceAll("\\{\\{\\{DATE_"+date+"\\}\\}\\}", ((LocalDate) param.get("ResultDate")).format(formatter)); + //(String) param.get("ResultDate")); + + } catch (Exception e) {} + + } + + + return fileName; + } + + private String getItemKeyFromResultType(SetFinderDAOFactory sfDAOFactory, + String resultTypeKey) { + // + IQueryBreakdownTypeDao queryBreakdownTypeDao = sfDAOFactory + .getQueryBreakdownTypeDao(); + QtQueryBreakdownType queryBreakdownType = queryBreakdownTypeDao + .getBreakdownTypeByName(resultTypeKey); + String itemKey = queryBreakdownType.getValue(); + return itemKey; + } + + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientGenderCountGenerator.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientGenderCountGenerator.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientGenderCountGenerator.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientGenderCountGenerator.java index 78d85e01..60f93911 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientGenderCountGenerator.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientGenderCountGenerator.java @@ -1,126 +1,126 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder; - -import java.io.StringWriter; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.util.Map; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.util.db.JDBCUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.i2b2result.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2result.DataType; -import edu.harvard.i2b2.crc.datavo.i2b2result.ResultEnvelopeType; -import edu.harvard.i2b2.crc.datavo.i2b2result.ResultType; - -public class QueryResultPatientGenderCountGenerator extends CRCDAO implements - IResultGenerator { - - public static final String RESULT_NAME = "PATIENT_GENDER_COUNT_XML"; - - @Override - public String getResults() { - return xmlResult; - } - - private String xmlResult = null; - - @Override - public void generateResult(Map param) throws I2B2DAOException { - - SetFinderConnection sfConn = (SetFinderConnection) param - .get("SetFinderConnection"); - SetFinderDAOFactory sfDAOFactory = (SetFinderDAOFactory) param - .get("SetFinderDAOFactory"); - // String patientSetId = (String)param.get("PatientSetId"); - String queryInstanceId = (String) param.get("QueryInstanceId"); - String TEMP_DX_TABLE = (String) param.get("TEMP_DX_TABLE"); - String resultInstanceId = (String) param.get("ResultInstanceId"); - this - .setDbSchemaName(sfDAOFactory.getDataSourceLookup() - .getFullSchema()); - - String demographics_count_sql = "select count(distinct dx.patient_num) as demo_count, case when cl.name_char IS NULL then pd.sex_cd else cl.name_char end pd_demo_cd from " - + " " - + " patient_dimension pd left join code_lookup cl on pd.sex_cd = cl.code_cd " - + " and lower(cl.table_cd) = 'patient_dimension' and upper(cl.column_cd) = 'SEX_CD' ," - + " " - + " dx where pd.patient_num = dx.patient_num" - + " group by case when cl.name_char IS NULL then pd.sex_cd else cl.name_char end"; - - boolean errorFlag = false; - int totalCount = 0; - try { - - log.debug("Executing[ " + demographics_count_sql + " ]"); - - String sqlFinal = demographics_count_sql.replace("", this.getDbSchemaName() ); - sqlFinal = sqlFinal.replace("", TEMP_DX_TABLE); - - PreparedStatement stmt = sfConn - .prepareStatement(sqlFinal); - ResultSet resultSet = stmt.executeQuery(); - ResultType resultType = new ResultType(); - resultType.setName(RESULT_NAME); - - while (resultSet.next()) { - String demoCount = resultSet.getString("demo_count"); - String raceCd = resultSet.getString("pd_demo_cd"); - DataType mdataType = new DataType(); - mdataType.setValue(demoCount); - mdataType.setColumn(raceCd); - mdataType.setType("int"); - resultType.getData().add(mdataType); - } - resultSet.close(); - stmt.close(); - - edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory(); - BodyType bodyType = new BodyType(); - bodyType.getAny().add(of.createResult(resultType)); - ResultEnvelopeType resultEnvelop = new ResultEnvelopeType(); - resultEnvelop.setBody(bodyType); - - JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); - - StringWriter strWriter = new StringWriter(); - - jaxbUtil.marshaller(of.createI2B2ResultEnvelope(resultEnvelop), - strWriter); - - IXmlResultDao xmlResultDao = sfDAOFactory.getXmlResultDao(); - xmlResult = strWriter.toString(); - xmlResultDao.createQueryXmlResult(resultInstanceId, strWriter - .toString()); - - } catch (Exception sqlEx) { - log.error("QueryResultPatientGenderCountGenerator.generateResult:" - + sqlEx.getMessage(), sqlEx); - throw new I2B2DAOException( - "QueryResultPatientGenderCountGenerator.generateResult:" - + sqlEx.getMessage(), sqlEx); - } finally { - IQueryResultInstanceDao resultInstanceDao = sfDAOFactory - .getPatientSetResultDAO(); - - if (errorFlag) { - resultInstanceDao.updatePatientSet(resultInstanceId, - QueryStatusTypeId.STATUSTYPE_ID_ERROR, 0); - } else { - resultInstanceDao.updatePatientSet(resultInstanceId, - QueryStatusTypeId.STATUSTYPE_ID_FINISHED, totalCount); - } - } - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder; + +import java.io.StringWriter; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.Map; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.util.db.JDBCUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; +import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; +import edu.harvard.i2b2.crc.datavo.i2b2result.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2result.DataType; +import edu.harvard.i2b2.crc.datavo.i2b2result.ResultEnvelopeType; +import edu.harvard.i2b2.crc.datavo.i2b2result.ResultType; + +public class QueryResultPatientGenderCountGenerator extends CRCDAO implements + IResultGenerator { + + public static final String RESULT_NAME = "PATIENT_GENDER_COUNT_XML"; + + @Override + public String getResults() { + return xmlResult; + } + + private String xmlResult = null; + + @Override + public void generateResult(Map param) throws I2B2DAOException { + + SetFinderConnection sfConn = (SetFinderConnection) param + .get("SetFinderConnection"); + SetFinderDAOFactory sfDAOFactory = (SetFinderDAOFactory) param + .get("SetFinderDAOFactory"); + // String patientSetId = (String)param.get("PatientSetId"); + String queryInstanceId = (String) param.get("QueryInstanceId"); + String TEMP_DX_TABLE = (String) param.get("TEMP_DX_TABLE"); + String resultInstanceId = (String) param.get("ResultInstanceId"); + this + .setDbSchemaName(sfDAOFactory.getDataSourceLookup() + .getFullSchema()); + + String demographics_count_sql = "select count(distinct dx.patient_num) as demo_count, case when cl.name_char IS NULL then pd.sex_cd else cl.name_char end pd_demo_cd from " + + " " + + " patient_dimension pd left join code_lookup cl on pd.sex_cd = cl.code_cd " + + " and lower(cl.table_cd) = 'patient_dimension' and upper(cl.column_cd) = 'SEX_CD' ," + + " " + + " dx where pd.patient_num = dx.patient_num" + + " group by case when cl.name_char IS NULL then pd.sex_cd else cl.name_char end"; + + boolean errorFlag = false; + int totalCount = 0; + try { + + log.debug("Executing[ " + demographics_count_sql + " ]"); + + String sqlFinal = demographics_count_sql.replace("", this.getDbSchemaName() ); + sqlFinal = sqlFinal.replace("", TEMP_DX_TABLE); + + PreparedStatement stmt = sfConn + .prepareStatement(sqlFinal); + ResultSet resultSet = stmt.executeQuery(); + ResultType resultType = new ResultType(); + resultType.setName(RESULT_NAME); + + while (resultSet.next()) { + String demoCount = resultSet.getString("demo_count"); + String raceCd = resultSet.getString("pd_demo_cd"); + DataType mdataType = new DataType(); + mdataType.setValue(demoCount); + mdataType.setColumn(raceCd); + mdataType.setType("int"); + resultType.getData().add(mdataType); + } + resultSet.close(); + stmt.close(); + + edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory(); + BodyType bodyType = new BodyType(); + bodyType.getAny().add(of.createResult(resultType)); + ResultEnvelopeType resultEnvelop = new ResultEnvelopeType(); + resultEnvelop.setBody(bodyType); + + JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); + + StringWriter strWriter = new StringWriter(); + + jaxbUtil.marshaller(of.createI2B2ResultEnvelope(resultEnvelop), + strWriter); + + IXmlResultDao xmlResultDao = sfDAOFactory.getXmlResultDao(); + xmlResult = strWriter.toString(); + xmlResultDao.createQueryXmlResult(resultInstanceId, strWriter + .toString()); + + } catch (Exception sqlEx) { + log.error("QueryResultPatientGenderCountGenerator.generateResult:" + + sqlEx.getMessage(), sqlEx); + throw new I2B2DAOException( + "QueryResultPatientGenderCountGenerator.generateResult:" + + sqlEx.getMessage(), sqlEx); + } finally { + IQueryResultInstanceDao resultInstanceDao = sfDAOFactory + .getPatientSetResultDAO(); + + if (errorFlag) { + resultInstanceDao.updatePatientSet(resultInstanceId, + QueryStatusTypeId.STATUSTYPE_ID_ERROR, 0); + } else { + resultInstanceDao.updatePatientSet(resultInstanceId, + QueryStatusTypeId.STATUSTYPE_ID_FINISHED, totalCount); + } + } + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientRaceCdCountGenerator.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientRaceCdCountGenerator.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientRaceCdCountGenerator.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientRaceCdCountGenerator.java index 4a14c568..2204fcae --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientRaceCdCountGenerator.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientRaceCdCountGenerator.java @@ -1,123 +1,123 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder; - -import java.io.StringWriter; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.util.Map; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.util.db.JDBCUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.i2b2result.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2result.DataType; -import edu.harvard.i2b2.crc.datavo.i2b2result.ResultEnvelopeType; -import edu.harvard.i2b2.crc.datavo.i2b2result.ResultType; - -public class QueryResultPatientRaceCdCountGenerator extends CRCDAO implements - IResultGenerator { - - public static final String RESULT_NAME = "PATIENT_RACE_COUNT_XML"; - - @Override - public String getResults() { - return xmlResult; - } - - private String xmlResult = null; - - @Override - public void generateResult(Map param) throws I2B2DAOException { - - SetFinderConnection sfConn = (SetFinderConnection) param - .get("SetFinderConnection"); - SetFinderDAOFactory sfDAOFactory = (SetFinderDAOFactory) param - .get("SetFinderDAOFactory"); - // String patientSetId = (String)param.get("PatientSetId"); - String queryInstanceId = (String) param.get("QueryInstanceId"); - String TEMP_DX_TABLE = (String) param.get("TEMP_DX_TABLE"); - String resultInstanceId = (String) param.get("ResultInstanceId"); - this - .setDbSchemaName(sfDAOFactory.getDataSourceLookup() - .getFullSchema()); - - String demographics_count_sql = "select count(distinct dx.patient_num) as race_count, case when cl.name_char IS NULL then pd.race_cd else cl.name_char end as pd_race_cd from " - + " " - + "patient_dimension pd left join code_lookup cl on pd.race_cd = cl.code_cd" - + " and lower(cl.table_cd) = 'patient_dimension' and upper(cl.column_cd) = 'RACE_CD', " - + " " - + " dx where pd.patient_num = dx.patient_num" - + " group by case when cl.name_char IS NULL then pd.race_cd else cl.name_char end"; - - boolean errorFlag = false; - int totalCount = 0; - try { - - log.debug("Executing[ " + demographics_count_sql + " ]"); - String sqlFinal = demographics_count_sql.replace("", this.getDbSchemaName() ); - sqlFinal = sqlFinal.replace("", TEMP_DX_TABLE); - - PreparedStatement stmt = sfConn - .prepareStatement(sqlFinal); - ResultSet resultSet = stmt.executeQuery(); - ResultType resultType = new ResultType(); - resultType.setName(RESULT_NAME); - while (resultSet.next()) { - String demoCount = resultSet.getString("race_count"); - String raceCd = resultSet.getString("pd_race_cd"); - DataType mdataType = new DataType(); - mdataType.setValue(demoCount); - mdataType.setColumn(raceCd); - mdataType.setType("int"); - resultType.getData().add(mdataType); - } - resultSet.close(); - stmt.close(); - edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory(); - BodyType bodyType = new BodyType(); - bodyType.getAny().add(of.createResult(resultType)); - ResultEnvelopeType resultEnvelop = new ResultEnvelopeType(); - resultEnvelop.setBody(bodyType); - - JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); - - StringWriter strWriter = new StringWriter(); - - jaxbUtil.marshaller(of.createI2B2ResultEnvelope(resultEnvelop), - strWriter); - - IXmlResultDao xmlResultDao = sfDAOFactory.getXmlResultDao(); - xmlResult = strWriter.toString(); - xmlResultDao.createQueryXmlResult(resultInstanceId, strWriter - .toString()); - - } catch (Exception sqlEx) { - log.error("QueryResultPatientRaceCdCountGenerator.generateResult:" - + sqlEx.getMessage(), sqlEx); - throw new I2B2DAOException( - "QueryResultPatientRaceCdCountGenerator.generateResult:" - + sqlEx.getMessage(), sqlEx); - } finally { - IQueryResultInstanceDao resultInstanceDao = sfDAOFactory - .getPatientSetResultDAO(); - - if (errorFlag) { - resultInstanceDao.updatePatientSet(resultInstanceId, - QueryStatusTypeId.STATUSTYPE_ID_ERROR, 0); - } else { - resultInstanceDao.updatePatientSet(resultInstanceId, - QueryStatusTypeId.STATUSTYPE_ID_FINISHED, totalCount); - } - } - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder; + +import java.io.StringWriter; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.Map; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.util.db.JDBCUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; +import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; +import edu.harvard.i2b2.crc.datavo.i2b2result.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2result.DataType; +import edu.harvard.i2b2.crc.datavo.i2b2result.ResultEnvelopeType; +import edu.harvard.i2b2.crc.datavo.i2b2result.ResultType; + +public class QueryResultPatientRaceCdCountGenerator extends CRCDAO implements + IResultGenerator { + + public static final String RESULT_NAME = "PATIENT_RACE_COUNT_XML"; + + @Override + public String getResults() { + return xmlResult; + } + + private String xmlResult = null; + + @Override + public void generateResult(Map param) throws I2B2DAOException { + + SetFinderConnection sfConn = (SetFinderConnection) param + .get("SetFinderConnection"); + SetFinderDAOFactory sfDAOFactory = (SetFinderDAOFactory) param + .get("SetFinderDAOFactory"); + // String patientSetId = (String)param.get("PatientSetId"); + String queryInstanceId = (String) param.get("QueryInstanceId"); + String TEMP_DX_TABLE = (String) param.get("TEMP_DX_TABLE"); + String resultInstanceId = (String) param.get("ResultInstanceId"); + this + .setDbSchemaName(sfDAOFactory.getDataSourceLookup() + .getFullSchema()); + + String demographics_count_sql = "select count(distinct dx.patient_num) as race_count, case when cl.name_char IS NULL then pd.race_cd else cl.name_char end as pd_race_cd from " + + " " + + "patient_dimension pd left join code_lookup cl on pd.race_cd = cl.code_cd" + + " and lower(cl.table_cd) = 'patient_dimension' and upper(cl.column_cd) = 'RACE_CD', " + + " " + + " dx where pd.patient_num = dx.patient_num" + + " group by case when cl.name_char IS NULL then pd.race_cd else cl.name_char end"; + + boolean errorFlag = false; + int totalCount = 0; + try { + + log.debug("Executing[ " + demographics_count_sql + " ]"); + String sqlFinal = demographics_count_sql.replace("", this.getDbSchemaName() ); + sqlFinal = sqlFinal.replace("", TEMP_DX_TABLE); + + PreparedStatement stmt = sfConn + .prepareStatement(sqlFinal); + ResultSet resultSet = stmt.executeQuery(); + ResultType resultType = new ResultType(); + resultType.setName(RESULT_NAME); + while (resultSet.next()) { + String demoCount = resultSet.getString("race_count"); + String raceCd = resultSet.getString("pd_race_cd"); + DataType mdataType = new DataType(); + mdataType.setValue(demoCount); + mdataType.setColumn(raceCd); + mdataType.setType("int"); + resultType.getData().add(mdataType); + } + resultSet.close(); + stmt.close(); + edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory(); + BodyType bodyType = new BodyType(); + bodyType.getAny().add(of.createResult(resultType)); + ResultEnvelopeType resultEnvelop = new ResultEnvelopeType(); + resultEnvelop.setBody(bodyType); + + JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); + + StringWriter strWriter = new StringWriter(); + + jaxbUtil.marshaller(of.createI2B2ResultEnvelope(resultEnvelop), + strWriter); + + IXmlResultDao xmlResultDao = sfDAOFactory.getXmlResultDao(); + xmlResult = strWriter.toString(); + xmlResultDao.createQueryXmlResult(resultInstanceId, strWriter + .toString()); + + } catch (Exception sqlEx) { + log.error("QueryResultPatientRaceCdCountGenerator.generateResult:" + + sqlEx.getMessage(), sqlEx); + throw new I2B2DAOException( + "QueryResultPatientRaceCdCountGenerator.generateResult:" + + sqlEx.getMessage(), sqlEx); + } finally { + IQueryResultInstanceDao resultInstanceDao = sfDAOFactory + .getPatientSetResultDAO(); + + if (errorFlag) { + resultInstanceDao.updatePatientSet(resultInstanceId, + QueryStatusTypeId.STATUSTYPE_ID_ERROR, 0); + } else { + resultInstanceDao.updatePatientSet(resultInstanceId, + QueryStatusTypeId.STATUSTYPE_ID_FINISHED, totalCount); + } + } + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientRequest.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientRequest.java similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientRequest.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientRequest.java index 291a75d8..39ffc520 100644 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientRequest.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientRequest.java @@ -1,561 +1,561 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder; - -import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; -import java.io.File; -import java.io.FileOutputStream; -import edu.harvard.i2b2.crc.dao.xml.ValueExporter; -import edu.harvard.i2b2.crc.dao.EmailUtil; - -/** - * To add Length of Stay (This is for Oracle and Postgresl) For Sql Server change the sql statement from (DX to #DX) - * - * Add a entry to QT_BREAKDOWN_PATH - * NAME = LENGTH_OF_STAY - * VALUE = select length_of_stay as patient_range, count(distinct a.PATIENT_num) as patient_count from visit_dimension a, DX b where a.patient_num = b.patient_num group by a.length_of_stay order by 1 - * - * Add a entry to QT_QUERY_RESULT_TYPE - * RESULT_TYPE_ID = 13 (Or any unused number) - * NAME = LENGTH_OF_STAY - * DESCRIPTION = Length of Dtay Brealdown - * DISPLAY_TYPE_ID = CATNUM - * VISUAL_ATTRIBUTE_TYPE_ID = LA - * - * Add a new in CRCApplicationContext.xml - * - * - * LENGTH_OF_STAY - * - * edu.harvard.i2b2.crc.dao.setfinder.QueryResultPatientSQLCountGenerator - * - * - */ - -import java.io.PrintWriter; -import java.io.StringWriter; -import java.io.UnsupportedEncodingException; -import java.security.SecureRandom; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.text.DateFormat; -import java.time.LocalDate; -import java.time.ZonedDateTime; -import java.time.format.DateTimeFormatter; -import java.time.format.FormatStyle; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import jakarta.mail.MessagingException; -import jakarta.xml.bind.JAXBContext; -import jakarta.xml.bind.JAXBException; -import jakarta.xml.bind.Unmarshaller; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.db.JDBCUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.ProcessTimingReportUtil; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.db.QtQueryBreakdownType; -import edu.harvard.i2b2.crc.datavo.db.QtQueryMaster; -import edu.harvard.i2b2.crc.datavo.db.QtQueryResultType; -import edu.harvard.i2b2.crc.datavo.i2b2result.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2result.DataType; -import edu.harvard.i2b2.crc.datavo.i2b2result.ResultEnvelopeType; -import edu.harvard.i2b2.crc.datavo.i2b2result.ResultType; -import edu.harvard.i2b2.crc.datavo.pm.UserType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.PanelType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultOutputOptionType; -import edu.harvard.i2b2.crc.delegate.pm.CallPMUtil; -import edu.harvard.i2b2.crc.opencsv.CSVWriter; -import edu.harvard.i2b2.crc.opencsv.ResultSetHelperService; -import edu.harvard.i2b2.crc.util.LogTimingUtil; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; -import edu.harvard.i2b2.crc.dao.xml.Item_orig; -import edu.harvard.i2b2.crc.dao.xml.Items; -import edu.harvard.i2b2.crc.dao.xml.ValueExport; -import net.lingala.zip4j.ZipFile; -//mport net.lingala.zip4j.ZipFile; -import net.lingala.zip4j.io.outputstream.ZipOutputStream; -import net.lingala.zip4j.model.ZipParameters; -import net.lingala.zip4j.model.enums.CompressionLevel; -import net.lingala.zip4j.model.enums.EncryptionMethod; -import java.io.StringReader; - -/** - * Setfinder's result genertor class. This class calculates patient break down - * for the result type. - * - * Calls the ontology to get the children for the result type and then - * calculates the patient count for each child of the result type. - */ -public class QueryResultPatientRequest extends CRCDAO implements IResultGenerator { - - protected final Log logesapi = LogFactory.getLog(getClass()); - - @Override - public String getResults() { - return xmlResult; - } - - private String xmlResult = null; - /** - * Function accepts parameter in Map. The patient count will be obfuscated - * if the user is OBFUS - */ - @Override - public void generateResult(Map param) throws CRCTimeOutException, - I2B2DAOException { - - - // mm create a csv in a folder - - - SetFinderConnection sfConn = (SetFinderConnection) param - .get("SetFinderConnection"); - SetFinderDAOFactory sfDAOFactory = (SetFinderDAOFactory) param - .get("SetFinderDAOFactory"); - - // String patientSetId = (String)param.get("PatientSetId"); - String queryInstanceId = (String) param.get("QueryInstanceId"); - String TEMP_DX_TABLE = (String) param.get("TEMP_DX_TABLE"); - String resultInstanceId = (String) param.get("ResultInstanceId"); - // String itemKey = (String) param.get("ItemKey"); - String resultTypeName = (String) param.get("ResultOptionName"); - - String requestedData = "\n"; - String finalResultOutput = ""; - - ValueExporter valueExport = null; - //ZipOutputStream zipStream; - - //List filesToAdd = new List; - //(String) param.get("ResultFullName"); - - String processTimingFlag = (String) param.get("ProcessTimingFlag"); - String projectId = (String) param.get("projectId"); - int obfuscatedRecordCount = (Integer) param.get("ObfuscatedRecordCount"); - int recordCount = (Integer) param.get("RecordCount"); - int resultPriority = (Integer) param.get("ResultPriority"); - int transactionTimeout = (Integer) param.get("TransactionTimeout"); - boolean obfscDataRoleFlag = (Boolean)param.get("ObfuscatedRoleFlag"); - QueryDefinitionType queryDef = (QueryDefinitionType)param.get("queryDef"); - List panelList = (List)param.get("panelList"); - List resultOptionList = (List) param.get("resultOptionList"); - - boolean skipCSV = false; - if ((Boolean)param.get("SkipCSV") != null) - skipCSV = (Boolean)param.get("SkipCSV"); - - this - .setDbSchemaName(sfDAOFactory.getDataSourceLookup() - .getFullSchema()); - Map ontologyKeyMap = (Map) param.get("setFinderResultOntologyKeyMap"); - String serverType = (String) param.get("ServerType"); - // CallOntologyUtil ontologyUtil = (CallOntologyUtil) param - // .get("CallOntologyUtil"); - List roles = (List) param.get("Roles"); - String tempTableName = ""; - PreparedStatement stmt = null; - boolean errorFlag = false, timeoutFlag = false; - //String itemKey = ""; - - int actualTotal = 0, obsfcTotal = 0; - - - QtQueryMaster queryMaster = sfDAOFactory.getQueryMasterDAO().getQueryDefinition(sfDAOFactory.getQueryInstanceDAO().getQueryInstanceByInstanceId(queryInstanceId).getQtQueryMaster().getQueryMasterId()); - UserType user = null; - sfDAOFactory.getQueryMasterDAO().renameQuery(queryMaster.getQueryMasterId(), "(" + queryMaster.getQueryMasterId() + ") " + queryDef.getQueryName()); - - try { - - if (recordCount==0) return; - - LogTimingUtil logTimingUtil = new LogTimingUtil(); - logTimingUtil.setStartTime(); - - LogTimingUtil subLogTimingUtil = new LogTimingUtil(); - subLogTimingUtil.setStartTime(); - - String exportItemXml = getItemKeyFromResultType(sfDAOFactory, resultTypeName); - - - - user = CallPMUtil.getUserFromResponse(queryMaster.getPmXml()); - - param.put("QueryStartDate", queryMaster.getCreateDate()); - param.put("FullName", user.getFullName()); - param.put("UserName", user.getUserName()); - param.put("Email", user.getEmail()); - //get break down count sigma from property file - - - //stmt = sfConn.prepareStatement(itemCountSql); - - CancelStatementRunner csr = new CancelStatementRunner(stmt, - transactionTimeout); - Thread csrThread = new Thread(csr); - csrThread.start(); - - //String sqlFinal = ""; - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - - valueExport = new ValueExporter(); - - - - valueExport = JaxbXmlToObj(exportItemXml); - - - //JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); - //ValueExport valueExport = (ValueExport) jaxbUtil - // .unMashallFromString(exportItemXml).getValue(); - - if (csr.getSqlFinishedFlag()) { - timeoutFlag = true; - throw new CRCTimeOutException("The query was canceled."); - } - - // - if (processTimingFlag != null) { - if (!processTimingFlag.trim().equalsIgnoreCase(ProcessTimingReportUtil.NONE) ) { - ProcessTimingReportUtil ptrUtil = new ProcessTimingReportUtil(sfDAOFactory.getDataSourceLookup()); - if (processTimingFlag.trim().equalsIgnoreCase(ProcessTimingReportUtil.DEBUG) ) { - ptrUtil.logProcessTimingMessage(queryInstanceId, ptrUtil.buildProcessTiming(subLogTimingUtil, "JAXB - " + resultTypeName , "")); - } - logTimingUtil.setEndTime(); - ptrUtil.logProcessTimingMessage(queryInstanceId, ptrUtil.buildProcessTiming(logTimingUtil, "BUILD - " + resultTypeName , "")); - } - } - //} - //tm.commit(); - - } catch (Exception sqlEx) { - - errorFlag = true; - log.error("QueryResultPatientSetGenerator.generateResult:" - + sqlEx.getMessage(), sqlEx); - throw new I2B2DAOException( - "QueryResultPatientSetGenerator.generateResult:" - + sqlEx.getMessage(), sqlEx); - } finally { - - if (resultInstanceId != null) { - IQueryResultInstanceDao resultInstanceDao = sfDAOFactory - .getPatientSetResultDAO(); - - if (errorFlag) { - resultInstanceDao.updatePatientSet(resultInstanceId, - QueryStatusTypeId.STATUSTYPE_ID_ERROR, 0); - } else { - // set the setsize and the description of the result instance if - // the user role is obfuscated - if (timeoutFlag == false) { // check if the query completed - try { - // tm.begin(); - - String obfusMethod = "", description = null; - if (obfscDataRoleFlag) { - obfusMethod = IQueryResultInstanceDao.OBSUBTOTAL; - // add () to the result type description - // read the description from result type - - } else { - obfuscatedRecordCount = recordCount; - } - IQueryResultTypeDao resultTypeDao = sfDAOFactory.getQueryResultTypeDao(); - List resultTypeList = resultTypeDao - .getQueryResultTypeByName(resultTypeName, null); - - // add "(Obfuscated)" in the description - //description = resultTypeList.get(0) - // .getDescription() - // + " (Obfuscated) "; - String queryName = sfDAOFactory.getQueryMasterDAO().getQueryDefinition( - sfDAOFactory.getQueryInstanceDAO().getQueryInstanceByInstanceId(queryInstanceId).getQtQueryMaster().getQueryMasterId()).getName(); - - - - resultInstanceDao.updatePatientSet(resultInstanceId, - QueryStatusTypeId.STATUSTYPE_ID_FINISHED, null, - //obsfcTotal, - obfuscatedRecordCount, recordCount, obfusMethod); - - if (recordCount == 0) - description = "0 patients, no email sent"; - else - description = resultTypeList.get(0) - .getDescription() + " for \"" + queryName +"\""; - - // set the result instance description - resultInstanceDao.updateResultInstanceDescription( - resultInstanceId, description); - // tm.commit(); - - - - if ((valueExport != null) && (recordCount != 0)) { - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - String letter = valueExport.getDataManagerEmailMessage(); - String requesterMessage = valueExport.getRequesterEmailMessage(); - if (letter != null) { - - letter = processFilename(letter, param); - - requesterMessage = processFilename(requesterMessage, param); - for (ResultOutputOptionType resultOutputOption : resultOptionList) { - String resultName = resultOutputOption.getName() - .toUpperCase(); - resultTypeList = resultTypeDao - .getQueryResultTypeByName(resultName, null); - if (resultTypeList.size() > 0) { - requestedData += resultTypeList.get(0).getDescription() + ", "; - finalResultOutput = resultTypeList.get(0).getName().toUpperCase(); - } - } - letter = letter.replaceAll("\\{\\{\\{REQUESTED_DATA_TYPE\\}\\}\\}",requestedData); - requesterMessage = requesterMessage.replaceAll("\\{\\{\\{REQUESTED_DATA_TYPE\\}\\}\\}",requestedData); - - - ResultType resultType = new ResultType(); - resultType.setName(resultTypeName); - DataType mdataType = new DataType(); - mdataType.setValue(String.valueOf(recordCount)); - mdataType.setColumn("patientCount"); - mdataType.setType("int"); - resultType.getData().add(mdataType); - mdataType = new DataType(); - mdataType.setValue(letter); - mdataType.setColumn("RequestEmail"); - mdataType.setType("string"); - resultType.getData().add(mdataType); - mdataType = new DataType(); - mdataType.setValue(qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.datamanageremail")); - mdataType.setColumn("DataManagerEmail"); - mdataType.setType("string"); - resultType.getData().add(mdataType); - - edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory(); - BodyType bodyType = new BodyType(); - bodyType.getAny().add(of.createResult(resultType)); - ResultEnvelopeType resultEnvelop = new ResultEnvelopeType(); - resultEnvelop.setBody(bodyType); - - //JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); - - StringWriter strWriter = new StringWriter(); - - //subLogTimingUtil.setStartTime(); - JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); - jaxbUtil.marshaller(of.createI2B2ResultEnvelope(resultEnvelop), - strWriter); - //subLogTimingUtil.setEndTime(); - //tm.begin(); - IXmlResultDao xmlResultDao = sfDAOFactory.getXmlResultDao(); - xmlResult = strWriter.toString(); - if (resultInstanceId != null) - xmlResultDao.createQueryXmlResult(resultInstanceId, strWriter - .toString()); -//qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.smtp.subject") - - if (qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.smtp.enabled").equalsIgnoreCase("true")) { - EmailUtil email = new EmailUtil(); - try { - - if (resultTypeName.equals(finalResultOutput)) { - email.email(qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.datamanageremail"), qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.datamanageremail"), "i2b2 Data Request", letter); - if (user.getEmail()!= null && !user.getEmail().equals("") && requesterMessage != null) - email.email(user.getEmail(), qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.datamanageremail"), "i2b2 Data Request", requesterMessage); - } - } catch (UnsupportedEncodingException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (I2B2Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (MessagingException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } - - - } - } catch (SecurityException e) { - throw new I2B2DAOException( - "Failed to write obfuscated description " - + e.getMessage(), e); - } catch (IllegalStateException e) { - throw new I2B2DAOException( - "Failed to write obfuscated description " - + e.getMessage(), e); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } - } - } - } - - - - - public static ValueExporter JaxbXmlToObj(String xmlString) { - - ValueExporter val = new ValueExporter(); - ValueExporter resultDataSet = null ; - JAXBContext jaxbContext; - try { - jaxbContext = JAXBContext.newInstance(val.getClass()); - - Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); - - resultDataSet = (ValueExporter) jaxbUnmarshaller.unmarshal(new StringReader(xmlString)); - - //System.out.println(resultDataSet); - } - catch (JAXBException e) { - e.printStackTrace(); - } - return resultDataSet; - } - private String sanitizeFilename(String filename) - { - - return filename.replaceAll("[^a-zA-Z0-9.-]", "_"); - } - /* - private static final Pattern TAG_REGEX = Pattern.compile("{{{(.+?)}}}", Pattern.DOTALL); - - - private static List getTagValues(final String str) { - final List tagValues = new ArrayList(); - final Matcher matcher = TAG_REGEX.matcher(str); - while (matcher.find()) { - tagValues.add(matcher.group(1)); - } - return tagValues; - } - */ - private char getChar(String sTerminatedBy) - { - if ("\\t".equals(sTerminatedBy)) { - return ( '\t'); - } else if ("\\n".equals(sTerminatedBy)) { - return ( '\n'); - } else if ("\\r".equals(sTerminatedBy)) { - return ( '\r'); - } else if ("\\f".equals(sTerminatedBy)) { - return ( '\f'); - } else if (null == sTerminatedBy || "".equals(sTerminatedBy) || "\\0".equals(sTerminatedBy)) { - return ('\0'); - } else { - return ( sTerminatedBy.charAt(0)); - } - - } - - private String processFilename(String fileName, Map param) - { - - - // SetFinderDAOFactory sfDAOFactory = (SetFinderDAOFactory) param - // .get("SetFinderDAOFactory"); - - String projectId = (String) param.get("projectId"); - String queryInstanceId = (String) param.get("QueryInstanceId"); - QueryDefinitionType queryDef = (QueryDefinitionType)param.get("queryDef"); - String resultFullName = queryDef.getQueryName(); - //queryDef.getQueryId() - - // String resultFullName = sfDAOFactory.getQueryMasterDAO().getQueryDefinition( - // sfDAOFactory.getQueryInstanceDAO().getQueryInstanceByInstanceId(queryInstanceId).getQtQueryMaster().getQueryMasterId()).getName(); - // QtQueryMaster qtMaster = sfDAOFactory.getQueryInstanceDAO().getQueryInstanceByInstanceId(queryInstanceId).getQtQueryMaster(); - - fileName = fileName.replaceAll("\\{\\{\\{USER_NAME\\}\\}\\}",(String) param.get("UserName"));//queryDef.getUserId()); - fileName = fileName.replaceAll("\\{\\{\\{QUERY_STARTDATE\\}\\}\\}", ((java.sql.Timestamp) param.get("QueryStartDate")).toLocaleString());//sfDAOFactory.getQueryInstanceDAO().getQueryInstanceByInstanceId(queryInstanceId).getStartDate().toLocaleString()); - fileName = fileName.replaceAll("\\{\\{\\{QUERY_ENDDATE\\}\\}\\}", new Date().toLocaleString()); - fileName = fileName.replaceAll("\\{\\{\\{QUERY_RUNTIME\\}\\}\\}", Integer.toString(Math.toIntExact(new Date().getTime() - ((java.sql.Timestamp) param.get("QueryStartDate")).getTime())/1000)); - - fileName = fileName.replaceAll("\\{\\{\\{PATIENT_COUNT\\}\\}\\}", param.get("RecordCount").toString()); - fileName = fileName.replaceAll("\\{\\{\\{FULL_NAME\\}\\}\\}", (String) param.get("FullName")); - fileName = fileName.replaceAll("\\{\\{\\{PROJECT_ID\\}\\}\\}", projectId.substring(1, projectId.length()-1)); - //fileName = fileName.replaceAll("\\{\\{\\{RESULT_INSTANCE_ID\\}\\}\\}", resultInstanceId); - fileName = fileName.replaceAll("\\{\\{\\{QUERY_NAME\\}\\}\\}", sanitizeFilename(resultFullName)); - fileName = fileName.replaceAll("\\{\\{\\{QUERY_MASTER_ID\\}\\}\\}", sanitizeFilename(queryInstanceId)); //qtMaster.getQueryMasterId())); - - while (fileName.contains("{{{RANDOM_")) - { - - try { - int start = fileName.indexOf("{{{RANDOM_"); - int end = fileName.indexOf("}}}", start); - int size = Integer.parseInt(fileName.substring(start+10, end)); - - //SecureRandom random = new SecureRandom(); - //fileName = fileName.replaceAll("\\{\\{\\{RANDOM_"+size+"\\}\\}\\}", String.valueOf(random.nextInt(size))); - fileName = fileName.replaceAll("\\{\\{\\{RANDOM_"+size+"\\}\\}\\}", (String) param.get("ResultRandom")); - - } catch (Exception e) {} - - } - // Deal with dates - while (fileName.contains("{{{DATE_")) - { - - try { - int start = fileName.indexOf("{{{DATE_"); - int end = fileName.indexOf("}}}", start); - String date = fileName.substring(start+8, end); - - //DateTimeFormatter formatter = DateTimeFormatter.ofPattern(date); - //fileName = fileName.replaceAll("\\{\\{\\{DATE_"+date+"\\}\\}\\}", LocalDate.now().format(formatter)); - - DateTimeFormatter formatter = DateTimeFormatter.ofPattern(date); - fileName = fileName.replaceAll("\\{\\{\\{DATE_"+date+"\\}\\}\\}", ((LocalDate) param.get("ResultDate")).format(formatter)); - //(String) param.get("ResultDate")); - - } catch (Exception e) {} - - } - - - return fileName; - } - - private String getItemKeyFromResultType(SetFinderDAOFactory sfDAOFactory, - String resultTypeKey) { - // - IQueryBreakdownTypeDao queryBreakdownTypeDao = sfDAOFactory - .getQueryBreakdownTypeDao(); - QtQueryBreakdownType queryBreakdownType = queryBreakdownTypeDao - .getBreakdownTypeByName(resultTypeKey); - String itemKey = queryBreakdownType.getValue(); - return itemKey; - } - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder; + +import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; +import java.io.File; +import java.io.FileOutputStream; +import edu.harvard.i2b2.crc.dao.xml.ValueExporter; +import edu.harvard.i2b2.crc.dao.EmailUtil; + +/** + * To add Length of Stay (This is for Oracle and Postgresl) For Sql Server change the sql statement from (DX to #DX) + * + * Add a entry to QT_BREAKDOWN_PATH + * NAME = LENGTH_OF_STAY + * VALUE = select length_of_stay as patient_range, count(distinct a.PATIENT_num) as patient_count from visit_dimension a, DX b where a.patient_num = b.patient_num group by a.length_of_stay order by 1 + * + * Add a entry to QT_QUERY_RESULT_TYPE + * RESULT_TYPE_ID = 13 (Or any unused number) + * NAME = LENGTH_OF_STAY + * DESCRIPTION = Length of Dtay Brealdown + * DISPLAY_TYPE_ID = CATNUM + * VISUAL_ATTRIBUTE_TYPE_ID = LA + * + * Add a new in CRCApplicationContext.xml + * + * + * LENGTH_OF_STAY + * + * edu.harvard.i2b2.crc.dao.setfinder.QueryResultPatientSQLCountGenerator + * + * + */ + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.io.UnsupportedEncodingException; +import java.security.SecureRandom; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.text.DateFormat; +import java.time.LocalDate; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.FormatStyle; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import jakarta.mail.MessagingException; +import jakarta.xml.bind.JAXBContext; +import jakarta.xml.bind.JAXBException; +import jakarta.xml.bind.Unmarshaller; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.db.JDBCUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.ProcessTimingReportUtil; +import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; +import edu.harvard.i2b2.crc.datavo.db.QtQueryBreakdownType; +import edu.harvard.i2b2.crc.datavo.db.QtQueryMaster; +import edu.harvard.i2b2.crc.datavo.db.QtQueryResultType; +import edu.harvard.i2b2.crc.datavo.i2b2result.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2result.DataType; +import edu.harvard.i2b2.crc.datavo.i2b2result.ResultEnvelopeType; +import edu.harvard.i2b2.crc.datavo.i2b2result.ResultType; +import edu.harvard.i2b2.crc.datavo.pm.UserType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.PanelType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultOutputOptionType; +import edu.harvard.i2b2.crc.delegate.pm.CallPMUtil; +import edu.harvard.i2b2.crc.opencsv.CSVWriter; +import edu.harvard.i2b2.crc.opencsv.ResultSetHelperService; +import edu.harvard.i2b2.crc.util.LogTimingUtil; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; +import edu.harvard.i2b2.crc.dao.xml.Item_orig; +import edu.harvard.i2b2.crc.dao.xml.Items; +import edu.harvard.i2b2.crc.dao.xml.ValueExport; +import net.lingala.zip4j.ZipFile; +//mport net.lingala.zip4j.ZipFile; +import net.lingala.zip4j.io.outputstream.ZipOutputStream; +import net.lingala.zip4j.model.ZipParameters; +import net.lingala.zip4j.model.enums.CompressionLevel; +import net.lingala.zip4j.model.enums.EncryptionMethod; +import java.io.StringReader; + +/** + * Setfinder's result genertor class. This class calculates patient break down + * for the result type. + * + * Calls the ontology to get the children for the result type and then + * calculates the patient count for each child of the result type. + */ +public class QueryResultPatientRequest extends CRCDAO implements IResultGenerator { + + protected final Log logesapi = LogFactory.getLog(getClass()); + + @Override + public String getResults() { + return xmlResult; + } + + private String xmlResult = null; + /** + * Function accepts parameter in Map. The patient count will be obfuscated + * if the user is OBFUS + */ + @Override + public void generateResult(Map param) throws CRCTimeOutException, + I2B2DAOException { + + + // mm create a csv in a folder + + + SetFinderConnection sfConn = (SetFinderConnection) param + .get("SetFinderConnection"); + SetFinderDAOFactory sfDAOFactory = (SetFinderDAOFactory) param + .get("SetFinderDAOFactory"); + + // String patientSetId = (String)param.get("PatientSetId"); + String queryInstanceId = (String) param.get("QueryInstanceId"); + String TEMP_DX_TABLE = (String) param.get("TEMP_DX_TABLE"); + String resultInstanceId = (String) param.get("ResultInstanceId"); + // String itemKey = (String) param.get("ItemKey"); + String resultTypeName = (String) param.get("ResultOptionName"); + + String requestedData = "\n"; + String finalResultOutput = ""; + + ValueExporter valueExport = null; + //ZipOutputStream zipStream; + + //List filesToAdd = new List; + //(String) param.get("ResultFullName"); + + String processTimingFlag = (String) param.get("ProcessTimingFlag"); + String projectId = (String) param.get("projectId"); + int obfuscatedRecordCount = (Integer) param.get("ObfuscatedRecordCount"); + int recordCount = (Integer) param.get("RecordCount"); + int resultPriority = (Integer) param.get("ResultPriority"); + int transactionTimeout = (Integer) param.get("TransactionTimeout"); + boolean obfscDataRoleFlag = (Boolean)param.get("ObfuscatedRoleFlag"); + QueryDefinitionType queryDef = (QueryDefinitionType)param.get("queryDef"); + List panelList = (List)param.get("panelList"); + List resultOptionList = (List) param.get("resultOptionList"); + + boolean skipCSV = false; + if ((Boolean)param.get("SkipCSV") != null) + skipCSV = (Boolean)param.get("SkipCSV"); + + this + .setDbSchemaName(sfDAOFactory.getDataSourceLookup() + .getFullSchema()); + Map ontologyKeyMap = (Map) param.get("setFinderResultOntologyKeyMap"); + String serverType = (String) param.get("ServerType"); + // CallOntologyUtil ontologyUtil = (CallOntologyUtil) param + // .get("CallOntologyUtil"); + List roles = (List) param.get("Roles"); + String tempTableName = ""; + PreparedStatement stmt = null; + boolean errorFlag = false, timeoutFlag = false; + //String itemKey = ""; + + int actualTotal = 0, obsfcTotal = 0; + + + QtQueryMaster queryMaster = sfDAOFactory.getQueryMasterDAO().getQueryDefinition(sfDAOFactory.getQueryInstanceDAO().getQueryInstanceByInstanceId(queryInstanceId).getQtQueryMaster().getQueryMasterId()); + UserType user = null; + sfDAOFactory.getQueryMasterDAO().renameQuery(queryMaster.getQueryMasterId(), "(" + queryMaster.getQueryMasterId() + ") " + queryDef.getQueryName()); + + try { + + if (recordCount==0) return; + + LogTimingUtil logTimingUtil = new LogTimingUtil(); + logTimingUtil.setStartTime(); + + LogTimingUtil subLogTimingUtil = new LogTimingUtil(); + subLogTimingUtil.setStartTime(); + + String exportItemXml = getItemKeyFromResultType(sfDAOFactory, resultTypeName); + + + + user = CallPMUtil.getUserFromResponse(queryMaster.getPmXml()); + + param.put("QueryStartDate", queryMaster.getCreateDate()); + param.put("FullName", user.getFullName()); + param.put("UserName", user.getUserName()); + param.put("Email", user.getEmail()); + //get break down count sigma from property file + + + //stmt = sfConn.prepareStatement(itemCountSql); + + CancelStatementRunner csr = new CancelStatementRunner(stmt, + transactionTimeout); + Thread csrThread = new Thread(csr); + csrThread.start(); + + //String sqlFinal = ""; + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + + valueExport = new ValueExporter(); + + + + valueExport = JaxbXmlToObj(exportItemXml); + + + //JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); + //ValueExport valueExport = (ValueExport) jaxbUtil + // .unMashallFromString(exportItemXml).getValue(); + + if (csr.getSqlFinishedFlag()) { + timeoutFlag = true; + throw new CRCTimeOutException("The query was canceled."); + } + + // + if (processTimingFlag != null) { + if (!processTimingFlag.trim().equalsIgnoreCase(ProcessTimingReportUtil.NONE) ) { + ProcessTimingReportUtil ptrUtil = new ProcessTimingReportUtil(sfDAOFactory.getDataSourceLookup()); + if (processTimingFlag.trim().equalsIgnoreCase(ProcessTimingReportUtil.DEBUG) ) { + ptrUtil.logProcessTimingMessage(queryInstanceId, ptrUtil.buildProcessTiming(subLogTimingUtil, "JAXB - " + resultTypeName , "")); + } + logTimingUtil.setEndTime(); + ptrUtil.logProcessTimingMessage(queryInstanceId, ptrUtil.buildProcessTiming(logTimingUtil, "BUILD - " + resultTypeName , "")); + } + } + //} + //tm.commit(); + + } catch (Exception sqlEx) { + + errorFlag = true; + log.error("QueryResultPatientSetGenerator.generateResult:" + + sqlEx.getMessage(), sqlEx); + throw new I2B2DAOException( + "QueryResultPatientSetGenerator.generateResult:" + + sqlEx.getMessage(), sqlEx); + } finally { + + if (resultInstanceId != null) { + IQueryResultInstanceDao resultInstanceDao = sfDAOFactory + .getPatientSetResultDAO(); + + if (errorFlag) { + resultInstanceDao.updatePatientSet(resultInstanceId, + QueryStatusTypeId.STATUSTYPE_ID_ERROR, 0); + } else { + // set the setsize and the description of the result instance if + // the user role is obfuscated + if (timeoutFlag == false) { // check if the query completed + try { + // tm.begin(); + + String obfusMethod = "", description = null; + if (obfscDataRoleFlag) { + obfusMethod = IQueryResultInstanceDao.OBSUBTOTAL; + // add () to the result type description + // read the description from result type + + } else { + obfuscatedRecordCount = recordCount; + } + IQueryResultTypeDao resultTypeDao = sfDAOFactory.getQueryResultTypeDao(); + List resultTypeList = resultTypeDao + .getQueryResultTypeByName(resultTypeName, null); + + // add "(Obfuscated)" in the description + //description = resultTypeList.get(0) + // .getDescription() + // + " (Obfuscated) "; + String queryName = sfDAOFactory.getQueryMasterDAO().getQueryDefinition( + sfDAOFactory.getQueryInstanceDAO().getQueryInstanceByInstanceId(queryInstanceId).getQtQueryMaster().getQueryMasterId()).getName(); + + + + resultInstanceDao.updatePatientSet(resultInstanceId, + QueryStatusTypeId.STATUSTYPE_ID_FINISHED, null, + //obsfcTotal, + obfuscatedRecordCount, recordCount, obfusMethod); + + if (recordCount == 0) + description = "0 patients, no email sent"; + else + description = resultTypeList.get(0) + .getDescription() + " for \"" + queryName +"\""; + + // set the result instance description + resultInstanceDao.updateResultInstanceDescription( + resultInstanceId, description); + // tm.commit(); + + + + if ((valueExport != null) && (recordCount != 0)) { + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + String letter = valueExport.getDataManagerEmailMessage(); + String requesterMessage = valueExport.getRequesterEmailMessage(); + if (letter != null) { + + letter = processFilename(letter, param); + + requesterMessage = processFilename(requesterMessage, param); + for (ResultOutputOptionType resultOutputOption : resultOptionList) { + String resultName = resultOutputOption.getName() + .toUpperCase(); + resultTypeList = resultTypeDao + .getQueryResultTypeByName(resultName, null); + if (resultTypeList.size() > 0) { + requestedData += resultTypeList.get(0).getDescription() + ", "; + finalResultOutput = resultTypeList.get(0).getName().toUpperCase(); + } + } + letter = letter.replaceAll("\\{\\{\\{REQUESTED_DATA_TYPE\\}\\}\\}",requestedData); + requesterMessage = requesterMessage.replaceAll("\\{\\{\\{REQUESTED_DATA_TYPE\\}\\}\\}",requestedData); + + + ResultType resultType = new ResultType(); + resultType.setName(resultTypeName); + DataType mdataType = new DataType(); + mdataType.setValue(String.valueOf(recordCount)); + mdataType.setColumn("patientCount"); + mdataType.setType("int"); + resultType.getData().add(mdataType); + mdataType = new DataType(); + mdataType.setValue(letter); + mdataType.setColumn("RequestEmail"); + mdataType.setType("string"); + resultType.getData().add(mdataType); + mdataType = new DataType(); + mdataType.setValue(qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.datamanageremail")); + mdataType.setColumn("DataManagerEmail"); + mdataType.setType("string"); + resultType.getData().add(mdataType); + + edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory(); + BodyType bodyType = new BodyType(); + bodyType.getAny().add(of.createResult(resultType)); + ResultEnvelopeType resultEnvelop = new ResultEnvelopeType(); + resultEnvelop.setBody(bodyType); + + //JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); + + StringWriter strWriter = new StringWriter(); + + //subLogTimingUtil.setStartTime(); + JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); + jaxbUtil.marshaller(of.createI2B2ResultEnvelope(resultEnvelop), + strWriter); + //subLogTimingUtil.setEndTime(); + //tm.begin(); + IXmlResultDao xmlResultDao = sfDAOFactory.getXmlResultDao(); + xmlResult = strWriter.toString(); + if (resultInstanceId != null) + xmlResultDao.createQueryXmlResult(resultInstanceId, strWriter + .toString()); +//qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.smtp.subject") + + if (qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.smtp.enabled").equalsIgnoreCase("true")) { + EmailUtil email = new EmailUtil(); + try { + + if (resultTypeName.equals(finalResultOutput)) { + email.email(qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.datamanageremail"), qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.datamanageremail"), "i2b2 Data Request", letter); + if (user.getEmail()!= null && !user.getEmail().equals("") && requesterMessage != null) + email.email(user.getEmail(), qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.datamanageremail"), "i2b2 Data Request", requesterMessage); + } + } catch (UnsupportedEncodingException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (I2B2Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (MessagingException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + + + } + } catch (SecurityException e) { + throw new I2B2DAOException( + "Failed to write obfuscated description " + + e.getMessage(), e); + } catch (IllegalStateException e) { + throw new I2B2DAOException( + "Failed to write obfuscated description " + + e.getMessage(), e); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + } + } + } + + + + + public static ValueExporter JaxbXmlToObj(String xmlString) { + + ValueExporter val = new ValueExporter(); + ValueExporter resultDataSet = null ; + JAXBContext jaxbContext; + try { + jaxbContext = JAXBContext.newInstance(val.getClass()); + + Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); + + resultDataSet = (ValueExporter) jaxbUnmarshaller.unmarshal(new StringReader(xmlString)); + + //System.out.println(resultDataSet); + } + catch (JAXBException e) { + e.printStackTrace(); + } + return resultDataSet; + } + private String sanitizeFilename(String filename) + { + + return filename.replaceAll("[^a-zA-Z0-9.-]", "_"); + } + /* + private static final Pattern TAG_REGEX = Pattern.compile("{{{(.+?)}}}", Pattern.DOTALL); + + + private static List getTagValues(final String str) { + final List tagValues = new ArrayList(); + final Matcher matcher = TAG_REGEX.matcher(str); + while (matcher.find()) { + tagValues.add(matcher.group(1)); + } + return tagValues; + } + */ + private char getChar(String sTerminatedBy) + { + if ("\\t".equals(sTerminatedBy)) { + return ( '\t'); + } else if ("\\n".equals(sTerminatedBy)) { + return ( '\n'); + } else if ("\\r".equals(sTerminatedBy)) { + return ( '\r'); + } else if ("\\f".equals(sTerminatedBy)) { + return ( '\f'); + } else if (null == sTerminatedBy || "".equals(sTerminatedBy) || "\\0".equals(sTerminatedBy)) { + return ('\0'); + } else { + return ( sTerminatedBy.charAt(0)); + } + + } + + private String processFilename(String fileName, Map param) + { + + + // SetFinderDAOFactory sfDAOFactory = (SetFinderDAOFactory) param + // .get("SetFinderDAOFactory"); + + String projectId = (String) param.get("projectId"); + String queryInstanceId = (String) param.get("QueryInstanceId"); + QueryDefinitionType queryDef = (QueryDefinitionType)param.get("queryDef"); + String resultFullName = queryDef.getQueryName(); + //queryDef.getQueryId() + + // String resultFullName = sfDAOFactory.getQueryMasterDAO().getQueryDefinition( + // sfDAOFactory.getQueryInstanceDAO().getQueryInstanceByInstanceId(queryInstanceId).getQtQueryMaster().getQueryMasterId()).getName(); + // QtQueryMaster qtMaster = sfDAOFactory.getQueryInstanceDAO().getQueryInstanceByInstanceId(queryInstanceId).getQtQueryMaster(); + + fileName = fileName.replaceAll("\\{\\{\\{USER_NAME\\}\\}\\}",(String) param.get("UserName"));//queryDef.getUserId()); + fileName = fileName.replaceAll("\\{\\{\\{QUERY_STARTDATE\\}\\}\\}", ((java.sql.Timestamp) param.get("QueryStartDate")).toLocaleString());//sfDAOFactory.getQueryInstanceDAO().getQueryInstanceByInstanceId(queryInstanceId).getStartDate().toLocaleString()); + fileName = fileName.replaceAll("\\{\\{\\{QUERY_ENDDATE\\}\\}\\}", new Date().toLocaleString()); + fileName = fileName.replaceAll("\\{\\{\\{QUERY_RUNTIME\\}\\}\\}", Integer.toString(Math.toIntExact(new Date().getTime() - ((java.sql.Timestamp) param.get("QueryStartDate")).getTime())/1000)); + + fileName = fileName.replaceAll("\\{\\{\\{PATIENT_COUNT\\}\\}\\}", param.get("RecordCount").toString()); + fileName = fileName.replaceAll("\\{\\{\\{FULL_NAME\\}\\}\\}", (String) param.get("FullName")); + fileName = fileName.replaceAll("\\{\\{\\{PROJECT_ID\\}\\}\\}", projectId.substring(1, projectId.length()-1)); + //fileName = fileName.replaceAll("\\{\\{\\{RESULT_INSTANCE_ID\\}\\}\\}", resultInstanceId); + fileName = fileName.replaceAll("\\{\\{\\{QUERY_NAME\\}\\}\\}", sanitizeFilename(resultFullName)); + fileName = fileName.replaceAll("\\{\\{\\{QUERY_MASTER_ID\\}\\}\\}", sanitizeFilename(queryInstanceId)); //qtMaster.getQueryMasterId())); + + while (fileName.contains("{{{RANDOM_")) + { + + try { + int start = fileName.indexOf("{{{RANDOM_"); + int end = fileName.indexOf("}}}", start); + int size = Integer.parseInt(fileName.substring(start+10, end)); + + //SecureRandom random = new SecureRandom(); + //fileName = fileName.replaceAll("\\{\\{\\{RANDOM_"+size+"\\}\\}\\}", String.valueOf(random.nextInt(size))); + fileName = fileName.replaceAll("\\{\\{\\{RANDOM_"+size+"\\}\\}\\}", (String) param.get("ResultRandom")); + + } catch (Exception e) {} + + } + // Deal with dates + while (fileName.contains("{{{DATE_")) + { + + try { + int start = fileName.indexOf("{{{DATE_"); + int end = fileName.indexOf("}}}", start); + String date = fileName.substring(start+8, end); + + //DateTimeFormatter formatter = DateTimeFormatter.ofPattern(date); + //fileName = fileName.replaceAll("\\{\\{\\{DATE_"+date+"\\}\\}\\}", LocalDate.now().format(formatter)); + + DateTimeFormatter formatter = DateTimeFormatter.ofPattern(date); + fileName = fileName.replaceAll("\\{\\{\\{DATE_"+date+"\\}\\}\\}", ((LocalDate) param.get("ResultDate")).format(formatter)); + //(String) param.get("ResultDate")); + + } catch (Exception e) {} + + } + + + return fileName; + } + + private String getItemKeyFromResultType(SetFinderDAOFactory sfDAOFactory, + String resultTypeKey) { + // + IQueryBreakdownTypeDao queryBreakdownTypeDao = sfDAOFactory + .getQueryBreakdownTypeDao(); + QtQueryBreakdownType queryBreakdownType = queryBreakdownTypeDao + .getBreakdownTypeByName(resultTypeKey); + String itemKey = queryBreakdownType.getValue(); + return itemKey; + } + + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientSQLCountGenerator.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientSQLCountGenerator.java similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientSQLCountGenerator.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientSQLCountGenerator.java index e4b76d00..cdb34d11 100644 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientSQLCountGenerator.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientSQLCountGenerator.java @@ -1,353 +1,353 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder; - - -/** - * To add Length of Stay (This is for Oracle and Postgresl) For Sql Server change the sql statement from (DX to #DX) - * - * Add a entry to QT_BREAKDOWN_PATH - * NAME = LENGTH_OF_STAY - * VALUE = select length_of_stay as patient_range, count(distinct a.PATIENT_num) as patient_count from visit_dimension a, DX b where a.patient_num = b.patient_num group by a.length_of_stay order by 1 - * - * Add a entry to QT_QUERY_RESULT_TYPE - * RESULT_TYPE_ID = 13 (Or any unused number) - * NAME = LENGTH_OF_STAY - * DESCRIPTION = Length of Dtay Brealdown - * DISPLAY_TYPE_ID = CATNUM - * VISUAL_ATTRIBUTE_TYPE_ID = LA - * - * Add a new in CRCApplicationContext.xml - * - * - * LENGTH_OF_STAY - * - * edu.harvard.i2b2.crc.dao.setfinder.QueryResultPatientSQLCountGenerator - * - * - */ - - -import java.io.StringWriter; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.List; -import java.util.Map; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.util.db.JDBCUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.ProcessTimingReportUtil; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.db.QtQueryBreakdownType; -import edu.harvard.i2b2.crc.datavo.db.QtQueryResultType; -import edu.harvard.i2b2.crc.datavo.i2b2result.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2result.DataType; -import edu.harvard.i2b2.crc.datavo.i2b2result.ResultEnvelopeType; -import edu.harvard.i2b2.crc.datavo.i2b2result.ResultType; -import edu.harvard.i2b2.crc.util.LogTimingUtil; - -/** - * Setfinder's result genertor class. This class calculates patient break down - * for the result type. - * - * Calls the ontology to get the children for the result type and then - * calculates the patient count for each child of the result type. - */ -public class QueryResultPatientSQLCountGenerator extends CRCDAO implements IResultGenerator { - - protected final Log logesapi = LogFactory.getLog(getClass()); - - @Override - public String getResults() { - return xmlResult; - } - - private String xmlResult = null; - /** - * Function accepts parameter in Map. The patient count will be obfuscated - * if the user is OBFUS - */ - @Override - public void generateResult(Map param) throws CRCTimeOutException, - I2B2DAOException { - - SetFinderConnection sfConn = (SetFinderConnection) param - .get("SetFinderConnection"); - SetFinderDAOFactory sfDAOFactory = (SetFinderDAOFactory) param - .get("SetFinderDAOFactory"); - - // String patientSetId = (String)param.get("PatientSetId"); - String queryInstanceId = (String) param.get("QueryInstanceId"); - String TEMP_DX_TABLE = (String) param.get("TEMP_DX_TABLE"); - String resultInstanceId = (String) param.get("ResultInstanceId"); - // String itemKey = (String) param.get("ItemKey"); - String resultTypeName = (String) param.get("ResultOptionName"); - String processTimingFlag = (String) param.get("ProcessTimingFlag"); - int obfuscatedRecordCount = (Integer) param.get("ObfuscatedRecordCount"); - int recordCount = (Integer) param.get("RecordCount"); - int transactionTimeout = (Integer) param.get("TransactionTimeout"); - long dxCreateTime = (Long) param.get("DXCreateTime"); - transactionTimeout = transactionTimeout - Math.toIntExact(dxCreateTime); - boolean obfscDataRoleFlag = (Boolean)param.get("ObfuscatedRoleFlag"); - - this - .setDbSchemaName(sfDAOFactory.getDataSourceLookup() - .getFullSchema()); - //Map ontologyKeyMap = (Map) param.get("setFinderResultOntologyKeyMap"); - String serverType = (String) param.get("ServerType"); - // CallOntologyUtil ontologyUtil = (CallOntologyUtil) param - // .get("CallOntologyUtil"); - List roles = (List) param.get("Roles"); - String tempTableName = ""; - PreparedStatement stmt = null; - boolean errorFlag = false, timeoutFlag = false; - //String itemKey = ""; - - int actualTotal = 0, obsfcTotal = 0; - - try { - LogTimingUtil logTimingUtil = new LogTimingUtil(); - logTimingUtil.setStartTime(); - - LogTimingUtil subLogTimingUtil = new LogTimingUtil(); - subLogTimingUtil.setStartTime(); - - String itemCountSql = getItemKeyFromResultType(sfDAOFactory, resultTypeName); - - //get break down count sigma from property file - - double breakdownCountSigma = GaussianBoxMuller.getBreakdownCountSigma(); - double obfuscatedMinimumValue = GaussianBoxMuller.getObfuscatedMinimumVal(); - - ResultType resultType = new ResultType(); - resultType.setName(resultTypeName); - //stmt = sfConn.prepareStatement(itemCountSql); - - CancelStatementRunner csr = new CancelStatementRunner(stmt, - transactionTimeout); - Thread csrThread = new Thread(csr); - csrThread.start(); - - //String sqlFinal = ""; - - if (itemCountSql.contains("{{{DX}}}")) - itemCountSql = itemCountSql.replaceAll("\\{\\{\\{DX\\}\\}\\}", TEMP_DX_TABLE); - if (itemCountSql.contains("{{{DATABASE_NAME}}}")) - itemCountSql = itemCountSql.replaceAll("\\{\\{\\{DATABASE_NAME\\}\\}\\}", this.getDbSchemaName()); - - - log.info("Timeout to run breakdowns: " + transactionTimeout); - String[] sqls = itemCountSql.split("<\\*>"); - int count = 0; - while (count < sqls.length - 1) - { - - stmt = sfConn.prepareStatement(sqls[count]); - stmt.setQueryTimeout(transactionTimeout); - logesapi.debug("Executing count sql [" + sqls[count] + "]"); - - // - subLogTimingUtil.setStartTime(); - ResultSet resultSet = stmt.executeQuery(); - if (csr.getSqlFinishedFlag()) { - timeoutFlag = true; - throw new CRCTimeOutException("The query was canceled."); - } - - count++; - } - - - stmt = sfConn.prepareStatement(sqls[count]); - stmt.setQueryTimeout(transactionTimeout); - logesapi.debug("Executing count sql [" + sqls[count] + "]"); - - // - subLogTimingUtil.setStartTime(); - ResultSet resultSet = stmt.executeQuery(); - if (csr.getSqlFinishedFlag()) { - timeoutFlag = true; - throw new CRCTimeOutException("The query was canceled."); - } - while (resultSet.next()) { - int demoCount = resultSet.getInt("patient_count"); - subLogTimingUtil.setEndTime(); - if (processTimingFlag != null) { - if (processTimingFlag.trim().equalsIgnoreCase(ProcessTimingReportUtil.DEBUG) ) { - ProcessTimingReportUtil ptrUtil = new ProcessTimingReportUtil(sfDAOFactory.getDataSourceLookup()); - ptrUtil.logProcessTimingMessage(queryInstanceId, ptrUtil.buildProcessTiming(subLogTimingUtil, "BUILD - " + resultTypeName, "sql="+itemCountSql)); - } - } - // - - actualTotal += demoCount; - if (obfscDataRoleFlag) { - GaussianBoxMuller gaussianBoxMuller = new GaussianBoxMuller(); - demoCount = (int) gaussianBoxMuller - .getNormalizedValueForCount(demoCount,breakdownCountSigma,obfuscatedMinimumValue); - obsfcTotal += demoCount; - } - DataType mdataType = new DataType(); - - String rangeCd = resultSet.getString("patient_range"); - - mdataType.setValue(String.valueOf(demoCount)); - mdataType.setColumn(rangeCd); - mdataType.setType("int"); - resultType.getData().add(mdataType); - - } - - csr.setSqlFinishedFlag(); - csrThread.interrupt(); - stmt.close(); - - edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory(); - BodyType bodyType = new BodyType(); - bodyType.getAny().add(of.createResult(resultType)); - ResultEnvelopeType resultEnvelop = new ResultEnvelopeType(); - resultEnvelop.setBody(bodyType); - - JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); - - StringWriter strWriter = new StringWriter(); - subLogTimingUtil.setStartTime(); - jaxbUtil.marshaller(of.createI2B2ResultEnvelope(resultEnvelop), - strWriter); - subLogTimingUtil.setEndTime(); - //tm.begin(); - IXmlResultDao xmlResultDao = sfDAOFactory.getXmlResultDao(); - xmlResult = strWriter.toString(); - if (resultInstanceId != null) - xmlResultDao.createQueryXmlResult(resultInstanceId, strWriter - .toString()); - // - if (processTimingFlag != null) { - if (!processTimingFlag.trim().equalsIgnoreCase(ProcessTimingReportUtil.NONE) ) { - ProcessTimingReportUtil ptrUtil = new ProcessTimingReportUtil(sfDAOFactory.getDataSourceLookup()); - if (processTimingFlag.trim().equalsIgnoreCase(ProcessTimingReportUtil.DEBUG) ) { - ptrUtil.logProcessTimingMessage(queryInstanceId, ptrUtil.buildProcessTiming(subLogTimingUtil, "JAXB - " + resultTypeName , "")); - } - logTimingUtil.setEndTime(); - ptrUtil.logProcessTimingMessage(queryInstanceId, ptrUtil.buildProcessTiming(logTimingUtil, "BUILD - " + resultTypeName , "")); - } - } - //tm.commit(); - - } catch (SQLException sqlEx) { - // catch oracle query timeout error ORA-01013 - if (sqlEx.toString().indexOf("ORA-01013") > -1) { - timeoutFlag = true; - throw new CRCTimeOutException(sqlEx.getMessage(), sqlEx); - } - if (sqlEx.getMessage().indexOf("The query was canceled.") > -1) { - timeoutFlag = true; - throw new CRCTimeOutException(sqlEx.getMessage(), sqlEx); - } - if (sqlEx.getMessage().indexOf("timed out") > -1) { - timeoutFlag = true; - throw new CRCTimeOutException(sqlEx.getMessage(), sqlEx); - } - errorFlag = true; - log.error("Error while executing sql", sqlEx); - throw new I2B2DAOException("Error while executing sql", sqlEx); - } catch (Exception sqlEx) { - - errorFlag = true; - log.error("QueryResultPatientSetGenerator.generateResult:" - + sqlEx.getMessage(), sqlEx); - throw new I2B2DAOException( - "QueryResultPatientSetGenerator.generateResult:" - + sqlEx.getMessage(), sqlEx); - } finally { - - if (resultInstanceId != null) { - IQueryResultInstanceDao resultInstanceDao = sfDAOFactory - .getPatientSetResultDAO(); - - if (errorFlag) { - resultInstanceDao.updatePatientSet(resultInstanceId, - QueryStatusTypeId.STATUSTYPE_ID_ERROR, 0); - } else { - // set the setsize and the description of the result instance if - // the user role is obfuscated - if (timeoutFlag == false) { // check if the query completed - try { - // tm.begin(); - - String obfusMethod = "", description = null; - if (obfscDataRoleFlag) { - obfusMethod = IQueryResultInstanceDao.OBSUBTOTAL; - // add () to the result type description - // read the description from result type - - } else { - obfuscatedRecordCount = recordCount; - } - IQueryResultTypeDao resultTypeDao = sfDAOFactory.getQueryResultTypeDao(); - List resultTypeList = resultTypeDao - .getQueryResultTypeByName(resultTypeName, roles); - - // add "(Obfuscated)" in the description - //description = resultTypeList.get(0) - // .getDescription() - // + " (Obfuscated) "; - String queryName = sfDAOFactory.getQueryMasterDAO().getQueryDefinition( - sfDAOFactory.getQueryInstanceDAO().getQueryInstanceByInstanceId(queryInstanceId).getQtQueryMaster().getQueryMasterId()).getName(); - - - - resultInstanceDao.updatePatientSet(resultInstanceId, - QueryStatusTypeId.STATUSTYPE_ID_FINISHED, null, - //obsfcTotal, - obfuscatedRecordCount, recordCount, obfusMethod); - - description = resultTypeList.get(0) - .getDescription() + " for \"" + queryName +"\""; - - // set the result instance description - resultInstanceDao.updateResultInstanceDescription( - resultInstanceId, description); - // tm.commit(); - } catch (SecurityException e) { - throw new I2B2DAOException( - "Failed to write obfuscated description " - + e.getMessage(), e); - } catch (IllegalStateException e) { - throw new I2B2DAOException( - "Failed to write obfuscated description " - + e.getMessage(), e); - } - } - } - } - } - - } - - private String getItemKeyFromResultType(SetFinderDAOFactory sfDAOFactory, - String resultTypeKey) { - // - IQueryBreakdownTypeDao queryBreakdownTypeDao = sfDAOFactory - .getQueryBreakdownTypeDao(); - QtQueryBreakdownType queryBreakdownType = queryBreakdownTypeDao - .getBreakdownTypeByName(resultTypeKey); - String itemKey = queryBreakdownType.getValue(); - return itemKey; - } - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder; + + +/** + * To add Length of Stay (This is for Oracle and Postgresl) For Sql Server change the sql statement from (DX to #DX) + * + * Add a entry to QT_BREAKDOWN_PATH + * NAME = LENGTH_OF_STAY + * VALUE = select length_of_stay as patient_range, count(distinct a.PATIENT_num) as patient_count from visit_dimension a, DX b where a.patient_num = b.patient_num group by a.length_of_stay order by 1 + * + * Add a entry to QT_QUERY_RESULT_TYPE + * RESULT_TYPE_ID = 13 (Or any unused number) + * NAME = LENGTH_OF_STAY + * DESCRIPTION = Length of Dtay Brealdown + * DISPLAY_TYPE_ID = CATNUM + * VISUAL_ATTRIBUTE_TYPE_ID = LA + * + * Add a new in CRCApplicationContext.xml + * + * + * LENGTH_OF_STAY + * + * edu.harvard.i2b2.crc.dao.setfinder.QueryResultPatientSQLCountGenerator + * + * + */ + + +import java.io.StringWriter; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.List; +import java.util.Map; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.util.db.JDBCUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.ProcessTimingReportUtil; +import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; +import edu.harvard.i2b2.crc.datavo.db.QtQueryBreakdownType; +import edu.harvard.i2b2.crc.datavo.db.QtQueryResultType; +import edu.harvard.i2b2.crc.datavo.i2b2result.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2result.DataType; +import edu.harvard.i2b2.crc.datavo.i2b2result.ResultEnvelopeType; +import edu.harvard.i2b2.crc.datavo.i2b2result.ResultType; +import edu.harvard.i2b2.crc.util.LogTimingUtil; + +/** + * Setfinder's result genertor class. This class calculates patient break down + * for the result type. + * + * Calls the ontology to get the children for the result type and then + * calculates the patient count for each child of the result type. + */ +public class QueryResultPatientSQLCountGenerator extends CRCDAO implements IResultGenerator { + + protected final Log logesapi = LogFactory.getLog(getClass()); + + @Override + public String getResults() { + return xmlResult; + } + + private String xmlResult = null; + /** + * Function accepts parameter in Map. The patient count will be obfuscated + * if the user is OBFUS + */ + @Override + public void generateResult(Map param) throws CRCTimeOutException, + I2B2DAOException { + + SetFinderConnection sfConn = (SetFinderConnection) param + .get("SetFinderConnection"); + SetFinderDAOFactory sfDAOFactory = (SetFinderDAOFactory) param + .get("SetFinderDAOFactory"); + + // String patientSetId = (String)param.get("PatientSetId"); + String queryInstanceId = (String) param.get("QueryInstanceId"); + String TEMP_DX_TABLE = (String) param.get("TEMP_DX_TABLE"); + String resultInstanceId = (String) param.get("ResultInstanceId"); + // String itemKey = (String) param.get("ItemKey"); + String resultTypeName = (String) param.get("ResultOptionName"); + String processTimingFlag = (String) param.get("ProcessTimingFlag"); + int obfuscatedRecordCount = (Integer) param.get("ObfuscatedRecordCount"); + int recordCount = (Integer) param.get("RecordCount"); + int transactionTimeout = (Integer) param.get("TransactionTimeout"); + long dxCreateTime = (Long) param.get("DXCreateTime"); + transactionTimeout = transactionTimeout - Math.toIntExact(dxCreateTime); + boolean obfscDataRoleFlag = (Boolean)param.get("ObfuscatedRoleFlag"); + + this + .setDbSchemaName(sfDAOFactory.getDataSourceLookup() + .getFullSchema()); + //Map ontologyKeyMap = (Map) param.get("setFinderResultOntologyKeyMap"); + String serverType = (String) param.get("ServerType"); + // CallOntologyUtil ontologyUtil = (CallOntologyUtil) param + // .get("CallOntologyUtil"); + List roles = (List) param.get("Roles"); + String tempTableName = ""; + PreparedStatement stmt = null; + boolean errorFlag = false, timeoutFlag = false; + //String itemKey = ""; + + int actualTotal = 0, obsfcTotal = 0; + + try { + LogTimingUtil logTimingUtil = new LogTimingUtil(); + logTimingUtil.setStartTime(); + + LogTimingUtil subLogTimingUtil = new LogTimingUtil(); + subLogTimingUtil.setStartTime(); + + String itemCountSql = getItemKeyFromResultType(sfDAOFactory, resultTypeName); + + //get break down count sigma from property file + + double breakdownCountSigma = GaussianBoxMuller.getBreakdownCountSigma(); + double obfuscatedMinimumValue = GaussianBoxMuller.getObfuscatedMinimumVal(); + + ResultType resultType = new ResultType(); + resultType.setName(resultTypeName); + //stmt = sfConn.prepareStatement(itemCountSql); + + CancelStatementRunner csr = new CancelStatementRunner(stmt, + transactionTimeout); + Thread csrThread = new Thread(csr); + csrThread.start(); + + //String sqlFinal = ""; + + if (itemCountSql.contains("{{{DX}}}")) + itemCountSql = itemCountSql.replaceAll("\\{\\{\\{DX\\}\\}\\}", TEMP_DX_TABLE); + if (itemCountSql.contains("{{{DATABASE_NAME}}}")) + itemCountSql = itemCountSql.replaceAll("\\{\\{\\{DATABASE_NAME\\}\\}\\}", this.getDbSchemaName()); + + + log.info("Timeout to run breakdowns: " + transactionTimeout); + String[] sqls = itemCountSql.split("<\\*>"); + int count = 0; + while (count < sqls.length - 1) + { + + stmt = sfConn.prepareStatement(sqls[count]); + stmt.setQueryTimeout(transactionTimeout); + logesapi.debug("Executing count sql [" + sqls[count] + "]"); + + // + subLogTimingUtil.setStartTime(); + ResultSet resultSet = stmt.executeQuery(); + if (csr.getSqlFinishedFlag()) { + timeoutFlag = true; + throw new CRCTimeOutException("The query was canceled."); + } + + count++; + } + + + stmt = sfConn.prepareStatement(sqls[count]); + stmt.setQueryTimeout(transactionTimeout); + logesapi.debug("Executing count sql [" + sqls[count] + "]"); + + // + subLogTimingUtil.setStartTime(); + ResultSet resultSet = stmt.executeQuery(); + if (csr.getSqlFinishedFlag()) { + timeoutFlag = true; + throw new CRCTimeOutException("The query was canceled."); + } + while (resultSet.next()) { + int demoCount = resultSet.getInt("patient_count"); + subLogTimingUtil.setEndTime(); + if (processTimingFlag != null) { + if (processTimingFlag.trim().equalsIgnoreCase(ProcessTimingReportUtil.DEBUG) ) { + ProcessTimingReportUtil ptrUtil = new ProcessTimingReportUtil(sfDAOFactory.getDataSourceLookup()); + ptrUtil.logProcessTimingMessage(queryInstanceId, ptrUtil.buildProcessTiming(subLogTimingUtil, "BUILD - " + resultTypeName, "sql="+itemCountSql)); + } + } + // + + actualTotal += demoCount; + if (obfscDataRoleFlag) { + GaussianBoxMuller gaussianBoxMuller = new GaussianBoxMuller(); + demoCount = (int) gaussianBoxMuller + .getNormalizedValueForCount(demoCount,breakdownCountSigma,obfuscatedMinimumValue); + obsfcTotal += demoCount; + } + DataType mdataType = new DataType(); + + String rangeCd = resultSet.getString("patient_range"); + + mdataType.setValue(String.valueOf(demoCount)); + mdataType.setColumn(rangeCd); + mdataType.setType("int"); + resultType.getData().add(mdataType); + + } + + csr.setSqlFinishedFlag(); + csrThread.interrupt(); + stmt.close(); + + edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory(); + BodyType bodyType = new BodyType(); + bodyType.getAny().add(of.createResult(resultType)); + ResultEnvelopeType resultEnvelop = new ResultEnvelopeType(); + resultEnvelop.setBody(bodyType); + + JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); + + StringWriter strWriter = new StringWriter(); + subLogTimingUtil.setStartTime(); + jaxbUtil.marshaller(of.createI2B2ResultEnvelope(resultEnvelop), + strWriter); + subLogTimingUtil.setEndTime(); + //tm.begin(); + IXmlResultDao xmlResultDao = sfDAOFactory.getXmlResultDao(); + xmlResult = strWriter.toString(); + if (resultInstanceId != null) + xmlResultDao.createQueryXmlResult(resultInstanceId, strWriter + .toString()); + // + if (processTimingFlag != null) { + if (!processTimingFlag.trim().equalsIgnoreCase(ProcessTimingReportUtil.NONE) ) { + ProcessTimingReportUtil ptrUtil = new ProcessTimingReportUtil(sfDAOFactory.getDataSourceLookup()); + if (processTimingFlag.trim().equalsIgnoreCase(ProcessTimingReportUtil.DEBUG) ) { + ptrUtil.logProcessTimingMessage(queryInstanceId, ptrUtil.buildProcessTiming(subLogTimingUtil, "JAXB - " + resultTypeName , "")); + } + logTimingUtil.setEndTime(); + ptrUtil.logProcessTimingMessage(queryInstanceId, ptrUtil.buildProcessTiming(logTimingUtil, "BUILD - " + resultTypeName , "")); + } + } + //tm.commit(); + + } catch (SQLException sqlEx) { + // catch oracle query timeout error ORA-01013 + if (sqlEx.toString().indexOf("ORA-01013") > -1) { + timeoutFlag = true; + throw new CRCTimeOutException(sqlEx.getMessage(), sqlEx); + } + if (sqlEx.getMessage().indexOf("The query was canceled.") > -1) { + timeoutFlag = true; + throw new CRCTimeOutException(sqlEx.getMessage(), sqlEx); + } + if (sqlEx.getMessage().indexOf("timed out") > -1) { + timeoutFlag = true; + throw new CRCTimeOutException(sqlEx.getMessage(), sqlEx); + } + errorFlag = true; + log.error("Error while executing sql", sqlEx); + throw new I2B2DAOException("Error while executing sql", sqlEx); + } catch (Exception sqlEx) { + + errorFlag = true; + log.error("QueryResultPatientSetGenerator.generateResult:" + + sqlEx.getMessage(), sqlEx); + throw new I2B2DAOException( + "QueryResultPatientSetGenerator.generateResult:" + + sqlEx.getMessage(), sqlEx); + } finally { + + if (resultInstanceId != null) { + IQueryResultInstanceDao resultInstanceDao = sfDAOFactory + .getPatientSetResultDAO(); + + if (errorFlag) { + resultInstanceDao.updatePatientSet(resultInstanceId, + QueryStatusTypeId.STATUSTYPE_ID_ERROR, 0); + } else { + // set the setsize and the description of the result instance if + // the user role is obfuscated + if (timeoutFlag == false) { // check if the query completed + try { + // tm.begin(); + + String obfusMethod = "", description = null; + if (obfscDataRoleFlag) { + obfusMethod = IQueryResultInstanceDao.OBSUBTOTAL; + // add () to the result type description + // read the description from result type + + } else { + obfuscatedRecordCount = recordCount; + } + IQueryResultTypeDao resultTypeDao = sfDAOFactory.getQueryResultTypeDao(); + List resultTypeList = resultTypeDao + .getQueryResultTypeByName(resultTypeName, roles); + + // add "(Obfuscated)" in the description + //description = resultTypeList.get(0) + // .getDescription() + // + " (Obfuscated) "; + String queryName = sfDAOFactory.getQueryMasterDAO().getQueryDefinition( + sfDAOFactory.getQueryInstanceDAO().getQueryInstanceByInstanceId(queryInstanceId).getQtQueryMaster().getQueryMasterId()).getName(); + + + + resultInstanceDao.updatePatientSet(resultInstanceId, + QueryStatusTypeId.STATUSTYPE_ID_FINISHED, null, + //obsfcTotal, + obfuscatedRecordCount, recordCount, obfusMethod); + + description = resultTypeList.get(0) + .getDescription() + " for \"" + queryName +"\""; + + // set the result instance description + resultInstanceDao.updateResultInstanceDescription( + resultInstanceId, description); + // tm.commit(); + } catch (SecurityException e) { + throw new I2B2DAOException( + "Failed to write obfuscated description " + + e.getMessage(), e); + } catch (IllegalStateException e) { + throw new I2B2DAOException( + "Failed to write obfuscated description " + + e.getMessage(), e); + } + } + } + } + } + + } + + private String getItemKeyFromResultType(SetFinderDAOFactory sfDAOFactory, + String resultTypeKey) { + // + IQueryBreakdownTypeDao queryBreakdownTypeDao = sfDAOFactory + .getQueryBreakdownTypeDao(); + QtQueryBreakdownType queryBreakdownType = queryBreakdownTypeDao + .getBreakdownTypeByName(resultTypeKey); + String itemKey = queryBreakdownType.getValue(); + return itemKey; + } + + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientSetGenerator.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientSetGenerator.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientSetGenerator.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientSetGenerator.java index 314a64d4..bd3f6767 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientSetGenerator.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientSetGenerator.java @@ -1,201 +1,201 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder; - -import java.sql.PreparedStatement; -import java.sql.SQLException; -import java.util.List; -import java.util.Map; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.dao.IDAOFactory; -import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.ProcessTimingReportUtil; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.ejb.role.MissingRoleException; -import edu.harvard.i2b2.crc.role.AuthrizationHelper; -import edu.harvard.i2b2.crc.util.LogTimingUtil; - -public class QueryResultPatientSetGenerator extends CRCDAO implements - IResultGenerator { - - protected final Log logesapi = LogFactory.getLog(getClass()); - - @Override - public String getResults() { - return xmlResult; - } - - private String xmlResult = null; - - - @Override - public void generateResult(Map param) throws I2B2DAOException { - - SetFinderConnection sfConn = (SetFinderConnection) param - .get("SetFinderConnection"); - SetFinderDAOFactory sfDAOFactory = (SetFinderDAOFactory) param - .get("SetFinderDAOFactory"); - // String patientSetId = (String)param.get("PatientSetId"); - String queryInstanceId = (String) param.get("QueryInstanceId"); - String TEMP_DX_TABLE = (String) param.get("TEMP_DX_TABLE"); - String resultInstanceId = (String) param.get("ResultInstanceId"); - String resultTypeName = (String) param.get("ResultOptionName"); - String processTimingFlag = (String) param.get("ProcessTimingFlag"); - int obfucatedRecordCount = (Integer) param.get("ObfuscatedRecordCount"); - DataSourceLookup originalDataSource = (DataSourceLookup) param - .get("OriginalDataSourceLookup"); - List roles = (List) param.get("Roles"); - this.setDbSchemaName(sfDAOFactory.getDataSourceLookup().getFullSchema()); - - boolean errorFlag = false; - Exception exception = null; - int loadCount = 0, realCount = 0; - String obfuscationDescription = "", obfusMethod = ""; - - try { - - int i = 0; - IPatientSetCollectionDao patientSetCollectionDao = sfDAOFactory - .getPatientSetCollectionDAO(); - patientSetCollectionDao - .createPatientSetCollection(resultInstanceId); - - String patientIdSql = " select distinct patient_num from " + TEMP_DX_TABLE - + " order by patient_num "; - - //// - //JNix: refactored to no longer pull down records just to insert back. - String sql = null; - String dbSchemaName = this.getDbSchemaName(); - if (sfDAOFactory.getDataSourceLookup().getServerType().equals(DAOFactoryHelper.ORACLE)) { - sql = "INSERT INTO qt_patient_set_collection" - + " (patient_set_coll_id, result_instance_id, set_index, patient_num) " - + "SELECT QT_SQ_QPR_PCID.nextval AS patient_set_coll_id, ? AS result_instance_id, rownum AS set_index, t.patient_num " - + "FROM (SELECT DISTINCT patient_num FROM ) t"; - } else if (sfDAOFactory.getDataSourceLookup().getServerType().equalsIgnoreCase(DAOFactoryHelper.SQLSERVER) || - sfDAOFactory.getDataSourceLookup().getServerType().equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { - sql = "INSERT INTO qt_patient_set_collection" - + " (result_instance_id, set_index, patient_num) " - + "SELECT ? AS result_instance_id, ROW_NUMBER() OVER(ORDER BY patient_num) AS set_index, t.patient_num " - + "FROM (SELECT DISTINCT patient_num FROM ) t"; - } - log.debug("Executing sql:\n" + sql); - - String sqlFinal = sql.replace("", this.getDbSchemaName() ); - sqlFinal = sqlFinal.replace("", TEMP_DX_TABLE); - - LogTimingUtil logTimingUtil = new LogTimingUtil(); - logTimingUtil.setStartTime(); - PreparedStatement ps = sfConn.prepareStatement(sqlFinal); - ps.setInt(1, Integer.parseInt(resultInstanceId)); - loadCount = ps.executeUpdate(); - ps.close(); - logTimingUtil.setEndTime(); - logesapi.debug("Total patients loaded for query instance =" - + queryInstanceId + " is [" + loadCount + "]"); - //// - if (processTimingFlag != null) { - if (!processTimingFlag.trim().equalsIgnoreCase(ProcessTimingReportUtil.NONE) ) { - ProcessTimingReportUtil ptrUtil = new ProcessTimingReportUtil(sfDAOFactory.getDataSourceLookup()); - ptrUtil.logProcessTimingMessage(queryInstanceId, ptrUtil.buildProcessTiming(logTimingUtil, "BUILD - PATIENTSET", "")); - } - } - realCount = loadCount; - - - // check for the user role to see if it needs data obfscation - DataSourceLookup dataSourceLookup = sfDAOFactory - .getOriginalDataSourceLookup(); - String domainId = originalDataSource.getDomainId(); - String projectId = originalDataSource.getProjectPath(); - String userId = originalDataSource.getOwnerId(); - boolean noDataAggFlag = false, noDataObfscFlag = false; - - DAOFactoryHelper helper = new DAOFactoryHelper(dataSourceLookup - .getDomainId(), dataSourceLookup.getProjectPath(), - dataSourceLookup.getOwnerId()); - - IDAOFactory daoFactory = helper.getDAOFactory(); - AuthrizationHelper authHelper = new AuthrizationHelper(domainId, - projectId, userId, daoFactory); - - try { - authHelper.checkRoleForProtectionLabel( - "SETFINDER_QRY_WITHOUT_DATAOBFSC", roles); - } catch (MissingRoleException noRoleEx) { - noDataAggFlag = true; - } catch (I2B2Exception e) { - throw e; - } - try { - authHelper.checkRoleForProtectionLabel( - "SETFINDER_QRY_WITH_DATAOBFSC", roles); - } catch (MissingRoleException noRoleEx) { - noDataObfscFlag = true; - } catch (I2B2Exception e) { - throw e; - } - - if (noDataAggFlag && !noDataObfscFlag) { - obfuscationDescription = "~"; - obfusMethod = IQueryResultInstanceDao.OBTOTAL; - GaussianBoxMuller gaussianBoxMuller = new GaussianBoxMuller(); - //read count sigma from property file - double countSigma = GaussianBoxMuller.getCountSigma(); - double obfuscatedMinimumValue = GaussianBoxMuller.getObfuscatedMinimumVal(); - loadCount = (int) gaussianBoxMuller - .getNormalizedValueForCount(loadCount,countSigma,obfuscatedMinimumValue); - } else { - obfucatedRecordCount = loadCount; - } - - // readQueryStmt.close(); - } catch (SQLException sqlEx) { - exception = sqlEx; - log.error("QueryResultPatientSetGenerator.generateResult:" - + sqlEx.getMessage(), sqlEx); - throw new I2B2DAOException( - "QueryResultPatientSetGenerator.generateResult:" - + sqlEx.getMessage(), sqlEx); - - } catch (Throwable throwable) { - throwable.printStackTrace(); - } finally { - IQueryResultInstanceDao resultInstanceDao = sfDAOFactory - .getPatientSetResultDAO(); - - String queryName = sfDAOFactory.getQueryMasterDAO().getQueryDefinition( - sfDAOFactory.getQueryInstanceDAO().getQueryInstanceByInstanceId(queryInstanceId).getQtQueryMaster().getQueryMasterId()).getName(); - - if (errorFlag) { - resultInstanceDao.updatePatientSet(resultInstanceId, - QueryStatusTypeId.STATUSTYPE_ID_ERROR, 0); - } else { - resultInstanceDao.updatePatientSet(resultInstanceId, - QueryStatusTypeId.STATUSTYPE_ID_FINISHED, "", - obfucatedRecordCount, - //loadCount, - realCount, obfusMethod); - //String description = "Patient Set - " + obfuscationDescription - // + loadCount + " Patients"; - String description = "Patient Set for \"" + queryName +"\""; - resultInstanceDao.updateResultInstanceDescription( - resultInstanceId, description); - - } - } - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder; + +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.List; +import java.util.Map; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.dao.IDAOFactory; +import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.ProcessTimingReportUtil; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.ejb.role.MissingRoleException; +import edu.harvard.i2b2.crc.role.AuthrizationHelper; +import edu.harvard.i2b2.crc.util.LogTimingUtil; + +public class QueryResultPatientSetGenerator extends CRCDAO implements + IResultGenerator { + + protected final Log logesapi = LogFactory.getLog(getClass()); + + @Override + public String getResults() { + return xmlResult; + } + + private String xmlResult = null; + + + @Override + public void generateResult(Map param) throws I2B2DAOException { + + SetFinderConnection sfConn = (SetFinderConnection) param + .get("SetFinderConnection"); + SetFinderDAOFactory sfDAOFactory = (SetFinderDAOFactory) param + .get("SetFinderDAOFactory"); + // String patientSetId = (String)param.get("PatientSetId"); + String queryInstanceId = (String) param.get("QueryInstanceId"); + String TEMP_DX_TABLE = (String) param.get("TEMP_DX_TABLE"); + String resultInstanceId = (String) param.get("ResultInstanceId"); + String resultTypeName = (String) param.get("ResultOptionName"); + String processTimingFlag = (String) param.get("ProcessTimingFlag"); + int obfucatedRecordCount = (Integer) param.get("ObfuscatedRecordCount"); + DataSourceLookup originalDataSource = (DataSourceLookup) param + .get("OriginalDataSourceLookup"); + List roles = (List) param.get("Roles"); + this.setDbSchemaName(sfDAOFactory.getDataSourceLookup().getFullSchema()); + + boolean errorFlag = false; + Exception exception = null; + int loadCount = 0, realCount = 0; + String obfuscationDescription = "", obfusMethod = ""; + + try { + + int i = 0; + IPatientSetCollectionDao patientSetCollectionDao = sfDAOFactory + .getPatientSetCollectionDAO(); + patientSetCollectionDao + .createPatientSetCollection(resultInstanceId); + + String patientIdSql = " select distinct patient_num from " + TEMP_DX_TABLE + + " order by patient_num "; + + //// + //JNix: refactored to no longer pull down records just to insert back. + String sql = null; + String dbSchemaName = this.getDbSchemaName(); + if (sfDAOFactory.getDataSourceLookup().getServerType().equals(DAOFactoryHelper.ORACLE)) { + sql = "INSERT INTO qt_patient_set_collection" + + " (patient_set_coll_id, result_instance_id, set_index, patient_num) " + + "SELECT QT_SQ_QPR_PCID.nextval AS patient_set_coll_id, ? AS result_instance_id, rownum AS set_index, t.patient_num " + + "FROM (SELECT DISTINCT patient_num FROM ) t"; + } else if (sfDAOFactory.getDataSourceLookup().getServerType().equalsIgnoreCase(DAOFactoryHelper.SQLSERVER) || + sfDAOFactory.getDataSourceLookup().getServerType().equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { + sql = "INSERT INTO qt_patient_set_collection" + + " (result_instance_id, set_index, patient_num) " + + "SELECT ? AS result_instance_id, ROW_NUMBER() OVER(ORDER BY patient_num) AS set_index, t.patient_num " + + "FROM (SELECT DISTINCT patient_num FROM ) t"; + } + log.debug("Executing sql:\n" + sql); + + String sqlFinal = sql.replace("", this.getDbSchemaName() ); + sqlFinal = sqlFinal.replace("", TEMP_DX_TABLE); + + LogTimingUtil logTimingUtil = new LogTimingUtil(); + logTimingUtil.setStartTime(); + PreparedStatement ps = sfConn.prepareStatement(sqlFinal); + ps.setInt(1, Integer.parseInt(resultInstanceId)); + loadCount = ps.executeUpdate(); + ps.close(); + logTimingUtil.setEndTime(); + logesapi.debug("Total patients loaded for query instance =" + + queryInstanceId + " is [" + loadCount + "]"); + //// + if (processTimingFlag != null) { + if (!processTimingFlag.trim().equalsIgnoreCase(ProcessTimingReportUtil.NONE) ) { + ProcessTimingReportUtil ptrUtil = new ProcessTimingReportUtil(sfDAOFactory.getDataSourceLookup()); + ptrUtil.logProcessTimingMessage(queryInstanceId, ptrUtil.buildProcessTiming(logTimingUtil, "BUILD - PATIENTSET", "")); + } + } + realCount = loadCount; + + + // check for the user role to see if it needs data obfscation + DataSourceLookup dataSourceLookup = sfDAOFactory + .getOriginalDataSourceLookup(); + String domainId = originalDataSource.getDomainId(); + String projectId = originalDataSource.getProjectPath(); + String userId = originalDataSource.getOwnerId(); + boolean noDataAggFlag = false, noDataObfscFlag = false; + + DAOFactoryHelper helper = new DAOFactoryHelper(dataSourceLookup + .getDomainId(), dataSourceLookup.getProjectPath(), + dataSourceLookup.getOwnerId()); + + IDAOFactory daoFactory = helper.getDAOFactory(); + AuthrizationHelper authHelper = new AuthrizationHelper(domainId, + projectId, userId, daoFactory); + + try { + authHelper.checkRoleForProtectionLabel( + "SETFINDER_QRY_WITHOUT_DATAOBFSC", roles); + } catch (MissingRoleException noRoleEx) { + noDataAggFlag = true; + } catch (I2B2Exception e) { + throw e; + } + try { + authHelper.checkRoleForProtectionLabel( + "SETFINDER_QRY_WITH_DATAOBFSC", roles); + } catch (MissingRoleException noRoleEx) { + noDataObfscFlag = true; + } catch (I2B2Exception e) { + throw e; + } + + if (noDataAggFlag && !noDataObfscFlag) { + obfuscationDescription = "~"; + obfusMethod = IQueryResultInstanceDao.OBTOTAL; + GaussianBoxMuller gaussianBoxMuller = new GaussianBoxMuller(); + //read count sigma from property file + double countSigma = GaussianBoxMuller.getCountSigma(); + double obfuscatedMinimumValue = GaussianBoxMuller.getObfuscatedMinimumVal(); + loadCount = (int) gaussianBoxMuller + .getNormalizedValueForCount(loadCount,countSigma,obfuscatedMinimumValue); + } else { + obfucatedRecordCount = loadCount; + } + + // readQueryStmt.close(); + } catch (SQLException sqlEx) { + exception = sqlEx; + log.error("QueryResultPatientSetGenerator.generateResult:" + + sqlEx.getMessage(), sqlEx); + throw new I2B2DAOException( + "QueryResultPatientSetGenerator.generateResult:" + + sqlEx.getMessage(), sqlEx); + + } catch (Throwable throwable) { + throwable.printStackTrace(); + } finally { + IQueryResultInstanceDao resultInstanceDao = sfDAOFactory + .getPatientSetResultDAO(); + + String queryName = sfDAOFactory.getQueryMasterDAO().getQueryDefinition( + sfDAOFactory.getQueryInstanceDAO().getQueryInstanceByInstanceId(queryInstanceId).getQtQueryMaster().getQueryMasterId()).getName(); + + if (errorFlag) { + resultInstanceDao.updatePatientSet(resultInstanceId, + QueryStatusTypeId.STATUSTYPE_ID_ERROR, 0); + } else { + resultInstanceDao.updatePatientSet(resultInstanceId, + QueryStatusTypeId.STATUSTYPE_ID_FINISHED, "", + obfucatedRecordCount, + //loadCount, + realCount, obfusMethod); + //String description = "Patient Set - " + obfuscationDescription + // + loadCount + " Patients"; + String description = "Patient Set for \"" + queryName +"\""; + resultInstanceDao.updateResultInstanceDescription( + resultInstanceId, description); + + } + } + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientSkipCSVDownload.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientSkipCSVDownload.java similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientSkipCSVDownload.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientSkipCSVDownload.java index 2bd24392..b184e35b 100644 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientSkipCSVDownload.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientSkipCSVDownload.java @@ -1,111 +1,111 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder; - - -import java.io.File; - -/** - * To add Length of Stay (This is for Oracle and Postgresl) For Sql Server change the sql statement from (DX to #DX) - * - * Add a entry to QT_BREAKDOWN_PATH - * NAME = LENGTH_OF_STAY - * VALUE = select length_of_stay as patient_range, count(distinct a.PATIENT_num) as patient_count from visit_dimension a, DX b where a.patient_num = b.patient_num group by a.length_of_stay order by 1 - * - * Add a entry to QT_QUERY_RESULT_TYPE - * RESULT_TYPE_ID = 13 (Or any unused number) - * NAME = LENGTH_OF_STAY - * DESCRIPTION = Length of Dtay Brealdown - * DISPLAY_TYPE_ID = CATNUM - * VISUAL_ATTRIBUTE_TYPE_ID = LA - * - * Add a new in CRCApplicationContext.xml - * - * - * LENGTH_OF_STAY - * - * edu.harvard.i2b2.crc.dao.setfinder.QueryResultPatientSQLCountGenerator - * - * - */ - - -import java.io.StringWriter; -import java.security.SecureRandom; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.time.LocalDate; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.util.db.JDBCUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.ProcessTimingReportUtil; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.db.QtQueryBreakdownType; -import edu.harvard.i2b2.crc.datavo.db.QtQueryResultType; -import edu.harvard.i2b2.crc.datavo.i2b2result.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2result.DataType; -import edu.harvard.i2b2.crc.datavo.i2b2result.ResultEnvelopeType; -import edu.harvard.i2b2.crc.datavo.i2b2result.ResultType; -import edu.harvard.i2b2.crc.opencsv.CSVWriter; -import edu.harvard.i2b2.crc.opencsv.ResultSetHelperService; -import edu.harvard.i2b2.crc.util.LogTimingUtil; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - -/** - * Setfinder's result genertor class. This class calculates patient break down - * for the result type. - * - * Calls the ontology to get the children for the result type and then - * calculates the patient count for each child of the result type. - */ -public class QueryResultPatientSkipCSVDownload extends CRCDAO implements IResultGenerator { - - protected final Log logesapi = LogFactory.getLog(getClass()); - - - - /** - * Function accepts parameter in Map. The patient count will be obfuscated - * if the user is OBFUS - */ - @Override - public void generateResult(Map param) throws CRCTimeOutException, - I2B2DAOException { - - param.put("SkipCSV", true); - QueryResultPatientDownload dl = new QueryResultPatientDownload(); - dl.generateResult(param); - } - - - - @Override - public String getResults() { - // TODO Auto-generated method stub - return null; - } - - - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder; + + +import java.io.File; + +/** + * To add Length of Stay (This is for Oracle and Postgresl) For Sql Server change the sql statement from (DX to #DX) + * + * Add a entry to QT_BREAKDOWN_PATH + * NAME = LENGTH_OF_STAY + * VALUE = select length_of_stay as patient_range, count(distinct a.PATIENT_num) as patient_count from visit_dimension a, DX b where a.patient_num = b.patient_num group by a.length_of_stay order by 1 + * + * Add a entry to QT_QUERY_RESULT_TYPE + * RESULT_TYPE_ID = 13 (Or any unused number) + * NAME = LENGTH_OF_STAY + * DESCRIPTION = Length of Dtay Brealdown + * DISPLAY_TYPE_ID = CATNUM + * VISUAL_ATTRIBUTE_TYPE_ID = LA + * + * Add a new in CRCApplicationContext.xml + * + * + * LENGTH_OF_STAY + * + * edu.harvard.i2b2.crc.dao.setfinder.QueryResultPatientSQLCountGenerator + * + * + */ + + +import java.io.StringWriter; +import java.security.SecureRandom; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.util.db.JDBCUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.ProcessTimingReportUtil; +import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; +import edu.harvard.i2b2.crc.datavo.db.QtQueryBreakdownType; +import edu.harvard.i2b2.crc.datavo.db.QtQueryResultType; +import edu.harvard.i2b2.crc.datavo.i2b2result.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2result.DataType; +import edu.harvard.i2b2.crc.datavo.i2b2result.ResultEnvelopeType; +import edu.harvard.i2b2.crc.datavo.i2b2result.ResultType; +import edu.harvard.i2b2.crc.opencsv.CSVWriter; +import edu.harvard.i2b2.crc.opencsv.ResultSetHelperService; +import edu.harvard.i2b2.crc.util.LogTimingUtil; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + +/** + * Setfinder's result genertor class. This class calculates patient break down + * for the result type. + * + * Calls the ontology to get the children for the result type and then + * calculates the patient count for each child of the result type. + */ +public class QueryResultPatientSkipCSVDownload extends CRCDAO implements IResultGenerator { + + protected final Log logesapi = LogFactory.getLog(getClass()); + + + + /** + * Function accepts parameter in Map. The patient count will be obfuscated + * if the user is OBFUS + */ + @Override + public void generateResult(Map param) throws CRCTimeOutException, + I2B2DAOException { + + param.put("SkipCSV", true); + QueryResultPatientDownload dl = new QueryResultPatientDownload(); + dl.generateResult(param); + } + + + + @Override + public String getResults() { + // TODO Auto-generated method stub + return null; + } + + + + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientVitalCdCountGenerator.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientVitalCdCountGenerator.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientVitalCdCountGenerator.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientVitalCdCountGenerator.java index 74cbecfe..9bd5d480 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientVitalCdCountGenerator.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryResultPatientVitalCdCountGenerator.java @@ -1,125 +1,125 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder; - -import java.io.StringWriter; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.util.Map; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.util.db.JDBCUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.i2b2result.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2result.DataType; -import edu.harvard.i2b2.crc.datavo.i2b2result.ResultEnvelopeType; -import edu.harvard.i2b2.crc.datavo.i2b2result.ResultType; - -public class QueryResultPatientVitalCdCountGenerator extends CRCDAO implements - IResultGenerator { - - @Override - public String getResults() { - return xmlResult; - } - - private String xmlResult = null; - - public static final String RESULT_NAME = "PATIENT_VITALSTATUS_COUNT_XML"; - - @Override - public void generateResult(Map param) throws I2B2DAOException { - - SetFinderConnection sfConn = (SetFinderConnection) param - .get("SetFinderConnection"); - SetFinderDAOFactory sfDAOFactory = (SetFinderDAOFactory) param - .get("SetFinderDAOFactory"); - // String patientSetId = (String)param.get("PatientSetId"); - String queryInstanceId = (String) param.get("QueryInstanceId"); - String TEMP_DX_TABLE = (String) param.get("TEMP_DX_TABLE"); - String resultInstanceId = (String) param.get("ResultInstanceId"); - this - .setDbSchemaName(sfDAOFactory.getDataSourceLookup() - .getFullSchema()); - - String demographics_count_sql = "select count(distinct dx.patient_num) as vital_status_count, case when cl.name_char IS NULL then pd.vital_status_cd else cl.name_char end as pd_vital_status_cd from " - + " " - + "patient_dimension pd left join code_lookup cl on pd.vital_status_cd = cl.code_cd " - + "and lower(cl.table_cd) = 'patient_dimension' and upper(cl.column_cd) = 'VITAL_STATUS_CD' ," - + "" - + " dx where pd.patient_num = dx.patient_num" - + " " - + " group by case when cl.name_char IS NULL then pd.vital_status_cd else cl.name_char end"; - - boolean errorFlag = false; - int totalCount = 0; - try { - - log.debug("Executing[ " + demographics_count_sql + " ]"); - - String sqlFinal = demographics_count_sql.replace("", this.getDbSchemaName() ); - sqlFinal = sqlFinal.replace("", TEMP_DX_TABLE); - - PreparedStatement stmt = sfConn - .prepareStatement(sqlFinal); - ResultSet resultSet = stmt.executeQuery(); - ResultType resultType = new ResultType(); - resultType.setName(RESULT_NAME); - while (resultSet.next()) { - String demoCount = resultSet.getString("vital_status_count"); - String raceCd = resultSet.getString("pd_vital_status_cd"); - DataType mdataType = new DataType(); - mdataType.setValue(demoCount); - mdataType.setColumn(raceCd); - mdataType.setType("int"); - resultType.getData().add(mdataType); - } - resultSet.close(); - stmt.close(); - edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory(); - BodyType bodyType = new BodyType(); - bodyType.getAny().add(of.createResult(resultType)); - ResultEnvelopeType resultEnvelop = new ResultEnvelopeType(); - resultEnvelop.setBody(bodyType); - - JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); - - StringWriter strWriter = new StringWriter(); - - jaxbUtil.marshaller(of.createI2B2ResultEnvelope(resultEnvelop), - strWriter); - - IXmlResultDao xmlResultDao = sfDAOFactory.getXmlResultDao(); - xmlResult = strWriter.toString(); - xmlResultDao.createQueryXmlResult(resultInstanceId, strWriter - .toString()); - - } catch (Exception sqlEx) { - log.error("QueryResultPatientVitalCdCountGenerator.generateResult:" - + sqlEx.getMessage(), sqlEx); - throw new I2B2DAOException( - "QueryResultPatientVitalCdCountGenerator.generateResult:" - + sqlEx.getMessage(), sqlEx); - } finally { - IQueryResultInstanceDao resultInstanceDao = sfDAOFactory - .getPatientSetResultDAO(); - - if (errorFlag) { - resultInstanceDao.updatePatientSet(resultInstanceId, - QueryStatusTypeId.STATUSTYPE_ID_ERROR, 0); - } else { - resultInstanceDao.updatePatientSet(resultInstanceId, - QueryStatusTypeId.STATUSTYPE_ID_FINISHED, totalCount); - } - } - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder; + +import java.io.StringWriter; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.Map; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.util.db.JDBCUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; +import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; +import edu.harvard.i2b2.crc.datavo.i2b2result.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2result.DataType; +import edu.harvard.i2b2.crc.datavo.i2b2result.ResultEnvelopeType; +import edu.harvard.i2b2.crc.datavo.i2b2result.ResultType; + +public class QueryResultPatientVitalCdCountGenerator extends CRCDAO implements + IResultGenerator { + + @Override + public String getResults() { + return xmlResult; + } + + private String xmlResult = null; + + public static final String RESULT_NAME = "PATIENT_VITALSTATUS_COUNT_XML"; + + @Override + public void generateResult(Map param) throws I2B2DAOException { + + SetFinderConnection sfConn = (SetFinderConnection) param + .get("SetFinderConnection"); + SetFinderDAOFactory sfDAOFactory = (SetFinderDAOFactory) param + .get("SetFinderDAOFactory"); + // String patientSetId = (String)param.get("PatientSetId"); + String queryInstanceId = (String) param.get("QueryInstanceId"); + String TEMP_DX_TABLE = (String) param.get("TEMP_DX_TABLE"); + String resultInstanceId = (String) param.get("ResultInstanceId"); + this + .setDbSchemaName(sfDAOFactory.getDataSourceLookup() + .getFullSchema()); + + String demographics_count_sql = "select count(distinct dx.patient_num) as vital_status_count, case when cl.name_char IS NULL then pd.vital_status_cd else cl.name_char end as pd_vital_status_cd from " + + " " + + "patient_dimension pd left join code_lookup cl on pd.vital_status_cd = cl.code_cd " + + "and lower(cl.table_cd) = 'patient_dimension' and upper(cl.column_cd) = 'VITAL_STATUS_CD' ," + + "" + + " dx where pd.patient_num = dx.patient_num" + + " " + + " group by case when cl.name_char IS NULL then pd.vital_status_cd else cl.name_char end"; + + boolean errorFlag = false; + int totalCount = 0; + try { + + log.debug("Executing[ " + demographics_count_sql + " ]"); + + String sqlFinal = demographics_count_sql.replace("", this.getDbSchemaName() ); + sqlFinal = sqlFinal.replace("", TEMP_DX_TABLE); + + PreparedStatement stmt = sfConn + .prepareStatement(sqlFinal); + ResultSet resultSet = stmt.executeQuery(); + ResultType resultType = new ResultType(); + resultType.setName(RESULT_NAME); + while (resultSet.next()) { + String demoCount = resultSet.getString("vital_status_count"); + String raceCd = resultSet.getString("pd_vital_status_cd"); + DataType mdataType = new DataType(); + mdataType.setValue(demoCount); + mdataType.setColumn(raceCd); + mdataType.setType("int"); + resultType.getData().add(mdataType); + } + resultSet.close(); + stmt.close(); + edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory(); + BodyType bodyType = new BodyType(); + bodyType.getAny().add(of.createResult(resultType)); + ResultEnvelopeType resultEnvelop = new ResultEnvelopeType(); + resultEnvelop.setBody(bodyType); + + JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); + + StringWriter strWriter = new StringWriter(); + + jaxbUtil.marshaller(of.createI2B2ResultEnvelope(resultEnvelop), + strWriter); + + IXmlResultDao xmlResultDao = sfDAOFactory.getXmlResultDao(); + xmlResult = strWriter.toString(); + xmlResultDao.createQueryXmlResult(resultInstanceId, strWriter + .toString()); + + } catch (Exception sqlEx) { + log.error("QueryResultPatientVitalCdCountGenerator.generateResult:" + + sqlEx.getMessage(), sqlEx); + throw new I2B2DAOException( + "QueryResultPatientVitalCdCountGenerator.generateResult:" + + sqlEx.getMessage(), sqlEx); + } finally { + IQueryResultInstanceDao resultInstanceDao = sfDAOFactory + .getPatientSetResultDAO(); + + if (errorFlag) { + resultInstanceDao.updatePatientSet(resultInstanceId, + QueryStatusTypeId.STATUSTYPE_ID_ERROR, 0); + } else { + resultInstanceDao.updatePatientSet(resultInstanceId, + QueryStatusTypeId.STATUSTYPE_ID_FINISHED, totalCount); + } + } + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryResultTypeSpringDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryResultTypeSpringDao.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryResultTypeSpringDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryResultTypeSpringDao.java index 029195a6..e517fe2c --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryResultTypeSpringDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryResultTypeSpringDao.java @@ -1,172 +1,172 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao.setfinder; - -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.Collections; -import java.util.List; -import java.util.Map; - -import javax.sql.DataSource; - -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.RowMapper; -import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; - -import edu.harvard.i2b2.common.util.db.JDBCUtil; -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.db.QtQueryMaster; -import edu.harvard.i2b2.crc.datavo.db.QtQueryResultType; - -/** - * Class to manager persistance operation of QtQueryMaster $Id: - * QueryResultTypeSpringDao.java,v 1.4 2008/05/07 21:38:56 rk903 Exp $ - * - * @author rkuttan - * @see QtQueryMaster - */ -public class QueryResultTypeSpringDao extends CRCDAO implements -IQueryResultTypeDao { - - JdbcTemplate jdbcTemplate = null; - NamedParameterJdbcTemplate namedParameterJdbcTemplate = null; - - QtResultTypeRowMapper queryResultTypeMapper = new QtResultTypeRowMapper(); - - private DataSourceLookup dataSourceLookup = null; - public QueryResultTypeSpringDao(DataSource dataSource, - DataSourceLookup dataSourceLookup) { - setDataSource(dataSource); - setDbSchemaName(dataSourceLookup.getFullSchema()); - jdbcTemplate = new JdbcTemplate(dataSource); - namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource); - this.dataSourceLookup = dataSourceLookup; - - } - - /** - * Returns list of query master by user id - * - * @param userId - * @return List - */ - @Override - @SuppressWarnings("unchecked") - public QtQueryResultType getQueryResultTypeById(int resultTypeId) { - - String sql = "select * from " + getDbSchemaName() - + "qt_query_result_type where result_type_id = ?"; - QtQueryResultType queryResultType = (QtQueryResultType) jdbcTemplate - .queryForObject(sql, new Object[] { resultTypeId }, - queryResultTypeMapper); - return queryResultType; - } - - /** - * Returns list of query master by user id - * - * @param userId - * @return List - */ - @Override - @SuppressWarnings("unchecked") - public String getQueryResultTypeClassname(String resultName) { - - String sql = "select * from " + getDbSchemaName() - + "qt_query_result_type where name = ?"; - QtQueryResultType queryResultType = (QtQueryResultType) jdbcTemplate - .queryForObject(sql, new Object[] { resultName }, - queryResultTypeMapper); - return queryResultType.getClassname(); - } - - - /** - * Returns list of query master by user id - * - * @param userId - * @return List - */ - @Override - @SuppressWarnings("unchecked") - public List getQueryResultTypeByName(String resultName,List roles) { - - List queryResultType = null; - - if (roles != null) - { - String sql = "select * from " - + "qt_query_result_type where name = '' and (user_role_cd = '@' or user_role_cd is null or user_role_cd in (:roleCd))"; - Map myRoles = Collections.singletonMap("roleCd", roles); - - - String sqlFinal = sql.replace("", this.getDbSchemaName() ); - sqlFinal = sqlFinal.replace("", resultName); - - queryResultType = namedParameterJdbcTemplate.query(sqlFinal, - myRoles, - queryResultTypeMapper); - } else - { - String sql = "select * from " + getDbSchemaName() - + "qt_query_result_type where name = ?"; - queryResultType = jdbcTemplate.query(sql, - new Object[] { resultName.toUpperCase() }, - queryResultTypeMapper); - } - return queryResultType; - } - - @Override - @SuppressWarnings("unchecked") - public List getAllQueryResultType(List roles) { - - List queryResultTypeList = null; - if (roles != null) - { - String sql = "select * from " + getDbSchemaName() - + "qt_query_result_type where user_role_cd = '@' or user_role_cd is null or user_role_cd in (:roleCd) order by result_type_id"; - Map myRoles = Collections.singletonMap("roleCd", roles); - queryResultTypeList = namedParameterJdbcTemplate.query(sql, - myRoles , - queryResultTypeMapper); - } else { - String sql = "select * from " + getDbSchemaName() - + "qt_query_result_type order by result_type_id"; - queryResultTypeList = jdbcTemplate.query(sql, - queryResultTypeMapper); - } - return queryResultTypeList; - } - - private static class QtResultTypeRowMapper implements RowMapper { - @Override - public Object mapRow(ResultSet rs, int rowNum) throws SQLException { - QtQueryResultType queryResultType = new QtQueryResultType(); - queryResultType.setResultTypeId(rs.getInt("RESULT_TYPE_ID")); - queryResultType.setName(rs.getString("NAME")); - queryResultType.setDescription(rs.getString("DESCRIPTION")); - queryResultType.setDisplayType(rs.getString("DISPLAY_TYPE_ID")); - queryResultType.setVisualAttributeType(rs - .getString("VISUAL_ATTRIBUTE_TYPE_ID")); - queryResultType.setUserRoleCd(rs.getString("USER_ROLE_CD")); - queryResultType.setClassname(rs.getString("CLASSNAME")); - return queryResultType; - } - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao.setfinder; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import javax.sql.DataSource; + +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.RowMapper; +import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; + +import edu.harvard.i2b2.common.util.db.JDBCUtil; +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.db.QtQueryMaster; +import edu.harvard.i2b2.crc.datavo.db.QtQueryResultType; + +/** + * Class to manager persistance operation of QtQueryMaster $Id: + * QueryResultTypeSpringDao.java,v 1.4 2008/05/07 21:38:56 rk903 Exp $ + * + * @author rkuttan + * @see QtQueryMaster + */ +public class QueryResultTypeSpringDao extends CRCDAO implements +IQueryResultTypeDao { + + JdbcTemplate jdbcTemplate = null; + NamedParameterJdbcTemplate namedParameterJdbcTemplate = null; + + QtResultTypeRowMapper queryResultTypeMapper = new QtResultTypeRowMapper(); + + private DataSourceLookup dataSourceLookup = null; + public QueryResultTypeSpringDao(DataSource dataSource, + DataSourceLookup dataSourceLookup) { + setDataSource(dataSource); + setDbSchemaName(dataSourceLookup.getFullSchema()); + jdbcTemplate = new JdbcTemplate(dataSource); + namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource); + this.dataSourceLookup = dataSourceLookup; + + } + + /** + * Returns list of query master by user id + * + * @param userId + * @return List + */ + @Override + @SuppressWarnings("unchecked") + public QtQueryResultType getQueryResultTypeById(int resultTypeId) { + + String sql = "select * from " + getDbSchemaName() + + "qt_query_result_type where result_type_id = ?"; + QtQueryResultType queryResultType = (QtQueryResultType) jdbcTemplate + .queryForObject(sql, new Object[] { resultTypeId }, + queryResultTypeMapper); + return queryResultType; + } + + /** + * Returns list of query master by user id + * + * @param userId + * @return List + */ + @Override + @SuppressWarnings("unchecked") + public String getQueryResultTypeClassname(String resultName) { + + String sql = "select * from " + getDbSchemaName() + + "qt_query_result_type where name = ?"; + QtQueryResultType queryResultType = (QtQueryResultType) jdbcTemplate + .queryForObject(sql, new Object[] { resultName }, + queryResultTypeMapper); + return queryResultType.getClassname(); + } + + + /** + * Returns list of query master by user id + * + * @param userId + * @return List + */ + @Override + @SuppressWarnings("unchecked") + public List getQueryResultTypeByName(String resultName,List roles) { + + List queryResultType = null; + + if (roles != null) + { + String sql = "select * from " + + "qt_query_result_type where name = '' and (user_role_cd = '@' or user_role_cd is null or user_role_cd in (:roleCd))"; + Map myRoles = Collections.singletonMap("roleCd", roles); + + + String sqlFinal = sql.replace("", this.getDbSchemaName() ); + sqlFinal = sqlFinal.replace("", resultName); + + queryResultType = namedParameterJdbcTemplate.query(sqlFinal, + myRoles, + queryResultTypeMapper); + } else + { + String sql = "select * from " + getDbSchemaName() + + "qt_query_result_type where name = ?"; + queryResultType = jdbcTemplate.query(sql, + new Object[] { resultName.toUpperCase() }, + queryResultTypeMapper); + } + return queryResultType; + } + + @Override + @SuppressWarnings("unchecked") + public List getAllQueryResultType(List roles) { + + List queryResultTypeList = null; + if (roles != null) + { + String sql = "select * from " + getDbSchemaName() + + "qt_query_result_type where user_role_cd = '@' or user_role_cd is null or user_role_cd in (:roleCd) order by result_type_id"; + Map myRoles = Collections.singletonMap("roleCd", roles); + queryResultTypeList = namedParameterJdbcTemplate.query(sql, + myRoles , + queryResultTypeMapper); + } else { + String sql = "select * from " + getDbSchemaName() + + "qt_query_result_type order by result_type_id"; + queryResultTypeList = jdbcTemplate.query(sql, + queryResultTypeMapper); + } + return queryResultTypeList; + } + + private static class QtResultTypeRowMapper implements RowMapper { + @Override + public Object mapRow(ResultSet rs, int rowNum) throws SQLException { + QtQueryResultType queryResultType = new QtQueryResultType(); + queryResultType.setResultTypeId(rs.getInt("RESULT_TYPE_ID")); + queryResultType.setName(rs.getString("NAME")); + queryResultType.setDescription(rs.getString("DESCRIPTION")); + queryResultType.setDisplayType(rs.getString("DISPLAY_TYPE_ID")); + queryResultType.setVisualAttributeType(rs + .getString("VISUAL_ATTRIBUTE_TYPE_ID")); + queryResultType.setUserRoleCd(rs.getString("USER_ROLE_CD")); + queryResultType.setClassname(rs.getString("CLASSNAME")); + return queryResultType; + } + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryResultUserCreated.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryResultUserCreated.java similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryResultUserCreated.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryResultUserCreated.java index 593d3436..3a37fdab 100644 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryResultUserCreated.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryResultUserCreated.java @@ -1,280 +1,280 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder; - - -/** - * To add Length of Stay (This is for Oracle and Postgresl) For Sql Server change the sql statement from (DX to #DX) - * - * Add a entry to QT_BREAKDOWN_PATH - * NAME = LENGTH_OF_STAY - * VALUE = select length_of_stay as patient_range, count(distinct a.PATIENT_num) as patient_count from visit_dimension a, DX b where a.patient_num = b.patient_num group by a.length_of_stay order by 1 - * - * Add a entry to QT_QUERY_RESULT_TYPE - * RESULT_TYPE_ID = 13 (Or any unused number) - * NAME = LENGTH_OF_STAY - * DESCRIPTION = Length of Dtay Brealdown - * DISPLAY_TYPE_ID = CATNUM - * VISUAL_ATTRIBUTE_TYPE_ID = LA - * - * Add a new in CRCApplicationContext.xml - * - * - * LENGTH_OF_STAY - * - * edu.harvard.i2b2.crc.dao.setfinder.QueryResultPatientSQLCountGenerator - * - * - */ - - -import java.io.StringWriter; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.List; -import java.util.Map; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.util.db.JDBCUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.ProcessTimingReportUtil; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.db.QtQueryBreakdownType; -import edu.harvard.i2b2.crc.datavo.db.QtQueryMaster; -import edu.harvard.i2b2.crc.datavo.db.QtQueryResultType; -import edu.harvard.i2b2.crc.datavo.i2b2result.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2result.DataType; -import edu.harvard.i2b2.crc.datavo.i2b2result.ResultEnvelopeType; -import edu.harvard.i2b2.crc.datavo.i2b2result.ResultType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionType; -import edu.harvard.i2b2.crc.util.LogTimingUtil; - -/** - * Setfinder's result genertor class. This class calculates patient break down - * for the result type. - * - * Calls the ontology to get the children for the result type and then - * calculates the patient count for each child of the result type. - */ -public class QueryResultUserCreated extends CRCDAO implements IResultGenerator { - - protected final Log logesapi = LogFactory.getLog(getClass()); - - @Override - public String getResults() { - return xmlResult; - } - - private String xmlResult = null; - /** - * Function accepts parameter in Map. The patient count will be obfuscated - * if the user is OBFUS - */ - @Override - public void generateResult(Map param) throws CRCTimeOutException, - I2B2DAOException { - - SetFinderConnection sfConn = (SetFinderConnection) param - .get("SetFinderConnection"); - SetFinderDAOFactory sfDAOFactory = (SetFinderDAOFactory) param - .get("SetFinderDAOFactory"); - - // String patientSetId = (String)param.get("PatientSetId"); - String queryInstanceId = (String) param.get("QueryInstanceId"); - String TEMP_DX_TABLE = (String) param.get("TEMP_DX_TABLE"); - String resultInstanceId = (String) param.get("ResultInstanceId"); - // String itemKey = (String) param.get("ItemKey"); - String resultTypeName = (String) param.get("ResultOptionName"); - String processTimingFlag = (String) param.get("ProcessTimingFlag"); - int obfuscatedRecordCount = (Integer) param.get("ObfuscatedRecordCount"); - int recordCount = (Integer) param.get("RecordCount"); - int transactionTimeout = (Integer) param.get("TransactionTimeout"); - long dxCreateTime = (Long) param.get("DXCreateTime"); - transactionTimeout = transactionTimeout - Math.toIntExact(dxCreateTime); - boolean obfscDataRoleFlag = (Boolean)param.get("ObfuscatedRoleFlag"); - - QueryDefinitionType queryDef = (QueryDefinitionType) param.get("queryDef"); - - - this - .setDbSchemaName(sfDAOFactory.getDataSourceLookup() - .getFullSchema()); - //Map ontologyKeyMap = (Map) param.get("setFinderResultOntologyKeyMap"); - String serverType = (String) param.get("ServerType"); - // CallOntologyUtil ontologyUtil = (CallOntologyUtil) param - // .get("CallOntologyUtil"); - List roles = (List) param.get("Roles"); - String tempTableName = ""; - PreparedStatement stmt = null; - boolean errorFlag = false, timeoutFlag = false; - //String itemKey = ""; - - int actualTotal = 0, obsfcTotal = 0; - - try { - LogTimingUtil logTimingUtil = new LogTimingUtil(); - logTimingUtil.setStartTime(); - - LogTimingUtil subLogTimingUtil = new LogTimingUtil(); - subLogTimingUtil.setStartTime(); - - String itemCountSql = getItemKeyFromResultType(sfDAOFactory, resultTypeName); - - - - - ResultType resultType = new ResultType(); - resultType.setName(resultTypeName); - - DataType mdataType = new DataType(); - - mdataType.setValue( new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime())); - mdataType.setColumn("Request Submitted"); - mdataType.setType("string"); - resultType.getData().add(mdataType); - - - mdataType = new DataType(); - - mdataType.setValue( queryDef.getEmail()); - mdataType.setColumn("Email"); - mdataType.setType("string"); - resultType.getData().add(mdataType); - - - edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory(); - BodyType bodyType = new BodyType(); - bodyType.getAny().add(of.createResult(resultType)); - ResultEnvelopeType resultEnvelop = new ResultEnvelopeType(); - resultEnvelop.setBody(bodyType); - - JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); - - StringWriter strWriter = new StringWriter(); - subLogTimingUtil.setStartTime(); - jaxbUtil.marshaller(of.createI2B2ResultEnvelope(resultEnvelop), - strWriter); - subLogTimingUtil.setEndTime(); - //tm.begin(); - IXmlResultDao xmlResultDao = sfDAOFactory.getXmlResultDao(); - xmlResult = strWriter.toString(); - - if (resultInstanceId != null) - xmlResultDao.createQueryXmlResult(resultInstanceId, xmlResult); - - - if (queryInstanceId != null) { - IQueryResultInstanceDao resultInstanceDao = sfDAOFactory - .getPatientSetResultDAO(); - resultInstanceDao.updateInstanceMessage(queryInstanceId, queryDef.getMessage()); - - QtQueryMaster qtQueryMaster = sfDAOFactory.getQueryMasterDAO().getQueryDefinition(sfDAOFactory.getQueryInstanceDAO().getQueryInstanceByInstanceId(queryInstanceId).getQtQueryMaster().getQueryMasterId()); - - qtQueryMaster.setMasterTypeCd("EXPORT"); - - sfDAOFactory.getQueryMasterDAO().updateMasterTypeAfterRun( - sfDAOFactory.getQueryInstanceDAO().getQueryInstanceByInstanceId(queryInstanceId).getQtQueryMaster().getQueryMasterId(), - "EXPORT"); - - } - } catch (Exception sqlEx) { - - errorFlag = true; - log.error("QueryResultPatientSetGenerator.generateResult:" - + sqlEx.getMessage(), sqlEx); - throw new I2B2DAOException( - "QueryResultPatientSetGenerator.generateResult:" - + sqlEx.getMessage(), sqlEx); - } finally { - - if (resultInstanceId != null) { - IQueryResultInstanceDao resultInstanceDao = sfDAOFactory - .getPatientSetResultDAO(); - - if (errorFlag) { - resultInstanceDao.updatePatientSet(resultInstanceId, - QueryStatusTypeId.STATUSTYPE_ID_ERROR, 0); - } else { - // set the setsize and the description of the result instance if - // the user role is obfuscated - if (timeoutFlag == false) { // check if the query completed - try { - // tm.begin(); - - String obfusMethod = "", description = null; - if (obfscDataRoleFlag) { - obfusMethod = IQueryResultInstanceDao.OBSUBTOTAL; - // add () to the result type description - // read the description from result type - - } else { - obfuscatedRecordCount = recordCount; - } - IQueryResultTypeDao resultTypeDao = sfDAOFactory.getQueryResultTypeDao(); - List resultTypeList = resultTypeDao - .getQueryResultTypeByName(resultTypeName, roles); - - // add "(Obfuscated)" in the description - //description = resultTypeList.get(0) - // .getDescription() - // + " (Obfuscated) "; - String queryName = sfDAOFactory.getQueryMasterDAO().getQueryDefinition( - sfDAOFactory.getQueryInstanceDAO().getQueryInstanceByInstanceId(queryInstanceId).getQtQueryMaster().getQueryMasterId()).getName(); - - - - resultInstanceDao.updatePatientSet(resultInstanceId, - QueryStatusTypeId.STATUSTYPE_ID_FINISHED, null, - //obsfcTotal, - obfuscatedRecordCount, recordCount, obfusMethod); - - description = resultTypeList.get(0) - .getDescription() + " for \"" + queryName +"\""; - - // set the result instance description - resultInstanceDao.updateResultInstanceDescription( - resultInstanceId, description); - // tm.commit(); - } catch (SecurityException e) { - throw new I2B2DAOException( - "Failed to write obfuscated description " - + e.getMessage(), e); - } catch (IllegalStateException e) { - throw new I2B2DAOException( - "Failed to write obfuscated description " - + e.getMessage(), e); - } - } - } - } - } - - } - - private String getItemKeyFromResultType(SetFinderDAOFactory sfDAOFactory, - String resultTypeKey) { - // - IQueryBreakdownTypeDao queryBreakdownTypeDao = sfDAOFactory - .getQueryBreakdownTypeDao(); - QtQueryBreakdownType queryBreakdownType = queryBreakdownTypeDao - .getBreakdownTypeByName(resultTypeKey); - String itemKey = queryBreakdownType.getValue(); - return itemKey; - } - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder; + + +/** + * To add Length of Stay (This is for Oracle and Postgresl) For Sql Server change the sql statement from (DX to #DX) + * + * Add a entry to QT_BREAKDOWN_PATH + * NAME = LENGTH_OF_STAY + * VALUE = select length_of_stay as patient_range, count(distinct a.PATIENT_num) as patient_count from visit_dimension a, DX b where a.patient_num = b.patient_num group by a.length_of_stay order by 1 + * + * Add a entry to QT_QUERY_RESULT_TYPE + * RESULT_TYPE_ID = 13 (Or any unused number) + * NAME = LENGTH_OF_STAY + * DESCRIPTION = Length of Dtay Brealdown + * DISPLAY_TYPE_ID = CATNUM + * VISUAL_ATTRIBUTE_TYPE_ID = LA + * + * Add a new in CRCApplicationContext.xml + * + * + * LENGTH_OF_STAY + * + * edu.harvard.i2b2.crc.dao.setfinder.QueryResultPatientSQLCountGenerator + * + * + */ + + +import java.io.StringWriter; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.List; +import java.util.Map; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.util.db.JDBCUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.ProcessTimingReportUtil; +import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; +import edu.harvard.i2b2.crc.datavo.db.QtQueryBreakdownType; +import edu.harvard.i2b2.crc.datavo.db.QtQueryMaster; +import edu.harvard.i2b2.crc.datavo.db.QtQueryResultType; +import edu.harvard.i2b2.crc.datavo.i2b2result.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2result.DataType; +import edu.harvard.i2b2.crc.datavo.i2b2result.ResultEnvelopeType; +import edu.harvard.i2b2.crc.datavo.i2b2result.ResultType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionType; +import edu.harvard.i2b2.crc.util.LogTimingUtil; + +/** + * Setfinder's result genertor class. This class calculates patient break down + * for the result type. + * + * Calls the ontology to get the children for the result type and then + * calculates the patient count for each child of the result type. + */ +public class QueryResultUserCreated extends CRCDAO implements IResultGenerator { + + protected final Log logesapi = LogFactory.getLog(getClass()); + + @Override + public String getResults() { + return xmlResult; + } + + private String xmlResult = null; + /** + * Function accepts parameter in Map. The patient count will be obfuscated + * if the user is OBFUS + */ + @Override + public void generateResult(Map param) throws CRCTimeOutException, + I2B2DAOException { + + SetFinderConnection sfConn = (SetFinderConnection) param + .get("SetFinderConnection"); + SetFinderDAOFactory sfDAOFactory = (SetFinderDAOFactory) param + .get("SetFinderDAOFactory"); + + // String patientSetId = (String)param.get("PatientSetId"); + String queryInstanceId = (String) param.get("QueryInstanceId"); + String TEMP_DX_TABLE = (String) param.get("TEMP_DX_TABLE"); + String resultInstanceId = (String) param.get("ResultInstanceId"); + // String itemKey = (String) param.get("ItemKey"); + String resultTypeName = (String) param.get("ResultOptionName"); + String processTimingFlag = (String) param.get("ProcessTimingFlag"); + int obfuscatedRecordCount = (Integer) param.get("ObfuscatedRecordCount"); + int recordCount = (Integer) param.get("RecordCount"); + int transactionTimeout = (Integer) param.get("TransactionTimeout"); + long dxCreateTime = (Long) param.get("DXCreateTime"); + transactionTimeout = transactionTimeout - Math.toIntExact(dxCreateTime); + boolean obfscDataRoleFlag = (Boolean)param.get("ObfuscatedRoleFlag"); + + QueryDefinitionType queryDef = (QueryDefinitionType) param.get("queryDef"); + + + this + .setDbSchemaName(sfDAOFactory.getDataSourceLookup() + .getFullSchema()); + //Map ontologyKeyMap = (Map) param.get("setFinderResultOntologyKeyMap"); + String serverType = (String) param.get("ServerType"); + // CallOntologyUtil ontologyUtil = (CallOntologyUtil) param + // .get("CallOntologyUtil"); + List roles = (List) param.get("Roles"); + String tempTableName = ""; + PreparedStatement stmt = null; + boolean errorFlag = false, timeoutFlag = false; + //String itemKey = ""; + + int actualTotal = 0, obsfcTotal = 0; + + try { + LogTimingUtil logTimingUtil = new LogTimingUtil(); + logTimingUtil.setStartTime(); + + LogTimingUtil subLogTimingUtil = new LogTimingUtil(); + subLogTimingUtil.setStartTime(); + + String itemCountSql = getItemKeyFromResultType(sfDAOFactory, resultTypeName); + + + + + ResultType resultType = new ResultType(); + resultType.setName(resultTypeName); + + DataType mdataType = new DataType(); + + mdataType.setValue( new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime())); + mdataType.setColumn("Request Submitted"); + mdataType.setType("string"); + resultType.getData().add(mdataType); + + + mdataType = new DataType(); + + mdataType.setValue( queryDef.getEmail()); + mdataType.setColumn("Email"); + mdataType.setType("string"); + resultType.getData().add(mdataType); + + + edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory(); + BodyType bodyType = new BodyType(); + bodyType.getAny().add(of.createResult(resultType)); + ResultEnvelopeType resultEnvelop = new ResultEnvelopeType(); + resultEnvelop.setBody(bodyType); + + JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); + + StringWriter strWriter = new StringWriter(); + subLogTimingUtil.setStartTime(); + jaxbUtil.marshaller(of.createI2B2ResultEnvelope(resultEnvelop), + strWriter); + subLogTimingUtil.setEndTime(); + //tm.begin(); + IXmlResultDao xmlResultDao = sfDAOFactory.getXmlResultDao(); + xmlResult = strWriter.toString(); + + if (resultInstanceId != null) + xmlResultDao.createQueryXmlResult(resultInstanceId, xmlResult); + + + if (queryInstanceId != null) { + IQueryResultInstanceDao resultInstanceDao = sfDAOFactory + .getPatientSetResultDAO(); + resultInstanceDao.updateInstanceMessage(queryInstanceId, queryDef.getMessage()); + + QtQueryMaster qtQueryMaster = sfDAOFactory.getQueryMasterDAO().getQueryDefinition(sfDAOFactory.getQueryInstanceDAO().getQueryInstanceByInstanceId(queryInstanceId).getQtQueryMaster().getQueryMasterId()); + + qtQueryMaster.setMasterTypeCd("EXPORT"); + + sfDAOFactory.getQueryMasterDAO().updateMasterTypeAfterRun( + sfDAOFactory.getQueryInstanceDAO().getQueryInstanceByInstanceId(queryInstanceId).getQtQueryMaster().getQueryMasterId(), + "EXPORT"); + + } + } catch (Exception sqlEx) { + + errorFlag = true; + log.error("QueryResultPatientSetGenerator.generateResult:" + + sqlEx.getMessage(), sqlEx); + throw new I2B2DAOException( + "QueryResultPatientSetGenerator.generateResult:" + + sqlEx.getMessage(), sqlEx); + } finally { + + if (resultInstanceId != null) { + IQueryResultInstanceDao resultInstanceDao = sfDAOFactory + .getPatientSetResultDAO(); + + if (errorFlag) { + resultInstanceDao.updatePatientSet(resultInstanceId, + QueryStatusTypeId.STATUSTYPE_ID_ERROR, 0); + } else { + // set the setsize and the description of the result instance if + // the user role is obfuscated + if (timeoutFlag == false) { // check if the query completed + try { + // tm.begin(); + + String obfusMethod = "", description = null; + if (obfscDataRoleFlag) { + obfusMethod = IQueryResultInstanceDao.OBSUBTOTAL; + // add () to the result type description + // read the description from result type + + } else { + obfuscatedRecordCount = recordCount; + } + IQueryResultTypeDao resultTypeDao = sfDAOFactory.getQueryResultTypeDao(); + List resultTypeList = resultTypeDao + .getQueryResultTypeByName(resultTypeName, roles); + + // add "(Obfuscated)" in the description + //description = resultTypeList.get(0) + // .getDescription() + // + " (Obfuscated) "; + String queryName = sfDAOFactory.getQueryMasterDAO().getQueryDefinition( + sfDAOFactory.getQueryInstanceDAO().getQueryInstanceByInstanceId(queryInstanceId).getQtQueryMaster().getQueryMasterId()).getName(); + + + + resultInstanceDao.updatePatientSet(resultInstanceId, + QueryStatusTypeId.STATUSTYPE_ID_FINISHED, null, + //obsfcTotal, + obfuscatedRecordCount, recordCount, obfusMethod); + + description = resultTypeList.get(0) + .getDescription() + " for \"" + queryName +"\""; + + // set the result instance description + resultInstanceDao.updateResultInstanceDescription( + resultInstanceId, description); + // tm.commit(); + } catch (SecurityException e) { + throw new I2B2DAOException( + "Failed to write obfuscated description " + + e.getMessage(), e); + } catch (IllegalStateException e) { + throw new I2B2DAOException( + "Failed to write obfuscated description " + + e.getMessage(), e); + } + } + } + } + } + + } + + private String getItemKeyFromResultType(SetFinderDAOFactory sfDAOFactory, + String resultTypeKey) { + // + IQueryBreakdownTypeDao queryBreakdownTypeDao = sfDAOFactory + .getQueryBreakdownTypeDao(); + QtQueryBreakdownType queryBreakdownType = queryBreakdownTypeDao + .getBreakdownTypeByName(resultTypeKey); + String itemKey = queryBreakdownType.getValue(); + return itemKey; + } + + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryStatusTypeId.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryStatusTypeId.java old mode 100755 new mode 100644 similarity index 98% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryStatusTypeId.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryStatusTypeId.java index 5c76e9c3..30af57cf --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryStatusTypeId.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryStatusTypeId.java @@ -1,18 +1,18 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder; - -public class QueryStatusTypeId { - public final static int STATUSTYPE_ID_QUEUED = 1; - public final static int STATUSTYPE_ID_PROCESSING = 2; - public final static int STATUSTYPE_ID_FINISHED = 3; - public final static int STATUSTYPE_ID_ERROR = 4; - public final static int STATUSTYPE_ID_INCOMPLETE = 5; - public final static int STATUSTYPE_ID_COMPLETED = 6; -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder; + +public class QueryStatusTypeId { + public final static int STATUSTYPE_ID_QUEUED = 1; + public final static int STATUSTYPE_ID_PROCESSING = 2; + public final static int STATUSTYPE_ID_FINISHED = 3; + public final static int STATUSTYPE_ID_ERROR = 4; + public final static int STATUSTYPE_ID_INCOMPLETE = 5; + public final static int STATUSTYPE_ID_COMPLETED = 6; +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryStatusTypeSpringDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryStatusTypeSpringDao.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryStatusTypeSpringDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryStatusTypeSpringDao.java index d18e729a..0996aa29 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/QueryStatusTypeSpringDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/QueryStatusTypeSpringDao.java @@ -1,83 +1,83 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao.setfinder; - -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.db.QtQueryMaster; -import edu.harvard.i2b2.crc.datavo.db.QtQueryStatusType; - -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.RowMapper; -import java.sql.ResultSet; -import java.sql.SQLException; -import javax.sql.DataSource; - - -/** - * Class to manager persistance operation of - * QtQueryMaster - * $Id: QueryStatusTypeSpringDao.java,v 1.3 2008/05/07 21:39:08 rk903 Exp $ - * @author rkuttan - * @see QtQueryMaster - */ -public class QueryStatusTypeSpringDao extends CRCDAO implements IQueryStatusTypeDao { - - JdbcTemplate jdbcTemplate = null; - - QtStatusTypeRowMapper queryStatusTypeMapper = new QtStatusTypeRowMapper(); - - - - - private DataSourceLookup dataSourceLookup = null; - - - public QueryStatusTypeSpringDao(DataSource dataSource,DataSourceLookup dataSourceLookup) { - setDataSource(dataSource); - setDbSchemaName(dataSourceLookup.getFullSchema()); - jdbcTemplate = new JdbcTemplate(dataSource); - this.dataSourceLookup = dataSourceLookup; - - } - - /** - * Returns list of query master by user id - * @param userId - * @return List - */ - @Override - @SuppressWarnings("unchecked") - public QtQueryStatusType getQueryStatusTypeById(int statusTypeId) { - - String sql = "select * from " + getDbSchemaName() + "qt_query_status_type where status_type_id = ?" ; - QtQueryStatusType queryStatusType = (QtQueryStatusType)jdbcTemplate.queryForObject(sql,new Object[]{statusTypeId},queryStatusTypeMapper ); - return queryStatusType; - } - - private static class QtStatusTypeRowMapper implements RowMapper { - @Override - public Object mapRow(ResultSet rs, int rowNum) throws SQLException { - QtQueryStatusType queryStatusType = new QtQueryStatusType(); - queryStatusType.setStatusTypeId(rs.getInt("STATUS_TYPE_ID")); - queryStatusType.setName(rs.getString("NAME")); - queryStatusType.setDescription(rs.getString("DESCRIPTION")); - - return queryStatusType; - } - } - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao.setfinder; + +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.db.QtQueryMaster; +import edu.harvard.i2b2.crc.datavo.db.QtQueryStatusType; + +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.RowMapper; +import java.sql.ResultSet; +import java.sql.SQLException; +import javax.sql.DataSource; + + +/** + * Class to manager persistance operation of + * QtQueryMaster + * $Id: QueryStatusTypeSpringDao.java,v 1.3 2008/05/07 21:39:08 rk903 Exp $ + * @author rkuttan + * @see QtQueryMaster + */ +public class QueryStatusTypeSpringDao extends CRCDAO implements IQueryStatusTypeDao { + + JdbcTemplate jdbcTemplate = null; + + QtStatusTypeRowMapper queryStatusTypeMapper = new QtStatusTypeRowMapper(); + + + + + private DataSourceLookup dataSourceLookup = null; + + + public QueryStatusTypeSpringDao(DataSource dataSource,DataSourceLookup dataSourceLookup) { + setDataSource(dataSource); + setDbSchemaName(dataSourceLookup.getFullSchema()); + jdbcTemplate = new JdbcTemplate(dataSource); + this.dataSourceLookup = dataSourceLookup; + + } + + /** + * Returns list of query master by user id + * @param userId + * @return List + */ + @Override + @SuppressWarnings("unchecked") + public QtQueryStatusType getQueryStatusTypeById(int statusTypeId) { + + String sql = "select * from " + getDbSchemaName() + "qt_query_status_type where status_type_id = ?" ; + QtQueryStatusType queryStatusType = (QtQueryStatusType)jdbcTemplate.queryForObject(sql,new Object[]{statusTypeId},queryStatusTypeMapper ); + return queryStatusType; + } + + private static class QtStatusTypeRowMapper implements RowMapper { + @Override + public Object mapRow(ResultSet rs, int rowNum) throws SQLException { + QtQueryStatusType queryStatusType = new QtQueryStatusType(); + queryStatusType.setStatusTypeId(rs.getInt("STATUS_TYPE_ID")); + queryStatusType.setName(rs.getString("NAME")); + queryStatusType.setDescription(rs.getString("DESCRIPTION")); + + return queryStatusType; + } + } + + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/SQLServerSequenceDAO.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/SQLServerSequenceDAO.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/SQLServerSequenceDAO.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/SQLServerSequenceDAO.java index 7377eae5..b59b268f --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/SQLServerSequenceDAO.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/SQLServerSequenceDAO.java @@ -1,68 +1,68 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder; - -import java.sql.CallableStatement; -import java.sql.Connection; -import java.sql.SQLException; -import java.sql.Types; - -import javax.sql.DataSource; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; - -public class SQLServerSequenceDAO extends CRCDAO { - /** logger **/ - protected final Log log = LogFactory.getLog(SQLServerSequenceDAO.class); - - public static final String QT_QUERY_MASTER_ID = "QT_QUERY_MASTER_ID"; - public static final String QT_QUERY_INSTANCE_ID = "QT_QUERY_INSTANCE_ID"; - public static final String QT_QUERY_RESULT_INSTANCE_ID="QT_QUERY_RESULT_INSTANCE_ID"; - public static final String QT_PATIENT_SET_COLLECTION_ID = "QT_PATIENT_SET_COLLECTION_ID"; - public static final String QT_XML_RESULT_ID = "QT_XML_RESULT_ID"; - public static final String QT_PATIENT_ENC_COLLECIOTN_ID = "QT_PATIENT_ENC_COLLECIOTN_ID"; - - private DataSourceLookup dataSourceLookup = null; - - public SQLServerSequenceDAO(DataSource dataSource,DataSourceLookup dataSourceLookup) { - setDataSource(dataSource); - this.dataSourceLookup = dataSourceLookup; - } - - public int generateSequence(String sequenceName) throws I2B2DAOException { - int newSeq = 0; - Connection conn = null; - try { - conn = dataSource.getConnection(); - CallableStatement cstmt = conn.prepareCall("{? = call dbo.p_get_next_sequence(?)}"); - cstmt.registerOutParameter(1, Types.INTEGER); - cstmt.setString(2, sequenceName); - cstmt.execute(); - newSeq = cstmt.getInt(1); - } catch (SQLException sqlEx) { - log.error("SQLServerSequenceDAO:generateSequence"+sqlEx.getMessage(),sqlEx); - throw new I2B2DAOException("SQLServerSequenceDAO:generateSequence"+sqlEx.getMessage(),sqlEx); - } finally { - if (conn !=null) { - try { - conn.close(); - } catch (SQLException e) { - ; - } - } - } - return newSeq; - - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder; + +import java.sql.CallableStatement; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.Types; + +import javax.sql.DataSource; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; + +public class SQLServerSequenceDAO extends CRCDAO { + /** logger **/ + protected final Log log = LogFactory.getLog(SQLServerSequenceDAO.class); + + public static final String QT_QUERY_MASTER_ID = "QT_QUERY_MASTER_ID"; + public static final String QT_QUERY_INSTANCE_ID = "QT_QUERY_INSTANCE_ID"; + public static final String QT_QUERY_RESULT_INSTANCE_ID="QT_QUERY_RESULT_INSTANCE_ID"; + public static final String QT_PATIENT_SET_COLLECTION_ID = "QT_PATIENT_SET_COLLECTION_ID"; + public static final String QT_XML_RESULT_ID = "QT_XML_RESULT_ID"; + public static final String QT_PATIENT_ENC_COLLECIOTN_ID = "QT_PATIENT_ENC_COLLECIOTN_ID"; + + private DataSourceLookup dataSourceLookup = null; + + public SQLServerSequenceDAO(DataSource dataSource,DataSourceLookup dataSourceLookup) { + setDataSource(dataSource); + this.dataSourceLookup = dataSourceLookup; + } + + public int generateSequence(String sequenceName) throws I2B2DAOException { + int newSeq = 0; + Connection conn = null; + try { + conn = dataSource.getConnection(); + CallableStatement cstmt = conn.prepareCall("{? = call dbo.p_get_next_sequence(?)}"); + cstmt.registerOutParameter(1, Types.INTEGER); + cstmt.setString(2, sequenceName); + cstmt.execute(); + newSeq = cstmt.getInt(1); + } catch (SQLException sqlEx) { + log.error("SQLServerSequenceDAO:generateSequence"+sqlEx.getMessage(),sqlEx); + throw new I2B2DAOException("SQLServerSequenceDAO:generateSequence"+sqlEx.getMessage(),sqlEx); + } finally { + if (conn !=null) { + try { + conn.close(); + } catch (SQLException e) { + ; + } + } + } + return newSeq; + + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/SchedulerStoredProcedure.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/SchedulerStoredProcedure.java similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/SchedulerStoredProcedure.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/SchedulerStoredProcedure.java index eef85ec0..8a26f9b4 100644 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/SchedulerStoredProcedure.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/SchedulerStoredProcedure.java @@ -1,452 +1,452 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder; - - -import java.io.File; - -/** - * To add Length of Stay (This is for Oracle and Postgresl) For Sql Server change the sql statement from (DX to #DX) - * - * Add a entry to QT_BREAKDOWN_PATH - * NAME = LENGTH_OF_STAY - * VALUE = select length_of_stay as patient_range, count(distinct a.PATIENT_num) as patient_count from visit_dimension a, DX b where a.patient_num = b.patient_num group by a.length_of_stay order by 1 - * - * Add a entry to QT_QUERY_RESULT_TYPE - * RESULT_TYPE_ID = 13 (Or any unused number) - * NAME = LENGTH_OF_STAY - * DESCRIPTION = Length of Dtay Brealdown - * DISPLAY_TYPE_ID = CATNUM - * VISUAL_ATTRIBUTE_TYPE_ID = LA - * - * Add a new in CRCApplicationContext.xml - * - * - * LENGTH_OF_STAY - * - * edu.harvard.i2b2.crc.dao.setfinder.QueryResultPatientSQLCountGenerator - * - * - */ - - -import java.io.StringWriter; -import java.security.SecureRandom; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.time.LocalDate; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.util.db.JDBCUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.ProcessTimingReportUtil; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.db.QtQueryBreakdownType; -import edu.harvard.i2b2.crc.datavo.db.QtQueryResultType; -import edu.harvard.i2b2.crc.datavo.i2b2result.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2result.DataType; -import edu.harvard.i2b2.crc.datavo.i2b2result.ResultEnvelopeType; -import edu.harvard.i2b2.crc.datavo.i2b2result.ResultType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.PanelType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionType; -import edu.harvard.i2b2.crc.opencsv.CSVWriter; -import edu.harvard.i2b2.crc.opencsv.ResultSetHelperService; -import edu.harvard.i2b2.crc.util.LogTimingUtil; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - -import org.quartz.Job; -import org.quartz.JobExecutionContext; -import org.quartz.JobExecutionException; - -/** - * Setfinder's result genertor class. This class calculates patient break down - * for the result type. - * - * Calls the ontology to get the children for the result type and then - * calculates the patient count for each child of the result type. - */ -public class SchedulerStoredProcedure extends CRCDAO implements IResultGenerator, Job { - - protected final Log logesapi = LogFactory.getLog(getClass()); - - private Map params; - @Override - public String getResults() { - return xmlResult; - } - - @Override - public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException { - params = jobExecutionContext.getJobDetail().getJobDataMap().getWrappedMap(); - try { - generateResult(params); - } catch (CRCTimeOutException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (I2B2DAOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - private String xmlResult = null; - /** - * Function accepts parameter in Map. The patient count will be obfuscated - * if the user is OBFUS - */ - @Override - public void generateResult(Map param) throws CRCTimeOutException, - I2B2DAOException { - - - // mm create a csv in a folder - - - SetFinderConnection sfConn = (SetFinderConnection) param - .get("SetFinderConnection"); - SetFinderDAOFactory sfDAOFactory = (SetFinderDAOFactory) param - .get("SetFinderDAOFactory"); - - // String patientSetId = (String)param.get("PatientSetId"); - String queryInstanceId = (String) param.get("QueryInstanceId"); - String TEMP_DX_TABLE = (String) param.get("TEMP_DX_TABLE"); - String resultInstanceId = (String) param.get("ResultInstanceId"); - // String itemKey = (String) param.get("ItemKey"); - String resultTypeName = (String) param.get("ResultOptionName"); - String resultFullName = (String) param.get("ResultFullName"); - - String processTimingFlag = (String) param.get("ProcessTimingFlag"); - String projectId = (String) param.get("projectId"); - int transactionTimeout = 180; - /* - int obfuscatedRecordCount = (Integer) param.get("ObfuscatedRecordCount"); - int recordCount = (Integer) param.get("RecordCount"); - int resultPriority = (Integer) param.get("ResultPriority"); - int transactionTimeout = (Integer) param.get("TransactionTimeout"); - boolean obfscDataRoleFlag = (Boolean)param.get("ObfuscatedRoleFlag"); - QueryDefinitionType queryDef = (QueryDefinitionType)param.get("queryDef"); - List panelList = (List)param.get("panelList"); - boolean skipCSV = false; - if ((Boolean)param.get("SkipCSV") != null) - skipCSV = (Boolean)param.get("SkipCSV"); - - */ - this - .setDbSchemaName(sfDAOFactory.getDataSourceLookup() - .getFullSchema()); - Map ontologyKeyMap = (Map) param.get("setFinderResultOntologyKeyMap"); - String serverType = (String) param.get("ServerType"); - // CallOntologyUtil ontologyUtil = (CallOntologyUtil) param - // .get("CallOntologyUtil"); - List roles = (List) param.get("Roles"); - String tempTableName = ""; - PreparedStatement stmt = null; - boolean errorFlag = false, timeoutFlag = false; - //String itemKey = ""; - - int actualTotal = 0, obsfcTotal = 0; - - - - - try { - LogTimingUtil logTimingUtil = new LogTimingUtil(); - logTimingUtil.setStartTime(); - - LogTimingUtil subLogTimingUtil = new LogTimingUtil(); - subLogTimingUtil.setStartTime(); - - String itemCountSql = getItemKeyFromResultType(sfDAOFactory, resultTypeName); - - //get break down count sigma from property file - - ResultType resultType = new ResultType(); - resultType.setName(resultTypeName); - //stmt = sfConn.prepareStatement(itemCountSql); - - CancelStatementRunner csr = new CancelStatementRunner(stmt, - transactionTimeout); - Thread csrThread = new Thread(csr); - csrThread.start(); - - //String sqlFinal = ""; - - if (itemCountSql.contains("{{{DX}}}")) - itemCountSql = itemCountSql.replaceAll("\\{\\{\\{DX\\}\\}\\}", TEMP_DX_TABLE); - if (itemCountSql.contains("{{{DATABASE_NAME}}}")) - itemCountSql = itemCountSql.replaceAll("\\{\\{\\{DATABASE_NAME\\}\\}\\}", this.getDbSchemaName()); - - - // String[] sqls = itemCountSql.split("<\\*>"); - // int count = 0; - // while (count < sqls.length - 1) - // { - - - - stmt = sfConn.prepareStatement(itemCountSql); - stmt.setQueryTimeout(transactionTimeout); - logesapi.debug("Executing count sql [" + itemCountSql + "]"); - - // - subLogTimingUtil.setStartTime(); - ResultSet resultSet = stmt.executeQuery(); - - //String fileName = "/tmp/"+ projectId +"output"+resultInstanceId + ".csv"; - //automatically compression if destination file extension is ".zip" or ".gz" - - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - char separator = ','; - char escapechar = '"'; - char lineEnd = '\n'; - String userName = ""; - char quotechar = '"'; - String fileName = ""; - int fetchSize = 50000; - int maxFetchRows = -1; - String separatorStr = qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.defaultseperator"); - if (separatorStr != null) { - separator = getChar(separatorStr); - } - String quotecharStr = qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.defaultquotechar"); - if (quotecharStr != null) { - quotechar = getChar(quotecharStr); - } - String escapecharStr = qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.defaultescapecharacter"); - if (escapecharStr != null) { - escapechar = getChar(escapecharStr); - } - String lineEndStr = qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.defaultlineend"); - if (lineEndStr != null) { - lineEnd = getChar(lineEndStr); - } - String fileNameStr = qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.filename"); - if (fileNameStr != null) { - fileName = fileNameStr; - } - String fetchSizeStr = qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.resultfetchsize"); - if (fetchSizeStr != null) { - fetchSize = Integer.parseInt(fetchSizeStr); - } - String maxFetchRowsStr = qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.maxfetchrows"); - if (maxFetchRowsStr != null) { - maxFetchRows = Integer.parseInt(maxFetchRowsStr); - } - fileName = fileName.replaceAll("\\{\\{\\{USER_NAME\\}\\}\\}", userName); - fileName = fileName.replaceAll("\\{\\{\\{FULL_NAME\\}\\}\\}", resultFullName); - fileName = fileName.replaceAll("\\{\\{\\{PROJECT_ID\\}\\}\\}", projectId.substring(1, projectId.length()-1)); - //fileName = fileName.replaceAll("\\{\\{\\{RESULT_INSTANCE_ID\\}\\}\\}", resultInstanceId); - //fileName = fileName.replaceAll("\\{\\{\\{QUERY_NAME\\}\\}\\}", sanitizeFilename(queryDef.getQueryName())); - - while (fileName.contains("{{{RANDOM_")) - { - - try { - int start = fileName.indexOf("{{{RANDOM_"); - int end = fileName.indexOf("}}}", start); - int size = Integer.parseInt(fileName.substring(start+10, end)); - - //SecureRandom random = new SecureRandom(); - //fileName = fileName.replaceAll("\\{\\{\\{RANDOM_"+size+"\\}\\}\\}", String.valueOf(random.nextInt(size))); - fileName = fileName.replaceAll("\\{\\{\\{RANDOM_"+size+"\\}\\}\\}", (String) param.get("ResultRandom")); - - } catch (Exception e) {} - - } - // Deal with dates - while (fileName.contains("{{{DATE_")) - { - - try { - int start = fileName.indexOf("{{{DATE_"); - int end = fileName.indexOf("}}}", start); - String date = fileName.substring(start+8, end); - - //DateTimeFormatter formatter = DateTimeFormatter.ofPattern(date); - //fileName = fileName.replaceAll("\\{\\{\\{DATE_"+date+"\\}\\}\\}", LocalDate.now().format(formatter)); - fileName = fileName.replaceAll("\\{\\{\\{DATE_"+date+"\\}\\}\\}", (String) param.get("ResultDate")); - - } catch (Exception e) {} - - } - - - - edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory(); - BodyType bodyType = new BodyType(); - bodyType.getAny().add(of.createResult(resultType)); - ResultEnvelopeType resultEnvelop = new ResultEnvelopeType(); - resultEnvelop.setBody(bodyType); - - JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); - - StringWriter strWriter = new StringWriter(); - subLogTimingUtil.setStartTime(); - jaxbUtil.marshaller(of.createI2B2ResultEnvelope(resultEnvelop), - strWriter); - subLogTimingUtil.setEndTime(); - //tm.begin(); - IXmlResultDao xmlResultDao = sfDAOFactory.getXmlResultDao(); - xmlResult = strWriter.toString(); - if (resultInstanceId != null) - xmlResultDao.createQueryXmlResult(resultInstanceId, strWriter - .toString()); - // - if (processTimingFlag != null) { - if (!processTimingFlag.trim().equalsIgnoreCase(ProcessTimingReportUtil.NONE) ) { - ProcessTimingReportUtil ptrUtil = new ProcessTimingReportUtil(sfDAOFactory.getDataSourceLookup()); - if (processTimingFlag.trim().equalsIgnoreCase(ProcessTimingReportUtil.DEBUG) ) { - ptrUtil.logProcessTimingMessage(queryInstanceId, ptrUtil.buildProcessTiming(subLogTimingUtil, "JAXB - " + resultTypeName , "")); - } - logTimingUtil.setEndTime(); - ptrUtil.logProcessTimingMessage(queryInstanceId, ptrUtil.buildProcessTiming(logTimingUtil, "BUILD - " + resultTypeName , "")); - } - } - //tm.commit(); - - } catch (SQLException sqlEx) { - // catch oracle query timeout error ORA-01013 - if (sqlEx.toString().indexOf("ORA-01013") > -1) { - timeoutFlag = true; - throw new CRCTimeOutException(sqlEx.getMessage(), sqlEx); - } - if (sqlEx.getMessage().indexOf("The query was canceled.") > -1) { - timeoutFlag = true; - throw new CRCTimeOutException(sqlEx.getMessage(), sqlEx); - } - if (sqlEx.getMessage().indexOf("timed out") > -1) { - timeoutFlag = true; - throw new CRCTimeOutException(sqlEx.getMessage(), sqlEx); - } - errorFlag = true; - log.error("Error while executing sql", sqlEx); - throw new I2B2DAOException("Error while executing sql", sqlEx); - } catch (Exception sqlEx) { - - errorFlag = true; - log.error("QueryResultPatientSetGenerator.generateResult:" - + sqlEx.getMessage(), sqlEx); - throw new I2B2DAOException( - "QueryResultPatientSetGenerator.generateResult:" - + sqlEx.getMessage(), sqlEx); - } finally { - - if (resultInstanceId != null) { - IQueryResultInstanceDao resultInstanceDao = sfDAOFactory - .getPatientSetResultDAO(); - - if (errorFlag) { - resultInstanceDao.updatePatientSet(resultInstanceId, - QueryStatusTypeId.STATUSTYPE_ID_ERROR, 0); - } else { - // set the setsize and the description of the result instance if - // the user role is obfuscated - if (timeoutFlag == false) { // check if the query completed - try { - // tm.begin(); - - String obfusMethod = "", description = null; - - IQueryResultTypeDao resultTypeDao = sfDAOFactory.getQueryResultTypeDao(); - List resultTypeList = resultTypeDao - .getQueryResultTypeByName(resultTypeName, roles); - - // add "(Obfuscated)" in the description - //description = resultTypeList.get(0) - // .getDescription() - // + " (Obfuscated) "; - String queryName = sfDAOFactory.getQueryMasterDAO().getQueryDefinition( - sfDAOFactory.getQueryInstanceDAO().getQueryInstanceByInstanceId(queryInstanceId).getQtQueryMaster().getQueryMasterId()).getName(); - - - description = resultTypeList.get(0) - .getDescription() + " for \"" + queryName +"\""; - - // set the result instance description - resultInstanceDao.updateResultInstanceDescription( - resultInstanceId, description); - // tm.commit(); - } catch (SecurityException e) { - throw new I2B2DAOException( - "Failed to write obfuscated description " - + e.getMessage(), e); - } catch (IllegalStateException e) { - throw new I2B2DAOException( - "Failed to write obfuscated description " - + e.getMessage(), e); - } - } - } - } - } - } - - - private String sanitizeFilename(String filename) - { - - return filename.replaceAll("[^a-zA-Z0-9.-]", "_"); - } - /* - private static final Pattern TAG_REGEX = Pattern.compile("{{{(.+?)}}}", Pattern.DOTALL); - - - private static List getTagValues(final String str) { - final List tagValues = new ArrayList(); - final Matcher matcher = TAG_REGEX.matcher(str); - while (matcher.find()) { - tagValues.add(matcher.group(1)); - } - return tagValues; - } - */ - private char getChar(String sTerminatedBy) - { - if ("\\t".equals(sTerminatedBy)) { - return ( '\t'); - } else if ("\\n".equals(sTerminatedBy)) { - return ( '\n'); - } else if ("\\r".equals(sTerminatedBy)) { - return ( '\r'); - } else if ("\\f".equals(sTerminatedBy)) { - return ( '\f'); - } else if (null == sTerminatedBy || "".equals(sTerminatedBy) || "\\0".equals(sTerminatedBy)) { - return ('\0'); - } else { - return ( sTerminatedBy.charAt(0)); - } - - } - - private String getItemKeyFromResultType(SetFinderDAOFactory sfDAOFactory, - String resultTypeKey) { - // - IQueryBreakdownTypeDao queryBreakdownTypeDao = sfDAOFactory - .getQueryBreakdownTypeDao(); - QtQueryBreakdownType queryBreakdownType = queryBreakdownTypeDao - .getBreakdownTypeByName(resultTypeKey); - String itemKey = queryBreakdownType.getValue(); - return itemKey; - } - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder; + + +import java.io.File; + +/** + * To add Length of Stay (This is for Oracle and Postgresl) For Sql Server change the sql statement from (DX to #DX) + * + * Add a entry to QT_BREAKDOWN_PATH + * NAME = LENGTH_OF_STAY + * VALUE = select length_of_stay as patient_range, count(distinct a.PATIENT_num) as patient_count from visit_dimension a, DX b where a.patient_num = b.patient_num group by a.length_of_stay order by 1 + * + * Add a entry to QT_QUERY_RESULT_TYPE + * RESULT_TYPE_ID = 13 (Or any unused number) + * NAME = LENGTH_OF_STAY + * DESCRIPTION = Length of Dtay Brealdown + * DISPLAY_TYPE_ID = CATNUM + * VISUAL_ATTRIBUTE_TYPE_ID = LA + * + * Add a new in CRCApplicationContext.xml + * + * + * LENGTH_OF_STAY + * + * edu.harvard.i2b2.crc.dao.setfinder.QueryResultPatientSQLCountGenerator + * + * + */ + + +import java.io.StringWriter; +import java.security.SecureRandom; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.util.db.JDBCUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.ProcessTimingReportUtil; +import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; +import edu.harvard.i2b2.crc.datavo.db.QtQueryBreakdownType; +import edu.harvard.i2b2.crc.datavo.db.QtQueryResultType; +import edu.harvard.i2b2.crc.datavo.i2b2result.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2result.DataType; +import edu.harvard.i2b2.crc.datavo.i2b2result.ResultEnvelopeType; +import edu.harvard.i2b2.crc.datavo.i2b2result.ResultType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.PanelType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionType; +import edu.harvard.i2b2.crc.opencsv.CSVWriter; +import edu.harvard.i2b2.crc.opencsv.ResultSetHelperService; +import edu.harvard.i2b2.crc.util.LogTimingUtil; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + +import org.quartz.Job; +import org.quartz.JobExecutionContext; +import org.quartz.JobExecutionException; + +/** + * Setfinder's result genertor class. This class calculates patient break down + * for the result type. + * + * Calls the ontology to get the children for the result type and then + * calculates the patient count for each child of the result type. + */ +public class SchedulerStoredProcedure extends CRCDAO implements IResultGenerator, Job { + + protected final Log logesapi = LogFactory.getLog(getClass()); + + private Map params; + @Override + public String getResults() { + return xmlResult; + } + + @Override + public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException { + params = jobExecutionContext.getJobDetail().getJobDataMap().getWrappedMap(); + try { + generateResult(params); + } catch (CRCTimeOutException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (I2B2DAOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + private String xmlResult = null; + /** + * Function accepts parameter in Map. The patient count will be obfuscated + * if the user is OBFUS + */ + @Override + public void generateResult(Map param) throws CRCTimeOutException, + I2B2DAOException { + + + // mm create a csv in a folder + + + SetFinderConnection sfConn = (SetFinderConnection) param + .get("SetFinderConnection"); + SetFinderDAOFactory sfDAOFactory = (SetFinderDAOFactory) param + .get("SetFinderDAOFactory"); + + // String patientSetId = (String)param.get("PatientSetId"); + String queryInstanceId = (String) param.get("QueryInstanceId"); + String TEMP_DX_TABLE = (String) param.get("TEMP_DX_TABLE"); + String resultInstanceId = (String) param.get("ResultInstanceId"); + // String itemKey = (String) param.get("ItemKey"); + String resultTypeName = (String) param.get("ResultOptionName"); + String resultFullName = (String) param.get("ResultFullName"); + + String processTimingFlag = (String) param.get("ProcessTimingFlag"); + String projectId = (String) param.get("projectId"); + int transactionTimeout = 180; + /* + int obfuscatedRecordCount = (Integer) param.get("ObfuscatedRecordCount"); + int recordCount = (Integer) param.get("RecordCount"); + int resultPriority = (Integer) param.get("ResultPriority"); + int transactionTimeout = (Integer) param.get("TransactionTimeout"); + boolean obfscDataRoleFlag = (Boolean)param.get("ObfuscatedRoleFlag"); + QueryDefinitionType queryDef = (QueryDefinitionType)param.get("queryDef"); + List panelList = (List)param.get("panelList"); + boolean skipCSV = false; + if ((Boolean)param.get("SkipCSV") != null) + skipCSV = (Boolean)param.get("SkipCSV"); + + */ + this + .setDbSchemaName(sfDAOFactory.getDataSourceLookup() + .getFullSchema()); + Map ontologyKeyMap = (Map) param.get("setFinderResultOntologyKeyMap"); + String serverType = (String) param.get("ServerType"); + // CallOntologyUtil ontologyUtil = (CallOntologyUtil) param + // .get("CallOntologyUtil"); + List roles = (List) param.get("Roles"); + String tempTableName = ""; + PreparedStatement stmt = null; + boolean errorFlag = false, timeoutFlag = false; + //String itemKey = ""; + + int actualTotal = 0, obsfcTotal = 0; + + + + + try { + LogTimingUtil logTimingUtil = new LogTimingUtil(); + logTimingUtil.setStartTime(); + + LogTimingUtil subLogTimingUtil = new LogTimingUtil(); + subLogTimingUtil.setStartTime(); + + String itemCountSql = getItemKeyFromResultType(sfDAOFactory, resultTypeName); + + //get break down count sigma from property file + + ResultType resultType = new ResultType(); + resultType.setName(resultTypeName); + //stmt = sfConn.prepareStatement(itemCountSql); + + CancelStatementRunner csr = new CancelStatementRunner(stmt, + transactionTimeout); + Thread csrThread = new Thread(csr); + csrThread.start(); + + //String sqlFinal = ""; + + if (itemCountSql.contains("{{{DX}}}")) + itemCountSql = itemCountSql.replaceAll("\\{\\{\\{DX\\}\\}\\}", TEMP_DX_TABLE); + if (itemCountSql.contains("{{{DATABASE_NAME}}}")) + itemCountSql = itemCountSql.replaceAll("\\{\\{\\{DATABASE_NAME\\}\\}\\}", this.getDbSchemaName()); + + + // String[] sqls = itemCountSql.split("<\\*>"); + // int count = 0; + // while (count < sqls.length - 1) + // { + + + + stmt = sfConn.prepareStatement(itemCountSql); + stmt.setQueryTimeout(transactionTimeout); + logesapi.debug("Executing count sql [" + itemCountSql + "]"); + + // + subLogTimingUtil.setStartTime(); + ResultSet resultSet = stmt.executeQuery(); + + //String fileName = "/tmp/"+ projectId +"output"+resultInstanceId + ".csv"; + //automatically compression if destination file extension is ".zip" or ".gz" + + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + char separator = ','; + char escapechar = '"'; + char lineEnd = '\n'; + String userName = ""; + char quotechar = '"'; + String fileName = ""; + int fetchSize = 50000; + int maxFetchRows = -1; + String separatorStr = qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.defaultseperator"); + if (separatorStr != null) { + separator = getChar(separatorStr); + } + String quotecharStr = qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.defaultquotechar"); + if (quotecharStr != null) { + quotechar = getChar(quotecharStr); + } + String escapecharStr = qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.defaultescapecharacter"); + if (escapecharStr != null) { + escapechar = getChar(escapecharStr); + } + String lineEndStr = qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.defaultlineend"); + if (lineEndStr != null) { + lineEnd = getChar(lineEndStr); + } + String fileNameStr = qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.filename"); + if (fileNameStr != null) { + fileName = fileNameStr; + } + String fetchSizeStr = qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.resultfetchsize"); + if (fetchSizeStr != null) { + fetchSize = Integer.parseInt(fetchSizeStr); + } + String maxFetchRowsStr = qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.maxfetchrows"); + if (maxFetchRowsStr != null) { + maxFetchRows = Integer.parseInt(maxFetchRowsStr); + } + fileName = fileName.replaceAll("\\{\\{\\{USER_NAME\\}\\}\\}", userName); + fileName = fileName.replaceAll("\\{\\{\\{FULL_NAME\\}\\}\\}", resultFullName); + fileName = fileName.replaceAll("\\{\\{\\{PROJECT_ID\\}\\}\\}", projectId.substring(1, projectId.length()-1)); + //fileName = fileName.replaceAll("\\{\\{\\{RESULT_INSTANCE_ID\\}\\}\\}", resultInstanceId); + //fileName = fileName.replaceAll("\\{\\{\\{QUERY_NAME\\}\\}\\}", sanitizeFilename(queryDef.getQueryName())); + + while (fileName.contains("{{{RANDOM_")) + { + + try { + int start = fileName.indexOf("{{{RANDOM_"); + int end = fileName.indexOf("}}}", start); + int size = Integer.parseInt(fileName.substring(start+10, end)); + + //SecureRandom random = new SecureRandom(); + //fileName = fileName.replaceAll("\\{\\{\\{RANDOM_"+size+"\\}\\}\\}", String.valueOf(random.nextInt(size))); + fileName = fileName.replaceAll("\\{\\{\\{RANDOM_"+size+"\\}\\}\\}", (String) param.get("ResultRandom")); + + } catch (Exception e) {} + + } + // Deal with dates + while (fileName.contains("{{{DATE_")) + { + + try { + int start = fileName.indexOf("{{{DATE_"); + int end = fileName.indexOf("}}}", start); + String date = fileName.substring(start+8, end); + + //DateTimeFormatter formatter = DateTimeFormatter.ofPattern(date); + //fileName = fileName.replaceAll("\\{\\{\\{DATE_"+date+"\\}\\}\\}", LocalDate.now().format(formatter)); + fileName = fileName.replaceAll("\\{\\{\\{DATE_"+date+"\\}\\}\\}", (String) param.get("ResultDate")); + + } catch (Exception e) {} + + } + + + + edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory(); + BodyType bodyType = new BodyType(); + bodyType.getAny().add(of.createResult(resultType)); + ResultEnvelopeType resultEnvelop = new ResultEnvelopeType(); + resultEnvelop.setBody(bodyType); + + JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); + + StringWriter strWriter = new StringWriter(); + subLogTimingUtil.setStartTime(); + jaxbUtil.marshaller(of.createI2B2ResultEnvelope(resultEnvelop), + strWriter); + subLogTimingUtil.setEndTime(); + //tm.begin(); + IXmlResultDao xmlResultDao = sfDAOFactory.getXmlResultDao(); + xmlResult = strWriter.toString(); + if (resultInstanceId != null) + xmlResultDao.createQueryXmlResult(resultInstanceId, strWriter + .toString()); + // + if (processTimingFlag != null) { + if (!processTimingFlag.trim().equalsIgnoreCase(ProcessTimingReportUtil.NONE) ) { + ProcessTimingReportUtil ptrUtil = new ProcessTimingReportUtil(sfDAOFactory.getDataSourceLookup()); + if (processTimingFlag.trim().equalsIgnoreCase(ProcessTimingReportUtil.DEBUG) ) { + ptrUtil.logProcessTimingMessage(queryInstanceId, ptrUtil.buildProcessTiming(subLogTimingUtil, "JAXB - " + resultTypeName , "")); + } + logTimingUtil.setEndTime(); + ptrUtil.logProcessTimingMessage(queryInstanceId, ptrUtil.buildProcessTiming(logTimingUtil, "BUILD - " + resultTypeName , "")); + } + } + //tm.commit(); + + } catch (SQLException sqlEx) { + // catch oracle query timeout error ORA-01013 + if (sqlEx.toString().indexOf("ORA-01013") > -1) { + timeoutFlag = true; + throw new CRCTimeOutException(sqlEx.getMessage(), sqlEx); + } + if (sqlEx.getMessage().indexOf("The query was canceled.") > -1) { + timeoutFlag = true; + throw new CRCTimeOutException(sqlEx.getMessage(), sqlEx); + } + if (sqlEx.getMessage().indexOf("timed out") > -1) { + timeoutFlag = true; + throw new CRCTimeOutException(sqlEx.getMessage(), sqlEx); + } + errorFlag = true; + log.error("Error while executing sql", sqlEx); + throw new I2B2DAOException("Error while executing sql", sqlEx); + } catch (Exception sqlEx) { + + errorFlag = true; + log.error("QueryResultPatientSetGenerator.generateResult:" + + sqlEx.getMessage(), sqlEx); + throw new I2B2DAOException( + "QueryResultPatientSetGenerator.generateResult:" + + sqlEx.getMessage(), sqlEx); + } finally { + + if (resultInstanceId != null) { + IQueryResultInstanceDao resultInstanceDao = sfDAOFactory + .getPatientSetResultDAO(); + + if (errorFlag) { + resultInstanceDao.updatePatientSet(resultInstanceId, + QueryStatusTypeId.STATUSTYPE_ID_ERROR, 0); + } else { + // set the setsize and the description of the result instance if + // the user role is obfuscated + if (timeoutFlag == false) { // check if the query completed + try { + // tm.begin(); + + String obfusMethod = "", description = null; + + IQueryResultTypeDao resultTypeDao = sfDAOFactory.getQueryResultTypeDao(); + List resultTypeList = resultTypeDao + .getQueryResultTypeByName(resultTypeName, roles); + + // add "(Obfuscated)" in the description + //description = resultTypeList.get(0) + // .getDescription() + // + " (Obfuscated) "; + String queryName = sfDAOFactory.getQueryMasterDAO().getQueryDefinition( + sfDAOFactory.getQueryInstanceDAO().getQueryInstanceByInstanceId(queryInstanceId).getQtQueryMaster().getQueryMasterId()).getName(); + + + description = resultTypeList.get(0) + .getDescription() + " for \"" + queryName +"\""; + + // set the result instance description + resultInstanceDao.updateResultInstanceDescription( + resultInstanceId, description); + // tm.commit(); + } catch (SecurityException e) { + throw new I2B2DAOException( + "Failed to write obfuscated description " + + e.getMessage(), e); + } catch (IllegalStateException e) { + throw new I2B2DAOException( + "Failed to write obfuscated description " + + e.getMessage(), e); + } + } + } + } + } + } + + + private String sanitizeFilename(String filename) + { + + return filename.replaceAll("[^a-zA-Z0-9.-]", "_"); + } + /* + private static final Pattern TAG_REGEX = Pattern.compile("{{{(.+?)}}}", Pattern.DOTALL); + + + private static List getTagValues(final String str) { + final List tagValues = new ArrayList(); + final Matcher matcher = TAG_REGEX.matcher(str); + while (matcher.find()) { + tagValues.add(matcher.group(1)); + } + return tagValues; + } + */ + private char getChar(String sTerminatedBy) + { + if ("\\t".equals(sTerminatedBy)) { + return ( '\t'); + } else if ("\\n".equals(sTerminatedBy)) { + return ( '\n'); + } else if ("\\r".equals(sTerminatedBy)) { + return ( '\r'); + } else if ("\\f".equals(sTerminatedBy)) { + return ( '\f'); + } else if (null == sTerminatedBy || "".equals(sTerminatedBy) || "\\0".equals(sTerminatedBy)) { + return ('\0'); + } else { + return ( sTerminatedBy.charAt(0)); + } + + } + + private String getItemKeyFromResultType(SetFinderDAOFactory sfDAOFactory, + String resultTypeKey) { + // + IQueryBreakdownTypeDao queryBreakdownTypeDao = sfDAOFactory + .getQueryBreakdownTypeDao(); + QtQueryBreakdownType queryBreakdownType = queryBreakdownTypeDao + .getBreakdownTypeByName(resultTypeKey); + String itemKey = queryBreakdownType.getValue(); + return itemKey; + } + + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/SetFinderConnection.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/SetFinderConnection.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/SetFinderConnection.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/SetFinderConnection.java index 78dc4604..7b3cfaad --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/SetFinderConnection.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/SetFinderConnection.java @@ -1,38 +1,38 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder; - -import java.sql.CallableStatement; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.SQLException; -import java.sql.Statement; - -public class SetFinderConnection { - private Connection conn = null; - - public SetFinderConnection(Connection conn) { - this.conn = conn; - } - - public Statement createStatement() throws SQLException { - return conn.createStatement(); - - } - - public PreparedStatement prepareStatement(String sql) throws SQLException { - return conn.prepareStatement(sql); - } - - public CallableStatement prepateCall(String sql) throws SQLException { - return conn.prepareCall(sql); - - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder; + +import java.sql.CallableStatement; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.sql.Statement; + +public class SetFinderConnection { + private Connection conn = null; + + public SetFinderConnection(Connection conn) { + this.conn = conn; + } + + public Statement createStatement() throws SQLException { + return conn.createStatement(); + + } + + public PreparedStatement prepareStatement(String sql) throws SQLException { + return conn.prepareStatement(sql); + } + + public CallableStatement prepateCall(String sql) throws SQLException { + return conn.prepareCall(sql); + + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/TempTableNameMap.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/TempTableNameMap.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/TempTableNameMap.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/TempTableNameMap.java index 471a9644..d8c21b6a --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/TempTableNameMap.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/TempTableNameMap.java @@ -1,50 +1,50 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder; - -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; - -public class TempTableNameMap { - - private String tempTableName = ""; - private String tempDxTableName = ""; - private String tempMasterTableName = ""; - private String noLockSqlServer = " "; - - - public TempTableNameMap(String serverType) { - if (serverType.equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER)) { - tempTableName = "#global_temp_table"; - tempDxTableName = "#dx"; - tempMasterTableName = "#master_global_temp_table"; - } else if (serverType.equalsIgnoreCase( - DAOFactoryHelper.ORACLE) || serverType.equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) { - tempTableName = "QUERY_GLOBAL_TEMP"; - tempDxTableName = "DX"; - tempMasterTableName = "MASTER_QUERY_GLOBAL_TEMP"; - - } - } - - public String getTempTableName() { - return this.tempTableName; - } - - public String getTempDxTableName() { - return this.tempDxTableName; - } - - public String getTempMasterTable() { - return this.tempMasterTableName; - } - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder; + +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; + +public class TempTableNameMap { + + private String tempTableName = ""; + private String tempDxTableName = ""; + private String tempMasterTableName = ""; + private String noLockSqlServer = " "; + + + public TempTableNameMap(String serverType) { + if (serverType.equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER)) { + tempTableName = "#global_temp_table"; + tempDxTableName = "#dx"; + tempMasterTableName = "#master_global_temp_table"; + } else if (serverType.equalsIgnoreCase( + DAOFactoryHelper.ORACLE) || serverType.equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) { + tempTableName = "QUERY_GLOBAL_TEMP"; + tempDxTableName = "DX"; + tempMasterTableName = "MASTER_QUERY_GLOBAL_TEMP"; + + } + } + + public String getTempTableName() { + return this.tempTableName; + } + + public String getTempDxTableName() { + return this.tempDxTableName; + } + + public String getTempMasterTable() { + return this.tempMasterTableName; + } + + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/XmlResultSpringDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/XmlResultSpringDao.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/XmlResultSpringDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/XmlResultSpringDao.java index 2e72a2ca..d2eceff8 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/XmlResultSpringDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/XmlResultSpringDao.java @@ -1,191 +1,191 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao.setfinder; - -import java.io.StringWriter; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.List; - -import javax.sql.DataSource; - -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.RowMapper; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.db.QtQueryInstance; -import edu.harvard.i2b2.crc.datavo.db.QtQueryResultInstance; -import edu.harvard.i2b2.crc.datavo.db.QtXmlResult; -import edu.harvard.i2b2.crc.datavo.i2b2result.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2result.DataType; -import edu.harvard.i2b2.crc.datavo.i2b2result.ResultEnvelopeType; -import edu.harvard.i2b2.crc.datavo.i2b2result.ResultType; - -/** - * Class to handle persistance operation of Query instance i.e. each run of - * query is called query instance $Id: QueryInstanceSpringDao.java,v 1.4 - * 2008/04/08 19:38:24 rk903 Exp $ - * - * @author rkuttan - * @see QtQueryInstance - */ -public class XmlResultSpringDao extends CRCDAO implements IXmlResultDao { - - JdbcTemplate jdbcTemplate = null; - - QtXmlResultRowMapper xmlResultMapper = new QtXmlResultRowMapper(); - private DataSourceLookup dataSourceLookup = null; - - public XmlResultSpringDao(DataSource dataSource, - DataSourceLookup dataSourceLookup) { - setDataSource(dataSource); - setDbSchemaName(dataSourceLookup.getFullSchema()); - jdbcTemplate = new JdbcTemplate(dataSource); - this.dataSourceLookup = dataSourceLookup; - - } - - /** - * Function to create query instance - * - * @param queryMasterId - * @param userId - * @param groupId - * @param batchMode - * @param statusId - * @return query instance id - */ - @Override - public String createQueryXmlResult(String resultInstanceId, String xmlValue) { - String ORACLE_SQL = "INSERT INTO " + getDbSchemaName() + "QT_XML_RESULT(xml_result_id,result_instance_id,xml_value) VALUES(?,?,?)"; - String POSTGRESQL_SQL = "INSERT INTO " + getDbSchemaName() + "QT_XML_RESULT(xml_result_id,result_instance_id,xml_value) VALUES(?,?,?)"; - String SQLSERVER_SQL = "INSERT INTO " + getDbSchemaName() + "QT_XML_RESULT(result_instance_id,xml_value) VALUES(?,?)"; - String SEQUENCE_ORACLE = "SELECT "+ dbSchemaName +"QT_SQ_QXR_XRID.nextval from dual"; - String SEQUENCE_POSTGRESQL = "SELECT nextval('qt_xml_result_xml_result_id_seq') "; - int xmlResultId = 0; - if (dataSourceLookup.getServerType().equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { - xmlResultId = jdbcTemplate.queryForObject(SEQUENCE_ORACLE, Integer.class); - jdbcTemplate.update(ORACLE_SQL, new Object[]{xmlResultId,resultInstanceId,xmlValue}); - } else if (dataSourceLookup.getServerType().equalsIgnoreCase(DAOFactoryHelper.SQLSERVER)) { - jdbcTemplate.update(SQLSERVER_SQL, new Object[]{resultInstanceId,xmlValue}); - xmlResultId = jdbcTemplate.queryForObject("SELECT @@IDENTITY", Integer.class); - } else if (dataSourceLookup.getServerType().equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { - xmlResultId = jdbcTemplate.queryForObject(SEQUENCE_POSTGRESQL, Integer.class); - jdbcTemplate.update(POSTGRESQL_SQL, new Object[]{xmlResultId,Integer.parseInt(resultInstanceId),xmlValue}); - - } - return String.valueOf(xmlResultId); - } - - /** - * Returns list of query instance for the given master id - * - * @param queryMasterId - * @return List - */ - @Override - @SuppressWarnings("unchecked") - public QtXmlResult getXmlResultByResultInstanceId(String resultInstanceId) throws I2B2DAOException { - String sql = "select * from " + getDbSchemaName() - + "qt_xml_result where result_instance_id = ?"; - List queryXmlResult = jdbcTemplate.query(sql, - new Object[] { Integer.parseInt(resultInstanceId) }, xmlResultMapper); - if (queryXmlResult != null && queryXmlResult.size()>0) { - return queryXmlResult.get(0); - } else { - //Check to see if it is being worked on - sql = "select b.name from " + getDbSchemaName() - + "qt_query_result_instance a, " + getDbSchemaName() - + "qt_query_result_type b where a.result_instance_id = ? and a.result_type_id = b.result_type_id"; - - String resultName = null; - - try { - - resultName = (String) jdbcTemplate.queryForObject( - sql, new Object[] { Integer.parseInt(resultInstanceId) }, String.class); - } catch (Exception e) - { - - } - - if (resultName != null) - { - ResultType resultType = new ResultType(); - resultType.setName(resultName); - DataType mdataType = new DataType(); - mdataType.setValue("-1"); - mdataType.setColumn("Processing"); - mdataType.setType("int"); - resultType.getData().add(mdataType); - - edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory(); - BodyType bodyType = new BodyType(); - bodyType.getAny().add(of.createResult(resultType)); - ResultEnvelopeType resultEnvelop = new ResultEnvelopeType(); - resultEnvelop.setBody(bodyType); - - JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); - - StringWriter strWriter = new StringWriter(); - - try { - jaxbUtil.marshaller(of.createI2B2ResultEnvelope(resultEnvelop), - strWriter); - } catch (JAXBUtilException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - QtXmlResult xmlResult = new QtXmlResult(); - xmlResult.setXmlResultId(resultInstanceId); - QtQueryResultInstance queryResultInstance = new QtQueryResultInstance(); - queryResultInstance.setResultInstanceId(resultInstanceId); - xmlResult.setQtQueryResultInstance(queryResultInstance); - xmlResult.setXmlValue(strWriter.toString()); - return xmlResult; - } else { - - throw new I2B2DAOException("Query result instance id " + resultInstanceId - + " not found"); - } - } - - } - - - - - private static class QtXmlResultRowMapper implements RowMapper { - @Override - public Object mapRow(ResultSet rs, int rowNum) throws SQLException { - QtXmlResult xmlResult = new QtXmlResult(); - xmlResult.setXmlResultId(rs.getString("XML_RESULT_ID")); - QtQueryResultInstance queryResultInstance = new QtQueryResultInstance(); - queryResultInstance.setResultInstanceId(rs.getString("RESULT_INSTANCE_ID")); - xmlResult.setQtQueryResultInstance(queryResultInstance); - xmlResult.setXmlValue(rs.getString("XML_VALUE")); - return xmlResult; - } - } - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao.setfinder; + +import java.io.StringWriter; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.List; + +import javax.sql.DataSource; + +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.RowMapper; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.db.QtQueryInstance; +import edu.harvard.i2b2.crc.datavo.db.QtQueryResultInstance; +import edu.harvard.i2b2.crc.datavo.db.QtXmlResult; +import edu.harvard.i2b2.crc.datavo.i2b2result.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2result.DataType; +import edu.harvard.i2b2.crc.datavo.i2b2result.ResultEnvelopeType; +import edu.harvard.i2b2.crc.datavo.i2b2result.ResultType; + +/** + * Class to handle persistance operation of Query instance i.e. each run of + * query is called query instance $Id: QueryInstanceSpringDao.java,v 1.4 + * 2008/04/08 19:38:24 rk903 Exp $ + * + * @author rkuttan + * @see QtQueryInstance + */ +public class XmlResultSpringDao extends CRCDAO implements IXmlResultDao { + + JdbcTemplate jdbcTemplate = null; + + QtXmlResultRowMapper xmlResultMapper = new QtXmlResultRowMapper(); + private DataSourceLookup dataSourceLookup = null; + + public XmlResultSpringDao(DataSource dataSource, + DataSourceLookup dataSourceLookup) { + setDataSource(dataSource); + setDbSchemaName(dataSourceLookup.getFullSchema()); + jdbcTemplate = new JdbcTemplate(dataSource); + this.dataSourceLookup = dataSourceLookup; + + } + + /** + * Function to create query instance + * + * @param queryMasterId + * @param userId + * @param groupId + * @param batchMode + * @param statusId + * @return query instance id + */ + @Override + public String createQueryXmlResult(String resultInstanceId, String xmlValue) { + String ORACLE_SQL = "INSERT INTO " + getDbSchemaName() + "QT_XML_RESULT(xml_result_id,result_instance_id,xml_value) VALUES(?,?,?)"; + String POSTGRESQL_SQL = "INSERT INTO " + getDbSchemaName() + "QT_XML_RESULT(xml_result_id,result_instance_id,xml_value) VALUES(?,?,?)"; + String SQLSERVER_SQL = "INSERT INTO " + getDbSchemaName() + "QT_XML_RESULT(result_instance_id,xml_value) VALUES(?,?)"; + String SEQUENCE_ORACLE = "SELECT "+ dbSchemaName +"QT_SQ_QXR_XRID.nextval from dual"; + String SEQUENCE_POSTGRESQL = "SELECT nextval('qt_xml_result_xml_result_id_seq') "; + int xmlResultId = 0; + if (dataSourceLookup.getServerType().equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { + xmlResultId = jdbcTemplate.queryForObject(SEQUENCE_ORACLE, Integer.class); + jdbcTemplate.update(ORACLE_SQL, new Object[]{xmlResultId,resultInstanceId,xmlValue}); + } else if (dataSourceLookup.getServerType().equalsIgnoreCase(DAOFactoryHelper.SQLSERVER)) { + jdbcTemplate.update(SQLSERVER_SQL, new Object[]{resultInstanceId,xmlValue}); + xmlResultId = jdbcTemplate.queryForObject("SELECT @@IDENTITY", Integer.class); + } else if (dataSourceLookup.getServerType().equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { + xmlResultId = jdbcTemplate.queryForObject(SEQUENCE_POSTGRESQL, Integer.class); + jdbcTemplate.update(POSTGRESQL_SQL, new Object[]{xmlResultId,Integer.parseInt(resultInstanceId),xmlValue}); + + } + return String.valueOf(xmlResultId); + } + + /** + * Returns list of query instance for the given master id + * + * @param queryMasterId + * @return List + */ + @Override + @SuppressWarnings("unchecked") + public QtXmlResult getXmlResultByResultInstanceId(String resultInstanceId) throws I2B2DAOException { + String sql = "select * from " + getDbSchemaName() + + "qt_xml_result where result_instance_id = ?"; + List queryXmlResult = jdbcTemplate.query(sql, + new Object[] { Integer.parseInt(resultInstanceId) }, xmlResultMapper); + if (queryXmlResult != null && queryXmlResult.size()>0) { + return queryXmlResult.get(0); + } else { + //Check to see if it is being worked on + sql = "select b.name from " + getDbSchemaName() + + "qt_query_result_instance a, " + getDbSchemaName() + + "qt_query_result_type b where a.result_instance_id = ? and a.result_type_id = b.result_type_id"; + + String resultName = null; + + try { + + resultName = (String) jdbcTemplate.queryForObject( + sql, new Object[] { Integer.parseInt(resultInstanceId) }, String.class); + } catch (Exception e) + { + + } + + if (resultName != null) + { + ResultType resultType = new ResultType(); + resultType.setName(resultName); + DataType mdataType = new DataType(); + mdataType.setValue("-1"); + mdataType.setColumn("Processing"); + mdataType.setType("int"); + resultType.getData().add(mdataType); + + edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory(); + BodyType bodyType = new BodyType(); + bodyType.getAny().add(of.createResult(resultType)); + ResultEnvelopeType resultEnvelop = new ResultEnvelopeType(); + resultEnvelop.setBody(bodyType); + + JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); + + StringWriter strWriter = new StringWriter(); + + try { + jaxbUtil.marshaller(of.createI2B2ResultEnvelope(resultEnvelop), + strWriter); + } catch (JAXBUtilException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + QtXmlResult xmlResult = new QtXmlResult(); + xmlResult.setXmlResultId(resultInstanceId); + QtQueryResultInstance queryResultInstance = new QtQueryResultInstance(); + queryResultInstance.setResultInstanceId(resultInstanceId); + xmlResult.setQtQueryResultInstance(queryResultInstance); + xmlResult.setXmlValue(strWriter.toString()); + return xmlResult; + } else { + + throw new I2B2DAOException("Query result instance id " + resultInstanceId + + " not found"); + } + } + + } + + + + + private static class QtXmlResultRowMapper implements RowMapper { + @Override + public Object mapRow(ResultSet rs, int rowNum) throws SQLException { + QtXmlResult xmlResult = new QtXmlResult(); + xmlResult.setXmlResultId(rs.getString("XML_RESULT_ID")); + QtQueryResultInstance queryResultInstance = new QtQueryResultInstance(); + queryResultInstance.setResultInstanceId(rs.getString("RESULT_INSTANCE_ID")); + xmlResult.setQtQueryResultInstance(queryResultInstance); + xmlResult.setXmlValue(rs.getString("XML_VALUE")); + return xmlResult; + } + } + + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/BuildInvertSql.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/BuildInvertSql.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/BuildInvertSql.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/BuildInvertSql.java index 35717db0..d643eb72 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/BuildInvertSql.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/BuildInvertSql.java @@ -1,47 +1,47 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; - -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; - -public class BuildInvertSql extends CRCDAO { - - private String tempTableName = null; - private DataSourceLookup dataSourceLookup = null; - - public BuildInvertSql(DataSourceLookup dataSourceLookup, String tempTableName) { - this.setDbSchemaName(dataSourceLookup.getFullSchema()); - this.dataSourceLookup = dataSourceLookup; - this.tempTableName = tempTableName; - } - - public String buildInsertInvertSql(String queryTiming) { - String insertInvertSql = ""; - - String selectEncounterNum = " ", selectPatientNum = " patient_num "; - String invertTableName = "patient_dimension pat "; - - QueryTimingHandler queryTimingHandler = new QueryTimingHandler(); - if (queryTimingHandler.isSameVisit(queryTiming)) { - selectEncounterNum = " , encounter_num "; - invertTableName = "visit_dimension visit "; - - } - - insertInvertSql = " insert into " + this.dbSchemaName - + this.tempTableName + " ( " + selectPatientNum - + selectEncounterNum + ", panel_count ) select distinct " + selectPatientNum - + selectEncounterNum + ",1 from " + this.dbSchemaName - + invertTableName ; - insertInvertSql += "\n<*>\n"; - return insertInvertSql; - - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; + +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; + +public class BuildInvertSql extends CRCDAO { + + private String tempTableName = null; + private DataSourceLookup dataSourceLookup = null; + + public BuildInvertSql(DataSourceLookup dataSourceLookup, String tempTableName) { + this.setDbSchemaName(dataSourceLookup.getFullSchema()); + this.dataSourceLookup = dataSourceLookup; + this.tempTableName = tempTableName; + } + + public String buildInsertInvertSql(String queryTiming) { + String insertInvertSql = ""; + + String selectEncounterNum = " ", selectPatientNum = " patient_num "; + String invertTableName = "patient_dimension pat "; + + QueryTimingHandler queryTimingHandler = new QueryTimingHandler(); + if (queryTimingHandler.isSameVisit(queryTiming)) { + selectEncounterNum = " , encounter_num "; + invertTableName = "visit_dimension visit "; + + } + + insertInvertSql = " insert into " + this.dbSchemaName + + this.tempTableName + " ( " + selectPatientNum + + selectEncounterNum + ", panel_count ) select distinct " + selectPatientNum + + selectEncounterNum + ",1 from " + this.dbSchemaName + + invertTableName ; + insertInvertSql += "\n<*>\n"; + return insertInvertSql; + + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/BuildPanelSql.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/BuildPanelSql.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/BuildPanelSql.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/BuildPanelSql.java index bf4f1664..2c154105 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/BuildPanelSql.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/BuildPanelSql.java @@ -1,166 +1,166 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; - -import java.util.List; - -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; - -public class BuildPanelSql extends CRCDAO { - private String tempTableName = null; - private DataSourceLookup dataSourceLookup = null; - - public BuildPanelSql(DataSourceLookup dataSourceLookup, String tempTableName) { - this.setDbSchemaName(dataSourceLookup.getFullSchema()); - this.dataSourceLookup = dataSourceLookup; - this.tempTableName = tempTableName; - } - - public String buildPanelSql(List itemSqlList, int panelCount,int oldPanelCount, - boolean firstPanelFlag, boolean encounterFlag, - boolean instanceNumFlag, boolean panelInvertFlag, boolean invertQueryFlag, boolean invertOnlyQueryFlag, String firstItemJoinTiming) { - StringBuffer panelSqlBuffer = new StringBuffer(); - boolean firstItemFlag = true; - - - for (String itemSql : itemSqlList) { - - // add the item sql to the temp table - if (firstPanelFlag && invertOnlyQueryFlag == false ) { - panelSqlBuffer.append(firstPanelItemSql(itemSql, - getTempTableName(), encounterFlag, instanceNumFlag,firstItemJoinTiming)); - - } else { - panelSqlBuffer.append(nonFirstPanelItemSql(itemSql, - getTempTableName(), panelCount, oldPanelCount, encounterFlag, - instanceNumFlag,panelInvertFlag,firstPanelFlag, invertQueryFlag,firstItemFlag)); - } - panelSqlBuffer.append(this.getSqlDelimitor()); - firstItemFlag = false; - } - return panelSqlBuffer.toString(); - } - - private String getTempTableName() { - return this.tempTableName; - } - - public String getSqlDelimitor() { - return "\n<*>\n"; - } - - private String firstPanelItemSql(String totalOccuranceSql, - String tempTableName, boolean encounterFlag, boolean instanceNumFlag, String firstItemJoinTiming) { - String selectClause = " patient_num , panel_count"; - String selectInvJoinClause = " invjoinof.patient_num , invjoinitem.panel_count"; - if (instanceNumFlag) { - selectClause = " provider_id, start_date, concept_cd, instance_num, encounter_num, " + selectClause; - selectInvJoinClause = " invjoinof.provider_id, invjoinof.start_date, invjoinof.concept_cd, invjoinof.instance_num, invjoinof.encounter_num, " + selectClause; - } else if (encounterFlag) { - selectClause = " encounter_num, " + selectClause; - selectInvJoinClause = " invjoinof.encounter_num, " + selectClause; - } - String firstPanelItemSql = ""; - - if (!firstItemJoinTiming.equalsIgnoreCase(QueryTimingHandler.ANY)) { - String invJoinOf = this.getDbSchemaName() + "visit_dimension "; - String whereEncounter = " ", onEncounter = " "; - if (firstItemJoinTiming.equalsIgnoreCase(QueryTimingHandler.SAMEINSTANCENUM)) { - invJoinOf = this.getDbSchemaName() + "observation_fact "; - whereEncounter = " and invjoinof.encounter_num = invjoinitem.encounter_num "; - onEncounter = whereEncounter; - } - firstPanelItemSql = " insert into " + this.getDbSchemaName()+ tempTableName + " (" + selectClause + ")" + "\n" + - " select " + selectInvJoinClause + " from " + invJoinOf + " invjoinof left outer join (" + - totalOccuranceSql + " ) invjoinitem " + - " on invjoinof.patient_num = invjoinitem.patient_num " + - onEncounter + - " where invjoinof.patient_num = invjoinitem.patient_num " + - whereEncounter; - } else { - firstPanelItemSql = " insert into " + this.getDbSchemaName() - + tempTableName + " (" + selectClause + ")" + "\n" - + totalOccuranceSql; - } - - return firstPanelItemSql; - } - - private String nonFirstPanelItemSql(String totalOccuranceSql, - String tempTableName, int panelCount, int oldPanelCount, boolean encounterFlag, - boolean instanceNumFlag, boolean panelInvertFlag, boolean firstPanelFlag, boolean invertQueryFlag, boolean firstItemFlag) { - String encounterNumClause = " ", instanceNumClause = " "; - if (instanceNumFlag) { - instanceNumClause = " and " + this.getDbSchemaName() - + tempTableName + ".encounter_num = t.encounter_num and " - + this.getDbSchemaName() + tempTableName - + ".instance_num = t.instance_num and " - + this.getDbSchemaName() + tempTableName - + ".start_date = t.start_date and " - + this.getDbSchemaName() + tempTableName - + ".concept_cd = t.concept_cd and " - + this.getDbSchemaName() + tempTableName - + ".provider_id = t.provider_id "; - } else if (encounterFlag) { - encounterNumClause = " and " + this.getDbSchemaName() - + tempTableName + ".encounter_num = t.encounter_num "; - } - String nonFirstPanelItemSql = " "; - if (panelInvertFlag) { - if (firstItemFlag) { - nonFirstPanelItemSql = " update " + this.getDbSchemaName() - + tempTableName + " set panel_count = " + panelCount + " where " + this.getDbSchemaName() + tempTableName - + ".panel_count = " + oldPanelCount + "\n<*>\n"; - } - if (firstPanelFlag) { - oldPanelCount = 1; - } - String groupByClause = getGroupBy( encounterFlag, instanceNumFlag); - - nonFirstPanelItemSql += " update " + this.getDbSchemaName() - + tempTableName + " set panel_count = -1 " - + " where " + this.getDbSchemaName() + tempTableName - + ".panel_count = " + panelCount + " and exists ( " + totalOccuranceSql + " where " - + this.getDbSchemaName() + tempTableName - + ".patient_num = t.patient_num " + encounterNumClause - + instanceNumClause + " group by " + groupByClause + " ) "; //group by patient_num - - } else { - String notExists = " "; - if (invertQueryFlag && firstPanelFlag) { - oldPanelCount = 1; - panelCount = -1; - notExists = " not "; - } - nonFirstPanelItemSql = " update " + this.getDbSchemaName() - + tempTableName + " set panel_count =" + panelCount - + " where " + notExists + " exists ( " + totalOccuranceSql + " where " - + this.getDbSchemaName() + tempTableName - + ".panel_count = " + oldPanelCount + " and " - + this.getDbSchemaName() + tempTableName - + ".patient_num = t.patient_num " + encounterNumClause - + instanceNumClause + " ) "; - } - return nonFirstPanelItemSql; - } - - private String getGroupBy(boolean encounterFlag, boolean instanceNumFlag) { - String groupbyClausePrefix ="", groupbyClause = ""; - if (instanceNumFlag) { - groupbyClause = " " + groupbyClausePrefix + "encounter_num ," + groupbyClausePrefix + "instance_num, " + groupbyClausePrefix + "concept_cd," + - groupbyClausePrefix + "start_date," + groupbyClausePrefix + "provider_id,"; - } else if (encounterFlag) { - groupbyClause = " " + groupbyClausePrefix + "encounter_num ,"; - } - groupbyClause += " " + groupbyClausePrefix + "patient_num "; - return groupbyClause; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; + +import java.util.List; + +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; + +public class BuildPanelSql extends CRCDAO { + private String tempTableName = null; + private DataSourceLookup dataSourceLookup = null; + + public BuildPanelSql(DataSourceLookup dataSourceLookup, String tempTableName) { + this.setDbSchemaName(dataSourceLookup.getFullSchema()); + this.dataSourceLookup = dataSourceLookup; + this.tempTableName = tempTableName; + } + + public String buildPanelSql(List itemSqlList, int panelCount,int oldPanelCount, + boolean firstPanelFlag, boolean encounterFlag, + boolean instanceNumFlag, boolean panelInvertFlag, boolean invertQueryFlag, boolean invertOnlyQueryFlag, String firstItemJoinTiming) { + StringBuffer panelSqlBuffer = new StringBuffer(); + boolean firstItemFlag = true; + + + for (String itemSql : itemSqlList) { + + // add the item sql to the temp table + if (firstPanelFlag && invertOnlyQueryFlag == false ) { + panelSqlBuffer.append(firstPanelItemSql(itemSql, + getTempTableName(), encounterFlag, instanceNumFlag,firstItemJoinTiming)); + + } else { + panelSqlBuffer.append(nonFirstPanelItemSql(itemSql, + getTempTableName(), panelCount, oldPanelCount, encounterFlag, + instanceNumFlag,panelInvertFlag,firstPanelFlag, invertQueryFlag,firstItemFlag)); + } + panelSqlBuffer.append(this.getSqlDelimitor()); + firstItemFlag = false; + } + return panelSqlBuffer.toString(); + } + + private String getTempTableName() { + return this.tempTableName; + } + + public String getSqlDelimitor() { + return "\n<*>\n"; + } + + private String firstPanelItemSql(String totalOccuranceSql, + String tempTableName, boolean encounterFlag, boolean instanceNumFlag, String firstItemJoinTiming) { + String selectClause = " patient_num , panel_count"; + String selectInvJoinClause = " invjoinof.patient_num , invjoinitem.panel_count"; + if (instanceNumFlag) { + selectClause = " provider_id, start_date, concept_cd, instance_num, encounter_num, " + selectClause; + selectInvJoinClause = " invjoinof.provider_id, invjoinof.start_date, invjoinof.concept_cd, invjoinof.instance_num, invjoinof.encounter_num, " + selectClause; + } else if (encounterFlag) { + selectClause = " encounter_num, " + selectClause; + selectInvJoinClause = " invjoinof.encounter_num, " + selectClause; + } + String firstPanelItemSql = ""; + + if (!firstItemJoinTiming.equalsIgnoreCase(QueryTimingHandler.ANY)) { + String invJoinOf = this.getDbSchemaName() + "visit_dimension "; + String whereEncounter = " ", onEncounter = " "; + if (firstItemJoinTiming.equalsIgnoreCase(QueryTimingHandler.SAMEINSTANCENUM)) { + invJoinOf = this.getDbSchemaName() + "observation_fact "; + whereEncounter = " and invjoinof.encounter_num = invjoinitem.encounter_num "; + onEncounter = whereEncounter; + } + firstPanelItemSql = " insert into " + this.getDbSchemaName()+ tempTableName + " (" + selectClause + ")" + "\n" + + " select " + selectInvJoinClause + " from " + invJoinOf + " invjoinof left outer join (" + + totalOccuranceSql + " ) invjoinitem " + + " on invjoinof.patient_num = invjoinitem.patient_num " + + onEncounter + + " where invjoinof.patient_num = invjoinitem.patient_num " + + whereEncounter; + } else { + firstPanelItemSql = " insert into " + this.getDbSchemaName() + + tempTableName + " (" + selectClause + ")" + "\n" + + totalOccuranceSql; + } + + return firstPanelItemSql; + } + + private String nonFirstPanelItemSql(String totalOccuranceSql, + String tempTableName, int panelCount, int oldPanelCount, boolean encounterFlag, + boolean instanceNumFlag, boolean panelInvertFlag, boolean firstPanelFlag, boolean invertQueryFlag, boolean firstItemFlag) { + String encounterNumClause = " ", instanceNumClause = " "; + if (instanceNumFlag) { + instanceNumClause = " and " + this.getDbSchemaName() + + tempTableName + ".encounter_num = t.encounter_num and " + + this.getDbSchemaName() + tempTableName + + ".instance_num = t.instance_num and " + + this.getDbSchemaName() + tempTableName + + ".start_date = t.start_date and " + + this.getDbSchemaName() + tempTableName + + ".concept_cd = t.concept_cd and " + + this.getDbSchemaName() + tempTableName + + ".provider_id = t.provider_id "; + } else if (encounterFlag) { + encounterNumClause = " and " + this.getDbSchemaName() + + tempTableName + ".encounter_num = t.encounter_num "; + } + String nonFirstPanelItemSql = " "; + if (panelInvertFlag) { + if (firstItemFlag) { + nonFirstPanelItemSql = " update " + this.getDbSchemaName() + + tempTableName + " set panel_count = " + panelCount + " where " + this.getDbSchemaName() + tempTableName + + ".panel_count = " + oldPanelCount + "\n<*>\n"; + } + if (firstPanelFlag) { + oldPanelCount = 1; + } + String groupByClause = getGroupBy( encounterFlag, instanceNumFlag); + + nonFirstPanelItemSql += " update " + this.getDbSchemaName() + + tempTableName + " set panel_count = -1 " + + " where " + this.getDbSchemaName() + tempTableName + + ".panel_count = " + panelCount + " and exists ( " + totalOccuranceSql + " where " + + this.getDbSchemaName() + tempTableName + + ".patient_num = t.patient_num " + encounterNumClause + + instanceNumClause + " group by " + groupByClause + " ) "; //group by patient_num + + } else { + String notExists = " "; + if (invertQueryFlag && firstPanelFlag) { + oldPanelCount = 1; + panelCount = -1; + notExists = " not "; + } + nonFirstPanelItemSql = " update " + this.getDbSchemaName() + + tempTableName + " set panel_count =" + panelCount + + " where " + notExists + " exists ( " + totalOccuranceSql + " where " + + this.getDbSchemaName() + tempTableName + + ".panel_count = " + oldPanelCount + " and " + + this.getDbSchemaName() + tempTableName + + ".patient_num = t.patient_num " + encounterNumClause + + instanceNumClause + " ) "; + } + return nonFirstPanelItemSql; + } + + private String getGroupBy(boolean encounterFlag, boolean instanceNumFlag) { + String groupbyClausePrefix ="", groupbyClause = ""; + if (instanceNumFlag) { + groupbyClause = " " + groupbyClausePrefix + "encounter_num ," + groupbyClausePrefix + "instance_num, " + groupbyClausePrefix + "concept_cd," + + groupbyClausePrefix + "start_date," + groupbyClausePrefix + "provider_id,"; + } else if (encounterFlag) { + groupbyClause = " " + groupbyClausePrefix + "encounter_num ,"; + } + groupbyClause += " " + groupbyClausePrefix + "patient_num "; + return groupbyClause; + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/BuildTempTableSql.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/BuildTempTableSql.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/BuildTempTableSql.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/BuildTempTableSql.java index eb1661a5..afbc8818 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/BuildTempTableSql.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/BuildTempTableSql.java @@ -1,590 +1,590 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.SortedMap; -import java.util.TreeMap; - -import org.w3c.dom.Element; -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.ontology.ConceptType; -import edu.harvard.i2b2.crc.datavo.ontology.ModifierType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ConstrainValueType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ItemType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ItemType.ConstrainByValue; -import edu.harvard.i2b2.crc.datavo.setfinder.query.PanelType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.PanelType.TotalItemOccurrences; -import edu.harvard.i2b2.crc.util.ItemKeyUtil; -import edu.harvard.i2b2.crc.util.LogTimingUtil; -import edu.harvard.i2b2.crc.util.ParamUtil; - -public class BuildTempTableSql extends CRCDAO { - - DataSourceLookup dataSourceLookup = null; - String queryXML = null; - String noLockSqlServer = " "; - StringBuffer ignoredItemMessageBuffer = new StringBuffer(); - ConceptTypeHandler conceptTypeHandler = null; - BuildPanelSql buildPanelSql = null; - BuildTotalOccuranceSql buildTotalOccuranceSql = null; - TempTableNameMap tempTableNameMap = null; - String processTimingFlag = "NONE"; - ProcessTimingReportUtil processTimingUtil = null; - String processTimingStr = ""; - Map projectParamMap = null; - boolean allowLargeTextValueConstrainFlag = true; - - public BuildTempTableSql(DataSourceLookup dataSourceLookup, String queryXML) { - this.setDbSchemaName(dataSourceLookup.getFullSchema()); - this.dataSourceLookup = dataSourceLookup; - this.queryXML = queryXML; - conceptTypeHandler = new ConceptTypeHandler(queryXML); - tempTableNameMap = new TempTableNameMap(dataSourceLookup.getServerType()); - buildPanelSql = new BuildPanelSql(dataSourceLookup, tempTableNameMap.getTempTableName()); - buildTotalOccuranceSql = new BuildTotalOccuranceSql(dataSourceLookup); - - //construct the process timing util - try { - this.processTimingUtil = new ProcessTimingReportUtil(dataSourceLookup); - } catch (I2B2DAOException e) { - log.error("Error constructing the ProcessTimingReportUtil [" + e.getMessage() + "]"); - } - - } - - public void setProcessTimingFlag(String level) { - this.processTimingFlag = level; - } - - public void setProjectParamMap(Map projectParamMap) { - this.projectParamMap = projectParamMap; - } - - public void setAllowLargeTextValueConstrainFlag(boolean allowLargeTextValueConstrainFlag) { - this.allowLargeTextValueConstrainFlag = allowLargeTextValueConstrainFlag; - } - - - public String getProcessTimingXml() { - return this.processTimingStr; - } - - - public Map buildTempTableSql( - List panelListType, boolean encounterFlag, - boolean instanceNumFlag, String queryTiming, int panelCount, - boolean firstPanelFlag, boolean invertQueryFlag, boolean invertOnlyQueryFlag,String firstItemJoinTiming) throws I2B2DAOException { - // read above panel parameters - - // read each panel - List itemListType = new ArrayList(); - List itemSqlList = new ArrayList(); - List panelSqlList = new ArrayList(); - - // - ignoredItemMessageBuffer.delete(0, ignoredItemMessageBuffer.length()); - - SortedMap panelSql = new TreeMap(); - int oldPanelCount = panelCount; - LogTimingUtil logTiming = new LogTimingUtil(); - for (PanelType panelType : panelListType) { - logTiming.setStartTime(); - // check if the panel is invert - boolean panelInvertFlag = getPanelInvertFlag(panelType.getInvert()); - // get the total item occurance value - TotalItemOccurrences totalOccurance = panelType - .getTotalItemOccurrences(); - - int panelAccuracyScale = panelType.getPanelAccuracyScale(); - //ignore panel accuracy scale value, bcos the function is reverted - panelAccuracyScale = 0; - - // read each item from the panel - itemListType = panelType.getItem(); - itemSqlList.removeAll(itemSqlList); - panelCount++; - - // generate panel date constrain - DateConstrainUtil dateConstrainUtil = new DateConstrainUtil( - this.dataSourceLookup); - String panelDateConstrainSql = dateConstrainUtil - .buildPanelDateSql(panelType); - - boolean singleValidItemInPanel = false; - for (ItemType itemType : itemListType) { - - // call the ontology with the item key. - ConceptType conceptType; - try { - - checkLargeTextConstrainPermission(itemType) ; - - conceptType = conceptTypeHandler.getConceptType(itemType - .getItemKey(), this.dataSourceLookup.getServerType()); - //check if the concept is a container, if so return error - if (conceptType.getVisualattributes() != null) { - String conceptVisualAtt = conceptType.getVisualattributes().trim(); - if (conceptVisualAtt.length()>0 && (conceptVisualAtt.startsWith("C") || - conceptVisualAtt.startsWith("c"))) { - throw new I2B2DAOException("The Container item is not valid in query [" +itemType.getItemKey() +"] " + - "in panel #" + panelCount); - } - } - - singleValidItemInPanel = true; - // build the dimension sql - String dimensionSql = buildDimensionSql(conceptType); - - // build the dimension join sql | need information like - // encounter_set,samevisit,same instance - String dimensionJoinSql = buildDimensionJoinSql( - dimensionSql, encounterFlag, instanceNumFlag, queryTiming, - itemType, conceptType, panelDateConstrainSql,panelAccuracyScale, totalOccurance); - - - // build the outer table with total occurrance constrain // - // String fullItemSql = buildFullItemSql(dimensionJoinSql, - // encounterFlag); - String totalOccuraneSql = buildTotalOccuranceSql - .buildTotalOccuranceSql(dimensionJoinSql, - encounterFlag, instanceNumFlag,queryTiming, panelCount, - totalOccurance,panelInvertFlag); - - itemSqlList.add(totalOccuraneSql); - } catch (ConceptNotFoundException e) { - handleConceptNotFoundException(e, panelCount); - } catch (OntologyException e) { - throw new I2B2DAOException(e.getMessage()); - } - } - if (singleValidItemInPanel) { - String panelItemSql = buildPanelSql.buildPanelSql(itemSqlList, - panelCount, oldPanelCount, firstPanelFlag, encounterFlag, - instanceNumFlag, panelInvertFlag,invertQueryFlag,invertOnlyQueryFlag,firstItemJoinTiming); - panelSql.put(panelCount, panelItemSql); - oldPanelCount = panelCount; - firstPanelFlag = false; - - } - logTiming.setEndTime(); - if (this.processTimingFlag.equalsIgnoreCase(ProcessTimingReportUtil.DEBUG)) { - //build the log xml and add it to the string variable. - processTimingStr += this.processTimingUtil.buildProcessTiming(logTiming, "BUILD SQL - PANEL", null) + "\n"; - } - - } - return panelSql; - - } - - private void handleConceptNotFoundException(ConceptNotFoundException e, - int panelCount) { - ignoredItemMessageBuffer - .append(e.getMessage() + " panel#" + panelCount); - } - - public String getIgnoredItemMessage() { - if (this.ignoredItemMessageBuffer != null - && this.ignoredItemMessageBuffer.length() > 0) { - return "Missing Concept in Ontology Cell : \n" - + this.ignoredItemMessageBuffer.toString(); - } else { - return ""; - } - - } - - public String buildDimensionSql(ConceptType conceptType) { - String dimensionSql = ""; - // if patient list - - - dimensionSql = conceptType.getFacttablecolumn() + " IN (select " - + conceptType.getFacttablecolumn() + " from " - + getDbSchemaName() + conceptType.getTablename() + " " - + noLockSqlServer + " where " + conceptType.getColumnname() - + " " + conceptType.getOperator() + " " - + conceptType.getDimcode(); - if ((conceptType.getOperator() != null) && (conceptType.getOperator().toUpperCase().equals("LIKE"))) - { - - dimensionSql += (!dataSourceLookup.getServerType().toUpperCase().equals("POSTGRESQL") ? " {ESCAPE '?'} " : "" ) ; - } - dimensionSql += ")"; - - return dimensionSql; - } - - // function to build - public String buildDimensionJoinSql(String dimensionSql, - boolean encounterFlag, boolean instanceNumFlag, String queryTiming,ItemType itemType, - ConceptType conceptType, String panelDateConstrainSql, int panelAccuracyScale, TotalItemOccurrences totalOccurance) - throws I2B2DAOException { - String joinTableName = "", joinContainsTable = ""; - String itemDateConstrainSql = " "; - String[] itemValueConstrainSql = new String[]{"",""} ; - String itemModifierConstrainSql = "" ; - String sqlHintClause = " "; - QueryTimingHandler timingHandler = new QueryTimingHandler(); - - if (panelDateConstrainSql == null) { - panelDateConstrainSql = ""; - } - panelDateConstrainSql = panelDateConstrainSql.trim(); - - if (itemType.getItemKey().toLowerCase().startsWith(ItemKeyUtil.ITEM_KEY_PATIENT_SET)) { - - // generate sql for item date constrain - //joinTableName = "qt_patient_set_collection"; - if (timingHandler.isSameVisit(queryTiming)) { - joinTableName = "visit_dimension"; - } else if (timingHandler.isSameInstanceNum(queryTiming)) { - joinTableName = "observation_fact"; - } else { - joinTableName = "qt_patient_set_collection"; - } - - // generate sql for item date constrain - itemDateConstrainSql = callDateConstrain(itemType); - - - - // generate sql for item value constrain - itemValueConstrainSql = callValueConstrain(itemType, "", "",panelAccuracyScale); - - - //check if dateconstrain or value constrain present in the item - if (itemDateConstrainSql.length() > 0 || itemValueConstrainSql[0].length()>0 || panelDateConstrainSql.length() >0 || totalOccurance.getValue() > 1) { - joinTableName = "observation_fact"; - } - - - - - } else if (itemType.getItemKey().toLowerCase().startsWith(ItemKeyUtil.ITEM_KEY_PATIENT_ENCOUNTER_SET)) { - if (timingHandler.isSameInstanceNum(queryTiming)) { - joinTableName = "observation_fact"; - } - joinTableName = "qt_patient_enc_collection"; - // generate sql for item date constrain - itemDateConstrainSql = callDateConstrain(itemType); - - // generate sql for item value constrain - itemValueConstrainSql = callValueConstrain(itemType,"","",panelAccuracyScale); - - //check if dateconstrain or value constrain present in the item - if (itemDateConstrainSql.length() > 0 || itemValueConstrainSql[0].length()>0 || panelDateConstrainSql.length() > 0 || totalOccurance.getValue() > 1) { - joinTableName = "observation_fact"; - } - - - } else if (itemType.getItemKey().toLowerCase().startsWith(ItemKeyUtil.ITEM_KEY_MASTERID)) { - String masterTableName = tempTableNameMap.getTempMasterTable(); - dimensionSql = " master_id = '" + itemType.getItemKey() + "'"; - - // generate sql for item date constrain - itemDateConstrainSql = callDateConstrain(itemType).trim(); - - // generate sql for item value constrain - itemValueConstrainSql = callValueConstrain(itemType,"","",panelAccuracyScale); - - //check if dateconstrain or value constrain present in the item - if (itemDateConstrainSql.length() > 0 || itemValueConstrainSql[0].length() > 0 || panelDateConstrainSql.length() > 0 ) { - String masterWhereClause = " j1.patient_num = j2.patient_num "; - String masterSelectClause = " j1.patient_num "; - if (timingHandler.isSameVisit(queryTiming)) { - masterWhereClause = " j1.encounter_num = j2.encounter_num and j1.patient_num = j2.patient_num " ; - masterSelectClause = " j1.encounter_num, j1.patient_num "; - } else if (timingHandler.isSameInstanceNum(queryTiming)) { - masterSelectClause = " j1.encounter_num, j1.patient_num, j1.instance_num, j1.concept_cd, j1.start_date, j1.provider_id "; - masterWhereClause = " j1.encounter_num = j2.encounter_num and j1.patient_num = j2.patient_num and " + - " j1.instance_num = j2.instance_num and j1.concept_cd = j2.concept_cd and j1.start_date = j2.start_date and j1.provider_id = j2.provider_id " ; - } - joinTableName = "observation_fact"; - //Fix Date Contraint by adding j2 brefore start and end date - panelDateConstrainSql = panelDateConstrainSql.replaceAll("start_date", "j1.start_date"); - panelDateConstrainSql = panelDateConstrainSql.replaceAll("end_date", "j1.end_date"); - - String masterDimensionJoinSql = "select " + masterSelectClause + " from " + this.getDbSchemaName() + joinTableName + " j1, " + this.getDbSchemaName() + masterTableName + " j2 " + " where " + masterWhereClause - + " " + itemValueConstrainSql[0] + " " - + itemDateConstrainSql + " AND " + panelDateConstrainSql; - return masterDimensionJoinSql; - } else { - joinTableName = masterTableName; - } - } else { - joinTableName = "observation_fact"; - - if (conceptType.getTablename().equalsIgnoreCase( - "patient_dimension")) { - joinTableName = "patient_dimension"; - if (timingHandler.isSameVisit(queryTiming)) { - joinTableName = "visit_dimension"; - } else if (timingHandler.isSameInstanceNum(queryTiming)) { - joinTableName = "observation_fact"; - } - } else if (conceptType.getTablename().equalsIgnoreCase( - "visit_dimension")) { - joinTableName = "visit_dimension"; - if (timingHandler.isSameInstanceNum(queryTiming)) { - joinTableName = "observation_fact"; - } - } - - if (conceptType.getTablename().equalsIgnoreCase( - "provider_dimension")) { - sqlHintClause = " /*+ index(observation_fact observation_fact_pk) */ "; - } else { - sqlHintClause = " /*+ index(f fact_cnpt_pat_enct_idx) */ "; - } - - ModifierType modifierType = this.getModifierMetadataFromOntology(itemType); - - //generate sql for item modifier constrain - if (modifierType != null) { - itemModifierConstrainSql = callModifierConstrain(modifierType,itemType); - } - - // generate sql for item date constrain - itemDateConstrainSql = callDateConstrain(itemType); - - - //generate sql for unit_cd conversion - String unitCdSwitchClause = "", unitCdInClause = ""; - String modifierUnitCdSwitchClause = "", modifierUnitCdInClause = ""; - - if ( projectParamMap != null && projectParamMap.get(ParamUtil.CRC_ENABLE_UNITCD_CONVERSION) != null) { - String unitCdConversionFlag = (String)projectParamMap.get(ParamUtil.CRC_ENABLE_UNITCD_CONVERSION); - if (unitCdConversionFlag != null && unitCdConversionFlag.equalsIgnoreCase("ON")) { - if (conceptType.getMetadataxml() != null && conceptType.getMetadataxml().getAny().get(0) != null) { - Element valueMetadataElement = conceptType.getMetadataxml().getAny().get(0); - UnitConverstionUtil unitConverstionUtil = new UnitConverstionUtil(); - unitCdSwitchClause = unitConverstionUtil.buildUnitCdSwitchClause(valueMetadataElement,false,""); - log.debug("concept unit Conversion sql " +unitCdSwitchClause ); - unitCdInClause = unitConverstionUtil.buildUnitCdInClause(valueMetadataElement,""); - - } - - if (modifierType != null && modifierType.getMetadataxml() != null && modifierType.getMetadataxml().getAny().get(0) != null) { - Element valueMetadataElement = modifierType.getMetadataxml().getAny().get(0); - UnitConverstionUtil unitConverstionUtil = new UnitConverstionUtil(); - modifierUnitCdSwitchClause = unitConverstionUtil.buildUnitCdSwitchClause(valueMetadataElement,false,""); - log.debug("modifier unit Conversion sql " +modifierUnitCdSwitchClause ); - modifierUnitCdInClause = unitConverstionUtil.buildUnitCdInClause(valueMetadataElement,""); - - } - } - } - - - - // generate sql for item value constrain - itemValueConstrainSql = callValueConstrain(itemType,unitCdSwitchClause,unitCdInClause,panelAccuracyScale ); - if (panelAccuracyScale >0) { - joinContainsTable = itemValueConstrainSql[1]; - } - - // generate sql for modifier value constrain - String[] modifierConstainSql = callModifierValueConstrain(itemType,modifierUnitCdSwitchClause,modifierUnitCdInClause,panelAccuracyScale ); - itemValueConstrainSql[0] += modifierConstainSql[0]; - if (panelAccuracyScale >0) { - joinContainsTable += modifierConstainSql[1]; - } - - - } - - // itemType.getConstrainByValue() - String selectClause = " patient_num "; - - if (timingHandler.isSameInstanceNum(queryTiming)) { - selectClause = " provider_id, start_date, concept_cd, instance_num, encounter_num, " + selectClause; - } else if (timingHandler.isSameVisit(queryTiming)) { - selectClause = " encounter_num, " + selectClause; - } - - if (panelDateConstrainSql.trim().length() > 0) { - panelDateConstrainSql = " AND ( " + panelDateConstrainSql - + " )"; - } - - if (itemValueConstrainSql[0] == null) { - itemValueConstrainSql[0] = " "; - } - - if (itemDateConstrainSql == null) { - itemDateConstrainSql = " "; - } - - if (itemModifierConstrainSql == null) { - itemModifierConstrainSql = " "; - } - - // - //" INNER JOIN freetexttable(observation_fact,observation_blob,'"+ containsSql + "') " - //+ " AS ft" + j + " ON text_search_index = ft" +j+ ".[KEY] " - //+ " AND - // - - if (!joinTableName.equalsIgnoreCase("observation_fact")) { - joinContainsTable = ""; - itemDateConstrainSql = ""; - itemModifierConstrainSql = ""; - panelDateConstrainSql = ""; - itemValueConstrainSql[0] = ""; - - } - - String dimensionJoinSql = " select " + sqlHintClause + selectClause - + " from " + this.getDbSchemaName() + joinTableName + joinContainsTable - + " where " + dimensionSql + " " + itemModifierConstrainSql - + itemValueConstrainSql[0] + itemDateConstrainSql + panelDateConstrainSql; - log.debug("Dimension select sql [" + dimensionJoinSql + "]"); - - return dimensionJoinSql; - } - - private boolean getPanelInvertFlag(int panelInvert) { - if (panelInvert == 1) { - return true; - } else { - return false; - } - } - - - private String callDateConstrain(ItemType itemType) { - // generate sql for item date constrain - DateConstrainUtil dateConstrainUtil = new DateConstrainUtil( - this.dataSourceLookup); - String itemDateConstrainSql = dateConstrainUtil.buildItemDateSql(itemType); - if (itemDateConstrainSql != null - && itemDateConstrainSql.trim().length() > 0) { - log.info("Item date constrain sql" + itemDateConstrainSql); - itemDateConstrainSql = " AND ( " + itemDateConstrainSql - + " ) "; - } else { - itemDateConstrainSql = ""; - } - return itemDateConstrainSql; - } - - private String[] callValueConstrain(ItemType itemType, String unitCdSwitchClause, String unitCdInClause, int panelAccuracyScale) throws I2B2DAOException { - ValueConstrainsHandler valueConstrainHandler = new ValueConstrainsHandler(); - if (unitCdSwitchClause.length()>0) { - valueConstrainHandler.setUnitCdConversionFlag(true, unitCdInClause, unitCdSwitchClause); - } - - String[] itemValueConstrainSql = valueConstrainHandler - .constructValueConstainClause(itemType - .getConstrainByValue(), this.dataSourceLookup.getServerType(), this.getDbSchemaName(),panelAccuracyScale); - log.info("Item value constrain sql " + itemValueConstrainSql); - - if (itemValueConstrainSql != null - && itemValueConstrainSql[0].trim().length() > 0) { - - itemValueConstrainSql[0] = " AND ( " + itemValueConstrainSql[0] - + " )"; - } else { - itemValueConstrainSql[0] = ""; - } - return itemValueConstrainSql; - } - - private String[] callModifierValueConstrain(ItemType itemType, String modifierUnitCdSwitchClause, String modifierUnitCdInClause,int panelAccuracyScale) throws I2B2DAOException { - ValueConstrainsHandler valueConstrainHandler = new ValueConstrainsHandler(); - if (modifierUnitCdSwitchClause.length()>0) { - valueConstrainHandler.setUnitCdConversionFlag(true, modifierUnitCdInClause, modifierUnitCdSwitchClause); - } - boolean oracleFlag = false; - if (this.dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE)) { - oracleFlag = true; - } - String itemModifierValueConstrainSql[] = new String[] {"",""} ; - - if (itemType.getConstrainByModifier() != null && itemType.getConstrainByModifier().getConstrainByValue() !=null) { - List itemValueConstrainList = buildItemValueConstrain(itemType.getConstrainByModifier().getConstrainByValue()); - itemModifierValueConstrainSql = valueConstrainHandler.constructValueConstainClause(itemValueConstrainList,this.dataSourceLookup.getServerType(),this.getDbSchemaName(),panelAccuracyScale); - if (itemModifierValueConstrainSql != null && itemModifierValueConstrainSql[0].length()>0) { - log.info("Modifier constrian value constrain sql " + itemModifierValueConstrainSql); - } - } - - if (itemModifierValueConstrainSql[0] != null - && itemModifierValueConstrainSql[0].trim().length() > 0) { - - itemModifierValueConstrainSql[0] = " AND ( " + itemModifierValueConstrainSql[0] - + " )"; - } else { - itemModifierValueConstrainSql[0] = ""; - } - return itemModifierValueConstrainSql; - } - - private String callModifierConstrain(ModifierType modifierType, ItemType itemType) throws I2B2DAOException { - - // generate sql for item date constrain - ModifierConstrainsHandler modifierConstrainUtil = new ModifierConstrainsHandler(this.getDbSchemaName()); - String itemModifierConstrainSql = modifierConstrainUtil.constructModifierConstainClause(modifierType); - if (itemModifierConstrainSql != null - && itemModifierConstrainSql.trim().length() > 0) { - log.info("Item modifier constrain sql" + itemModifierConstrainSql); - itemModifierConstrainSql = " AND ( " + itemModifierConstrainSql - + " ) "; - } else { - itemModifierConstrainSql = " "; - } - - return itemModifierConstrainSql; - } - private ModifierType getModifierMetadataFromOntology(ItemType itemType) throws I2B2DAOException { - ItemType.ConstrainByModifier modifierConstrain = itemType.getConstrainByModifier(); - if (modifierConstrain == null) { - return null; - } - String modifierKey = modifierConstrain.getModifierKey(); - String modifierAppliedPath = modifierConstrain.getAppliedPath(); - ItemMetaDataHandler metadataHandler = new ItemMetaDataHandler( - queryXML); - ModifierType modifierType = metadataHandler.getModifierDataFromOntologyCell(modifierKey,modifierAppliedPath, this.dataSourceLookup.getServerType()); - return modifierType; - } - - private void checkLargeTextConstrainPermission(ItemType itemType) throws I2B2DAOException{ - for (ConstrainByValue cvt : itemType.getConstrainByValue()) { - if (cvt.getValueType().equals(ConstrainValueType.LARGETEXT)) { - if (this.allowLargeTextValueConstrainFlag == false) { - throw new I2B2DAOException("Insufficient user role for LARGETEXT constrain. Required minimum role DATA_DEID"); - } - } - } - } - - private List buildItemValueConstrain(List modifierConstrainList) { - List itemValueConstrainList = new ArrayList(); - for (ItemType.ConstrainByModifier.ConstrainByValue modifierValueConstrain : modifierConstrainList) { - ItemType.ConstrainByValue constrainByValue = new ItemType.ConstrainByValue(); - constrainByValue.setValueConstraint(modifierValueConstrain.getValueConstraint()); - constrainByValue.setValueOperator(modifierValueConstrain.getValueOperator()) ; - constrainByValue.setValueType(modifierValueConstrain.getValueType()); - constrainByValue.setValueUnitOfMeasure(modifierValueConstrain.getValueUnitOfMeasure()) ; - itemValueConstrainList.add(constrainByValue); - } - return itemValueConstrainList; - } - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.SortedMap; +import java.util.TreeMap; + +import org.w3c.dom.Element; +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.ontology.ConceptType; +import edu.harvard.i2b2.crc.datavo.ontology.ModifierType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ConstrainValueType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ItemType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ItemType.ConstrainByValue; +import edu.harvard.i2b2.crc.datavo.setfinder.query.PanelType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.PanelType.TotalItemOccurrences; +import edu.harvard.i2b2.crc.util.ItemKeyUtil; +import edu.harvard.i2b2.crc.util.LogTimingUtil; +import edu.harvard.i2b2.crc.util.ParamUtil; + +public class BuildTempTableSql extends CRCDAO { + + DataSourceLookup dataSourceLookup = null; + String queryXML = null; + String noLockSqlServer = " "; + StringBuffer ignoredItemMessageBuffer = new StringBuffer(); + ConceptTypeHandler conceptTypeHandler = null; + BuildPanelSql buildPanelSql = null; + BuildTotalOccuranceSql buildTotalOccuranceSql = null; + TempTableNameMap tempTableNameMap = null; + String processTimingFlag = "NONE"; + ProcessTimingReportUtil processTimingUtil = null; + String processTimingStr = ""; + Map projectParamMap = null; + boolean allowLargeTextValueConstrainFlag = true; + + public BuildTempTableSql(DataSourceLookup dataSourceLookup, String queryXML) { + this.setDbSchemaName(dataSourceLookup.getFullSchema()); + this.dataSourceLookup = dataSourceLookup; + this.queryXML = queryXML; + conceptTypeHandler = new ConceptTypeHandler(queryXML); + tempTableNameMap = new TempTableNameMap(dataSourceLookup.getServerType()); + buildPanelSql = new BuildPanelSql(dataSourceLookup, tempTableNameMap.getTempTableName()); + buildTotalOccuranceSql = new BuildTotalOccuranceSql(dataSourceLookup); + + //construct the process timing util + try { + this.processTimingUtil = new ProcessTimingReportUtil(dataSourceLookup); + } catch (I2B2DAOException e) { + log.error("Error constructing the ProcessTimingReportUtil [" + e.getMessage() + "]"); + } + + } + + public void setProcessTimingFlag(String level) { + this.processTimingFlag = level; + } + + public void setProjectParamMap(Map projectParamMap) { + this.projectParamMap = projectParamMap; + } + + public void setAllowLargeTextValueConstrainFlag(boolean allowLargeTextValueConstrainFlag) { + this.allowLargeTextValueConstrainFlag = allowLargeTextValueConstrainFlag; + } + + + public String getProcessTimingXml() { + return this.processTimingStr; + } + + + public Map buildTempTableSql( + List panelListType, boolean encounterFlag, + boolean instanceNumFlag, String queryTiming, int panelCount, + boolean firstPanelFlag, boolean invertQueryFlag, boolean invertOnlyQueryFlag,String firstItemJoinTiming) throws I2B2DAOException { + // read above panel parameters + + // read each panel + List itemListType = new ArrayList(); + List itemSqlList = new ArrayList(); + List panelSqlList = new ArrayList(); + + // + ignoredItemMessageBuffer.delete(0, ignoredItemMessageBuffer.length()); + + SortedMap panelSql = new TreeMap(); + int oldPanelCount = panelCount; + LogTimingUtil logTiming = new LogTimingUtil(); + for (PanelType panelType : panelListType) { + logTiming.setStartTime(); + // check if the panel is invert + boolean panelInvertFlag = getPanelInvertFlag(panelType.getInvert()); + // get the total item occurance value + TotalItemOccurrences totalOccurance = panelType + .getTotalItemOccurrences(); + + int panelAccuracyScale = panelType.getPanelAccuracyScale(); + //ignore panel accuracy scale value, bcos the function is reverted + panelAccuracyScale = 0; + + // read each item from the panel + itemListType = panelType.getItem(); + itemSqlList.removeAll(itemSqlList); + panelCount++; + + // generate panel date constrain + DateConstrainUtil dateConstrainUtil = new DateConstrainUtil( + this.dataSourceLookup); + String panelDateConstrainSql = dateConstrainUtil + .buildPanelDateSql(panelType); + + boolean singleValidItemInPanel = false; + for (ItemType itemType : itemListType) { + + // call the ontology with the item key. + ConceptType conceptType; + try { + + checkLargeTextConstrainPermission(itemType) ; + + conceptType = conceptTypeHandler.getConceptType(itemType + .getItemKey(), this.dataSourceLookup.getServerType()); + //check if the concept is a container, if so return error + if (conceptType.getVisualattributes() != null) { + String conceptVisualAtt = conceptType.getVisualattributes().trim(); + if (conceptVisualAtt.length()>0 && (conceptVisualAtt.startsWith("C") || + conceptVisualAtt.startsWith("c"))) { + throw new I2B2DAOException("The Container item is not valid in query [" +itemType.getItemKey() +"] " + + "in panel #" + panelCount); + } + } + + singleValidItemInPanel = true; + // build the dimension sql + String dimensionSql = buildDimensionSql(conceptType); + + // build the dimension join sql | need information like + // encounter_set,samevisit,same instance + String dimensionJoinSql = buildDimensionJoinSql( + dimensionSql, encounterFlag, instanceNumFlag, queryTiming, + itemType, conceptType, panelDateConstrainSql,panelAccuracyScale, totalOccurance); + + + // build the outer table with total occurrance constrain // + // String fullItemSql = buildFullItemSql(dimensionJoinSql, + // encounterFlag); + String totalOccuraneSql = buildTotalOccuranceSql + .buildTotalOccuranceSql(dimensionJoinSql, + encounterFlag, instanceNumFlag,queryTiming, panelCount, + totalOccurance,panelInvertFlag); + + itemSqlList.add(totalOccuraneSql); + } catch (ConceptNotFoundException e) { + handleConceptNotFoundException(e, panelCount); + } catch (OntologyException e) { + throw new I2B2DAOException(e.getMessage()); + } + } + if (singleValidItemInPanel) { + String panelItemSql = buildPanelSql.buildPanelSql(itemSqlList, + panelCount, oldPanelCount, firstPanelFlag, encounterFlag, + instanceNumFlag, panelInvertFlag,invertQueryFlag,invertOnlyQueryFlag,firstItemJoinTiming); + panelSql.put(panelCount, panelItemSql); + oldPanelCount = panelCount; + firstPanelFlag = false; + + } + logTiming.setEndTime(); + if (this.processTimingFlag.equalsIgnoreCase(ProcessTimingReportUtil.DEBUG)) { + //build the log xml and add it to the string variable. + processTimingStr += this.processTimingUtil.buildProcessTiming(logTiming, "BUILD SQL - PANEL", null) + "\n"; + } + + } + return panelSql; + + } + + private void handleConceptNotFoundException(ConceptNotFoundException e, + int panelCount) { + ignoredItemMessageBuffer + .append(e.getMessage() + " panel#" + panelCount); + } + + public String getIgnoredItemMessage() { + if (this.ignoredItemMessageBuffer != null + && this.ignoredItemMessageBuffer.length() > 0) { + return "Missing Concept in Ontology Cell : \n" + + this.ignoredItemMessageBuffer.toString(); + } else { + return ""; + } + + } + + public String buildDimensionSql(ConceptType conceptType) { + String dimensionSql = ""; + // if patient list + + + dimensionSql = conceptType.getFacttablecolumn() + " IN (select " + + conceptType.getFacttablecolumn() + " from " + + getDbSchemaName() + conceptType.getTablename() + " " + + noLockSqlServer + " where " + conceptType.getColumnname() + + " " + conceptType.getOperator() + " " + + conceptType.getDimcode(); + if ((conceptType.getOperator() != null) && (conceptType.getOperator().toUpperCase().equals("LIKE"))) + { + + dimensionSql += (!dataSourceLookup.getServerType().toUpperCase().equals("POSTGRESQL") ? " {ESCAPE '?'} " : "" ) ; + } + dimensionSql += ")"; + + return dimensionSql; + } + + // function to build + public String buildDimensionJoinSql(String dimensionSql, + boolean encounterFlag, boolean instanceNumFlag, String queryTiming,ItemType itemType, + ConceptType conceptType, String panelDateConstrainSql, int panelAccuracyScale, TotalItemOccurrences totalOccurance) + throws I2B2DAOException { + String joinTableName = "", joinContainsTable = ""; + String itemDateConstrainSql = " "; + String[] itemValueConstrainSql = new String[]{"",""} ; + String itemModifierConstrainSql = "" ; + String sqlHintClause = " "; + QueryTimingHandler timingHandler = new QueryTimingHandler(); + + if (panelDateConstrainSql == null) { + panelDateConstrainSql = ""; + } + panelDateConstrainSql = panelDateConstrainSql.trim(); + + if (itemType.getItemKey().toLowerCase().startsWith(ItemKeyUtil.ITEM_KEY_PATIENT_SET)) { + + // generate sql for item date constrain + //joinTableName = "qt_patient_set_collection"; + if (timingHandler.isSameVisit(queryTiming)) { + joinTableName = "visit_dimension"; + } else if (timingHandler.isSameInstanceNum(queryTiming)) { + joinTableName = "observation_fact"; + } else { + joinTableName = "qt_patient_set_collection"; + } + + // generate sql for item date constrain + itemDateConstrainSql = callDateConstrain(itemType); + + + + // generate sql for item value constrain + itemValueConstrainSql = callValueConstrain(itemType, "", "",panelAccuracyScale); + + + //check if dateconstrain or value constrain present in the item + if (itemDateConstrainSql.length() > 0 || itemValueConstrainSql[0].length()>0 || panelDateConstrainSql.length() >0 || totalOccurance.getValue() > 1) { + joinTableName = "observation_fact"; + } + + + + + } else if (itemType.getItemKey().toLowerCase().startsWith(ItemKeyUtil.ITEM_KEY_PATIENT_ENCOUNTER_SET)) { + if (timingHandler.isSameInstanceNum(queryTiming)) { + joinTableName = "observation_fact"; + } + joinTableName = "qt_patient_enc_collection"; + // generate sql for item date constrain + itemDateConstrainSql = callDateConstrain(itemType); + + // generate sql for item value constrain + itemValueConstrainSql = callValueConstrain(itemType,"","",panelAccuracyScale); + + //check if dateconstrain or value constrain present in the item + if (itemDateConstrainSql.length() > 0 || itemValueConstrainSql[0].length()>0 || panelDateConstrainSql.length() > 0 || totalOccurance.getValue() > 1) { + joinTableName = "observation_fact"; + } + + + } else if (itemType.getItemKey().toLowerCase().startsWith(ItemKeyUtil.ITEM_KEY_MASTERID)) { + String masterTableName = tempTableNameMap.getTempMasterTable(); + dimensionSql = " master_id = '" + itemType.getItemKey() + "'"; + + // generate sql for item date constrain + itemDateConstrainSql = callDateConstrain(itemType).trim(); + + // generate sql for item value constrain + itemValueConstrainSql = callValueConstrain(itemType,"","",panelAccuracyScale); + + //check if dateconstrain or value constrain present in the item + if (itemDateConstrainSql.length() > 0 || itemValueConstrainSql[0].length() > 0 || panelDateConstrainSql.length() > 0 ) { + String masterWhereClause = " j1.patient_num = j2.patient_num "; + String masterSelectClause = " j1.patient_num "; + if (timingHandler.isSameVisit(queryTiming)) { + masterWhereClause = " j1.encounter_num = j2.encounter_num and j1.patient_num = j2.patient_num " ; + masterSelectClause = " j1.encounter_num, j1.patient_num "; + } else if (timingHandler.isSameInstanceNum(queryTiming)) { + masterSelectClause = " j1.encounter_num, j1.patient_num, j1.instance_num, j1.concept_cd, j1.start_date, j1.provider_id "; + masterWhereClause = " j1.encounter_num = j2.encounter_num and j1.patient_num = j2.patient_num and " + + " j1.instance_num = j2.instance_num and j1.concept_cd = j2.concept_cd and j1.start_date = j2.start_date and j1.provider_id = j2.provider_id " ; + } + joinTableName = "observation_fact"; + //Fix Date Contraint by adding j2 brefore start and end date + panelDateConstrainSql = panelDateConstrainSql.replaceAll("start_date", "j1.start_date"); + panelDateConstrainSql = panelDateConstrainSql.replaceAll("end_date", "j1.end_date"); + + String masterDimensionJoinSql = "select " + masterSelectClause + " from " + this.getDbSchemaName() + joinTableName + " j1, " + this.getDbSchemaName() + masterTableName + " j2 " + " where " + masterWhereClause + + " " + itemValueConstrainSql[0] + " " + + itemDateConstrainSql + " AND " + panelDateConstrainSql; + return masterDimensionJoinSql; + } else { + joinTableName = masterTableName; + } + } else { + joinTableName = "observation_fact"; + + if (conceptType.getTablename().equalsIgnoreCase( + "patient_dimension")) { + joinTableName = "patient_dimension"; + if (timingHandler.isSameVisit(queryTiming)) { + joinTableName = "visit_dimension"; + } else if (timingHandler.isSameInstanceNum(queryTiming)) { + joinTableName = "observation_fact"; + } + } else if (conceptType.getTablename().equalsIgnoreCase( + "visit_dimension")) { + joinTableName = "visit_dimension"; + if (timingHandler.isSameInstanceNum(queryTiming)) { + joinTableName = "observation_fact"; + } + } + + if (conceptType.getTablename().equalsIgnoreCase( + "provider_dimension")) { + sqlHintClause = " /*+ index(observation_fact observation_fact_pk) */ "; + } else { + sqlHintClause = " /*+ index(f fact_cnpt_pat_enct_idx) */ "; + } + + ModifierType modifierType = this.getModifierMetadataFromOntology(itemType); + + //generate sql for item modifier constrain + if (modifierType != null) { + itemModifierConstrainSql = callModifierConstrain(modifierType,itemType); + } + + // generate sql for item date constrain + itemDateConstrainSql = callDateConstrain(itemType); + + + //generate sql for unit_cd conversion + String unitCdSwitchClause = "", unitCdInClause = ""; + String modifierUnitCdSwitchClause = "", modifierUnitCdInClause = ""; + + if ( projectParamMap != null && projectParamMap.get(ParamUtil.CRC_ENABLE_UNITCD_CONVERSION) != null) { + String unitCdConversionFlag = (String)projectParamMap.get(ParamUtil.CRC_ENABLE_UNITCD_CONVERSION); + if (unitCdConversionFlag != null && unitCdConversionFlag.equalsIgnoreCase("ON")) { + if (conceptType.getMetadataxml() != null && conceptType.getMetadataxml().getAny().get(0) != null) { + Element valueMetadataElement = conceptType.getMetadataxml().getAny().get(0); + UnitConverstionUtil unitConverstionUtil = new UnitConverstionUtil(); + unitCdSwitchClause = unitConverstionUtil.buildUnitCdSwitchClause(valueMetadataElement,false,""); + log.debug("concept unit Conversion sql " +unitCdSwitchClause ); + unitCdInClause = unitConverstionUtil.buildUnitCdInClause(valueMetadataElement,""); + + } + + if (modifierType != null && modifierType.getMetadataxml() != null && modifierType.getMetadataxml().getAny().get(0) != null) { + Element valueMetadataElement = modifierType.getMetadataxml().getAny().get(0); + UnitConverstionUtil unitConverstionUtil = new UnitConverstionUtil(); + modifierUnitCdSwitchClause = unitConverstionUtil.buildUnitCdSwitchClause(valueMetadataElement,false,""); + log.debug("modifier unit Conversion sql " +modifierUnitCdSwitchClause ); + modifierUnitCdInClause = unitConverstionUtil.buildUnitCdInClause(valueMetadataElement,""); + + } + } + } + + + + // generate sql for item value constrain + itemValueConstrainSql = callValueConstrain(itemType,unitCdSwitchClause,unitCdInClause,panelAccuracyScale ); + if (panelAccuracyScale >0) { + joinContainsTable = itemValueConstrainSql[1]; + } + + // generate sql for modifier value constrain + String[] modifierConstainSql = callModifierValueConstrain(itemType,modifierUnitCdSwitchClause,modifierUnitCdInClause,panelAccuracyScale ); + itemValueConstrainSql[0] += modifierConstainSql[0]; + if (panelAccuracyScale >0) { + joinContainsTable += modifierConstainSql[1]; + } + + + } + + // itemType.getConstrainByValue() + String selectClause = " patient_num "; + + if (timingHandler.isSameInstanceNum(queryTiming)) { + selectClause = " provider_id, start_date, concept_cd, instance_num, encounter_num, " + selectClause; + } else if (timingHandler.isSameVisit(queryTiming)) { + selectClause = " encounter_num, " + selectClause; + } + + if (panelDateConstrainSql.trim().length() > 0) { + panelDateConstrainSql = " AND ( " + panelDateConstrainSql + + " )"; + } + + if (itemValueConstrainSql[0] == null) { + itemValueConstrainSql[0] = " "; + } + + if (itemDateConstrainSql == null) { + itemDateConstrainSql = " "; + } + + if (itemModifierConstrainSql == null) { + itemModifierConstrainSql = " "; + } + + // + //" INNER JOIN freetexttable(observation_fact,observation_blob,'"+ containsSql + "') " + //+ " AS ft" + j + " ON text_search_index = ft" +j+ ".[KEY] " + //+ " AND + // + + if (!joinTableName.equalsIgnoreCase("observation_fact")) { + joinContainsTable = ""; + itemDateConstrainSql = ""; + itemModifierConstrainSql = ""; + panelDateConstrainSql = ""; + itemValueConstrainSql[0] = ""; + + } + + String dimensionJoinSql = " select " + sqlHintClause + selectClause + + " from " + this.getDbSchemaName() + joinTableName + joinContainsTable + + " where " + dimensionSql + " " + itemModifierConstrainSql + + itemValueConstrainSql[0] + itemDateConstrainSql + panelDateConstrainSql; + log.debug("Dimension select sql [" + dimensionJoinSql + "]"); + + return dimensionJoinSql; + } + + private boolean getPanelInvertFlag(int panelInvert) { + if (panelInvert == 1) { + return true; + } else { + return false; + } + } + + + private String callDateConstrain(ItemType itemType) { + // generate sql for item date constrain + DateConstrainUtil dateConstrainUtil = new DateConstrainUtil( + this.dataSourceLookup); + String itemDateConstrainSql = dateConstrainUtil.buildItemDateSql(itemType); + if (itemDateConstrainSql != null + && itemDateConstrainSql.trim().length() > 0) { + log.info("Item date constrain sql" + itemDateConstrainSql); + itemDateConstrainSql = " AND ( " + itemDateConstrainSql + + " ) "; + } else { + itemDateConstrainSql = ""; + } + return itemDateConstrainSql; + } + + private String[] callValueConstrain(ItemType itemType, String unitCdSwitchClause, String unitCdInClause, int panelAccuracyScale) throws I2B2DAOException { + ValueConstrainsHandler valueConstrainHandler = new ValueConstrainsHandler(); + if (unitCdSwitchClause.length()>0) { + valueConstrainHandler.setUnitCdConversionFlag(true, unitCdInClause, unitCdSwitchClause); + } + + String[] itemValueConstrainSql = valueConstrainHandler + .constructValueConstainClause(itemType + .getConstrainByValue(), this.dataSourceLookup.getServerType(), this.getDbSchemaName(),panelAccuracyScale); + log.info("Item value constrain sql " + itemValueConstrainSql); + + if (itemValueConstrainSql != null + && itemValueConstrainSql[0].trim().length() > 0) { + + itemValueConstrainSql[0] = " AND ( " + itemValueConstrainSql[0] + + " )"; + } else { + itemValueConstrainSql[0] = ""; + } + return itemValueConstrainSql; + } + + private String[] callModifierValueConstrain(ItemType itemType, String modifierUnitCdSwitchClause, String modifierUnitCdInClause,int panelAccuracyScale) throws I2B2DAOException { + ValueConstrainsHandler valueConstrainHandler = new ValueConstrainsHandler(); + if (modifierUnitCdSwitchClause.length()>0) { + valueConstrainHandler.setUnitCdConversionFlag(true, modifierUnitCdInClause, modifierUnitCdSwitchClause); + } + boolean oracleFlag = false; + if (this.dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.ORACLE)) { + oracleFlag = true; + } + String itemModifierValueConstrainSql[] = new String[] {"",""} ; + + if (itemType.getConstrainByModifier() != null && itemType.getConstrainByModifier().getConstrainByValue() !=null) { + List itemValueConstrainList = buildItemValueConstrain(itemType.getConstrainByModifier().getConstrainByValue()); + itemModifierValueConstrainSql = valueConstrainHandler.constructValueConstainClause(itemValueConstrainList,this.dataSourceLookup.getServerType(),this.getDbSchemaName(),panelAccuracyScale); + if (itemModifierValueConstrainSql != null && itemModifierValueConstrainSql[0].length()>0) { + log.info("Modifier constrian value constrain sql " + itemModifierValueConstrainSql); + } + } + + if (itemModifierValueConstrainSql[0] != null + && itemModifierValueConstrainSql[0].trim().length() > 0) { + + itemModifierValueConstrainSql[0] = " AND ( " + itemModifierValueConstrainSql[0] + + " )"; + } else { + itemModifierValueConstrainSql[0] = ""; + } + return itemModifierValueConstrainSql; + } + + private String callModifierConstrain(ModifierType modifierType, ItemType itemType) throws I2B2DAOException { + + // generate sql for item date constrain + ModifierConstrainsHandler modifierConstrainUtil = new ModifierConstrainsHandler(this.getDbSchemaName()); + String itemModifierConstrainSql = modifierConstrainUtil.constructModifierConstainClause(modifierType); + if (itemModifierConstrainSql != null + && itemModifierConstrainSql.trim().length() > 0) { + log.info("Item modifier constrain sql" + itemModifierConstrainSql); + itemModifierConstrainSql = " AND ( " + itemModifierConstrainSql + + " ) "; + } else { + itemModifierConstrainSql = " "; + } + + return itemModifierConstrainSql; + } + private ModifierType getModifierMetadataFromOntology(ItemType itemType) throws I2B2DAOException { + ItemType.ConstrainByModifier modifierConstrain = itemType.getConstrainByModifier(); + if (modifierConstrain == null) { + return null; + } + String modifierKey = modifierConstrain.getModifierKey(); + String modifierAppliedPath = modifierConstrain.getAppliedPath(); + ItemMetaDataHandler metadataHandler = new ItemMetaDataHandler( + queryXML); + ModifierType modifierType = metadataHandler.getModifierDataFromOntologyCell(modifierKey,modifierAppliedPath, this.dataSourceLookup.getServerType()); + return modifierType; + } + + private void checkLargeTextConstrainPermission(ItemType itemType) throws I2B2DAOException{ + for (ConstrainByValue cvt : itemType.getConstrainByValue()) { + if (cvt.getValueType().equals(ConstrainValueType.LARGETEXT)) { + if (this.allowLargeTextValueConstrainFlag == false) { + throw new I2B2DAOException("Insufficient user role for LARGETEXT constrain. Required minimum role DATA_DEID"); + } + } + } + } + + private List buildItemValueConstrain(List modifierConstrainList) { + List itemValueConstrainList = new ArrayList(); + for (ItemType.ConstrainByModifier.ConstrainByValue modifierValueConstrain : modifierConstrainList) { + ItemType.ConstrainByValue constrainByValue = new ItemType.ConstrainByValue(); + constrainByValue.setValueConstraint(modifierValueConstrain.getValueConstraint()); + constrainByValue.setValueOperator(modifierValueConstrain.getValueOperator()) ; + constrainByValue.setValueType(modifierValueConstrain.getValueType()); + constrainByValue.setValueUnitOfMeasure(modifierValueConstrain.getValueUnitOfMeasure()) ; + itemValueConstrainList.add(constrainByValue); + } + return itemValueConstrainList; + } + + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/BuildTotalOccuranceSql.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/BuildTotalOccuranceSql.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/BuildTotalOccuranceSql.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/BuildTotalOccuranceSql.java index d079527e..fc88d831 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/BuildTotalOccuranceSql.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/BuildTotalOccuranceSql.java @@ -1,108 +1,108 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.pdo.query.TotOccuranceOperatorType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.PanelType.TotalItemOccurrences; - -public class BuildTotalOccuranceSql { - protected final Log log = LogFactory.getLog(BuildTotalOccuranceSql.class); - - DataSourceLookup dataSourceLookup = null; - - public BuildTotalOccuranceSql(DataSourceLookup dataSourceLookup) { - this.dataSourceLookup = dataSourceLookup; - } - - public String buildTotalOccuranceSql(String dimensionJoinSql, - boolean encounterFlag, boolean instanceNumFlag, String queryTiming, int panelNumber, - TotalItemOccurrences totalOccurances, boolean panelInvertFlag) { - - String selectClause = " ", groupbyClause = " "; - TotalItemOccurrenceHandler totalItemOccurrencHandler = new TotalItemOccurrenceHandler(); - String totalItemOccurrenceClause = totalItemOccurrencHandler - .buildTotalItemOccurrenceClause(totalOccurances); - - if (panelNumber != 1) { - selectClause = " 1 as panel_count "; - } else { - if (instanceNumFlag) { - selectClause = "provider_id, start_date, concept_cd, instance_num, encounter_num, "; - } else if (encounterFlag) { - selectClause = "encounter_num, "; - } - selectClause += " patient_num ," + panelNumber + " as panel_count "; - } - - //check if the dimensionJoinSql is query in query with fact constrains - String groupbyClausePrefix = ""; - if (dimensionJoinSql.indexOf("j1.")>0) { - groupbyClausePrefix = "j1."; - } - - //if (instanceNumFlag) { - // groupbyClause = " " + groupbyClausePrefix + "encounter_num ," + groupbyClausePrefix + "instance_num,"; - //} else if (encounterFlag) { - // groupbyClause = " " + groupbyClausePrefix + "encounter_num ,"; - //} - //groupbyClause += " " + groupbyClausePrefix + "patient_num "; - - - QueryTimingHandler timingHandler = new QueryTimingHandler(); - if (timingHandler.isSameInstanceNum(queryTiming)) { - groupbyClause = " " + groupbyClausePrefix + "encounter_num ," + groupbyClausePrefix + "instance_num, " + groupbyClausePrefix + "concept_cd," + - groupbyClausePrefix + "start_date," + groupbyClausePrefix + "provider_id,"; - } else if (timingHandler.isSameVisit(queryTiming)) { - groupbyClause = " " + groupbyClausePrefix + "encounter_num ,"; - } - groupbyClause += " " + groupbyClausePrefix + "patient_num "; - - String totalOccuranceSql = "select " + selectClause + " from (" - + dimensionJoinSql ; - - //if (panelInvertFlag == false) { - totalOccuranceSql += " group by " + groupbyClause ; - //} - - if (totalOccurances != null) { - // TotOccuranceOperatorType - - if ((totalOccurances.getOperator() != null && totalOccurances.getOperator().value() != null && totalOccurances.getOperator().value().equalsIgnoreCase(TotOccuranceOperatorType.GE.value())) && totalOccurances.getValue()==1) { - } else { - log.debug("Setfinder query total occurrences operator value [" + totalOccurances.getOperator().value() + "]"); - String countDistinct = "*"; - if (this.dataSourceLookup.getServerType().equalsIgnoreCase(DAOFactoryHelper.SQLSERVER)) { - countDistinct = " distinct cast(patient_num as varchar) + '|' + cast(encounter_num as varchar) + '|' + " + - " provider_id + '|' + cast(start_date as varchar) + '|' + cast(instance_num as varchar) + '|' +concept_cd"; - } else if (this.dataSourceLookup.getServerType().equalsIgnoreCase(DAOFactoryHelper.ORACLE) || - this.dataSourceLookup.getServerType().equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL) ) { - countDistinct = " distinct patient_num || '|' || encounter_num || '|' || provider_id || '|' || instance_num || '|' ||concept_cd || '|' ||cast(start_date as varchar(50) ) "; - } - totalOccuranceSql += " having count("+countDistinct+") " + totalItemOccurrenceClause;// + " group by " + selectClause; - /*if (panelInvertFlag == true && totalItemOccurrenceClause.trim() != "") - { - if (instanceNumFlag) - selectClause = " group by provider_id, start_date, concept_cd, instance_num, encounter_num "; - else if (encounterFlag) - selectClause = " group by encounter_num "; - else - totalOccuranceSql += " group by patient_num "; - }*/ - } - } - totalOccuranceSql +=" ) t"; - - return totalOccuranceSql; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.pdo.query.TotOccuranceOperatorType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.PanelType.TotalItemOccurrences; + +public class BuildTotalOccuranceSql { + protected final Log log = LogFactory.getLog(BuildTotalOccuranceSql.class); + + DataSourceLookup dataSourceLookup = null; + + public BuildTotalOccuranceSql(DataSourceLookup dataSourceLookup) { + this.dataSourceLookup = dataSourceLookup; + } + + public String buildTotalOccuranceSql(String dimensionJoinSql, + boolean encounterFlag, boolean instanceNumFlag, String queryTiming, int panelNumber, + TotalItemOccurrences totalOccurances, boolean panelInvertFlag) { + + String selectClause = " ", groupbyClause = " "; + TotalItemOccurrenceHandler totalItemOccurrencHandler = new TotalItemOccurrenceHandler(); + String totalItemOccurrenceClause = totalItemOccurrencHandler + .buildTotalItemOccurrenceClause(totalOccurances); + + if (panelNumber != 1) { + selectClause = " 1 as panel_count "; + } else { + if (instanceNumFlag) { + selectClause = "provider_id, start_date, concept_cd, instance_num, encounter_num, "; + } else if (encounterFlag) { + selectClause = "encounter_num, "; + } + selectClause += " patient_num ," + panelNumber + " as panel_count "; + } + + //check if the dimensionJoinSql is query in query with fact constrains + String groupbyClausePrefix = ""; + if (dimensionJoinSql.indexOf("j1.")>0) { + groupbyClausePrefix = "j1."; + } + + //if (instanceNumFlag) { + // groupbyClause = " " + groupbyClausePrefix + "encounter_num ," + groupbyClausePrefix + "instance_num,"; + //} else if (encounterFlag) { + // groupbyClause = " " + groupbyClausePrefix + "encounter_num ,"; + //} + //groupbyClause += " " + groupbyClausePrefix + "patient_num "; + + + QueryTimingHandler timingHandler = new QueryTimingHandler(); + if (timingHandler.isSameInstanceNum(queryTiming)) { + groupbyClause = " " + groupbyClausePrefix + "encounter_num ," + groupbyClausePrefix + "instance_num, " + groupbyClausePrefix + "concept_cd," + + groupbyClausePrefix + "start_date," + groupbyClausePrefix + "provider_id,"; + } else if (timingHandler.isSameVisit(queryTiming)) { + groupbyClause = " " + groupbyClausePrefix + "encounter_num ,"; + } + groupbyClause += " " + groupbyClausePrefix + "patient_num "; + + String totalOccuranceSql = "select " + selectClause + " from (" + + dimensionJoinSql ; + + //if (panelInvertFlag == false) { + totalOccuranceSql += " group by " + groupbyClause ; + //} + + if (totalOccurances != null) { + // TotOccuranceOperatorType + + if ((totalOccurances.getOperator() != null && totalOccurances.getOperator().value() != null && totalOccurances.getOperator().value().equalsIgnoreCase(TotOccuranceOperatorType.GE.value())) && totalOccurances.getValue()==1) { + } else { + log.debug("Setfinder query total occurrences operator value [" + totalOccurances.getOperator().value() + "]"); + String countDistinct = "*"; + if (this.dataSourceLookup.getServerType().equalsIgnoreCase(DAOFactoryHelper.SQLSERVER)) { + countDistinct = " distinct cast(patient_num as varchar) + '|' + cast(encounter_num as varchar) + '|' + " + + " provider_id + '|' + cast(start_date as varchar) + '|' + cast(instance_num as varchar) + '|' +concept_cd"; + } else if (this.dataSourceLookup.getServerType().equalsIgnoreCase(DAOFactoryHelper.ORACLE) || + this.dataSourceLookup.getServerType().equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL) ) { + countDistinct = " distinct patient_num || '|' || encounter_num || '|' || provider_id || '|' || instance_num || '|' ||concept_cd || '|' ||cast(start_date as varchar(50) ) "; + } + totalOccuranceSql += " having count("+countDistinct+") " + totalItemOccurrenceClause;// + " group by " + selectClause; + /*if (panelInvertFlag == true && totalItemOccurrenceClause.trim() != "") + { + if (instanceNumFlag) + selectClause = " group by provider_id, start_date, concept_cd, instance_num, encounter_num "; + else if (encounterFlag) + selectClause = " group by encounter_num "; + else + totalOccuranceSql += " group by patient_num "; + }*/ + } + } + totalOccuranceSql +=" ) t"; + + return totalOccuranceSql; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/CalulateQueryTiming.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/CalulateQueryTiming.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/CalulateQueryTiming.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/CalulateQueryTiming.java index c43de5bc..9a047952 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/CalulateQueryTiming.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/CalulateQueryTiming.java @@ -1,31 +1,31 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; - -import java.util.List; - -import edu.harvard.i2b2.crc.datavo.setfinder.query.PanelType; - - -public class CalulateQueryTiming { - - public String getQueryTiming(List panelList) { - String calcQueryTiming = "ANY"; - for (PanelType panel : panelList) { - if(panel.getPanelTiming() != null && panel.getPanelTiming().equalsIgnoreCase(QueryTimingHandler.SAMEINSTANCENUM)) { - calcQueryTiming = QueryTimingHandler.SAMEINSTANCENUM; - break; - } else if (panel.getPanelTiming() != null && (panel.getPanelTiming().equalsIgnoreCase(QueryTimingHandler.SAMEVISIT) || - panel.getPanelTiming().equalsIgnoreCase(QueryTimingHandler.SAME))) { - calcQueryTiming = QueryTimingHandler.SAMEVISIT ; - } - } - return calcQueryTiming; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; + +import java.util.List; + +import edu.harvard.i2b2.crc.datavo.setfinder.query.PanelType; + + +public class CalulateQueryTiming { + + public String getQueryTiming(List panelList) { + String calcQueryTiming = "ANY"; + for (PanelType panel : panelList) { + if(panel.getPanelTiming() != null && panel.getPanelTiming().equalsIgnoreCase(QueryTimingHandler.SAMEINSTANCENUM)) { + calcQueryTiming = QueryTimingHandler.SAMEINSTANCENUM; + break; + } else if (panel.getPanelTiming() != null && (panel.getPanelTiming().equalsIgnoreCase(QueryTimingHandler.SAMEVISIT) || + panel.getPanelTiming().equalsIgnoreCase(QueryTimingHandler.SAME))) { + calcQueryTiming = QueryTimingHandler.SAMEVISIT ; + } + } + return calcQueryTiming; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/ConceptNotFoundException.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/ConceptNotFoundException.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/ConceptNotFoundException.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/ConceptNotFoundException.java index d6a6c267..ca0b7dd1 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/ConceptNotFoundException.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/ConceptNotFoundException.java @@ -1,41 +1,41 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; - -public class ConceptNotFoundException extends I2B2DAOException { - - /** - * - */ - private static final long serialVersionUID = 1L; - - - public ConceptNotFoundException() { - } - - /** - * Constructor that takes message and the exception as inputs. - * @param message - * @param e - */ - public ConceptNotFoundException(String message, Exception e) { - super(message, e); - } - - /** - * Constructor that takes message as input. - * @param message - */ - public ConceptNotFoundException(String message) { - super(message); - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; + +public class ConceptNotFoundException extends I2B2DAOException { + + /** + * + */ + private static final long serialVersionUID = 1L; + + + public ConceptNotFoundException() { + } + + /** + * Constructor that takes message and the exception as inputs. + * @param message + * @param e + */ + public ConceptNotFoundException(String message, Exception e) { + super(message, e); + } + + /** + * Constructor that takes message as input. + * @param message + */ + public ConceptNotFoundException(String message) { + super(message); + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/ConceptTypeHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/ConceptTypeHandler.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/ConceptTypeHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/ConceptTypeHandler.java index ff4c78bb..0b1f128d --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/ConceptTypeHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/ConceptTypeHandler.java @@ -1,73 +1,73 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; - -import edu.harvard.i2b2.crc.datavo.ontology.ConceptType; -import edu.harvard.i2b2.crc.util.ItemKeyUtil; - -public class ConceptTypeHandler { - - private String queryXML = null; - StringBuffer ignoredItemMessageBuffer = new StringBuffer(); - - public ConceptTypeHandler(String queryXML) { - this.queryXML = queryXML; - } - - public ConceptType getConceptType(String itemKey, String dbType) - throws ConceptNotFoundException, OntologyException { - - ConceptType conceptType = null; - - // if patient list - if (itemKey.toLowerCase().startsWith(ItemKeyUtil.ITEM_KEY_PATIENT_SET)) { - String[] patientSetId = itemKey.split(":"); - if (patientSetId[1] != null) { - conceptType = new ConceptType(); - conceptType.setColumnname(" result_instance_id "); - conceptType.setOperator(" = "); - conceptType.setFacttablecolumn(" patient_num "); - conceptType.setTablename("qt_patient_set_collection "); - conceptType.setDimcode(patientSetId[1]); - } - - } else if (itemKey.toLowerCase().startsWith(ItemKeyUtil.ITEM_KEY_PATIENT_ENCOUNTER_SET)) { // if event - String[] encounterSetId = itemKey.split(":"); - if (encounterSetId[1] != null) { - conceptType = new ConceptType(); - conceptType.setColumnname(" result_instance_id "); - conceptType.setOperator(" = "); - conceptType.setFacttablecolumn(" encounter_num "); - conceptType.setTablename("qt_patient_enc_collection "); - conceptType.setDimcode(encounterSetId[1]); - } - } else if (itemKey.toLowerCase().startsWith(ItemKeyUtil.ITEM_KEY_MASTERID)) { - String[] masterId = itemKey.split(":"); - conceptType = new ConceptType(); - conceptType.setDimcode("'" + masterId[1] + "'"); - - } else { - ItemMetaDataHandler metadataHandler = new ItemMetaDataHandler( - queryXML); - conceptType = metadataHandler.getMetaDataFromOntologyCell(itemKey, dbType); - - } - return conceptType; - } - - public void handleConceptNotFoundException(ConceptNotFoundException e, - int panelCount) { - ignoredItemMessageBuffer - .append(e.getMessage() + " panel#" + panelCount); - } - - public String getIgnoredItem() { - return ignoredItemMessageBuffer.toString(); - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; + +import edu.harvard.i2b2.crc.datavo.ontology.ConceptType; +import edu.harvard.i2b2.crc.util.ItemKeyUtil; + +public class ConceptTypeHandler { + + private String queryXML = null; + StringBuffer ignoredItemMessageBuffer = new StringBuffer(); + + public ConceptTypeHandler(String queryXML) { + this.queryXML = queryXML; + } + + public ConceptType getConceptType(String itemKey, String dbType) + throws ConceptNotFoundException, OntologyException { + + ConceptType conceptType = null; + + // if patient list + if (itemKey.toLowerCase().startsWith(ItemKeyUtil.ITEM_KEY_PATIENT_SET)) { + String[] patientSetId = itemKey.split(":"); + if (patientSetId[1] != null) { + conceptType = new ConceptType(); + conceptType.setColumnname(" result_instance_id "); + conceptType.setOperator(" = "); + conceptType.setFacttablecolumn(" patient_num "); + conceptType.setTablename("qt_patient_set_collection "); + conceptType.setDimcode(patientSetId[1]); + } + + } else if (itemKey.toLowerCase().startsWith(ItemKeyUtil.ITEM_KEY_PATIENT_ENCOUNTER_SET)) { // if event + String[] encounterSetId = itemKey.split(":"); + if (encounterSetId[1] != null) { + conceptType = new ConceptType(); + conceptType.setColumnname(" result_instance_id "); + conceptType.setOperator(" = "); + conceptType.setFacttablecolumn(" encounter_num "); + conceptType.setTablename("qt_patient_enc_collection "); + conceptType.setDimcode(encounterSetId[1]); + } + } else if (itemKey.toLowerCase().startsWith(ItemKeyUtil.ITEM_KEY_MASTERID)) { + String[] masterId = itemKey.split(":"); + conceptType = new ConceptType(); + conceptType.setDimcode("'" + masterId[1] + "'"); + + } else { + ItemMetaDataHandler metadataHandler = new ItemMetaDataHandler( + queryXML); + conceptType = metadataHandler.getMetaDataFromOntologyCell(itemKey, dbType); + + } + return conceptType; + } + + public void handleConceptNotFoundException(ConceptNotFoundException e, + int panelCount) { + ignoredItemMessageBuffer + .append(e.getMessage() + " panel#" + panelCount); + } + + public String getIgnoredItem() { + return ignoredItemMessageBuffer.toString(); + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/DateConstrainHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/DateConstrainHandler.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/DateConstrainHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/DateConstrainHandler.java index a2e426f4..3617645f --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/DateConstrainHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/DateConstrainHandler.java @@ -1,128 +1,128 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; - -import java.text.SimpleDateFormat; -import javax.xml.datatype.XMLGregorianCalendar; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.setfinder.query.InclusiveType; - -/** - * Class to generate date constrains sqls clause. $Id: - * DateConstrainHandler.java,v 1.4 2008/06/26 03:58:56 rk903 Exp $ - * - * @author rkuttan - */ -public class DateConstrainHandler { - /** log **/ - protected final Log log = LogFactory.getLog(getClass()); - private SimpleDateFormat dateFormat = new SimpleDateFormat( - "dd-MMM-yyyy HH:mm:ss"); - private DataSourceLookup dataSourceLookup = null; - - public DateConstrainHandler(DataSourceLookup dataSourceLookup) { - this.dataSourceLookup = dataSourceLookup; - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE)) { - dateFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss"); - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER) || dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) { - // ISO 8601 - dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); - } - } - - public String constructDateConstrainClause(String fromDateField, - String toDateField, InclusiveType fromInclusiveType, - InclusiveType toInclusiveType, XMLGregorianCalendar fromDate, - XMLGregorianCalendar toDate) { - String dateConstrainSql = null; - String sqlOperator = null; - - if (fromDate != null) { - dateFormat.setTimeZone(fromDate.toGregorianCalendar().getTimeZone()); - String fromDateString = dateFormat.format(fromDate - .toGregorianCalendar().getTime()); - - if (fromInclusiveType != null - && fromInclusiveType.name().equals(InclusiveType.NO.name())) { - sqlOperator = " > "; - } else { - sqlOperator = " >= "; - } - - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE)) { - dateConstrainSql = fromDateField + sqlOperator + "to_date('" - + fromDateString + "','DD-MON-YYYY HH24:MI:SS')"; - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER) ) { - // {ts '2005-06-27 00:00:00'} - dateConstrainSql = fromDateField + sqlOperator + " '" - + fromDateString + "'"; - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) { - // {ts '2005-06-27 00:00:00'} - dateConstrainSql = fromDateField + sqlOperator + " '" - + fromDateString + ".00'"; - } - } - - if (toDate != null) { - sqlOperator = null; - - dateFormat.setTimeZone(toDate.toGregorianCalendar().getTimeZone()); - String toDateString = dateFormat.format(toDate - .toGregorianCalendar().getTime()); - - if (toInclusiveType != null - && toInclusiveType.name().equals(InclusiveType.NO.name())) { - sqlOperator = " < "; - } else { - sqlOperator = " <= "; - } - - if (dateConstrainSql != null) { - dateConstrainSql += " AND "; - } - - if (dateConstrainSql == null) { - dateConstrainSql = " "; - } - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE)) { - dateConstrainSql += (toDateField + sqlOperator + "to_date('" - + toDateString + "','DD-MON-YYYY HH24:MI:SS')"); - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER) ) { - dateConstrainSql += (toDateField + sqlOperator + " '" - + toDateString + "'"); - } else if ( dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) { - dateConstrainSql += (toDateField + sqlOperator + " '" - + toDateString + ".99'"); - } - } - - return dateConstrainSql; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; + +import java.text.SimpleDateFormat; +import javax.xml.datatype.XMLGregorianCalendar; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.setfinder.query.InclusiveType; + +/** + * Class to generate date constrains sqls clause. $Id: + * DateConstrainHandler.java,v 1.4 2008/06/26 03:58:56 rk903 Exp $ + * + * @author rkuttan + */ +public class DateConstrainHandler { + /** log **/ + protected final Log log = LogFactory.getLog(getClass()); + private SimpleDateFormat dateFormat = new SimpleDateFormat( + "dd-MMM-yyyy HH:mm:ss"); + private DataSourceLookup dataSourceLookup = null; + + public DateConstrainHandler(DataSourceLookup dataSourceLookup) { + this.dataSourceLookup = dataSourceLookup; + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.ORACLE)) { + dateFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss"); + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER) || dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) { + // ISO 8601 + dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); + } + } + + public String constructDateConstrainClause(String fromDateField, + String toDateField, InclusiveType fromInclusiveType, + InclusiveType toInclusiveType, XMLGregorianCalendar fromDate, + XMLGregorianCalendar toDate) { + String dateConstrainSql = null; + String sqlOperator = null; + + if (fromDate != null) { + dateFormat.setTimeZone(fromDate.toGregorianCalendar().getTimeZone()); + String fromDateString = dateFormat.format(fromDate + .toGregorianCalendar().getTime()); + + if (fromInclusiveType != null + && fromInclusiveType.name().equals(InclusiveType.NO.name())) { + sqlOperator = " > "; + } else { + sqlOperator = " >= "; + } + + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.ORACLE)) { + dateConstrainSql = fromDateField + sqlOperator + "to_date('" + + fromDateString + "','DD-MON-YYYY HH24:MI:SS')"; + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER) ) { + // {ts '2005-06-27 00:00:00'} + dateConstrainSql = fromDateField + sqlOperator + " '" + + fromDateString + "'"; + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) { + // {ts '2005-06-27 00:00:00'} + dateConstrainSql = fromDateField + sqlOperator + " '" + + fromDateString + ".00'"; + } + } + + if (toDate != null) { + sqlOperator = null; + + dateFormat.setTimeZone(toDate.toGregorianCalendar().getTimeZone()); + String toDateString = dateFormat.format(toDate + .toGregorianCalendar().getTime()); + + if (toInclusiveType != null + && toInclusiveType.name().equals(InclusiveType.NO.name())) { + sqlOperator = " < "; + } else { + sqlOperator = " <= "; + } + + if (dateConstrainSql != null) { + dateConstrainSql += " AND "; + } + + if (dateConstrainSql == null) { + dateConstrainSql = " "; + } + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.ORACLE)) { + dateConstrainSql += (toDateField + sqlOperator + "to_date('" + + toDateString + "','DD-MON-YYYY HH24:MI:SS')"); + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER) ) { + dateConstrainSql += (toDateField + sqlOperator + " '" + + toDateString + "'"); + } else if ( dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) { + dateConstrainSql += (toDateField + sqlOperator + " '" + + toDateString + ".99'"); + } + } + + return dateConstrainSql; + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/DateConstrainUtil.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/DateConstrainUtil.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/DateConstrainUtil.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/DateConstrainUtil.java index 47ccd0da..92b08d78 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/DateConstrainUtil.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/DateConstrainUtil.java @@ -1,177 +1,177 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; - -import java.util.List; - -import javax.xml.datatype.XMLGregorianCalendar; - -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ConstrainDateTimeType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ConstrainDateType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.InclusiveType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ItemType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.PanelType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ItemType.ConstrainByDate; - -public class DateConstrainUtil { - - DateConstrainHandler dateConstrainHandler = null; - - public DateConstrainUtil(DataSourceLookup dataSourceLookup) { - dateConstrainHandler = new DateConstrainHandler(dataSourceLookup); - - } - - public String buildPanelDateSql(PanelType panelType){ - return buildPanelDateSql(panelType, ""); - } - - public String buildPanelDateSql(PanelType panelType, String tableAlias) { - String panelDateConstrain = " "; - if (panelType.getPanelDateFrom() != null - || panelType.getPanelDateTo() != null) { - panelDateConstrain = generatePanelDateConstrain( - dateConstrainHandler, panelType.getPanelDateFrom(), - panelType.getPanelDateTo(), tableAlias); - } - return panelDateConstrain; - } - - public String buildItemDateSql(ItemType item){ - return buildItemDateSql(item, ""); - } - - public String buildItemDateSql(ItemType item, String tableAlias) { - if (tableAlias==null) - tableAlias = ""; - if (tableAlias.trim().length()>0&&!tableAlias.endsWith(".")) - tableAlias = tableAlias + "."; - String dateConstrainSql = null; - String fullItemDateSql = ""; - List constrainByDateList = item.getConstrainByDate(); - boolean firstFlag = true; - for (ConstrainByDate constrainByDate : constrainByDateList) { - ConstrainDateType dateFrom = constrainByDate.getDateFrom(); - ConstrainDateType dateTo = constrainByDate.getDateTo(); - - String dateFromColumn = null, dateToColumn = null; - InclusiveType dateFromInclusive = null, dateToInclusive = null; - XMLGregorianCalendar dateFromValue = null, dateToValue = null; - - if (dateFrom != null || dateTo != null) { - - if (dateFrom != null) { - dateFromInclusive = dateFrom.getInclusive(); - dateFromValue = dateFrom.getValue(); - dateFrom.getTime(); - if (dateFrom.getTime() != null - && dateFrom.getTime().name() != null - && dateFrom.getTime().name().equalsIgnoreCase( - ConstrainDateTimeType.END_DATE.name())) { - dateFromColumn = tableAlias + "end_date"; - } else { - dateFromColumn = tableAlias + "start_date"; - } - - } - - if (dateTo != null) { - dateToInclusive = dateTo.getInclusive(); - dateToValue = dateTo.getValue(); - dateTo.getTime(); - if (dateTo.getTime() != null - && dateTo.getTime().name() != null - && dateTo.getTime().name().equalsIgnoreCase( - ConstrainDateTimeType.END_DATE.name())) { - dateToColumn = tableAlias + "end_date"; - } else { - dateToColumn = tableAlias + "start_date"; - } - } - - dateConstrainSql = dateConstrainHandler - .constructDateConstrainClause(dateFromColumn, - dateToColumn, dateFromInclusive, - dateToInclusive, dateFromValue, dateToValue); - - if (dateConstrainSql != null) { - if (!firstFlag) { - fullItemDateSql += " AND "; - } else { - firstFlag = false; - } - - fullItemDateSql += " " + dateConstrainSql + "\n"; - } - - } - } - - return fullItemDateSql; - } - - private String generatePanelDateConstrain( - DateConstrainHandler dateConstrainHandler, - ConstrainDateType dateFrom, ConstrainDateType dateTo, - String tableAlias) { - if (tableAlias==null) - tableAlias = ""; - if (tableAlias.trim().length()>0&&!tableAlias.endsWith(".")) - tableAlias = tableAlias + "."; - - String dateFromColumn = null, dateToColumn = null; - InclusiveType dateFromInclusive = null, dateToInclusive = null; - XMLGregorianCalendar dateFromValue = null, dateToValue = null; - String dateConstrainSql = null; - - if (dateFrom != null || dateTo != null) { - - if (dateFrom != null) { - dateFromInclusive = dateFrom.getInclusive(); - dateFromValue = dateFrom.getValue(); - - dateFrom.getTime(); - if (dateFrom.getTime() != null - && dateFrom.getTime().name() != null - && dateFrom.getTime().name().equalsIgnoreCase( - ConstrainDateTimeType.END_DATE.name())) { - dateFromColumn = tableAlias + "end_date"; - } else { - - dateFromColumn = tableAlias + "start_date"; - } - - } - - if (dateTo != null) { - dateToInclusive = dateTo.getInclusive(); - dateToValue = dateTo.getValue(); - - dateTo.getTime(); - if (dateTo.getTime() != null - && dateTo.getTime().name() != null - && dateTo.getTime().name().equalsIgnoreCase( - ConstrainDateTimeType.END_DATE.name())) { - dateToColumn = tableAlias + "end_date"; - } else { - - dateToColumn = tableAlias + "start_date"; - } - - } - - dateConstrainSql = dateConstrainHandler - .constructDateConstrainClause(dateFromColumn, dateToColumn, - dateFromInclusive, dateToInclusive, dateFromValue, - dateToValue); - } - return dateConstrainSql; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; + +import java.util.List; + +import javax.xml.datatype.XMLGregorianCalendar; + +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ConstrainDateTimeType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ConstrainDateType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.InclusiveType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ItemType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.PanelType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ItemType.ConstrainByDate; + +public class DateConstrainUtil { + + DateConstrainHandler dateConstrainHandler = null; + + public DateConstrainUtil(DataSourceLookup dataSourceLookup) { + dateConstrainHandler = new DateConstrainHandler(dataSourceLookup); + + } + + public String buildPanelDateSql(PanelType panelType){ + return buildPanelDateSql(panelType, ""); + } + + public String buildPanelDateSql(PanelType panelType, String tableAlias) { + String panelDateConstrain = " "; + if (panelType.getPanelDateFrom() != null + || panelType.getPanelDateTo() != null) { + panelDateConstrain = generatePanelDateConstrain( + dateConstrainHandler, panelType.getPanelDateFrom(), + panelType.getPanelDateTo(), tableAlias); + } + return panelDateConstrain; + } + + public String buildItemDateSql(ItemType item){ + return buildItemDateSql(item, ""); + } + + public String buildItemDateSql(ItemType item, String tableAlias) { + if (tableAlias==null) + tableAlias = ""; + if (tableAlias.trim().length()>0&&!tableAlias.endsWith(".")) + tableAlias = tableAlias + "."; + String dateConstrainSql = null; + String fullItemDateSql = ""; + List constrainByDateList = item.getConstrainByDate(); + boolean firstFlag = true; + for (ConstrainByDate constrainByDate : constrainByDateList) { + ConstrainDateType dateFrom = constrainByDate.getDateFrom(); + ConstrainDateType dateTo = constrainByDate.getDateTo(); + + String dateFromColumn = null, dateToColumn = null; + InclusiveType dateFromInclusive = null, dateToInclusive = null; + XMLGregorianCalendar dateFromValue = null, dateToValue = null; + + if (dateFrom != null || dateTo != null) { + + if (dateFrom != null) { + dateFromInclusive = dateFrom.getInclusive(); + dateFromValue = dateFrom.getValue(); + dateFrom.getTime(); + if (dateFrom.getTime() != null + && dateFrom.getTime().name() != null + && dateFrom.getTime().name().equalsIgnoreCase( + ConstrainDateTimeType.END_DATE.name())) { + dateFromColumn = tableAlias + "end_date"; + } else { + dateFromColumn = tableAlias + "start_date"; + } + + } + + if (dateTo != null) { + dateToInclusive = dateTo.getInclusive(); + dateToValue = dateTo.getValue(); + dateTo.getTime(); + if (dateTo.getTime() != null + && dateTo.getTime().name() != null + && dateTo.getTime().name().equalsIgnoreCase( + ConstrainDateTimeType.END_DATE.name())) { + dateToColumn = tableAlias + "end_date"; + } else { + dateToColumn = tableAlias + "start_date"; + } + } + + dateConstrainSql = dateConstrainHandler + .constructDateConstrainClause(dateFromColumn, + dateToColumn, dateFromInclusive, + dateToInclusive, dateFromValue, dateToValue); + + if (dateConstrainSql != null) { + if (!firstFlag) { + fullItemDateSql += " AND "; + } else { + firstFlag = false; + } + + fullItemDateSql += " " + dateConstrainSql + "\n"; + } + + } + } + + return fullItemDateSql; + } + + private String generatePanelDateConstrain( + DateConstrainHandler dateConstrainHandler, + ConstrainDateType dateFrom, ConstrainDateType dateTo, + String tableAlias) { + if (tableAlias==null) + tableAlias = ""; + if (tableAlias.trim().length()>0&&!tableAlias.endsWith(".")) + tableAlias = tableAlias + "."; + + String dateFromColumn = null, dateToColumn = null; + InclusiveType dateFromInclusive = null, dateToInclusive = null; + XMLGregorianCalendar dateFromValue = null, dateToValue = null; + String dateConstrainSql = null; + + if (dateFrom != null || dateTo != null) { + + if (dateFrom != null) { + dateFromInclusive = dateFrom.getInclusive(); + dateFromValue = dateFrom.getValue(); + + dateFrom.getTime(); + if (dateFrom.getTime() != null + && dateFrom.getTime().name() != null + && dateFrom.getTime().name().equalsIgnoreCase( + ConstrainDateTimeType.END_DATE.name())) { + dateFromColumn = tableAlias + "end_date"; + } else { + + dateFromColumn = tableAlias + "start_date"; + } + + } + + if (dateTo != null) { + dateToInclusive = dateTo.getInclusive(); + dateToValue = dateTo.getValue(); + + dateTo.getTime(); + if (dateTo.getTime() != null + && dateTo.getTime().name() != null + && dateTo.getTime().name().equalsIgnoreCase( + ConstrainDateTimeType.END_DATE.name())) { + dateToColumn = tableAlias + "end_date"; + } else { + + dateToColumn = tableAlias + "start_date"; + } + + } + + dateConstrainSql = dateConstrainHandler + .constructDateConstrainClause(dateFromColumn, dateToColumn, + dateFromInclusive, dateToInclusive, dateFromValue, + dateToValue); + } + return dateConstrainSql; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/DirectQueryForSinglePanel.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/DirectQueryForSinglePanel.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/DirectQueryForSinglePanel.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/DirectQueryForSinglePanel.java index 024b06e2..0e1ddc26 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/DirectQueryForSinglePanel.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/DirectQueryForSinglePanel.java @@ -1,76 +1,76 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -public class DirectQueryForSinglePanel { - - protected final Log log = LogFactory.getLog(DirectQueryForSinglePanel.class); - - - - - - public DirectQueryForSinglePanel() { - - } - - - public String buildSqlWithOR(String tempTableSql) { - - String[] individualSql = tempTableSql.split("<\\*>"); - StringBuffer convertedSqlBuffer = new StringBuffer(); - String individualSqlLowerCase = ""; - for (int i =0 ; i0) { - - String constraint = ""; - - Pattern p = Pattern.compile("\\bwhere\\b(.*?)(?:(\\bgroup by\\b|\\border by\\b|$))", Pattern.DOTALL|Pattern.CASE_INSENSITIVE); - Matcher m = p.matcher(individualSqlLowerCase); - if (m.find() && m.groupCount()>0) - constraint = m.group(1).trim(); - - convertedSqlBuffer.append( "( " + constraint + ")"); - //System.out.println("original split sql " + individualSql[i]); - if (i+1"); - StringBuffer convertedSqlBuffer = new StringBuffer(); - String individualSqlLowerCase = ""; - for (int i =0 ; i0) { - convertedSqlBuffer.append(individualSql[i].substring(individualSqlLowerCase.indexOf("select"),individualSqlLowerCase.length())); - //System.out.println("original split sql " + individualSql[i]); - if (i+1"); + StringBuffer convertedSqlBuffer = new StringBuffer(); + String individualSqlLowerCase = ""; + for (int i =0 ; i0) { + + String constraint = ""; + + Pattern p = Pattern.compile("\\bwhere\\b(.*?)(?:(\\bgroup by\\b|\\border by\\b|$))", Pattern.DOTALL|Pattern.CASE_INSENSITIVE); + Matcher m = p.matcher(individualSqlLowerCase); + if (m.find() && m.groupCount()>0) + constraint = m.group(1).trim(); + + convertedSqlBuffer.append( "( " + constraint + ")"); + //System.out.println("original split sql " + individualSql[i]); + if (i+1"); + StringBuffer convertedSqlBuffer = new StringBuffer(); + String individualSqlLowerCase = ""; + for (int i =0 ; i0) { + convertedSqlBuffer.append(individualSql[i].substring(individualSqlLowerCase.indexOf("select"),individualSqlLowerCase.length())); + //System.out.println("original split sql " + individualSql[i]); + if (i+1> groupPanelByTiming( - List panelList, String queryTiming) { - List anyPanelList = new ArrayList(); - List sameVisitPanelList = new ArrayList(); - List sameInstanceNumPanelList = new ArrayList(); - // iterate the panel list and put them in seperate bucket - String panelTiming = null, finalTiming = QueryTimingHandler.ANY; - HashMap> panelTimingMap = new HashMap>(); - for (PanelType panel : panelList) { - panelTiming = panel.getPanelTiming(); - if (panelTiming != null) { - finalTiming = panelTiming; - } else if (queryTiming != null) { - finalTiming = queryTiming; - } else { - finalTiming = "ANY"; - } - - if (finalTiming.equals(QueryTimingHandler.ANY)) { - anyPanelList.add(panel); - } else if (finalTiming.equalsIgnoreCase(QueryTimingHandler.SAME) - || finalTiming.equals(QueryTimingHandler.SAMEVISIT)) { - sameVisitPanelList.add(panel); - } else if (finalTiming - .equalsIgnoreCase(QueryTimingHandler.SAMEINSTANCENUM)) { - sameInstanceNumPanelList.add(panel); - - } - } - // - panelTimingMap.put(QueryTimingHandler.ANY, anyPanelList); - panelTimingMap.put(QueryTimingHandler.SAMEVISIT, sameVisitPanelList); - panelTimingMap.put(QueryTimingHandler.SAMEINSTANCENUM, - sameInstanceNumPanelList); - return panelTimingMap; - } - - - public List filterByInverFlag(List panelList, boolean excludeFlag) { - int checkInvertVal = 0; - if (excludeFlag == true) { - checkInvertVal = 1; - } - List excludePanelList = new ArrayList(); - for (PanelType panelType : panelList) { - - int invert = panelType.getInvert(); - if (invert == checkInvertVal ) { - excludePanelList.add(panelType); - } - } - return excludePanelList; - } - - public Map> filterByExcludeFlag(Map> groupPanelByTimingMap,boolean excludeFlag) { - Map> invertGroupPanelByTimingMap = new HashMap>(); - - String[] timingOrder = new String[] { - QueryTimingHandler.SAMEINSTANCENUM, - QueryTimingHandler.SAMEVISIT, QueryTimingHandler.ANY }; - - for (int k = 0; k < timingOrder.length; k++) { - List panelList = groupPanelByTimingMap.get(timingOrder[k]); - if (panelList == null) { - continue; - } - List filteredPanelList1 = filterByInverFlag (panelList, excludeFlag); - - - if (filteredPanelList1.size()>0) { - invertGroupPanelByTimingMap .put(timingOrder[k], filteredPanelList1); - } - - } - - return invertGroupPanelByTimingMap; - - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import edu.harvard.i2b2.crc.datavo.setfinder.query.PanelType; + +public class GroupPanelByTiming { + + public HashMap> groupPanelByTiming( + List panelList, String queryTiming) { + List anyPanelList = new ArrayList(); + List sameVisitPanelList = new ArrayList(); + List sameInstanceNumPanelList = new ArrayList(); + // iterate the panel list and put them in seperate bucket + String panelTiming = null, finalTiming = QueryTimingHandler.ANY; + HashMap> panelTimingMap = new HashMap>(); + for (PanelType panel : panelList) { + panelTiming = panel.getPanelTiming(); + if (panelTiming != null) { + finalTiming = panelTiming; + } else if (queryTiming != null) { + finalTiming = queryTiming; + } else { + finalTiming = "ANY"; + } + + if (finalTiming.equals(QueryTimingHandler.ANY)) { + anyPanelList.add(panel); + } else if (finalTiming.equalsIgnoreCase(QueryTimingHandler.SAME) + || finalTiming.equals(QueryTimingHandler.SAMEVISIT)) { + sameVisitPanelList.add(panel); + } else if (finalTiming + .equalsIgnoreCase(QueryTimingHandler.SAMEINSTANCENUM)) { + sameInstanceNumPanelList.add(panel); + + } + } + // + panelTimingMap.put(QueryTimingHandler.ANY, anyPanelList); + panelTimingMap.put(QueryTimingHandler.SAMEVISIT, sameVisitPanelList); + panelTimingMap.put(QueryTimingHandler.SAMEINSTANCENUM, + sameInstanceNumPanelList); + return panelTimingMap; + } + + + public List filterByInverFlag(List panelList, boolean excludeFlag) { + int checkInvertVal = 0; + if (excludeFlag == true) { + checkInvertVal = 1; + } + List excludePanelList = new ArrayList(); + for (PanelType panelType : panelList) { + + int invert = panelType.getInvert(); + if (invert == checkInvertVal ) { + excludePanelList.add(panelType); + } + } + return excludePanelList; + } + + public Map> filterByExcludeFlag(Map> groupPanelByTimingMap,boolean excludeFlag) { + Map> invertGroupPanelByTimingMap = new HashMap>(); + + String[] timingOrder = new String[] { + QueryTimingHandler.SAMEINSTANCENUM, + QueryTimingHandler.SAMEVISIT, QueryTimingHandler.ANY }; + + for (int k = 0; k < timingOrder.length; k++) { + List panelList = groupPanelByTimingMap.get(timingOrder[k]); + if (panelList == null) { + continue; + } + List filteredPanelList1 = filterByInverFlag (panelList, excludeFlag); + + + if (filteredPanelList1.size()>0) { + invertGroupPanelByTimingMap .put(timingOrder[k], filteredPanelList1); + } + + } + + return invertGroupPanelByTimingMap; + + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/IdentityPanelEntry.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/IdentityPanelEntry.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/IdentityPanelEntry.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/IdentityPanelEntry.java index 3dc8ee8b..373db1cc --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/IdentityPanelEntry.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/IdentityPanelEntry.java @@ -1,63 +1,63 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; - -/** - * Panel bean class - * $Id: IdentityPanelEntry.java,v 1.4 2008/07/21 20:04:21 rk903 Exp $ - * @author chris - */ -public class IdentityPanelEntry extends PanelEntry { - private static int identityValue = 1; - - public IdentityPanelEntry() { - this.Panel = identityValue; - identityValue++; - } - - public IdentityPanelEntry(PanelEntry p) { - this.AllShort = p.AllShort; - this.EstPanelSize = p.EstPanelSize; - this.FirstPanel = p.FirstPanel; - this.ForInsert = p.ForInsert; - this.Invert = p.Invert; - this.Items = p.Items; - this.OldPanel = p.Panel; - this.totalItemOccurrences = p.totalItemOccurrences; - this.totalItemOccurrencesOperator = p.totalItemOccurrencesOperator; - this.Panel = identityValue; - identityValue++; - } - - @Override - public boolean equals(Object o) { - if ((o != null) && (o.getClass().equals(this.getClass()))) { - IdentityPanelEntry p = (IdentityPanelEntry) o; - - if ((this.OldPanel == p.OldPanel) && (this.Invert == p.Invert) && - (this.EstPanelSize == p.EstPanelSize) && - (this.Items == p.Items) && (this.AllShort == p.AllShort) && - (this.ForInsert == p.ForInsert) && - (this.FirstPanel == p.FirstPanel) && - (this.totalItemOccurrences == p.totalItemOccurrences)) { - return true; - } else { - return false; - } - } else { - return false; - } - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; + +/** + * Panel bean class + * $Id: IdentityPanelEntry.java,v 1.4 2008/07/21 20:04:21 rk903 Exp $ + * @author chris + */ +public class IdentityPanelEntry extends PanelEntry { + private static int identityValue = 1; + + public IdentityPanelEntry() { + this.Panel = identityValue; + identityValue++; + } + + public IdentityPanelEntry(PanelEntry p) { + this.AllShort = p.AllShort; + this.EstPanelSize = p.EstPanelSize; + this.FirstPanel = p.FirstPanel; + this.ForInsert = p.ForInsert; + this.Invert = p.Invert; + this.Items = p.Items; + this.OldPanel = p.Panel; + this.totalItemOccurrences = p.totalItemOccurrences; + this.totalItemOccurrencesOperator = p.totalItemOccurrencesOperator; + this.Panel = identityValue; + identityValue++; + } + + @Override + public boolean equals(Object o) { + if ((o != null) && (o.getClass().equals(this.getClass()))) { + IdentityPanelEntry p = (IdentityPanelEntry) o; + + if ((this.OldPanel == p.OldPanel) && (this.Invert == p.Invert) && + (this.EstPanelSize == p.EstPanelSize) && + (this.Items == p.Items) && (this.AllShort == p.AllShort) && + (this.ForInsert == p.ForInsert) && + (this.FirstPanel == p.FirstPanel) && + (this.totalItemOccurrences == p.totalItemOccurrences)) { + return true; + } else { + return false; + } + } else { + return false; + } + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/ItemEntry.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/ItemEntry.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/ItemEntry.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/ItemEntry.java index 65c26fb8..976c61a0 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/ItemEntry.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/ItemEntry.java @@ -1,55 +1,55 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; -/** - * ItemEntry bean class - * $Id: ItemEntry.java,v 1.3 2007/08/31 14:46:23 rk903 Exp $ - * @author chris - */ -public class ItemEntry { - public Integer Panel; - public String TableName; - public String FieldName; - public long EstItemSize; - public int SqlX; - public String Sql0; - public String Sql1; - - public ItemEntry() { - } - - /** - * Override equals function - */ - @Override - public boolean equals(Object o) { - if ((o != null) && (o.getClass().equals(this.getClass()))) { - ItemEntry p = (ItemEntry) o; - - if ((this.Panel.equals(p.Panel)) && - (this.TableName.equals(p.TableName)) && - (this.FieldName.equals(p.FieldName)) && - (this.EstItemSize == p.EstItemSize) && - (this.SqlX == p.SqlX) && (this.Sql0.equals(p.Sql0)) && - (this.Sql1.equals(p.Sql1))) { - return true; - } else { - return false; - } - } else { - return false; - } - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; +/** + * ItemEntry bean class + * $Id: ItemEntry.java,v 1.3 2007/08/31 14:46:23 rk903 Exp $ + * @author chris + */ +public class ItemEntry { + public Integer Panel; + public String TableName; + public String FieldName; + public long EstItemSize; + public int SqlX; + public String Sql0; + public String Sql1; + + public ItemEntry() { + } + + /** + * Override equals function + */ + @Override + public boolean equals(Object o) { + if ((o != null) && (o.getClass().equals(this.getClass()))) { + ItemEntry p = (ItemEntry) o; + + if ((this.Panel.equals(p.Panel)) && + (this.TableName.equals(p.TableName)) && + (this.FieldName.equals(p.FieldName)) && + (this.EstItemSize == p.EstItemSize) && + (this.SqlX == p.SqlX) && (this.Sql0.equals(p.Sql0)) && + (this.Sql1.equals(p.Sql1))) { + return true; + } else { + return false; + } + } else { + return false; + } + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/ItemMetaDataHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/ItemMetaDataHandler.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/ItemMetaDataHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/ItemMetaDataHandler.java index b2ea6f24..c16b6aa0 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/ItemMetaDataHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/ItemMetaDataHandler.java @@ -1,209 +1,209 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; - -import jakarta.xml.bind.JAXBElement; -import javax.xml.stream.XMLStreamException; - -import org.apache.axis2.AxisFault; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.exception.StackTraceUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; -import edu.harvard.i2b2.crc.datavo.ontology.ConceptType; -import edu.harvard.i2b2.crc.datavo.ontology.ModifierType; -import edu.harvard.i2b2.crc.delegate.ontology.CallOntologyUtil; -import edu.harvard.i2b2.crc.util.PMServiceAccountUtil; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; -import edu.harvard.i2b2.crc.util.SqlClauseUtil; -import edu.harvard.i2b2.crc.util.StringUtil; - -public class ItemMetaDataHandler { - - private String queryXML = ""; - protected final Log log = LogFactory.getLog(ItemMetaDataHandler.class); - - public ItemMetaDataHandler(String queryXML) { - this.queryXML = queryXML; - } - - public ConceptType getMetaDataFromOntologyCell(String itemKey, String dbType) - throws ConceptNotFoundException, OntologyException { - ConceptType conceptType = null; - CallOntologyUtil ontologyUtil; - try { - // ontologyUtil = new CallOntologyUtil(queryXML); - // if regular concepts - // conceptType = ontologyUtil.callOntology(itemKey); - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil() - .unMashallFromString(queryXML); - RequestMessageType request = (RequestMessageType) responseJaxb - .getValue(); - String projectId = request.getMessageHeader().getProjectId(); - SecurityType tempSecurityType = request.getMessageHeader() - .getSecurity(); - SecurityType securityType = PMServiceAccountUtil - .getServiceSecurityType(tempSecurityType.getDomain()); - - conceptType = CallOntologyUtil.callOntology(itemKey, securityType, projectId, QueryProcessorUtil.getInstance().getOntologyUrl()); - } catch (JAXBUtilException e) { - - log.error("Error while fetching metadata [" + itemKey - + "] from ontology ", e); - throw new OntologyException("Error while fetching metadata [" - + itemKey + "] from ontology " - + StackTraceUtil.getStackTrace(e)); - } catch (I2B2Exception e) { - log.error("Error while fetching metadata from ontology ", e); - throw new OntologyException("Error while fetching metadata [" - + itemKey + "] from ontology " - + StackTraceUtil.getStackTrace(e)); - } catch (AxisFault e) { - log.error("Error while fetching metadata from ontology ", e); - throw new OntologyException("Error while fetching metadata [" - + itemKey + "] from ontology " - + StackTraceUtil.getStackTrace(e)); - } catch (XMLStreamException e) { - log.error("Error while fetching metadata from ontology ", e); - throw new OntologyException("Error while fetching metadata [" - + itemKey + "] from ontology " - + StackTraceUtil.getStackTrace(e)); - } - - if (conceptType == null) { - // add it the message - // ignoredItemMessageBuffer.append("\n [" + itemKey + "] in panel #" - // + i + "\n"); - throw new ConceptNotFoundException("[" + itemKey + "] "); - - } else { - String theData = conceptType.getDimcode(); - if (conceptType.getColumndatatype() != null - && conceptType.getColumndatatype().equalsIgnoreCase("T")) { - - - if(dbType.toUpperCase().equals("SQLSERVER")){ - conceptType.setDimcode(StringUtil.escapeSQLSERVER(conceptType.getDimcode())); - } - - else if(dbType.toUpperCase().equals("ORACLE")){ - conceptType.setDimcode(StringUtil.escapeORACLE(conceptType.getDimcode())); - } - - - theData = SqlClauseUtil.handleMetaDataTextValue( - conceptType.getOperator(), conceptType.getDimcode()); - } else if (conceptType.getColumndatatype() != null - && conceptType.getColumndatatype().equalsIgnoreCase("N")) { - theData = SqlClauseUtil.handleMetaDataNumericValue( - conceptType.getOperator(), conceptType.getDimcode()); - } else if (conceptType.getColumndatatype() != null - && conceptType.getColumndatatype().equalsIgnoreCase("D")) { - theData = SqlClauseUtil.handleMetaDataDateValue( - conceptType.getOperator(), conceptType.getDimcode()); - } - conceptType.setDimcode(theData); - } - - return conceptType; - } - - public ModifierType getModifierDataFromOntologyCell(String modifierKey, String appliedPath, String dbType) - throws ConceptNotFoundException, OntologyException { - ModifierType modifierType = null; - CallOntologyUtil ontologyUtil; - try { - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - String ontologyUrl = qpUtil - .getCRCPropertyValue(QueryProcessorUtil.ONTOLOGYCELL_ROOT_WS_URL_PROPERTIES); - String getModifierOperationName = qpUtil - .getCRCPropertyValue(QueryProcessorUtil.ONTOLOGYCELL_GETMODIFIERINFO_URL_PROPERTIES); - String ontologyGetModifierInfoUrl = ontologyUrl - + getModifierOperationName; - log.debug("Ontology getModifierinfo url from property file ["+ ontologyGetModifierInfoUrl + "]"); - //ontologyUtil = new CallOntologyUtil(ontologyGetModifierInfoUrl,queryXML); - // if regular concepts - //modifierType = ontologyUtil.callGetModifierInfo(modifierKey,appliedPath); - - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil() - .unMashallFromString(queryXML); - RequestMessageType request = (RequestMessageType) responseJaxb - .getValue(); - String projectId = request.getMessageHeader().getProjectId(); - SecurityType tempSecurityType = request.getMessageHeader() - .getSecurity(); - SecurityType securityType = PMServiceAccountUtil - .getServiceSecurityType(tempSecurityType.getDomain()); - - modifierType = CallOntologyUtil.callGetModifierInfo(modifierKey,appliedPath, securityType, projectId, ontologyGetModifierInfoUrl); - - } catch (JAXBUtilException e) { - - log.error("Error while fetching metadata [" + modifierKey - + "] from ontology ", e); - throw new OntologyException("Error while fetching metadata [" - + modifierKey + "] from ontology " - + StackTraceUtil.getStackTrace(e)); - } catch (I2B2Exception e) { - log.error("Error while fetching metadata from ontology ", e); - throw new OntologyException("Error while fetching metadata [" - + modifierKey + "] from ontology " - + StackTraceUtil.getStackTrace(e)); - } catch (AxisFault e) { - log.error("Error while fetching metadata from ontology ", e); - throw new OntologyException("Error while fetching metadata [" - + modifierKey + "] from ontology " - + StackTraceUtil.getStackTrace(e)); - } catch (XMLStreamException e) { - log.error("Error while fetching metadata from ontology ", e); - throw new OntologyException("Error while fetching metadata [" - + modifierKey + "] from ontology " - + StackTraceUtil.getStackTrace(e)); - } - - if (modifierType == null) { - // add it the message - // ignoredItemMessageBuffer.append("\n [" + itemKey + "] in panel #" - // + i + "\n"); - throw new ConceptNotFoundException("Error getting modifierinfo for modifier key [" + modifierKey + "] and appliedPath [" + appliedPath + "]"); - - } else { - String theData = modifierType.getDimcode(); - if (modifierType.getColumndatatype() != null - && modifierType.getColumndatatype().equalsIgnoreCase("T")) { - - if(dbType.toUpperCase().equals("SQLSERVER")){ - modifierType.setDimcode(StringUtil.escapeSQLSERVER(modifierType.getDimcode())); - } - - else if(dbType.toUpperCase().equals("ORACLE")){ - modifierType.setDimcode(StringUtil.escapeORACLE(modifierType.getDimcode())); - } - theData = SqlClauseUtil.handleMetaDataTextValue( - modifierType.getOperator(), modifierType.getDimcode()); - } else if (modifierType.getColumndatatype() != null - && modifierType.getColumndatatype().equalsIgnoreCase("N")) { - theData = SqlClauseUtil.handleMetaDataNumericValue( - modifierType.getOperator(), modifierType.getDimcode()); - } else if (modifierType.getColumndatatype() != null - && modifierType.getColumndatatype().equalsIgnoreCase("D")) { - theData = SqlClauseUtil.handleMetaDataDateValue( - modifierType.getOperator(), modifierType.getDimcode()); - } - modifierType.setDimcode(theData); - } - - return modifierType; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; + +import jakarta.xml.bind.JAXBElement; +import javax.xml.stream.XMLStreamException; + +import org.apache.axis2.AxisFault; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.exception.StackTraceUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; +import edu.harvard.i2b2.crc.datavo.ontology.ConceptType; +import edu.harvard.i2b2.crc.datavo.ontology.ModifierType; +import edu.harvard.i2b2.crc.delegate.ontology.CallOntologyUtil; +import edu.harvard.i2b2.crc.util.PMServiceAccountUtil; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; +import edu.harvard.i2b2.crc.util.SqlClauseUtil; +import edu.harvard.i2b2.crc.util.StringUtil; + +public class ItemMetaDataHandler { + + private String queryXML = ""; + protected final Log log = LogFactory.getLog(ItemMetaDataHandler.class); + + public ItemMetaDataHandler(String queryXML) { + this.queryXML = queryXML; + } + + public ConceptType getMetaDataFromOntologyCell(String itemKey, String dbType) + throws ConceptNotFoundException, OntologyException { + ConceptType conceptType = null; + CallOntologyUtil ontologyUtil; + try { + // ontologyUtil = new CallOntologyUtil(queryXML); + // if regular concepts + // conceptType = ontologyUtil.callOntology(itemKey); + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil() + .unMashallFromString(queryXML); + RequestMessageType request = (RequestMessageType) responseJaxb + .getValue(); + String projectId = request.getMessageHeader().getProjectId(); + SecurityType tempSecurityType = request.getMessageHeader() + .getSecurity(); + SecurityType securityType = PMServiceAccountUtil + .getServiceSecurityType(tempSecurityType.getDomain()); + + conceptType = CallOntologyUtil.callOntology(itemKey, securityType, projectId, QueryProcessorUtil.getInstance().getOntologyUrl()); + } catch (JAXBUtilException e) { + + log.error("Error while fetching metadata [" + itemKey + + "] from ontology ", e); + throw new OntologyException("Error while fetching metadata [" + + itemKey + "] from ontology " + + StackTraceUtil.getStackTrace(e)); + } catch (I2B2Exception e) { + log.error("Error while fetching metadata from ontology ", e); + throw new OntologyException("Error while fetching metadata [" + + itemKey + "] from ontology " + + StackTraceUtil.getStackTrace(e)); + } catch (AxisFault e) { + log.error("Error while fetching metadata from ontology ", e); + throw new OntologyException("Error while fetching metadata [" + + itemKey + "] from ontology " + + StackTraceUtil.getStackTrace(e)); + } catch (XMLStreamException e) { + log.error("Error while fetching metadata from ontology ", e); + throw new OntologyException("Error while fetching metadata [" + + itemKey + "] from ontology " + + StackTraceUtil.getStackTrace(e)); + } + + if (conceptType == null) { + // add it the message + // ignoredItemMessageBuffer.append("\n [" + itemKey + "] in panel #" + // + i + "\n"); + throw new ConceptNotFoundException("[" + itemKey + "] "); + + } else { + String theData = conceptType.getDimcode(); + if (conceptType.getColumndatatype() != null + && conceptType.getColumndatatype().equalsIgnoreCase("T")) { + + + if(dbType.toUpperCase().equals("SQLSERVER")){ + conceptType.setDimcode(StringUtil.escapeSQLSERVER(conceptType.getDimcode())); + } + + else if(dbType.toUpperCase().equals("ORACLE")){ + conceptType.setDimcode(StringUtil.escapeORACLE(conceptType.getDimcode())); + } + + + theData = SqlClauseUtil.handleMetaDataTextValue( + conceptType.getOperator(), conceptType.getDimcode()); + } else if (conceptType.getColumndatatype() != null + && conceptType.getColumndatatype().equalsIgnoreCase("N")) { + theData = SqlClauseUtil.handleMetaDataNumericValue( + conceptType.getOperator(), conceptType.getDimcode()); + } else if (conceptType.getColumndatatype() != null + && conceptType.getColumndatatype().equalsIgnoreCase("D")) { + theData = SqlClauseUtil.handleMetaDataDateValue( + conceptType.getOperator(), conceptType.getDimcode()); + } + conceptType.setDimcode(theData); + } + + return conceptType; + } + + public ModifierType getModifierDataFromOntologyCell(String modifierKey, String appliedPath, String dbType) + throws ConceptNotFoundException, OntologyException { + ModifierType modifierType = null; + CallOntologyUtil ontologyUtil; + try { + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + String ontologyUrl = qpUtil + .getCRCPropertyValue(QueryProcessorUtil.ONTOLOGYCELL_ROOT_WS_URL_PROPERTIES); + String getModifierOperationName = qpUtil + .getCRCPropertyValue(QueryProcessorUtil.ONTOLOGYCELL_GETMODIFIERINFO_URL_PROPERTIES); + String ontologyGetModifierInfoUrl = ontologyUrl + + getModifierOperationName; + log.debug("Ontology getModifierinfo url from property file ["+ ontologyGetModifierInfoUrl + "]"); + //ontologyUtil = new CallOntologyUtil(ontologyGetModifierInfoUrl,queryXML); + // if regular concepts + //modifierType = ontologyUtil.callGetModifierInfo(modifierKey,appliedPath); + + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil() + .unMashallFromString(queryXML); + RequestMessageType request = (RequestMessageType) responseJaxb + .getValue(); + String projectId = request.getMessageHeader().getProjectId(); + SecurityType tempSecurityType = request.getMessageHeader() + .getSecurity(); + SecurityType securityType = PMServiceAccountUtil + .getServiceSecurityType(tempSecurityType.getDomain()); + + modifierType = CallOntologyUtil.callGetModifierInfo(modifierKey,appliedPath, securityType, projectId, ontologyGetModifierInfoUrl); + + } catch (JAXBUtilException e) { + + log.error("Error while fetching metadata [" + modifierKey + + "] from ontology ", e); + throw new OntologyException("Error while fetching metadata [" + + modifierKey + "] from ontology " + + StackTraceUtil.getStackTrace(e)); + } catch (I2B2Exception e) { + log.error("Error while fetching metadata from ontology ", e); + throw new OntologyException("Error while fetching metadata [" + + modifierKey + "] from ontology " + + StackTraceUtil.getStackTrace(e)); + } catch (AxisFault e) { + log.error("Error while fetching metadata from ontology ", e); + throw new OntologyException("Error while fetching metadata [" + + modifierKey + "] from ontology " + + StackTraceUtil.getStackTrace(e)); + } catch (XMLStreamException e) { + log.error("Error while fetching metadata from ontology ", e); + throw new OntologyException("Error while fetching metadata [" + + modifierKey + "] from ontology " + + StackTraceUtil.getStackTrace(e)); + } + + if (modifierType == null) { + // add it the message + // ignoredItemMessageBuffer.append("\n [" + itemKey + "] in panel #" + // + i + "\n"); + throw new ConceptNotFoundException("Error getting modifierinfo for modifier key [" + modifierKey + "] and appliedPath [" + appliedPath + "]"); + + } else { + String theData = modifierType.getDimcode(); + if (modifierType.getColumndatatype() != null + && modifierType.getColumndatatype().equalsIgnoreCase("T")) { + + if(dbType.toUpperCase().equals("SQLSERVER")){ + modifierType.setDimcode(StringUtil.escapeSQLSERVER(modifierType.getDimcode())); + } + + else if(dbType.toUpperCase().equals("ORACLE")){ + modifierType.setDimcode(StringUtil.escapeORACLE(modifierType.getDimcode())); + } + theData = SqlClauseUtil.handleMetaDataTextValue( + modifierType.getOperator(), modifierType.getDimcode()); + } else if (modifierType.getColumndatatype() != null + && modifierType.getColumndatatype().equalsIgnoreCase("N")) { + theData = SqlClauseUtil.handleMetaDataNumericValue( + modifierType.getOperator(), modifierType.getDimcode()); + } else if (modifierType.getColumndatatype() != null + && modifierType.getColumndatatype().equalsIgnoreCase("D")) { + theData = SqlClauseUtil.handleMetaDataDateValue( + modifierType.getOperator(), modifierType.getDimcode()); + } + modifierType.setDimcode(theData); + } + + return modifierType; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/ModifierConstrainsHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/ModifierConstrainsHandler.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/ModifierConstrainsHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/ModifierConstrainsHandler.java index 31332afc..94bff76a --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/ModifierConstrainsHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/ModifierConstrainsHandler.java @@ -1,89 +1,89 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.crc.datavo.ontology.ModifierType; - -/** - * Class to handle modifier constrains. Generates sql where clause based on the - * list of modifier constrains. - * - * @author rkuttan - */ -public class ModifierConstrainsHandler { - /** log **/ - protected final Log log = LogFactory.getLog(getClass()); - String schemaName = null; - - public ModifierConstrainsHandler(String schemaName) { - this.schemaName = schemaName; - } - - public String constructModifierConstainClause( - ModifierType modifierType) - throws I2B2DAOException { - - String dimPath = "", dimColumnName = "", dimCode = "", dimOperator = "", dimTableName = "", factTableColumn = ""; - - String constrainSql = null; - if (modifierType != null) { - dimPath = modifierType.getFullname(); - dimColumnName = modifierType.getColumnname(); - dimCode = modifierType.getDimcode(); - dimOperator = modifierType.getOperator(); - dimTableName = modifierType.getTablename(); - factTableColumn = modifierType.getFacttablecolumn(); - - if (dimPath == null || dimColumnName == null || dimCode == null - || dimOperator == null || dimTableName == null - || factTableColumn == null) { - throw new I2B2DAOException( - "Error modifier constrain information has null value path [" - + dimPath + "] column name [" + dimColumnName - + "] dim code [" + dimCode - + "] dim operator [ " + dimOperator - + "] dim table name [" + dimTableName - + "] fact table column [" + factTableColumn - + "]"); - } - } - - //dimPath.replaceAll("'", "''"); - //dimCode = dimCode.replaceAll("'", "''"); - - constrainSql = " (" + factTableColumn + " IN ( select " - + factTableColumn + " from " + this.schemaName + dimTableName + " where " - + dimColumnName + " " + dimOperator + " " + dimCode ; - - - if ((dimOperator.toUpperCase() != null) && (dimOperator.toUpperCase().equals("LIKE"))) - { - - constrainSql += " {ESCAPE '?'} "; - } - constrainSql += "))"; - - - - - return constrainSql; - } - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.crc.datavo.ontology.ModifierType; + +/** + * Class to handle modifier constrains. Generates sql where clause based on the + * list of modifier constrains. + * + * @author rkuttan + */ +public class ModifierConstrainsHandler { + /** log **/ + protected final Log log = LogFactory.getLog(getClass()); + String schemaName = null; + + public ModifierConstrainsHandler(String schemaName) { + this.schemaName = schemaName; + } + + public String constructModifierConstainClause( + ModifierType modifierType) + throws I2B2DAOException { + + String dimPath = "", dimColumnName = "", dimCode = "", dimOperator = "", dimTableName = "", factTableColumn = ""; + + String constrainSql = null; + if (modifierType != null) { + dimPath = modifierType.getFullname(); + dimColumnName = modifierType.getColumnname(); + dimCode = modifierType.getDimcode(); + dimOperator = modifierType.getOperator(); + dimTableName = modifierType.getTablename(); + factTableColumn = modifierType.getFacttablecolumn(); + + if (dimPath == null || dimColumnName == null || dimCode == null + || dimOperator == null || dimTableName == null + || factTableColumn == null) { + throw new I2B2DAOException( + "Error modifier constrain information has null value path [" + + dimPath + "] column name [" + dimColumnName + + "] dim code [" + dimCode + + "] dim operator [ " + dimOperator + + "] dim table name [" + dimTableName + + "] fact table column [" + factTableColumn + + "]"); + } + } + + //dimPath.replaceAll("'", "''"); + //dimCode = dimCode.replaceAll("'", "''"); + + constrainSql = " (" + factTableColumn + " IN ( select " + + factTableColumn + " from " + this.schemaName + dimTableName + " where " + + dimColumnName + " " + dimOperator + " " + dimCode ; + + + if ((dimOperator.toUpperCase() != null) && (dimOperator.toUpperCase().equals("LIKE"))) + { + + constrainSql += " {ESCAPE '?'} "; + } + constrainSql += "))"; + + + + + return constrainSql; + } + + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/OntologyException.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/OntologyException.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/OntologyException.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/OntologyException.java index efe5940e..fe5118c7 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/OntologyException.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/OntologyException.java @@ -1,41 +1,41 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; - -public class OntologyException extends I2B2DAOException { - - /** - * - */ - private static final long serialVersionUID = 1L; - - - public OntologyException() { - } - - /** - * Constructor that takes message and the exception as inputs. - * @param message - * @param e - */ - public OntologyException(String message, Exception e) { - super(message, e); - } - - /** - * Constructor that takes message as input. - * @param message - */ - public OntologyException(String message) { - super(message); - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; + +public class OntologyException extends I2B2DAOException { + + /** + * + */ + private static final long serialVersionUID = 1L; + + + public OntologyException() { + } + + /** + * Constructor that takes message and the exception as inputs. + * @param message + * @param e + */ + public OntologyException(String message, Exception e) { + super(message, e); + } + + /** + * Constructor that takes message as input. + * @param message + */ + public OntologyException(String message) { + super(message); + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/PanelEntry.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/PanelEntry.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/PanelEntry.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/PanelEntry.java index e461ec31..0709269d --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/PanelEntry.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/PanelEntry.java @@ -1,58 +1,58 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; -/** - * Panel Entry bean class - * $Id: PanelEntry.java,v 1.4 2008/07/21 20:04:21 rk903 Exp $ - * @author chris - */ -public class PanelEntry -{ - public Integer Panel = 0; - public Integer OldPanel = -1; - public int Invert= 0;; - public long EstPanelSize = 0; - public int Items = 0; - public int AllShort = 0; - public int ForInsert = 0; - public int FirstPanel = 0; - public int totalItemOccurrences = 0; - public String totalItemOccurrencesOperator = ""; - - @Override - public boolean equals(Object o) - { - if ((o!=null)&&(o.getClass().equals(this.getClass()))) - { - PanelEntry p = (PanelEntry) o; - if ((this.Panel==p.Panel)&& - (this.Invert==p.Invert)&& - (this.EstPanelSize==p.EstPanelSize)&& - (this.Items==p.Items)&& - (this.AllShort==p.AllShort)&& - (this.ForInsert==p.ForInsert)&& - (this.FirstPanel==p.FirstPanel) && - (this.totalItemOccurrences == p.totalItemOccurrences)) - return true; - else - return false; - } - else - return false; - } - - -} - +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; +/** + * Panel Entry bean class + * $Id: PanelEntry.java,v 1.4 2008/07/21 20:04:21 rk903 Exp $ + * @author chris + */ +public class PanelEntry +{ + public Integer Panel = 0; + public Integer OldPanel = -1; + public int Invert= 0;; + public long EstPanelSize = 0; + public int Items = 0; + public int AllShort = 0; + public int ForInsert = 0; + public int FirstPanel = 0; + public int totalItemOccurrences = 0; + public String totalItemOccurrencesOperator = ""; + + @Override + public boolean equals(Object o) + { + if ((o!=null)&&(o.getClass().equals(this.getClass()))) + { + PanelEntry p = (PanelEntry) o; + if ((this.Panel==p.Panel)&& + (this.Invert==p.Invert)&& + (this.EstPanelSize==p.EstPanelSize)&& + (this.Items==p.Items)&& + (this.AllShort==p.AllShort)&& + (this.ForInsert==p.ForInsert)&& + (this.FirstPanel==p.FirstPanel) && + (this.totalItemOccurrences == p.totalItemOccurrences)) + return true; + else + return false; + } + else + return false; + } + + +} + diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/PanelEntryComparator.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/PanelEntryComparator.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/PanelEntryComparator.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/PanelEntryComparator.java index 8afc2be4..765cc982 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/PanelEntryComparator.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/PanelEntryComparator.java @@ -1,51 +1,51 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; - -import java.util.Comparator; - - -/** - * Implement comparator for panelentry - * $Id: PanelEntryComparator.java,v 1.3 2007/08/31 14:46:23 rk903 Exp $ - * @author chris - */ -public class PanelEntryComparator implements Comparator { - @Override - public int compare(Object element1, Object element2) { - if ((element1.getClass().equals(PanelEntry.class)) && - (element2.getClass().equals((PanelEntry.class)))) { - PanelEntry p1 = (PanelEntry) element1; - PanelEntry p2 = (PanelEntry) element2; - int compare = new Integer(p1.Invert).compareTo(new Integer( - p2.Invert)); - - if (compare == 0) { - compare = new Long(p1.EstPanelSize).compareTo(new Long( - p2.EstPanelSize)); - - if (compare == 0) { - return p1.Panel.compareTo(p2.Panel); - } else { - return compare; - } - } else { - return compare; - } - } else { - return element1.toString().compareTo(element2.toString()); - } - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; + +import java.util.Comparator; + + +/** + * Implement comparator for panelentry + * $Id: PanelEntryComparator.java,v 1.3 2007/08/31 14:46:23 rk903 Exp $ + * @author chris + */ +public class PanelEntryComparator implements Comparator { + @Override + public int compare(Object element1, Object element2) { + if ((element1.getClass().equals(PanelEntry.class)) && + (element2.getClass().equals((PanelEntry.class)))) { + PanelEntry p1 = (PanelEntry) element1; + PanelEntry p2 = (PanelEntry) element2; + int compare = new Integer(p1.Invert).compareTo(new Integer( + p2.Invert)); + + if (compare == 0) { + compare = new Long(p1.EstPanelSize).compareTo(new Long( + p2.EstPanelSize)); + + if (compare == 0) { + return p1.Panel.compareTo(p2.Panel); + } else { + return compare; + } + } else { + return compare; + } + } else { + return element1.toString().compareTo(element2.toString()); + } + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/ProcessTimingReportUtil.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/ProcessTimingReportUtil.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/ProcessTimingReportUtil.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/ProcessTimingReportUtil.java index 04b0bb2d..f44f24ac --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/ProcessTimingReportUtil.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/ProcessTimingReportUtil.java @@ -1,71 +1,71 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; - -import java.io.StringWriter; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.util.jaxb.DTOFactory; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; -import edu.harvard.i2b2.crc.dao.setfinder.IQueryInstanceDao; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.setfinder.query.TimingStepType; -import edu.harvard.i2b2.crc.util.LogTimingUtil; - -public class ProcessTimingReportUtil { - - public static final String INFO = "INFO"; - public static final String DEBUG = "DEBUG"; - public static final String NONE = "NONE"; - - IQueryInstanceDao queryInstanceDao = null; - - public ProcessTimingReportUtil(DataSourceLookup dataSourceLookup) throws I2B2DAOException { - SetFinderDAOFactory sfDaoFactory = this.getSetFinderDaoFactory( - dataSourceLookup.getDomainId(), dataSourceLookup - .getProjectPath(), dataSourceLookup.getOwnerId()); - queryInstanceDao = sfDaoFactory.getQueryInstanceDAO(); - } - - public String buildProcessTiming(LogTimingUtil logTimingUtil,String name, String message) throws I2B2DAOException { - DTOFactory dtoFactory = new DTOFactory(); - TimingStepType timingStepType = new TimingStepType(); - timingStepType.setStartDate(dtoFactory.getXMLGregorianCalendar(logTimingUtil.getStartTime()) ); - timingStepType.setEndDate(dtoFactory.getXMLGregorianCalendar(logTimingUtil.getEndTime()) ); - timingStepType.setTotalTimeSecond(logTimingUtil.getDiffTime()); - timingStepType.setName(name); - timingStepType.setMessage(message); - edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); - StringWriter strWriter = new StringWriter(); - try { - CRCJAXBUtil.getJAXBUtil().marshaller(of.createProcessStepTiming(timingStepType), strWriter) ; - } catch (JAXBUtilException e) { - throw new I2B2DAOException(e.getMessage()); - } - return "\n" + strWriter.toString() + "\n"; - } - - public void logProcessTimingMessage(String queryInstanceId, String message) throws I2B2DAOException { - queryInstanceDao.updateMessage(queryInstanceId, message, true); - } - - private SetFinderDAOFactory getSetFinderDaoFactory(String domainId, - String projectPath, String ownerId) throws I2B2DAOException { - DAOFactoryHelper helper = new DAOFactoryHelper(domainId, projectPath, - ownerId); - SetFinderDAOFactory sfDaoFactory = helper.getDAOFactory() - .getSetFinderDAOFactory(); - return sfDaoFactory; - } -} - - +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; + +import java.io.StringWriter; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.util.jaxb.DTOFactory; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; +import edu.harvard.i2b2.crc.dao.setfinder.IQueryInstanceDao; +import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.setfinder.query.TimingStepType; +import edu.harvard.i2b2.crc.util.LogTimingUtil; + +public class ProcessTimingReportUtil { + + public static final String INFO = "INFO"; + public static final String DEBUG = "DEBUG"; + public static final String NONE = "NONE"; + + IQueryInstanceDao queryInstanceDao = null; + + public ProcessTimingReportUtil(DataSourceLookup dataSourceLookup) throws I2B2DAOException { + SetFinderDAOFactory sfDaoFactory = this.getSetFinderDaoFactory( + dataSourceLookup.getDomainId(), dataSourceLookup + .getProjectPath(), dataSourceLookup.getOwnerId()); + queryInstanceDao = sfDaoFactory.getQueryInstanceDAO(); + } + + public String buildProcessTiming(LogTimingUtil logTimingUtil,String name, String message) throws I2B2DAOException { + DTOFactory dtoFactory = new DTOFactory(); + TimingStepType timingStepType = new TimingStepType(); + timingStepType.setStartDate(dtoFactory.getXMLGregorianCalendar(logTimingUtil.getStartTime()) ); + timingStepType.setEndDate(dtoFactory.getXMLGregorianCalendar(logTimingUtil.getEndTime()) ); + timingStepType.setTotalTimeSecond(logTimingUtil.getDiffTime()); + timingStepType.setName(name); + timingStepType.setMessage(message); + edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); + StringWriter strWriter = new StringWriter(); + try { + CRCJAXBUtil.getJAXBUtil().marshaller(of.createProcessStepTiming(timingStepType), strWriter) ; + } catch (JAXBUtilException e) { + throw new I2B2DAOException(e.getMessage()); + } + return "\n" + strWriter.toString() + "\n"; + } + + public void logProcessTimingMessage(String queryInstanceId, String message) throws I2B2DAOException { + queryInstanceDao.updateMessage(queryInstanceId, message, true); + } + + private SetFinderDAOFactory getSetFinderDaoFactory(String domainId, + String projectPath, String ownerId) throws I2B2DAOException { + DAOFactoryHelper helper = new DAOFactoryHelper(domainId, projectPath, + ownerId); + SetFinderDAOFactory sfDaoFactory = helper.getDAOFactory() + .getSetFinderDAOFactory(); + return sfDaoFactory; + } +} + + diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/QPanelEntryComparator.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/QPanelEntryComparator.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/QPanelEntryComparator.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/QPanelEntryComparator.java index 2c34f8e9..21e8764f --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/QPanelEntryComparator.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/QPanelEntryComparator.java @@ -1,61 +1,61 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; - -import java.util.Comparator; -/** - * Implement comparator for QPanelentry - * $Id: QPanelEntryComparator.java,v 1.3 2007/08/31 14:46:23 rk903 Exp $ - * @author chris - */ -public class QPanelEntryComparator implements Comparator { - - @Override - public int compare(Object element1, Object element2) { - if ((element1.getClass().equals(PanelEntry.class))&& - (element2.getClass().equals((PanelEntry.class)))) - { - PanelEntry p1 = (PanelEntry) element1; - PanelEntry p2 = (PanelEntry) element2; - int compare = (new Integer(p1.ForInsert).compareTo(new Integer(p2.ForInsert))) * -1; - if (compare==0) - { - compare = (new Integer(p1.FirstPanel).compareTo(new Integer(p2.FirstPanel))) * -1; - if (compare==0) - { - compare = (new Integer(p1.Invert).compareTo(new Integer(p2.Invert))); - if (compare==0) - { - compare = (new Integer(p1.AllShort).compareTo(new Integer(p2.AllShort))); - if (compare==0) - { - compare = new Long(p1.EstPanelSize).compareTo(new Long(p2.EstPanelSize)); - if (compare==0) - return p1.Panel.compareTo(p2.Panel); - } - } - } - } - return compare; - } - else - return element1.toString().compareTo(element2.toString()); - } -} - - -/*"order by forinsert desc, firstpanel desc, invert, allshort, " + -"(case when forinsert = 1 then estpanelsize else estpanelsize end), panel \r\n");*/ - +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; + +import java.util.Comparator; +/** + * Implement comparator for QPanelentry + * $Id: QPanelEntryComparator.java,v 1.3 2007/08/31 14:46:23 rk903 Exp $ + * @author chris + */ +public class QPanelEntryComparator implements Comparator { + + @Override + public int compare(Object element1, Object element2) { + if ((element1.getClass().equals(PanelEntry.class))&& + (element2.getClass().equals((PanelEntry.class)))) + { + PanelEntry p1 = (PanelEntry) element1; + PanelEntry p2 = (PanelEntry) element2; + int compare = (new Integer(p1.ForInsert).compareTo(new Integer(p2.ForInsert))) * -1; + if (compare==0) + { + compare = (new Integer(p1.FirstPanel).compareTo(new Integer(p2.FirstPanel))) * -1; + if (compare==0) + { + compare = (new Integer(p1.Invert).compareTo(new Integer(p2.Invert))); + if (compare==0) + { + compare = (new Integer(p1.AllShort).compareTo(new Integer(p2.AllShort))); + if (compare==0) + { + compare = new Long(p1.EstPanelSize).compareTo(new Long(p2.EstPanelSize)); + if (compare==0) + return p1.Panel.compareTo(p2.Panel); + } + } + } + } + return compare; + } + else + return element1.toString().compareTo(element2.toString()); + } +} + + +/*"order by forinsert desc, firstpanel desc, invert, allshort, " + +"(case when forinsert = 1 then estpanelsize else estpanelsize end), panel \r\n");*/ + diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/QueryDefinitionUnWrapUtil.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/QueryDefinitionUnWrapUtil.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/QueryDefinitionUnWrapUtil.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/QueryDefinitionUnWrapUtil.java index 677f462b..b074a3f0 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/QueryDefinitionUnWrapUtil.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/QueryDefinitionUnWrapUtil.java @@ -1,68 +1,68 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.StackTraceUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionRequestType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultOutputOptionListType; - -public class QueryDefinitionUnWrapUtil { - - public QueryDefinitionType getQueryDefinitionType(String queryXML) - throws I2B2DAOException { - - QueryDefinitionType queryDefType = null; - try { - JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); - RequestMessageType reqMsgType = (RequestMessageType) jaxbUtil - .unMashallFromString(queryXML).getValue(); - - JAXBUnWrapHelper unWrapHelper = new JAXBUnWrapHelper(); - QueryDefinitionRequestType queryDefRequestType = (QueryDefinitionRequestType) unWrapHelper - .getObjectByClass( - reqMsgType.getMessageBody().getAny(), - edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionRequestType.class); - queryDefType = queryDefRequestType.getQueryDefinition(); - } catch (JAXBUtilException e) { - throw new I2B2DAOException( - "Error while reading the querydefinition from request xml " - + StackTraceUtil.getStackTrace(e)); - } - return queryDefType; - } - - public ResultOutputOptionListType getResultOuputOptionType(String queryXML) - throws I2B2DAOException { - ResultOutputOptionListType resultOutputListType = null; - try { - JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); - RequestMessageType reqMsgType = (RequestMessageType) jaxbUtil - .unMashallFromString(queryXML).getValue(); - - JAXBUnWrapHelper unWrapHelper = new JAXBUnWrapHelper(); - QueryDefinitionRequestType queryDefRequestType = (QueryDefinitionRequestType) unWrapHelper - .getObjectByClass( - reqMsgType.getMessageBody().getAny(), - edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionRequestType.class); - resultOutputListType = queryDefRequestType.getResultOutputList(); - } catch (JAXBUtilException e) { - throw new I2B2DAOException( - "Error while reading the querydefinition from request xml " - + StackTraceUtil.getStackTrace(e)); - } - return resultOutputListType; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.StackTraceUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionRequestType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultOutputOptionListType; + +public class QueryDefinitionUnWrapUtil { + + public QueryDefinitionType getQueryDefinitionType(String queryXML) + throws I2B2DAOException { + + QueryDefinitionType queryDefType = null; + try { + JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); + RequestMessageType reqMsgType = (RequestMessageType) jaxbUtil + .unMashallFromString(queryXML).getValue(); + + JAXBUnWrapHelper unWrapHelper = new JAXBUnWrapHelper(); + QueryDefinitionRequestType queryDefRequestType = (QueryDefinitionRequestType) unWrapHelper + .getObjectByClass( + reqMsgType.getMessageBody().getAny(), + edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionRequestType.class); + queryDefType = queryDefRequestType.getQueryDefinition(); + } catch (JAXBUtilException e) { + throw new I2B2DAOException( + "Error while reading the querydefinition from request xml " + + StackTraceUtil.getStackTrace(e)); + } + return queryDefType; + } + + public ResultOutputOptionListType getResultOuputOptionType(String queryXML) + throws I2B2DAOException { + ResultOutputOptionListType resultOutputListType = null; + try { + JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); + RequestMessageType reqMsgType = (RequestMessageType) jaxbUtil + .unMashallFromString(queryXML).getValue(); + + JAXBUnWrapHelper unWrapHelper = new JAXBUnWrapHelper(); + QueryDefinitionRequestType queryDefRequestType = (QueryDefinitionRequestType) unWrapHelper + .getObjectByClass( + reqMsgType.getMessageBody().getAny(), + edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionRequestType.class); + resultOutputListType = queryDefRequestType.getResultOutputList(); + } catch (JAXBUtilException e) { + throw new I2B2DAOException( + "Error while reading the querydefinition from request xml " + + StackTraceUtil.getStackTrace(e)); + } + return resultOutputListType; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/QueryTimingHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/QueryTimingHandler.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/QueryTimingHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/QueryTimingHandler.java index 1fa5409f..f6493721 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/QueryTimingHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/QueryTimingHandler.java @@ -1,66 +1,66 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; - -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionType; - -public class QueryTimingHandler { - - public static final String ANY = "ANY"; - public static final String SAME = "SAME"; - public static final String SAMEVISIT = "SAMEVISIT"; - public static final String SAMEINSTANCENUM = "SAMEINSTANCENUM"; - - public boolean isSameVisit(QueryDefinitionType queryDefType) { - String queryTiming = queryDefType.getQueryTiming(); - return isSameVisit(queryTiming); - } - - public boolean isSameInstanceNum(QueryDefinitionType queryDefType) { - String queryTiming = queryDefType.getQueryTiming(); - return isSameInstanceNum(queryTiming); - } - - public boolean isSameVisit(String queryTiming) { - if (queryTiming == null) { - return false; - } - if (queryTiming.equalsIgnoreCase("SAME") - || queryTiming.equalsIgnoreCase("SAMEVISIT")) { - return true; - } else { - return false; - } - } - public boolean isSameInstanceNum(String queryTiming) { - - if (queryTiming == null) { - return false; - } - if (queryTiming.equalsIgnoreCase("SAMEINSTANCENUM")) { - return true; - } else { - return false; - } - } - - public boolean isAny(String queryTiming) { - - if (queryTiming == null) { - return false; - } - if (queryTiming.equalsIgnoreCase("ANY")) { - return true; - } else { - return false; - } - } - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; + +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionType; + +public class QueryTimingHandler { + + public static final String ANY = "ANY"; + public static final String SAME = "SAME"; + public static final String SAMEVISIT = "SAMEVISIT"; + public static final String SAMEINSTANCENUM = "SAMEINSTANCENUM"; + + public boolean isSameVisit(QueryDefinitionType queryDefType) { + String queryTiming = queryDefType.getQueryTiming(); + return isSameVisit(queryTiming); + } + + public boolean isSameInstanceNum(QueryDefinitionType queryDefType) { + String queryTiming = queryDefType.getQueryTiming(); + return isSameInstanceNum(queryTiming); + } + + public boolean isSameVisit(String queryTiming) { + if (queryTiming == null) { + return false; + } + if (queryTiming.equalsIgnoreCase("SAME") + || queryTiming.equalsIgnoreCase("SAMEVISIT")) { + return true; + } else { + return false; + } + } + public boolean isSameInstanceNum(String queryTiming) { + + if (queryTiming == null) { + return false; + } + if (queryTiming.equalsIgnoreCase("SAMEINSTANCENUM")) { + return true; + } else { + return false; + } + } + + public boolean isAny(String queryTiming) { + + if (queryTiming == null) { + return false; + } + if (queryTiming.equalsIgnoreCase("ANY")) { + return true; + } else { + return false; + } + } + + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/QueryToolUtil.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/QueryToolUtil.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/QueryToolUtil.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/QueryToolUtil.java index d9de1167..8455d067 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/QueryToolUtil.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/QueryToolUtil.java @@ -1,698 +1,698 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; - -import java.io.IOException; -import java.io.StringReader; -import java.sql.Connection; -import java.sql.ResultSet; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.Enumeration; -import java.util.Hashtable; -import java.util.Iterator; -import java.util.List; - -import javax.xml.datatype.DatatypeFactory; -import javax.xml.datatype.XMLGregorianCalendar; -import javax.xml.transform.stream.StreamSource; - - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.xml.XMLOperatorLookup; -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.dao.pdo.input.DateConstrainHandler; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.ontology.ConceptType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ConstrainOperatorType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ConstrainValueType; -import edu.harvard.i2b2.crc.delegate.ontology.CallOntologyUtil; -import edu.harvard.i2b2.crc.util.SqlClauseUtil; - -/** - * Main class to generate setfinder sql from query definition xml. $Id: - * QueryToolUtil.java,v 1.18 2008/04/18 15:20:51 rk903 Exp $ - * - * @author chris,rkuttan - */ -public class QueryToolUtil extends CRCDAO { - - private SimpleDateFormat dateFormat = new SimpleDateFormat( - "dd-MMM-yyyy HH:mm:ss"); - - DatabaseType dbType = DatabaseType.Oracle; - Connection conn = null; - - // DATABASE VARIABLES - private String FACT_TABLE = "dw_f_conc_noval"; - private String PATIENT_TABLE = "dw_dim_patient"; - private String ENCOUNTER_TABLE = "dw_dim_enct"; - private String CONCEPT_TABLE = "dw_dim_concept"; - private String PROVIDER_TABLE = "dw_dim_provider"; - private String PATIENTLISTS_TABLE = "dw_patientlists"; - private String ENCOUNTER_SHORTCUT_TABLE = "dw_dim_patient_enct"; - private String ENCOUNTER_DIM_ID = "encounter_id_e"; - private String ENCOUNTER_INOUT_COL = "inout_cd"; - private String ENCOUNTER_COMPANY_COL = "company_cd"; - private String ENCOUNTER_START_DATE = "start_date"; - private String ENCOUNTER_PATIENT_ID = "patient_id_e"; - private String CONCEPT_DIM_ID = "c_basecode"; - private String CONCEPT_DIM_PATH = "c_fullname"; - private String PROVIDER_DIM_ID = "c_basecode"; - private String PROVIDER_DIM_PATH = "c_fullname"; - private String PATIENTLISTS_DIM_ID = "patient_id_e"; - private String PATIENTLISTS_DIM_PATH = "filename"; - private String PATIENT_DIM_ID = "patient_id_e"; - private String FACT_VAL_TYPE = "valtype"; - private String FACT_TEXT_VAL = "tval"; - private String FACT_NUM_VAL = "nval"; - private String FACT_FLAG_VAL = "valueflag"; - private String FACT_CONCEPT_RANK = "principal_concept"; - private String FACT_START_DATE = "start_date"; - private String FACT_END_DATE = "end_date"; - private String FACT_ENCOUNTER_ID = "encounter_id_e"; - private String FACT_PATIENT_ID = "patient_id_e"; - private String FACT_CONCEPT_ID = "concept_id"; - private String FACT_PROVIDER_ID = "practitioner_id"; - private String TEMP_TABLE = "#t"; - private String TEMP_TABLE_PATIENT_ID = "patient_num"; - private String TEMP_TABLE_PATIENT_DATATYPE = "varchar(100)"; - private String TEMP_TABLE_ENCOUNTER_ID = "encounter_num"; - private String TEMP_TABLE_ENCOUNTER_DATATYPE = "varchar(100)"; - private String TEMP_PANELCOUNT_DATATYPE = "tinyint"; - private String TEMP_RETURN_TABLE = "#DX"; - private String METADATA_DATABASE = "MetaData_8086"; - private String METADATA_COLUMNNAME = "c_column_name"; - private String METADATA_TABLENAME = "c_table_name"; - private String METADATA_DIMCODE = "c_dim_code"; - private String METADATA_OPERATOR = "c_operator"; - private String METADATA_FULLNAME = "c_fullname"; - - private CallOntologyUtil ontologyUtil = null; - private DataSourceLookup dataSourceLookup = null; - private StringBuffer ignoredItemMessageBuffer = new StringBuffer(); - - public QueryToolUtil() { - SetQueryDatabaseConstants(dbType); - } - - public QueryToolUtil(DataSourceLookup dataSourceLookup) { - this.setDbSchemaName(dataSourceLookup.getFullSchema()); - SetQueryDatabaseConstants(dbType); - this.dataSourceLookup = dataSourceLookup; - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE) || dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) { - TEMP_TABLE = "QUERY_GLOBAL_TEMP"; - TEMP_RETURN_TABLE = "DX"; - dateFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss"); - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER)) { - TEMP_TABLE = "#global_temp_table"; - TEMP_RETURN_TABLE = "#dx"; - dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); - } - } - - public String getIgnoredItemMessage() { - if (this.ignoredItemMessageBuffer != null - && this.ignoredItemMessageBuffer.length() > 0) { - return "Missing Concept in Ontology Cell : \n" - + this.ignoredItemMessageBuffer.toString(); - } else { - return ""; - } - - } - - private void SetQueryDatabaseConstants(DatabaseType dbType) { - if (dbType == DatabaseType.SqlServer) { - FACT_TABLE = "dw_f_conc_noval"; - PATIENT_TABLE = "dw_dim_patient"; - ENCOUNTER_TABLE = "dw_dim_enct"; - CONCEPT_TABLE = "dw_dim_concept"; - PROVIDER_TABLE = "dw_dim_provider"; - PATIENTLISTS_TABLE = "dw_patientlists"; - ENCOUNTER_SHORTCUT_TABLE = "dw_dim_patient_enct"; - - ENCOUNTER_DIM_ID = "encounter_id_e"; - ENCOUNTER_INOUT_COL = "inout_cd"; - ENCOUNTER_COMPANY_COL = "company_cd"; - ENCOUNTER_START_DATE = "start_date"; - ENCOUNTER_PATIENT_ID = "patient_id_e"; - - CONCEPT_DIM_ID = "c_basecode"; - CONCEPT_DIM_PATH = "c_fullname"; - - PROVIDER_DIM_ID = "c_basecode"; - PROVIDER_DIM_PATH = "c_fullname"; - - PATIENT_DIM_ID = "patient_id_e"; - - PATIENTLISTS_DIM_ID = "patient_id_e"; - PATIENTLISTS_DIM_PATH = "filename"; - - FACT_VAL_TYPE = "valtype"; - FACT_TEXT_VAL = "tval"; - FACT_NUM_VAL = "nval"; - FACT_FLAG_VAL = "valueflag"; - FACT_CONCEPT_RANK = "principal_concept"; - FACT_START_DATE = "start_date"; - FACT_END_DATE = "end_date"; - FACT_ENCOUNTER_ID = "encounter_id_e"; - FACT_PATIENT_ID = "patient_id_e"; - FACT_CONCEPT_ID = "concept_id"; - FACT_PROVIDER_ID = "practitioner_id"; - - TEMP_TABLE = "#t"; - TEMP_TABLE_PATIENT_ID = "patient_id_e"; - TEMP_TABLE_PATIENT_DATATYPE = "varchar(100)"; - TEMP_TABLE_ENCOUNTER_ID = "encounter_id_e"; - TEMP_TABLE_ENCOUNTER_DATATYPE = "varchar(100)"; - TEMP_PANELCOUNT_DATATYPE = "tinyint"; - TEMP_RETURN_TABLE = "#DX"; - - METADATA_DATABASE = ""; - METADATA_COLUMNNAME = "c_column_name"; - METADATA_TABLENAME = "c_table_name"; - METADATA_DIMCODE = "c_dim_code"; - METADATA_OPERATOR = "c_operator"; - METADATA_FULLNAME = "c_fullname"; - } else if (dbType == DatabaseType.Oracle) { - FACT_TABLE = "observation_fact"; - PATIENT_TABLE = "patient_dimension"; - ENCOUNTER_TABLE = "visit_dimension"; - CONCEPT_TABLE = "concept_dimension"; - PROVIDER_TABLE = "provider_dimension"; - PATIENTLISTS_TABLE = "dw_patientlists"; // not sure on this yet - ENCOUNTER_SHORTCUT_TABLE = "visit_dimension"; - - ENCOUNTER_DIM_ID = "encounter_num"; - ENCOUNTER_INOUT_COL = "inout_cd"; - ENCOUNTER_COMPANY_COL = "location_cd"; - ENCOUNTER_START_DATE = "start_date"; - ENCOUNTER_PATIENT_ID = "patient_num"; - - CONCEPT_DIM_ID = "concept_cd"; - CONCEPT_DIM_PATH = "concept_path"; - - PROVIDER_DIM_ID = "provider_id"; - PROVIDER_DIM_PATH = "provider_path"; - - PATIENT_DIM_ID = "patient_num"; - - PATIENTLISTS_DIM_ID = "patient_id_e"; // ?? - PATIENTLISTS_DIM_PATH = "filename"; // ?? - - FACT_VAL_TYPE = "valtype_cd"; - FACT_TEXT_VAL = "tval_char"; - FACT_NUM_VAL = "nval_num"; - FACT_FLAG_VAL = "valueflag_cd"; - FACT_CONCEPT_RANK = "modifier_cd"; - FACT_START_DATE = "start_date"; - FACT_END_DATE = "end_date"; - FACT_ENCOUNTER_ID = "encounter_num"; - FACT_PATIENT_ID = "patient_num"; - FACT_CONCEPT_ID = "concept_cd"; - FACT_PROVIDER_ID = "provider_id"; - - TEMP_TABLE = "QUERY_GLOBAL_TEMP"; - TEMP_TABLE_PATIENT_ID = "patient_num"; - TEMP_TABLE_PATIENT_DATATYPE = "number(22,0)"; - TEMP_TABLE_ENCOUNTER_ID = "encounter_num"; - TEMP_TABLE_ENCOUNTER_DATATYPE = "number(22,0)"; - TEMP_PANELCOUNT_DATATYPE = "number(5)"; - TEMP_RETURN_TABLE = "DX"; - - // METADATA_DATABASE = "MetaData"; - // METADATA_DATABASE = "MetaData_8086"; - METADATA_COLUMNNAME = "c_columnname"; - METADATA_TABLENAME = "c_tablename"; - METADATA_DIMCODE = "c_dimcode"; - METADATA_OPERATOR = "c_operator"; - METADATA_FULLNAME = "c_fullname"; - } - } - - protected long GetEstimatedSize(Connection conn, String theTableName, - String theColumnName, String theOperator, String theData, - long DBNumPatients) { - long EstSize = 0; - String sql = ""; - - try { - if (theTableName.equals(CONCEPT_TABLE)) { - sql = "select sum(n.patient_count) n " - + "from rpdrconceptlookup n " + "where table_name = '" - + FACT_TABLE + "' " + "and column_name = '" - + FACT_CONCEPT_ID + "'" + "and concept_t_value in " - + "(select " + CONCEPT_DIM_ID + " from " + "" - + CONCEPT_TABLE + " c " + "where " + CONCEPT_DIM_PATH - + " " + theOperator + " " + theData + ")"; - - java.sql.Statement st1 = conn.createStatement(); - ResultSet rs = st1.executeQuery(sql); - - if (rs.next()) { - EstSize = rs.getLong("n"); - } - - rs.close(); - st1.close(); - } else if (theTableName.equals(PROVIDER_TABLE)) { - sql = "select sum(n.patient_count) n " - + "from rpdrconceptlookup n " + "where table_name = '" - + FACT_TABLE + "' " + "and column_name = '" - + FACT_PROVIDER_ID + "'" + "and concept_t_value in " - + "(select " + PROVIDER_DIM_ID + " " + "from " - + PROVIDER_TABLE + " c " + "where " + PROVIDER_DIM_PATH - + " " + theOperator + " " + theData + ")"; - - java.sql.Statement st1 = conn.createStatement(); - ResultSet rs = st1.executeQuery(sql); - - if (rs.next()) { - EstSize = rs.getLong("n"); - } - - rs.close(); - st1.close(); - } else if (theTableName.equals(ENCOUNTER_TABLE)) { - sql = "select sum(n.patient_count) n " - + "from rpdrconceptlookup n " + "where table_name = '" - + ENCOUNTER_TABLE + "' " + "and column_name = '" - + theColumnName + "' " + "and concept_t_value " - + theOperator + " " + theData; - - java.sql.Statement st1 = conn.createStatement(); - ResultSet rs = st1.executeQuery(sql); - - if (rs.next()) { - EstSize = rs.getLong("n"); - } - - rs.close(); - st1.close(); - } else if (theTableName.equals(PATIENT_TABLE)) { - if (theColumnName.equals("age_in_years_num")) { - sql = "select sum(n.patient_count) n " - + "from rpdrconceptlookup n " - + "where table_name = '" + PATIENT_TABLE + "' " - + "and column_name = '" + theColumnName + "' " - + "and concept_n_value " + theOperator + " " - + theData; - } else { - sql = "select sum(n.patient_count) n " - + "from rpdrconceptlookup n " - + "where table_name = '" + PATIENT_TABLE + "' " - + "and column_name = '" + theColumnName + "' " - + "and concept_t_value " + theOperator + " " - + theData; - } - - java.sql.Statement st1 = conn.createStatement(); - ResultSet rs = st1.executeQuery(sql); - - if (rs.next()) { - EstSize = rs.getLong("n"); - } - - rs.close(); - st1.close(); - } else { - EstSize = 1; - } - } catch (Exception e) { - log.error("Unable to get Estimated Size: " + e.getMessage()); - } - - return EstSize; - } - - private String buildDateConstrain(String dateColumn, String fromDateValue, - String toDateValue) { - - String dateConstrain = " "; - String serverType = dataSourceLookup.getServerType(); - String fromFormatDateValue = ""; - String toFormatDateValue = ""; - if (fromDateValue != null && fromDateValue.trim().length() > 0) { - if (serverType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { - fromFormatDateValue = " to_date('" - + fromDateValue.substring(0, fromDateValue.length()) - + "','DD-MON-YYYY HH24:MI:SS')"; - } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.SQLSERVER)) { - fromFormatDateValue = " '" + fromDateValue + "'"; - } - } - if (toDateValue != null && toDateValue.trim().length() > 0) { - if (serverType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { - toFormatDateValue = " to_date('" - + toDateValue.substring(0, toDateValue.length()) - + "','DD-MON-YYYY HH24:MI:SS')"; - } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.SQLSERVER)) { - toFormatDateValue = " '" + toDateValue + "'"; - } - } - if (fromDateValue != null - && toDateValue != null - && (fromDateValue.trim().length() > 0 && toDateValue.trim() - .length() > 0)) { - dateConstrain = " AND " + dateColumn + " between " - + fromFormatDateValue + " AND " + toFormatDateValue; - } - - if (fromDateValue != null && fromDateValue.trim().length() > 0) { - dateConstrain = " AND " + dateColumn + " >= " + fromFormatDateValue; - } - if (toDateValue != null && toDateValue.trim().length() > 0) { - dateConstrain = " AND " + dateColumn + " <= " + toFormatDateValue; - } - - return dateConstrain; - - } - - private String buildDateConstrainNew(String fromDateColumn, - String toDateColumn, String fromInclusive, String toInclusive, - String fromDateValue, String toDateValue) { - - String dateConstrain = " "; - String serverType = dataSourceLookup.getServerType(); - String fromFormatDateValue = ""; - String toFormatDateValue = ""; - - if (fromInclusive == null) { - fromInclusive = "yes"; - } - if (toInclusive == null) { - toInclusive = "yes"; - } - if (fromDateValue != null && fromDateValue.trim().length() > 0) { - if (serverType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { - fromFormatDateValue = " to_date('" - + fromDateValue.substring(0, fromDateValue.length()) - + "','DD-MON-YYYY HH24:MI:SS')"; - } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.SQLSERVER)) { - fromFormatDateValue = " '" + fromDateValue + "'"; - } - } - if (toDateValue != null && toDateValue.trim().length() > 0) { - if (serverType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { - toFormatDateValue = " to_date('" - + toDateValue.substring(0, toDateValue.length()) - + "','DD-MON-YYYY HH24:MI:SS')"; - } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.SQLSERVER)) { - toFormatDateValue = " '" + toDateValue + "'"; - } - } - if (fromDateValue != null - && toDateValue != null - && (fromDateValue.trim().length() > 0 && toDateValue.trim() - .length() > 0)) { - if (fromDateColumn.equalsIgnoreCase(toDateColumn) - && fromInclusive.equalsIgnoreCase("yes") - && toInclusive.equalsIgnoreCase("yes")) { - dateConstrain = " AND " + fromDateColumn + " between " - + fromFormatDateValue + " AND " + toFormatDateValue; - return dateConstrain; - } - } - - if (fromDateValue != null && fromDateValue.trim().length() > 0) { - dateConstrain = " AND " + fromDateColumn; - if (fromInclusive.equalsIgnoreCase("yes")) { - dateConstrain += ">=" + fromFormatDateValue; - } else { - dateConstrain += ">" + fromFormatDateValue; - } - - } - if (toDateValue != null && toDateValue.trim().length() > 0) { - dateConstrain += " AND " + toDateColumn; - if (toInclusive.equalsIgnoreCase("yes")) { - dateConstrain += " <= " + toFormatDateValue; - } else { - dateConstrain += " < " + toFormatDateValue; - } - } - - return dateConstrain; - - } - - private ResultEntry[] OrderPanels(ArrayList panelEntries, - ArrayList itemEntries, boolean sameVisit, int specificity) { - try { - Integer firstPanel = -1; - - // first set all inverted panels to one panel - ArrayList invertPanels = new ArrayList(); - Integer minInvert = -1; - - for (int i = 0; i < panelEntries.size(); i++) { - PanelEntry p = (PanelEntry) panelEntries.get(i); - - if (p.Invert == 1) { - invertPanels.add(p.Panel); - - if (minInvert < 0) { - minInvert = p.Panel; - } else if (minInvert > p.Panel) { - minInvert = p.Panel; - } - } - } - - /* - * if (minInvert>=0) { for (int i=0; i= 0) && (invertPanels.contains(t.Panel)) - && (t.Panel != minInvert)) { - t.Panel = minInvert; - } - - if (!v.containsKey(t.Panel)) { - ArrayList vItems = new ArrayList(); - vItems.add(t); - v.put(t.Panel, vItems); - } else { - ArrayList vItems = (ArrayList) v.get(t.Panel); - - if (!vItems.contains(t)) { - vItems.add(t); - } - } - } - - // update panelEntries with the count of items from v - for (int p = 0; p < panelEntries.size(); p++) { - PanelEntry panel = (PanelEntry) panelEntries.get(p); - ArrayList items = (ArrayList) v.get(panel.Panel); - - if (items != null) { - panel.Items = items.size(); - } else { - panel.Items = 0; - } - } - - // now, find first Panel - Comparator comp = new PanelEntryComparator(); - Collections.sort(panelEntries, comp); - ((PanelEntry) panelEntries.get(0)).FirstPanel = 1; - firstPanel = ((PanelEntry) panelEntries.get(0)).Panel; - - int e = 0; - - if (sameVisit) { - // find count of encounter and concept panels - for (Enumeration i = v.keys(); i.hasMoreElements();) { - ArrayList vItems = (ArrayList) v.get(i.nextElement()); - - for (int vi = 0; vi < vItems.size(); vi++) { - ItemEntry t = (ItemEntry) vItems.get(vi); - - if ((t.TableName.equals(CONCEPT_TABLE)) - || (t.TableName.equals(ENCOUNTER_TABLE))) { - e++; - vi = vItems.size(); - } - } - } - } - - // since we're no longer ordering ids by these columns this update - // isn't valid - /* - * itemSql.append("update @v set sqlx = 1 " + "where panel <> @f " + - * "and lower(thetable) = '" + PATIENT_TABLE + "' " + "and - * lower(thefield) in " + - * "('age_in_years_num','vital_status_cd','sex_cd','race_cd','vip_cd') - * \r\n"); - */ - if (e > 1) { - for (Enumeration i = v.keys(); i.hasMoreElements();) { - Integer panel = (Integer) i.nextElement(); - - if (!panel.equals(firstPanel)) { - ArrayList vItems = (ArrayList) v.get(panel); - - for (int vi = 0; vi < vItems.size(); vi++) { - ItemEntry t = (ItemEntry) vItems.get(vi); - - if (t.TableName.equals(ENCOUNTER_TABLE)) { - t.SqlX = 1; - } - } - } - } - } - - // set all short values - // all shorts stands for shortcut values...we can't use shortcuts - // with - // the current database structure - /* - * for (int i=0; i 0) xitems++; - * - * if (p.Items==xitems) p.AllShort = 1; } - * - * if ((p.AllShort==1)||(p.FirstPanel==1)) p.ForInsert = 1; } - */ - comp = new QPanelEntryComparator(); - Collections.sort(panelEntries, comp); - - ArrayList q = new ArrayList(); - - for (int i = 0; i < panelEntries.size(); i++) { - PanelEntry p = (PanelEntry) panelEntries.get(i); - // RAJ comment for panel with not item - // if (p.Items > 0) { - // IdentityPanelEntry ip = new IdentityPanelEntry(p); - // q.add(ip); - // } - IdentityPanelEntry ip = new IdentityPanelEntry(p); - q.add(ip); - } - - ArrayList resultArray = new ArrayList(); - - for (int i = 0; i < q.size(); i++) { - IdentityPanelEntry p = (IdentityPanelEntry) q.get(i); - ArrayList vItems = (ArrayList) v.get(p.OldPanel); - - if (vItems == null) { - resultArray.add(new ResultEntry(e, p, new ItemEntry())); - } else { - for (int vi = 0; vi < vItems.size(); vi++) { - resultArray.add(new ResultEntry(e, p, - ((ItemEntry) vItems.get(vi)))); - } - } - } - - if (specificity > 1) { - comp = new ResultEntryComparator(PATIENT_TABLE, - ENCOUNTER_TABLE, PROVIDER_TABLE); - } else { - comp = new ResultEntryComparator(PATIENT_TABLE, - ENCOUNTER_TABLE, CONCEPT_TABLE); - } - - Collections.sort(resultArray, comp); - - ResultEntry[] rs = new ResultEntry[resultArray.size()]; - - return (ResultEntry[]) resultArray.toArray(rs); - } catch (Exception e) { - log.error(e.getMessage()); - - return null; - } - } - - public class ItemMetaData { - public String QueryTable; - public String QueryColumn; - public String QueryOp; - public String QueryCode; - public String QueryFactTableColumn; - public String QueryColumnDataType; - } - - public enum DatabaseType { - SqlServer, Oracle; - } - - public enum XmlFormat { - RPDR, I2B2; - } - - private PanelEntry callPanelIfNoItem(boolean doInvert, - int totalItemOccurance, String totalItemOccurrenceOperator, - long EstQuerySize, long EstPanelSize, int panelNumber) { - PanelEntry panel = new PanelEntry(); - if (doInvert) { - EstQuerySize = EstQuerySize + (1 - EstPanelSize); - - // EstQuerySize = EstQuerySize * (1 - EstPanelSize); - - panel.Panel = panelNumber; - panel.Invert = 1; - panel.EstPanelSize = (1 - EstPanelSize); - panel.Items = 0; - panel.AllShort = 0; - panel.ForInsert = 0; - panel.FirstPanel = 0; - panel.totalItemOccurrences = totalItemOccurance; - panel.totalItemOccurrencesOperator = totalItemOccurrenceOperator; - - } else { - EstQuerySize = EstQuerySize + EstPanelSize; - - panel.Panel = panelNumber; - panel.Invert = 0; - panel.EstPanelSize = EstPanelSize; - panel.Items = 0; - panel.AllShort = 0; - panel.ForInsert = 0; - panel.FirstPanel = 0; - panel.totalItemOccurrences = totalItemOccurance; - panel.totalItemOccurrencesOperator = totalItemOccurrenceOperator; - - } - return panel; - - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; + +import java.io.IOException; +import java.io.StringReader; +import java.sql.Connection; +import java.sql.ResultSet; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.Enumeration; +import java.util.Hashtable; +import java.util.Iterator; +import java.util.List; + +import javax.xml.datatype.DatatypeFactory; +import javax.xml.datatype.XMLGregorianCalendar; +import javax.xml.transform.stream.StreamSource; + + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.xml.XMLOperatorLookup; +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.dao.pdo.input.DateConstrainHandler; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.ontology.ConceptType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ConstrainOperatorType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ConstrainValueType; +import edu.harvard.i2b2.crc.delegate.ontology.CallOntologyUtil; +import edu.harvard.i2b2.crc.util.SqlClauseUtil; + +/** + * Main class to generate setfinder sql from query definition xml. $Id: + * QueryToolUtil.java,v 1.18 2008/04/18 15:20:51 rk903 Exp $ + * + * @author chris,rkuttan + */ +public class QueryToolUtil extends CRCDAO { + + private SimpleDateFormat dateFormat = new SimpleDateFormat( + "dd-MMM-yyyy HH:mm:ss"); + + DatabaseType dbType = DatabaseType.Oracle; + Connection conn = null; + + // DATABASE VARIABLES + private String FACT_TABLE = "dw_f_conc_noval"; + private String PATIENT_TABLE = "dw_dim_patient"; + private String ENCOUNTER_TABLE = "dw_dim_enct"; + private String CONCEPT_TABLE = "dw_dim_concept"; + private String PROVIDER_TABLE = "dw_dim_provider"; + private String PATIENTLISTS_TABLE = "dw_patientlists"; + private String ENCOUNTER_SHORTCUT_TABLE = "dw_dim_patient_enct"; + private String ENCOUNTER_DIM_ID = "encounter_id_e"; + private String ENCOUNTER_INOUT_COL = "inout_cd"; + private String ENCOUNTER_COMPANY_COL = "company_cd"; + private String ENCOUNTER_START_DATE = "start_date"; + private String ENCOUNTER_PATIENT_ID = "patient_id_e"; + private String CONCEPT_DIM_ID = "c_basecode"; + private String CONCEPT_DIM_PATH = "c_fullname"; + private String PROVIDER_DIM_ID = "c_basecode"; + private String PROVIDER_DIM_PATH = "c_fullname"; + private String PATIENTLISTS_DIM_ID = "patient_id_e"; + private String PATIENTLISTS_DIM_PATH = "filename"; + private String PATIENT_DIM_ID = "patient_id_e"; + private String FACT_VAL_TYPE = "valtype"; + private String FACT_TEXT_VAL = "tval"; + private String FACT_NUM_VAL = "nval"; + private String FACT_FLAG_VAL = "valueflag"; + private String FACT_CONCEPT_RANK = "principal_concept"; + private String FACT_START_DATE = "start_date"; + private String FACT_END_DATE = "end_date"; + private String FACT_ENCOUNTER_ID = "encounter_id_e"; + private String FACT_PATIENT_ID = "patient_id_e"; + private String FACT_CONCEPT_ID = "concept_id"; + private String FACT_PROVIDER_ID = "practitioner_id"; + private String TEMP_TABLE = "#t"; + private String TEMP_TABLE_PATIENT_ID = "patient_num"; + private String TEMP_TABLE_PATIENT_DATATYPE = "varchar(100)"; + private String TEMP_TABLE_ENCOUNTER_ID = "encounter_num"; + private String TEMP_TABLE_ENCOUNTER_DATATYPE = "varchar(100)"; + private String TEMP_PANELCOUNT_DATATYPE = "tinyint"; + private String TEMP_RETURN_TABLE = "#DX"; + private String METADATA_DATABASE = "MetaData_8086"; + private String METADATA_COLUMNNAME = "c_column_name"; + private String METADATA_TABLENAME = "c_table_name"; + private String METADATA_DIMCODE = "c_dim_code"; + private String METADATA_OPERATOR = "c_operator"; + private String METADATA_FULLNAME = "c_fullname"; + + private CallOntologyUtil ontologyUtil = null; + private DataSourceLookup dataSourceLookup = null; + private StringBuffer ignoredItemMessageBuffer = new StringBuffer(); + + public QueryToolUtil() { + SetQueryDatabaseConstants(dbType); + } + + public QueryToolUtil(DataSourceLookup dataSourceLookup) { + this.setDbSchemaName(dataSourceLookup.getFullSchema()); + SetQueryDatabaseConstants(dbType); + this.dataSourceLookup = dataSourceLookup; + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.ORACLE) || dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) { + TEMP_TABLE = "QUERY_GLOBAL_TEMP"; + TEMP_RETURN_TABLE = "DX"; + dateFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss"); + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER)) { + TEMP_TABLE = "#global_temp_table"; + TEMP_RETURN_TABLE = "#dx"; + dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); + } + } + + public String getIgnoredItemMessage() { + if (this.ignoredItemMessageBuffer != null + && this.ignoredItemMessageBuffer.length() > 0) { + return "Missing Concept in Ontology Cell : \n" + + this.ignoredItemMessageBuffer.toString(); + } else { + return ""; + } + + } + + private void SetQueryDatabaseConstants(DatabaseType dbType) { + if (dbType == DatabaseType.SqlServer) { + FACT_TABLE = "dw_f_conc_noval"; + PATIENT_TABLE = "dw_dim_patient"; + ENCOUNTER_TABLE = "dw_dim_enct"; + CONCEPT_TABLE = "dw_dim_concept"; + PROVIDER_TABLE = "dw_dim_provider"; + PATIENTLISTS_TABLE = "dw_patientlists"; + ENCOUNTER_SHORTCUT_TABLE = "dw_dim_patient_enct"; + + ENCOUNTER_DIM_ID = "encounter_id_e"; + ENCOUNTER_INOUT_COL = "inout_cd"; + ENCOUNTER_COMPANY_COL = "company_cd"; + ENCOUNTER_START_DATE = "start_date"; + ENCOUNTER_PATIENT_ID = "patient_id_e"; + + CONCEPT_DIM_ID = "c_basecode"; + CONCEPT_DIM_PATH = "c_fullname"; + + PROVIDER_DIM_ID = "c_basecode"; + PROVIDER_DIM_PATH = "c_fullname"; + + PATIENT_DIM_ID = "patient_id_e"; + + PATIENTLISTS_DIM_ID = "patient_id_e"; + PATIENTLISTS_DIM_PATH = "filename"; + + FACT_VAL_TYPE = "valtype"; + FACT_TEXT_VAL = "tval"; + FACT_NUM_VAL = "nval"; + FACT_FLAG_VAL = "valueflag"; + FACT_CONCEPT_RANK = "principal_concept"; + FACT_START_DATE = "start_date"; + FACT_END_DATE = "end_date"; + FACT_ENCOUNTER_ID = "encounter_id_e"; + FACT_PATIENT_ID = "patient_id_e"; + FACT_CONCEPT_ID = "concept_id"; + FACT_PROVIDER_ID = "practitioner_id"; + + TEMP_TABLE = "#t"; + TEMP_TABLE_PATIENT_ID = "patient_id_e"; + TEMP_TABLE_PATIENT_DATATYPE = "varchar(100)"; + TEMP_TABLE_ENCOUNTER_ID = "encounter_id_e"; + TEMP_TABLE_ENCOUNTER_DATATYPE = "varchar(100)"; + TEMP_PANELCOUNT_DATATYPE = "tinyint"; + TEMP_RETURN_TABLE = "#DX"; + + METADATA_DATABASE = ""; + METADATA_COLUMNNAME = "c_column_name"; + METADATA_TABLENAME = "c_table_name"; + METADATA_DIMCODE = "c_dim_code"; + METADATA_OPERATOR = "c_operator"; + METADATA_FULLNAME = "c_fullname"; + } else if (dbType == DatabaseType.Oracle) { + FACT_TABLE = "observation_fact"; + PATIENT_TABLE = "patient_dimension"; + ENCOUNTER_TABLE = "visit_dimension"; + CONCEPT_TABLE = "concept_dimension"; + PROVIDER_TABLE = "provider_dimension"; + PATIENTLISTS_TABLE = "dw_patientlists"; // not sure on this yet + ENCOUNTER_SHORTCUT_TABLE = "visit_dimension"; + + ENCOUNTER_DIM_ID = "encounter_num"; + ENCOUNTER_INOUT_COL = "inout_cd"; + ENCOUNTER_COMPANY_COL = "location_cd"; + ENCOUNTER_START_DATE = "start_date"; + ENCOUNTER_PATIENT_ID = "patient_num"; + + CONCEPT_DIM_ID = "concept_cd"; + CONCEPT_DIM_PATH = "concept_path"; + + PROVIDER_DIM_ID = "provider_id"; + PROVIDER_DIM_PATH = "provider_path"; + + PATIENT_DIM_ID = "patient_num"; + + PATIENTLISTS_DIM_ID = "patient_id_e"; // ?? + PATIENTLISTS_DIM_PATH = "filename"; // ?? + + FACT_VAL_TYPE = "valtype_cd"; + FACT_TEXT_VAL = "tval_char"; + FACT_NUM_VAL = "nval_num"; + FACT_FLAG_VAL = "valueflag_cd"; + FACT_CONCEPT_RANK = "modifier_cd"; + FACT_START_DATE = "start_date"; + FACT_END_DATE = "end_date"; + FACT_ENCOUNTER_ID = "encounter_num"; + FACT_PATIENT_ID = "patient_num"; + FACT_CONCEPT_ID = "concept_cd"; + FACT_PROVIDER_ID = "provider_id"; + + TEMP_TABLE = "QUERY_GLOBAL_TEMP"; + TEMP_TABLE_PATIENT_ID = "patient_num"; + TEMP_TABLE_PATIENT_DATATYPE = "number(22,0)"; + TEMP_TABLE_ENCOUNTER_ID = "encounter_num"; + TEMP_TABLE_ENCOUNTER_DATATYPE = "number(22,0)"; + TEMP_PANELCOUNT_DATATYPE = "number(5)"; + TEMP_RETURN_TABLE = "DX"; + + // METADATA_DATABASE = "MetaData"; + // METADATA_DATABASE = "MetaData_8086"; + METADATA_COLUMNNAME = "c_columnname"; + METADATA_TABLENAME = "c_tablename"; + METADATA_DIMCODE = "c_dimcode"; + METADATA_OPERATOR = "c_operator"; + METADATA_FULLNAME = "c_fullname"; + } + } + + protected long GetEstimatedSize(Connection conn, String theTableName, + String theColumnName, String theOperator, String theData, + long DBNumPatients) { + long EstSize = 0; + String sql = ""; + + try { + if (theTableName.equals(CONCEPT_TABLE)) { + sql = "select sum(n.patient_count) n " + + "from rpdrconceptlookup n " + "where table_name = '" + + FACT_TABLE + "' " + "and column_name = '" + + FACT_CONCEPT_ID + "'" + "and concept_t_value in " + + "(select " + CONCEPT_DIM_ID + " from " + "" + + CONCEPT_TABLE + " c " + "where " + CONCEPT_DIM_PATH + + " " + theOperator + " " + theData + ")"; + + java.sql.Statement st1 = conn.createStatement(); + ResultSet rs = st1.executeQuery(sql); + + if (rs.next()) { + EstSize = rs.getLong("n"); + } + + rs.close(); + st1.close(); + } else if (theTableName.equals(PROVIDER_TABLE)) { + sql = "select sum(n.patient_count) n " + + "from rpdrconceptlookup n " + "where table_name = '" + + FACT_TABLE + "' " + "and column_name = '" + + FACT_PROVIDER_ID + "'" + "and concept_t_value in " + + "(select " + PROVIDER_DIM_ID + " " + "from " + + PROVIDER_TABLE + " c " + "where " + PROVIDER_DIM_PATH + + " " + theOperator + " " + theData + ")"; + + java.sql.Statement st1 = conn.createStatement(); + ResultSet rs = st1.executeQuery(sql); + + if (rs.next()) { + EstSize = rs.getLong("n"); + } + + rs.close(); + st1.close(); + } else if (theTableName.equals(ENCOUNTER_TABLE)) { + sql = "select sum(n.patient_count) n " + + "from rpdrconceptlookup n " + "where table_name = '" + + ENCOUNTER_TABLE + "' " + "and column_name = '" + + theColumnName + "' " + "and concept_t_value " + + theOperator + " " + theData; + + java.sql.Statement st1 = conn.createStatement(); + ResultSet rs = st1.executeQuery(sql); + + if (rs.next()) { + EstSize = rs.getLong("n"); + } + + rs.close(); + st1.close(); + } else if (theTableName.equals(PATIENT_TABLE)) { + if (theColumnName.equals("age_in_years_num")) { + sql = "select sum(n.patient_count) n " + + "from rpdrconceptlookup n " + + "where table_name = '" + PATIENT_TABLE + "' " + + "and column_name = '" + theColumnName + "' " + + "and concept_n_value " + theOperator + " " + + theData; + } else { + sql = "select sum(n.patient_count) n " + + "from rpdrconceptlookup n " + + "where table_name = '" + PATIENT_TABLE + "' " + + "and column_name = '" + theColumnName + "' " + + "and concept_t_value " + theOperator + " " + + theData; + } + + java.sql.Statement st1 = conn.createStatement(); + ResultSet rs = st1.executeQuery(sql); + + if (rs.next()) { + EstSize = rs.getLong("n"); + } + + rs.close(); + st1.close(); + } else { + EstSize = 1; + } + } catch (Exception e) { + log.error("Unable to get Estimated Size: " + e.getMessage()); + } + + return EstSize; + } + + private String buildDateConstrain(String dateColumn, String fromDateValue, + String toDateValue) { + + String dateConstrain = " "; + String serverType = dataSourceLookup.getServerType(); + String fromFormatDateValue = ""; + String toFormatDateValue = ""; + if (fromDateValue != null && fromDateValue.trim().length() > 0) { + if (serverType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { + fromFormatDateValue = " to_date('" + + fromDateValue.substring(0, fromDateValue.length()) + + "','DD-MON-YYYY HH24:MI:SS')"; + } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.SQLSERVER)) { + fromFormatDateValue = " '" + fromDateValue + "'"; + } + } + if (toDateValue != null && toDateValue.trim().length() > 0) { + if (serverType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { + toFormatDateValue = " to_date('" + + toDateValue.substring(0, toDateValue.length()) + + "','DD-MON-YYYY HH24:MI:SS')"; + } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.SQLSERVER)) { + toFormatDateValue = " '" + toDateValue + "'"; + } + } + if (fromDateValue != null + && toDateValue != null + && (fromDateValue.trim().length() > 0 && toDateValue.trim() + .length() > 0)) { + dateConstrain = " AND " + dateColumn + " between " + + fromFormatDateValue + " AND " + toFormatDateValue; + } + + if (fromDateValue != null && fromDateValue.trim().length() > 0) { + dateConstrain = " AND " + dateColumn + " >= " + fromFormatDateValue; + } + if (toDateValue != null && toDateValue.trim().length() > 0) { + dateConstrain = " AND " + dateColumn + " <= " + toFormatDateValue; + } + + return dateConstrain; + + } + + private String buildDateConstrainNew(String fromDateColumn, + String toDateColumn, String fromInclusive, String toInclusive, + String fromDateValue, String toDateValue) { + + String dateConstrain = " "; + String serverType = dataSourceLookup.getServerType(); + String fromFormatDateValue = ""; + String toFormatDateValue = ""; + + if (fromInclusive == null) { + fromInclusive = "yes"; + } + if (toInclusive == null) { + toInclusive = "yes"; + } + if (fromDateValue != null && fromDateValue.trim().length() > 0) { + if (serverType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { + fromFormatDateValue = " to_date('" + + fromDateValue.substring(0, fromDateValue.length()) + + "','DD-MON-YYYY HH24:MI:SS')"; + } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.SQLSERVER)) { + fromFormatDateValue = " '" + fromDateValue + "'"; + } + } + if (toDateValue != null && toDateValue.trim().length() > 0) { + if (serverType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { + toFormatDateValue = " to_date('" + + toDateValue.substring(0, toDateValue.length()) + + "','DD-MON-YYYY HH24:MI:SS')"; + } else if (serverType.equalsIgnoreCase(DAOFactoryHelper.SQLSERVER)) { + toFormatDateValue = " '" + toDateValue + "'"; + } + } + if (fromDateValue != null + && toDateValue != null + && (fromDateValue.trim().length() > 0 && toDateValue.trim() + .length() > 0)) { + if (fromDateColumn.equalsIgnoreCase(toDateColumn) + && fromInclusive.equalsIgnoreCase("yes") + && toInclusive.equalsIgnoreCase("yes")) { + dateConstrain = " AND " + fromDateColumn + " between " + + fromFormatDateValue + " AND " + toFormatDateValue; + return dateConstrain; + } + } + + if (fromDateValue != null && fromDateValue.trim().length() > 0) { + dateConstrain = " AND " + fromDateColumn; + if (fromInclusive.equalsIgnoreCase("yes")) { + dateConstrain += ">=" + fromFormatDateValue; + } else { + dateConstrain += ">" + fromFormatDateValue; + } + + } + if (toDateValue != null && toDateValue.trim().length() > 0) { + dateConstrain += " AND " + toDateColumn; + if (toInclusive.equalsIgnoreCase("yes")) { + dateConstrain += " <= " + toFormatDateValue; + } else { + dateConstrain += " < " + toFormatDateValue; + } + } + + return dateConstrain; + + } + + private ResultEntry[] OrderPanels(ArrayList panelEntries, + ArrayList itemEntries, boolean sameVisit, int specificity) { + try { + Integer firstPanel = -1; + + // first set all inverted panels to one panel + ArrayList invertPanels = new ArrayList(); + Integer minInvert = -1; + + for (int i = 0; i < panelEntries.size(); i++) { + PanelEntry p = (PanelEntry) panelEntries.get(i); + + if (p.Invert == 1) { + invertPanels.add(p.Panel); + + if (minInvert < 0) { + minInvert = p.Panel; + } else if (minInvert > p.Panel) { + minInvert = p.Panel; + } + } + } + + /* + * if (minInvert>=0) { for (int i=0; i= 0) && (invertPanels.contains(t.Panel)) + && (t.Panel != minInvert)) { + t.Panel = minInvert; + } + + if (!v.containsKey(t.Panel)) { + ArrayList vItems = new ArrayList(); + vItems.add(t); + v.put(t.Panel, vItems); + } else { + ArrayList vItems = (ArrayList) v.get(t.Panel); + + if (!vItems.contains(t)) { + vItems.add(t); + } + } + } + + // update panelEntries with the count of items from v + for (int p = 0; p < panelEntries.size(); p++) { + PanelEntry panel = (PanelEntry) panelEntries.get(p); + ArrayList items = (ArrayList) v.get(panel.Panel); + + if (items != null) { + panel.Items = items.size(); + } else { + panel.Items = 0; + } + } + + // now, find first Panel + Comparator comp = new PanelEntryComparator(); + Collections.sort(panelEntries, comp); + ((PanelEntry) panelEntries.get(0)).FirstPanel = 1; + firstPanel = ((PanelEntry) panelEntries.get(0)).Panel; + + int e = 0; + + if (sameVisit) { + // find count of encounter and concept panels + for (Enumeration i = v.keys(); i.hasMoreElements();) { + ArrayList vItems = (ArrayList) v.get(i.nextElement()); + + for (int vi = 0; vi < vItems.size(); vi++) { + ItemEntry t = (ItemEntry) vItems.get(vi); + + if ((t.TableName.equals(CONCEPT_TABLE)) + || (t.TableName.equals(ENCOUNTER_TABLE))) { + e++; + vi = vItems.size(); + } + } + } + } + + // since we're no longer ordering ids by these columns this update + // isn't valid + /* + * itemSql.append("update @v set sqlx = 1 " + "where panel <> @f " + + * "and lower(thetable) = '" + PATIENT_TABLE + "' " + "and + * lower(thefield) in " + + * "('age_in_years_num','vital_status_cd','sex_cd','race_cd','vip_cd') + * \r\n"); + */ + if (e > 1) { + for (Enumeration i = v.keys(); i.hasMoreElements();) { + Integer panel = (Integer) i.nextElement(); + + if (!panel.equals(firstPanel)) { + ArrayList vItems = (ArrayList) v.get(panel); + + for (int vi = 0; vi < vItems.size(); vi++) { + ItemEntry t = (ItemEntry) vItems.get(vi); + + if (t.TableName.equals(ENCOUNTER_TABLE)) { + t.SqlX = 1; + } + } + } + } + } + + // set all short values + // all shorts stands for shortcut values...we can't use shortcuts + // with + // the current database structure + /* + * for (int i=0; i 0) xitems++; + * + * if (p.Items==xitems) p.AllShort = 1; } + * + * if ((p.AllShort==1)||(p.FirstPanel==1)) p.ForInsert = 1; } + */ + comp = new QPanelEntryComparator(); + Collections.sort(panelEntries, comp); + + ArrayList q = new ArrayList(); + + for (int i = 0; i < panelEntries.size(); i++) { + PanelEntry p = (PanelEntry) panelEntries.get(i); + // RAJ comment for panel with not item + // if (p.Items > 0) { + // IdentityPanelEntry ip = new IdentityPanelEntry(p); + // q.add(ip); + // } + IdentityPanelEntry ip = new IdentityPanelEntry(p); + q.add(ip); + } + + ArrayList resultArray = new ArrayList(); + + for (int i = 0; i < q.size(); i++) { + IdentityPanelEntry p = (IdentityPanelEntry) q.get(i); + ArrayList vItems = (ArrayList) v.get(p.OldPanel); + + if (vItems == null) { + resultArray.add(new ResultEntry(e, p, new ItemEntry())); + } else { + for (int vi = 0; vi < vItems.size(); vi++) { + resultArray.add(new ResultEntry(e, p, + ((ItemEntry) vItems.get(vi)))); + } + } + } + + if (specificity > 1) { + comp = new ResultEntryComparator(PATIENT_TABLE, + ENCOUNTER_TABLE, PROVIDER_TABLE); + } else { + comp = new ResultEntryComparator(PATIENT_TABLE, + ENCOUNTER_TABLE, CONCEPT_TABLE); + } + + Collections.sort(resultArray, comp); + + ResultEntry[] rs = new ResultEntry[resultArray.size()]; + + return (ResultEntry[]) resultArray.toArray(rs); + } catch (Exception e) { + log.error(e.getMessage()); + + return null; + } + } + + public class ItemMetaData { + public String QueryTable; + public String QueryColumn; + public String QueryOp; + public String QueryCode; + public String QueryFactTableColumn; + public String QueryColumnDataType; + } + + public enum DatabaseType { + SqlServer, Oracle; + } + + public enum XmlFormat { + RPDR, I2B2; + } + + private PanelEntry callPanelIfNoItem(boolean doInvert, + int totalItemOccurance, String totalItemOccurrenceOperator, + long EstQuerySize, long EstPanelSize, int panelNumber) { + PanelEntry panel = new PanelEntry(); + if (doInvert) { + EstQuerySize = EstQuerySize + (1 - EstPanelSize); + + // EstQuerySize = EstQuerySize * (1 - EstPanelSize); + + panel.Panel = panelNumber; + panel.Invert = 1; + panel.EstPanelSize = (1 - EstPanelSize); + panel.Items = 0; + panel.AllShort = 0; + panel.ForInsert = 0; + panel.FirstPanel = 0; + panel.totalItemOccurrences = totalItemOccurance; + panel.totalItemOccurrencesOperator = totalItemOccurrenceOperator; + + } else { + EstQuerySize = EstQuerySize + EstPanelSize; + + panel.Panel = panelNumber; + panel.Invert = 0; + panel.EstPanelSize = EstPanelSize; + panel.Items = 0; + panel.AllShort = 0; + panel.ForInsert = 0; + panel.FirstPanel = 0; + panel.totalItemOccurrences = totalItemOccurance; + panel.totalItemOccurrencesOperator = totalItemOccurrenceOperator; + + } + return panel; + + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/QueryToolUtilNew.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/QueryToolUtilNew.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/QueryToolUtilNew.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/QueryToolUtilNew.java index 30a5d408..9ec328ed --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/QueryToolUtilNew.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/QueryToolUtilNew.java @@ -1,368 +1,368 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc. dao.setfinder.querybuilder; - - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import jakarta.xml.bind.JAXBElement; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.PanelType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionType; -import edu.harvard.i2b2.crc.util.LogTimingUtil; -import edu.harvard.i2b2.crc.util.PMServiceAccountUtil; - -public class QueryToolUtilNew extends CRCDAO { - - DataSourceLookup dataSourceLookup = null; - String queryXML = null; - String noLockSqlServer = " "; - String tempTableName = " ", tempDxTableName = " "; - StringBuffer ignoredItemMessageBuffer = new StringBuffer(); - boolean encounterSetOutputFlag = false; - int maxPanelNum = 0; - ProcessTimingReportUtil processTimingUtil = null; - String processTimingFlag = ProcessTimingReportUtil.NONE; - Map projectParamMap = null; - StringBuffer processTimingStr = new StringBuffer(); - boolean allowLargeTextValueConstrainFlag = true; - - - public QueryToolUtilNew(DataSourceLookup dataSourceLookup, String queryXML, - boolean encounterSetOutputFlag) { - this.setDbSchemaName(dataSourceLookup.getFullSchema()); - this.dataSourceLookup = dataSourceLookup; - this.queryXML = queryXML; - this.encounterSetOutputFlag = encounterSetOutputFlag; - try { - this.processTimingUtil = new ProcessTimingReportUtil(dataSourceLookup); - } catch (I2B2DAOException e) { - log.error("Error creating ProcessTimingReportUtil [" + e.getMessage() + "]"); - } - - if (this.dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER)) { - noLockSqlServer = " WITH(NOLOCK) "; - tempTableName = "#global_temp_table"; - tempDxTableName = "#dx"; - } else if (this.dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE) || this.dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) { - tempTableName = "QUERY_GLOBAL_TEMP"; - tempDxTableName = "DX"; - } - - - } - - public int getMaxPanelNumber() { - return maxPanelNum; - } - - public void setProcessTimingFlag(String level) { - this.processTimingFlag = level; - } - - public void setProjectParamMap(Map projectParamMap) { - this.projectParamMap = projectParamMap; - } - - public String getProcessTimingMessage() { - return this.processTimingStr.toString(); - } - - public void setAllowLargeTextValueConstrainFlag(boolean allowLargeTextValueConstrainFlag) { - this.allowLargeTextValueConstrainFlag = allowLargeTextValueConstrainFlag; - } - - - - public String getSetfinderSqlForQueryDefinition() throws JAXBUtilException, I2B2Exception { - StringBuffer setfinderSql = new StringBuffer(); - QueryDefinitionUnWrapUtil queryDefUnWrapHelper = new QueryDefinitionUnWrapUtil(); - - QueryDefinitionType queryDefType = queryDefUnWrapHelper - .getQueryDefinitionType(this.queryXML); - - - - boolean invertFlag = isInvert(queryDefType); - boolean onlyInvertFlag = isOnlyInvert(queryDefType); - if (onlyInvertFlag) { - BuildInvertSql buildInvertSql = new BuildInvertSql(dataSourceLookup, this - .getTempTableName()); - setfinderSql.append(buildInvertSql.buildInsertInvertSql(queryDefType.getQueryTiming())); - } - // sort the panel - /* - CallOntologyUtil ontologyUtil = null; - try { - ontologyUtil = new CallOntologyUtil(queryXML); - } catch (JAXBUtilException e) { - throw new I2B2DAOException("Error in reading the request xml " - + queryXML + StackTraceUtil.getStackTrace(e)); - } catch (I2B2Exception e) { - throw new I2B2DAOException("Error in reading the request xml " - + queryXML + StackTraceUtil.getStackTrace(e)); - } - */ - - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil() - .unMashallFromString(queryXML); - RequestMessageType request = (RequestMessageType) responseJaxb - .getValue(); - String projectId = request.getMessageHeader().getProjectId(); - SecurityType tempSecurityType = request.getMessageHeader() - .getSecurity(); - SecurityType securityType = PMServiceAccountUtil - .getServiceSecurityType(tempSecurityType.getDomain()); - - //if query timing is null, then take the timing from panel timing - String queryTimingVal = queryDefType.getQueryTiming(); - if (queryDefType.getQueryTiming() == null) { - CalulateQueryTiming calculateTiming = new CalulateQueryTiming(); - String calcQueryTiming = calculateTiming.getQueryTiming(queryDefType.getPanel()); - queryDefType.setQueryTiming(calcQueryTiming); - queryTimingVal = calcQueryTiming; - } - - // group panels by the timing(query_timing & panel_timing) - GroupPanelByTiming grpPanelTiming = new GroupPanelByTiming(); - Map> grpPanelByTimingMap = grpPanelTiming - .groupPanelByTiming(queryDefType.getPanel(), queryDefType - .getQueryTiming()); - - - - Map possibleMap = new HashMap(); - possibleMap.put("ANY", "SAME:SAMEVISIT:SAMEINSTANCENUM"); - possibleMap.put("SAMEVISIT", "SAMEINSTANCENUM"); - possibleMap.put("SAME", "SAMEINSTANCENUM"); - possibleMap.put("SAMEINSTANCENUM", ""); - - String panelTiming = ""; - String validPanelTiming = possibleMap.get(queryTimingVal); - String[] valueList = validPanelTiming.split(":"); - List valList = Arrays.asList(valueList); - for (Iterator i = grpPanelByTimingMap.keySet().iterator();i.hasNext();) { - panelTiming = i.next(); - List pl = grpPanelByTimingMap.get(panelTiming); - if (pl.size() == 0) { - continue; - } - - log.debug("Checking for valid query timing [" + queryTimingVal + "] with panel timing [" + panelTiming + "]"); - - - if (valList.indexOf(panelTiming)>-1) { - throw new I2B2DAOException("Query timing ["+ queryTimingVal +"] and panel timing [" + panelTiming +"] is not valid"); - } - } - - - QueryTimingHandler queryTiming = new QueryTimingHandler(); - boolean encounterFlag = queryTiming.isSameVisit(queryDefType); - boolean instanceNumFlag = queryTiming.isSameInstanceNum(queryDefType); - - String[] timingOrder = new String[] { - QueryTimingHandler.SAMEINSTANCENUM, - QueryTimingHandler.SAMEVISIT, QueryTimingHandler.ANY }; - List groupedPanelList = null; - - - boolean firstPanelFlag = true; - - Map> invertGroupPanelByTimingMap = grpPanelTiming.filterByExcludeFlag(grpPanelByTimingMap,true); - Map> nonInvertGroupPanelByTimingMap = grpPanelTiming.filterByExcludeFlag(grpPanelByTimingMap,false); - ArrayList>> t = new ArrayList>>(); - if (nonInvertGroupPanelByTimingMap.size() > 0) { - t.add(nonInvertGroupPanelByTimingMap); - } - t.add(invertGroupPanelByTimingMap); - - String firstItemJoinTiming = calculateFirstItemJoin(timingOrder,invertGroupPanelByTimingMap, nonInvertGroupPanelByTimingMap); - - for (Map> panelGroupByInvertList : t) { - for (int k = 0; k < timingOrder.length; k++) { - groupedPanelList = panelGroupByInvertList.get(timingOrder[k]); - - - if (groupedPanelList != null && groupedPanelList.size()>0) { - if (timingOrder[k] - .equalsIgnoreCase(QueryTimingHandler.SAMEINSTANCENUM)) { - instanceNumFlag = true; - encounterFlag = false; - } else if (timingOrder[k] - .equalsIgnoreCase(QueryTimingHandler.SAMEVISIT)) { - encounterFlag = true; - instanceNumFlag = false; - } else if (timingOrder[k] - .equalsIgnoreCase(QueryTimingHandler.ANY)) { - encounterFlag = false; - instanceNumFlag = false; - } - log.debug("setfinder panel size for ["+ timingOrder[k] + "] timins is " + groupedPanelList.size()); - Map panelSql = generateSqlForGroupedPanelList( - groupedPanelList, queryDefType, securityType, projectId, - encounterFlag, instanceNumFlag, maxPanelNum, - firstPanelFlag, invertFlag, onlyInvertFlag,firstItemJoinTiming); - firstPanelFlag = false; - for (Integer key : panelSql.keySet()) { - setfinderSql.append(panelSql.get(key)); - // setfinderSql.append(getSqlDelimitor()); - // panelSql.remove(key); - // maxPanelNum = key; - } - maxPanelNum = maxPanelNum + groupedPanelList.size(); - panelSql.clear(); - - } - } - } - - - // call build dx temp table insert sql - DxTableHandler dxTableHandler = new DxTableHandler(this - .getDbSchemaName(), this.getTempDxTableName(), this - .getTempTableName()); - String dxTempTableSql = dxTableHandler.buildDxInsertSql( - encounterFlag, instanceNumFlag, maxPanelNum); - - setfinderSql.append(dxTempTableSql); - log.debug(setfinderSql.toString()); - return setfinderSql.toString(); - - } - - private Map generateSqlForGroupedPanelList( - List panelList, QueryDefinitionType queryDefType, - SecurityType securityType, String projectId, boolean encounterFlag, - boolean instanceNumFlag, int panelCount, boolean firstPanelFlag, boolean invertQueryFlag, boolean invertOnlyQueryFlag, - String firstItemJoinTiming) - throws I2B2Exception { - SortPanel sortPanel = new SortPanel(); - LogTimingUtil timingUtil = new LogTimingUtil(); - timingUtil.setStartTime(); - List sortedPanelList = sortPanel.sortedPanelList(panelList, - securityType, projectId); - timingUtil.setEndTime(); - //build the log xml and add it to the string variable. - this.processTimingStr.append(this.processTimingUtil.buildProcessTiming(timingUtil, "SORT PANEL", null)); - - BuildTempTableSql tempTableSql = new BuildTempTableSql( - dataSourceLookup, queryXML); - tempTableSql.setProjectParamMap(projectParamMap); - tempTableSql.setAllowLargeTextValueConstrainFlag(this.allowLargeTextValueConstrainFlag); - - // build sql for each panel - Map panelSql = tempTableSql.buildTempTableSql( - sortedPanelList, encounterFlag, instanceNumFlag, queryDefType - .getQueryTiming(), panelCount, firstPanelFlag, invertQueryFlag, invertOnlyQueryFlag,firstItemJoinTiming); - this.processTimingStr.append("\n"); - this.processTimingStr.append(tempTableSql.getProcessTimingXml()); - - // store ignored item message to buffer - this.ignoredItemMessageBuffer.append(tempTableSql - .getIgnoredItemMessage()); - - return panelSql; - - } - - private boolean isInvert(QueryDefinitionType queryDefType) { - List panelList = queryDefType.getPanel(); - - for (PanelType panelType : panelList) { - if (panelType.getInvert() == 1) { - return true; - } - } - return false; - } - - private boolean isOnlyInvert(QueryDefinitionType queryDefType) { - List panelList = queryDefType.getPanel(); - - for (PanelType panelType : panelList) { - if (panelType.getInvert() != 1) { - return false; - } - } - return true; - } - - - /** - * Return the ignored item list - * - * @return - */ - public String getIgnoredItemMessage() { - if (this.ignoredItemMessageBuffer != null - && this.ignoredItemMessageBuffer.length() > 0) { - return "Missing Concept in Ontology Cell : \n" - + this.ignoredItemMessageBuffer.toString(); - } else { - return ""; - } - - } - - private String getTempTableName() { - - return this.tempTableName; - } - - private String getTempDxTableName() { - return this.tempDxTableName; - } - - private String calculateFirstItemJoin(String[] timingOrder,Map> invertGroupPanelByTimingMap,Map> nonInvertGroupPanelByTimingMap) { - String invertTiming = "ANY", nonInvertTiming = "ANY", firstItemJoinTiming = "ANY"; - for (int i=0;i> grpPanelByTimingMap = grpPanelTiming + .groupPanelByTiming(queryDefType.getPanel(), queryDefType + .getQueryTiming()); + + + + Map possibleMap = new HashMap(); + possibleMap.put("ANY", "SAME:SAMEVISIT:SAMEINSTANCENUM"); + possibleMap.put("SAMEVISIT", "SAMEINSTANCENUM"); + possibleMap.put("SAME", "SAMEINSTANCENUM"); + possibleMap.put("SAMEINSTANCENUM", ""); + + String panelTiming = ""; + String validPanelTiming = possibleMap.get(queryTimingVal); + String[] valueList = validPanelTiming.split(":"); + List valList = Arrays.asList(valueList); + for (Iterator i = grpPanelByTimingMap.keySet().iterator();i.hasNext();) { + panelTiming = i.next(); + List pl = grpPanelByTimingMap.get(panelTiming); + if (pl.size() == 0) { + continue; + } + + log.debug("Checking for valid query timing [" + queryTimingVal + "] with panel timing [" + panelTiming + "]"); + + + if (valList.indexOf(panelTiming)>-1) { + throw new I2B2DAOException("Query timing ["+ queryTimingVal +"] and panel timing [" + panelTiming +"] is not valid"); + } + } + + + QueryTimingHandler queryTiming = new QueryTimingHandler(); + boolean encounterFlag = queryTiming.isSameVisit(queryDefType); + boolean instanceNumFlag = queryTiming.isSameInstanceNum(queryDefType); + + String[] timingOrder = new String[] { + QueryTimingHandler.SAMEINSTANCENUM, + QueryTimingHandler.SAMEVISIT, QueryTimingHandler.ANY }; + List groupedPanelList = null; + + + boolean firstPanelFlag = true; + + Map> invertGroupPanelByTimingMap = grpPanelTiming.filterByExcludeFlag(grpPanelByTimingMap,true); + Map> nonInvertGroupPanelByTimingMap = grpPanelTiming.filterByExcludeFlag(grpPanelByTimingMap,false); + ArrayList>> t = new ArrayList>>(); + if (nonInvertGroupPanelByTimingMap.size() > 0) { + t.add(nonInvertGroupPanelByTimingMap); + } + t.add(invertGroupPanelByTimingMap); + + String firstItemJoinTiming = calculateFirstItemJoin(timingOrder,invertGroupPanelByTimingMap, nonInvertGroupPanelByTimingMap); + + for (Map> panelGroupByInvertList : t) { + for (int k = 0; k < timingOrder.length; k++) { + groupedPanelList = panelGroupByInvertList.get(timingOrder[k]); + + + if (groupedPanelList != null && groupedPanelList.size()>0) { + if (timingOrder[k] + .equalsIgnoreCase(QueryTimingHandler.SAMEINSTANCENUM)) { + instanceNumFlag = true; + encounterFlag = false; + } else if (timingOrder[k] + .equalsIgnoreCase(QueryTimingHandler.SAMEVISIT)) { + encounterFlag = true; + instanceNumFlag = false; + } else if (timingOrder[k] + .equalsIgnoreCase(QueryTimingHandler.ANY)) { + encounterFlag = false; + instanceNumFlag = false; + } + log.debug("setfinder panel size for ["+ timingOrder[k] + "] timins is " + groupedPanelList.size()); + Map panelSql = generateSqlForGroupedPanelList( + groupedPanelList, queryDefType, securityType, projectId, + encounterFlag, instanceNumFlag, maxPanelNum, + firstPanelFlag, invertFlag, onlyInvertFlag,firstItemJoinTiming); + firstPanelFlag = false; + for (Integer key : panelSql.keySet()) { + setfinderSql.append(panelSql.get(key)); + // setfinderSql.append(getSqlDelimitor()); + // panelSql.remove(key); + // maxPanelNum = key; + } + maxPanelNum = maxPanelNum + groupedPanelList.size(); + panelSql.clear(); + + } + } + } + + + // call build dx temp table insert sql + DxTableHandler dxTableHandler = new DxTableHandler(this + .getDbSchemaName(), this.getTempDxTableName(), this + .getTempTableName()); + String dxTempTableSql = dxTableHandler.buildDxInsertSql( + encounterFlag, instanceNumFlag, maxPanelNum); + + setfinderSql.append(dxTempTableSql); + log.debug(setfinderSql.toString()); + return setfinderSql.toString(); + + } + + private Map generateSqlForGroupedPanelList( + List panelList, QueryDefinitionType queryDefType, + SecurityType securityType, String projectId, boolean encounterFlag, + boolean instanceNumFlag, int panelCount, boolean firstPanelFlag, boolean invertQueryFlag, boolean invertOnlyQueryFlag, + String firstItemJoinTiming) + throws I2B2Exception { + SortPanel sortPanel = new SortPanel(); + LogTimingUtil timingUtil = new LogTimingUtil(); + timingUtil.setStartTime(); + List sortedPanelList = sortPanel.sortedPanelList(panelList, + securityType, projectId); + timingUtil.setEndTime(); + //build the log xml and add it to the string variable. + this.processTimingStr.append(this.processTimingUtil.buildProcessTiming(timingUtil, "SORT PANEL", null)); + + BuildTempTableSql tempTableSql = new BuildTempTableSql( + dataSourceLookup, queryXML); + tempTableSql.setProjectParamMap(projectParamMap); + tempTableSql.setAllowLargeTextValueConstrainFlag(this.allowLargeTextValueConstrainFlag); + + // build sql for each panel + Map panelSql = tempTableSql.buildTempTableSql( + sortedPanelList, encounterFlag, instanceNumFlag, queryDefType + .getQueryTiming(), panelCount, firstPanelFlag, invertQueryFlag, invertOnlyQueryFlag,firstItemJoinTiming); + this.processTimingStr.append("\n"); + this.processTimingStr.append(tempTableSql.getProcessTimingXml()); + + // store ignored item message to buffer + this.ignoredItemMessageBuffer.append(tempTableSql + .getIgnoredItemMessage()); + + return panelSql; + + } + + private boolean isInvert(QueryDefinitionType queryDefType) { + List panelList = queryDefType.getPanel(); + + for (PanelType panelType : panelList) { + if (panelType.getInvert() == 1) { + return true; + } + } + return false; + } + + private boolean isOnlyInvert(QueryDefinitionType queryDefType) { + List panelList = queryDefType.getPanel(); + + for (PanelType panelType : panelList) { + if (panelType.getInvert() != 1) { + return false; + } + } + return true; + } + + + /** + * Return the ignored item list + * + * @return + */ + public String getIgnoredItemMessage() { + if (this.ignoredItemMessageBuffer != null + && this.ignoredItemMessageBuffer.length() > 0) { + return "Missing Concept in Ontology Cell : \n" + + this.ignoredItemMessageBuffer.toString(); + } else { + return ""; + } + + } + + private String getTempTableName() { + + return this.tempTableName; + } + + private String getTempDxTableName() { + return this.tempDxTableName; + } + + private String calculateFirstItemJoin(String[] timingOrder,Map> invertGroupPanelByTimingMap,Map> nonInvertGroupPanelByTimingMap) { + String invertTiming = "ANY", nonInvertTiming = "ANY", firstItemJoinTiming = "ANY"; + for (int i=0;i masterIdLIFO = new ArrayList(); - private DataSourceLookup dataSourceLookup = null; - private String queryXML = null; - private boolean encounterSetOutputFlag = false; - private TempTableNameMap tempTableNameMap = null; - private StringBuffer processTimingMessageBuffer = new StringBuffer(); - private Map projectParamMap = null; - private String processTimingFlag = ""; - private boolean allowLargeTextValueConstrainFlag = true; - - - - - public RecursiveBuild(DataSourceLookup dataSourceLookup, String queryXML, - boolean encounterSetOutputFlag) { - this.dataSourceLookup = dataSourceLookup; - this.queryXML = queryXML; - this.encounterSetOutputFlag = encounterSetOutputFlag; - this.setDbSchemaName(dataSourceLookup.getFullSchema()); - tempTableNameMap = new TempTableNameMap(dataSourceLookup.getServerType()); - } - - - - - public String getProcessTimingMessage() { - return this.processTimingMessageBuffer.toString(); - } - - public void setProjectParamMap(Map projectParamMap) { - this.projectParamMap = projectParamMap; - if (projectParamMap != null && projectParamMap.get(ParamUtil.PM_ENABLE_PROCESS_TIMING) != null) { - this.processTimingFlag = (String)projectParamMap.get(ParamUtil.PM_ENABLE_PROCESS_TIMING); - } - } - - public void setAllowLargeTextValueConstrainFlag(boolean allowLargeTextValueConstrainFlag) { - this.allowLargeTextValueConstrainFlag = allowLargeTextValueConstrainFlag; - } - - - public Map getProjectParamMap() { - return this.projectParamMap; - } - - - - private QueryDefinitionType getQueryDefinitionType(String requestString) throws I2B2DAOException { - QueryDefinitionRequestType queryDefReqType = null; - JAXBElement responseJaxb; - try { - responseJaxb = CRCJAXBUtil.getJAXBUtil() - .unMashallFromString(requestString); - - RequestMessageType r = (RequestMessageType) responseJaxb.getValue(); - BodyType bodyType = r.getMessageBody(); - // get body and search for analysis definition - JAXBUnWrapHelper unWraphHelper = new JAXBUnWrapHelper(); - - - queryDefReqType = (QueryDefinitionRequestType) unWraphHelper - .getObjectByClass(bodyType.getAny(), - QueryDefinitionRequestType.class); - } catch (JAXBUtilException e) { - throw new I2B2DAOException(e.getMessage()); - } - - return queryDefReqType.getQueryDefinition(); - } - - public String getSql() { - return sqlBuffer.toString(); - } - - public String getIgnoredItemMessage() { - return ignoredItemBuffer.toString(); - } - - public void startSqlBuild() throws JAXBUtilException, I2B2Exception { - LogTimingUtil logTimingUtil = new LogTimingUtil(); - logTimingUtil.setStartTime(); - execQuery(this.queryXML,null,0); - - logTimingUtil.setEndTime(); - if (processTimingFlag.equalsIgnoreCase(ProcessTimingReportUtil.INFO) || processTimingFlag.equalsIgnoreCase(ProcessTimingReportUtil.DEBUG) ) { - ProcessTimingReportUtil ptrUtil = new ProcessTimingReportUtil(this.dataSourceLookup); - this.processTimingMessageBuffer.append(ptrUtil.buildProcessTiming(logTimingUtil, "BUILD SQL", null)); - } - } - - private String[] execQuery(String requestXML, String itemName, int level) throws JAXBUtilException, I2B2Exception { - String returnTempTableName = ""; - //ExecSql execSql = new ExecSql(conn); - QueryToolUtilNew queryTool = null; - - QueryDefinitionType queryDef = getQueryDefinitionType(requestXML); - String queryTiming = queryDef.getQueryTiming(); - List panelList = queryDef.getPanel(); - for (PanelType singlePanel : panelList) { - List itemList = singlePanel.getItem(); - for (ItemType singleItem : itemList) { - if (singleItem.getItemKey().toLowerCase().startsWith(ItemKeyUtil.ITEM_KEY_MASTERID)) { - - if ((singlePanel.getPanelDateTo() != null) || (singlePanel.getPanelDateFrom() != null)) - throw new I2B2DAOException("Date Contraints is not supported with Query in Query"); - log.debug("In RecursiveBuild, total occurrences: " + singlePanel.getTotalItemOccurrences().getValue()); - if (singlePanel.getTotalItemOccurrences().getValue() > 1) - throw new I2B2DAOException("Total Occurances greater than 0 is not supported with Query in Query."); - - String requestXml = getQueryDefinitionRequestXml(singleItem.getItemKey()); - String[] sql = execQuery(requestXml,singleItem.getItemKey(), level+1); - QueryDefinitionType masterQueryDef = getQueryDefinitionType(requestXml); - String masterQueryTiming = masterQueryDef.getQueryTiming(); - //copy the dx data to master temp table - //execSql.copyDxToMaster(singleItem.getItemKey(), false, false); - //System.out.println("insert into master_temp(m"); - if (queryTiming == null) { - CalulateQueryTiming calculateTiming = new CalulateQueryTiming(); - queryTiming = calculateTiming.getQueryTiming(queryDef.getPanel()); - } - sqlBuffer.append("\n<*>\n"); - sqlBuffer.append(copyDxToMaster(singleItem.getItemKey(), queryTiming, masterQueryTiming, false, false,sql[1],level) ); - sqlBuffer.append("\n<*>\n"); - //delete the dx temp table - //execSql.deleteDx(); - sqlBuffer.append(deleteTempTable()); - sqlBuffer.append("\n<*>\n"); - masterIdLIFO.add(singleItem.getItemKey()); - } - } - } - - - //build sql - queryTool = new QueryToolUtilNew(dataSourceLookup, requestXML, - false); - queryTool.setProjectParamMap(this.projectParamMap); - - if (this.processTimingFlag.equalsIgnoreCase(ProcessTimingReportUtil.DEBUG)) { - queryTool.setProcessTimingFlag(this.processTimingFlag); - } - queryTool.setAllowLargeTextValueConstrainFlag(allowLargeTextValueConstrainFlag); - - - String sql = ""; - String maxPanelNum = ""; - //if (itemName != null) { - sql = queryTool.getSetfinderSqlForQueryDefinition(); - maxPanelNum = String.valueOf(queryTool.getMaxPanelNumber()); - - ignoredItemBuffer.append(queryTool.getIgnoredItemMessage()); - if (this.processTimingFlag.equalsIgnoreCase(ProcessTimingReportUtil.DEBUG)) { - processTimingMessageBuffer.append(queryTool.getProcessTimingMessage()) ; - } - - //execute sql - log.debug("generated sql " + sql); - sqlBuffer.append(sql); - // } - - - if (itemName != null && itemName.startsWith("masterid")) { - - for(Iterator i = masterIdLIFO.listIterator();i.hasNext();) { - log.debug("master id to delete " + i.next()); - - } - - int j=0; - for(Iterator i = masterIdLIFO.listIterator();i.hasNext();j++) { - - sqlBuffer.append(deleteTempMaster( masterIdLIFO.get(j),level)); - masterIdLIFO.remove(j); - } - - } - return new String[] { sql, maxPanelNum}; - } - - public String getQueryDefinitionRequestXml(String itemKey) throws I2B2DAOException { - - - DAOFactoryHelper helper = new DAOFactoryHelper(dataSourceLookup.getDomainId(), dataSourceLookup.getProjectPath(), - dataSourceLookup.getProjectPath()); - SetFinderDAOFactory sfDaoFactory = helper.getDAOFactory() - .getSetFinderDAOFactory(); - - //get master id - String masterId = itemKey.substring(9); - //get query definition - QtQueryMaster queryMaster = sfDaoFactory.getQueryMasterDAO().getQueryDefinition(masterId); - return queryMaster.getI2b2RequestXml(); - } - - - - public String copyDxToMaster(String masterId, String queryTiming, String masterQueryTiming, boolean selectEncounterFlag, boolean selectInstanceFlag, - String maxPanelNum, int level) { - String selectFields = " "; - String joinTableName = tempTableNameMap.getTempTableName(); - String joinColumnName = "patient_num"; - if (selectInstanceFlag) { - selectFields = " encounter_num, instance_num, patient_num, concept_cd, start_date, provider_id, "; - } else if (selectEncounterFlag) { - selectFields = "encounter_num, patient_num, "; - } else { - selectFields = " patient_num, "; - } - - if (queryTiming != null && masterQueryTiming != null) { - if (!queryTiming.equalsIgnoreCase(masterQueryTiming)) { - QueryTimingHandler queryTimingHandler = new QueryTimingHandler(); - if (queryTimingHandler.isSameVisit(queryTiming) && queryTimingHandler.isAny(masterQueryTiming)) { - joinTableName = "visit_dimension"; - joinColumnName = "patient_num"; - selectFields = "encounter_num, patient_num, "; - } else if (queryTimingHandler.isSameInstanceNum(queryTiming) && queryTimingHandler.isAny(masterQueryTiming)) { - joinTableName = "observation_fact"; - joinColumnName = "patient_num"; - selectFields = " encounter_num, instance_num, patient_num, concept_cd, start_date, provider_id, "; - } else if (queryTimingHandler.isSameInstanceNum(queryTiming) && queryTimingHandler.isSameVisit(masterQueryTiming)) { - joinTableName = "observation_fact"; - joinColumnName = "encounter_num"; - selectFields = " encounter_num, instance_num, patient_num, concept_cd, start_date, provider_id, "; - } - } - } - //return " insert into " + this.getDbSchemaName() + tempTableNameMap.getTempMasterTable() + "(master_id, " + selectFields + " level_no) " + - // "select '" + masterId + "', " + selectFields + level + " from " + this.getDbSchemaName() + tempTableNameMap.getTempTableName() +" where panel_count = " + maxPanelNum; - - return " insert into " + this.getDbSchemaName() + tempTableNameMap.getTempMasterTable() + "(master_id, " + selectFields + " level_no) " + - "select '" + masterId + "', " + selectFields + level + " from " + this.getDbSchemaName() + joinTableName + " where " + joinColumnName + " IN ( " + - "select " + joinColumnName + " from " + this.getDbSchemaName() + tempTableNameMap.getTempTableName() +" where panel_count = " + maxPanelNum + " ) "; - - - } - - public String deleteTempTable() { - - return " delete "+ this.getDbSchemaName() + tempTableNameMap.getTempDxTableName() + " \n<*>\n delete " + this.getDbSchemaName()+ tempTableNameMap.getTempTableName(); - - } - - - public String deleteTempMaster(String masterId,int level) { - return "\n <*> \n delete " + this.getDbSchemaName() + tempTableNameMap.getTempMasterTable() +" where master_id = '" + masterId + "' and level_no >= " + level + "\n<*>"; - } - - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import jakarta.xml.bind.JAXBElement; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; +import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.db.QtQueryMaster; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ItemType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.PanelType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionRequestType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionType; +import edu.harvard.i2b2.crc.util.ItemKeyUtil; +import edu.harvard.i2b2.crc.util.LogTimingUtil; +import edu.harvard.i2b2.crc.util.ParamUtil; + +public class RecursiveBuild extends CRCDAO { + + private static String testFileDir = null; + private StringBuffer sqlBuffer = new StringBuffer(); + private StringBuffer ignoredItemBuffer = new StringBuffer(); + private ArrayList masterIdLIFO = new ArrayList(); + private DataSourceLookup dataSourceLookup = null; + private String queryXML = null; + private boolean encounterSetOutputFlag = false; + private TempTableNameMap tempTableNameMap = null; + private StringBuffer processTimingMessageBuffer = new StringBuffer(); + private Map projectParamMap = null; + private String processTimingFlag = ""; + private boolean allowLargeTextValueConstrainFlag = true; + + + + + public RecursiveBuild(DataSourceLookup dataSourceLookup, String queryXML, + boolean encounterSetOutputFlag) { + this.dataSourceLookup = dataSourceLookup; + this.queryXML = queryXML; + this.encounterSetOutputFlag = encounterSetOutputFlag; + this.setDbSchemaName(dataSourceLookup.getFullSchema()); + tempTableNameMap = new TempTableNameMap(dataSourceLookup.getServerType()); + } + + + + + public String getProcessTimingMessage() { + return this.processTimingMessageBuffer.toString(); + } + + public void setProjectParamMap(Map projectParamMap) { + this.projectParamMap = projectParamMap; + if (projectParamMap != null && projectParamMap.get(ParamUtil.PM_ENABLE_PROCESS_TIMING) != null) { + this.processTimingFlag = (String)projectParamMap.get(ParamUtil.PM_ENABLE_PROCESS_TIMING); + } + } + + public void setAllowLargeTextValueConstrainFlag(boolean allowLargeTextValueConstrainFlag) { + this.allowLargeTextValueConstrainFlag = allowLargeTextValueConstrainFlag; + } + + + public Map getProjectParamMap() { + return this.projectParamMap; + } + + + + private QueryDefinitionType getQueryDefinitionType(String requestString) throws I2B2DAOException { + QueryDefinitionRequestType queryDefReqType = null; + JAXBElement responseJaxb; + try { + responseJaxb = CRCJAXBUtil.getJAXBUtil() + .unMashallFromString(requestString); + + RequestMessageType r = (RequestMessageType) responseJaxb.getValue(); + BodyType bodyType = r.getMessageBody(); + // get body and search for analysis definition + JAXBUnWrapHelper unWraphHelper = new JAXBUnWrapHelper(); + + + queryDefReqType = (QueryDefinitionRequestType) unWraphHelper + .getObjectByClass(bodyType.getAny(), + QueryDefinitionRequestType.class); + } catch (JAXBUtilException e) { + throw new I2B2DAOException(e.getMessage()); + } + + return queryDefReqType.getQueryDefinition(); + } + + public String getSql() { + return sqlBuffer.toString(); + } + + public String getIgnoredItemMessage() { + return ignoredItemBuffer.toString(); + } + + public void startSqlBuild() throws JAXBUtilException, I2B2Exception { + LogTimingUtil logTimingUtil = new LogTimingUtil(); + logTimingUtil.setStartTime(); + execQuery(this.queryXML,null,0); + + logTimingUtil.setEndTime(); + if (processTimingFlag.equalsIgnoreCase(ProcessTimingReportUtil.INFO) || processTimingFlag.equalsIgnoreCase(ProcessTimingReportUtil.DEBUG) ) { + ProcessTimingReportUtil ptrUtil = new ProcessTimingReportUtil(this.dataSourceLookup); + this.processTimingMessageBuffer.append(ptrUtil.buildProcessTiming(logTimingUtil, "BUILD SQL", null)); + } + } + + private String[] execQuery(String requestXML, String itemName, int level) throws JAXBUtilException, I2B2Exception { + String returnTempTableName = ""; + //ExecSql execSql = new ExecSql(conn); + QueryToolUtilNew queryTool = null; + + QueryDefinitionType queryDef = getQueryDefinitionType(requestXML); + String queryTiming = queryDef.getQueryTiming(); + List panelList = queryDef.getPanel(); + for (PanelType singlePanel : panelList) { + List itemList = singlePanel.getItem(); + for (ItemType singleItem : itemList) { + if (singleItem.getItemKey().toLowerCase().startsWith(ItemKeyUtil.ITEM_KEY_MASTERID)) { + + if ((singlePanel.getPanelDateTo() != null) || (singlePanel.getPanelDateFrom() != null)) + throw new I2B2DAOException("Date Contraints is not supported with Query in Query"); + log.debug("In RecursiveBuild, total occurrences: " + singlePanel.getTotalItemOccurrences().getValue()); + if (singlePanel.getTotalItemOccurrences().getValue() > 1) + throw new I2B2DAOException("Total Occurances greater than 0 is not supported with Query in Query."); + + String requestXml = getQueryDefinitionRequestXml(singleItem.getItemKey()); + String[] sql = execQuery(requestXml,singleItem.getItemKey(), level+1); + QueryDefinitionType masterQueryDef = getQueryDefinitionType(requestXml); + String masterQueryTiming = masterQueryDef.getQueryTiming(); + //copy the dx data to master temp table + //execSql.copyDxToMaster(singleItem.getItemKey(), false, false); + //System.out.println("insert into master_temp(m"); + if (queryTiming == null) { + CalulateQueryTiming calculateTiming = new CalulateQueryTiming(); + queryTiming = calculateTiming.getQueryTiming(queryDef.getPanel()); + } + sqlBuffer.append("\n<*>\n"); + sqlBuffer.append(copyDxToMaster(singleItem.getItemKey(), queryTiming, masterQueryTiming, false, false,sql[1],level) ); + sqlBuffer.append("\n<*>\n"); + //delete the dx temp table + //execSql.deleteDx(); + sqlBuffer.append(deleteTempTable()); + sqlBuffer.append("\n<*>\n"); + masterIdLIFO.add(singleItem.getItemKey()); + } + } + } + + + //build sql + queryTool = new QueryToolUtilNew(dataSourceLookup, requestXML, + false); + queryTool.setProjectParamMap(this.projectParamMap); + + if (this.processTimingFlag.equalsIgnoreCase(ProcessTimingReportUtil.DEBUG)) { + queryTool.setProcessTimingFlag(this.processTimingFlag); + } + queryTool.setAllowLargeTextValueConstrainFlag(allowLargeTextValueConstrainFlag); + + + String sql = ""; + String maxPanelNum = ""; + //if (itemName != null) { + sql = queryTool.getSetfinderSqlForQueryDefinition(); + maxPanelNum = String.valueOf(queryTool.getMaxPanelNumber()); + + ignoredItemBuffer.append(queryTool.getIgnoredItemMessage()); + if (this.processTimingFlag.equalsIgnoreCase(ProcessTimingReportUtil.DEBUG)) { + processTimingMessageBuffer.append(queryTool.getProcessTimingMessage()) ; + } + + //execute sql + log.debug("generated sql " + sql); + sqlBuffer.append(sql); + // } + + + if (itemName != null && itemName.startsWith("masterid")) { + + for(Iterator i = masterIdLIFO.listIterator();i.hasNext();) { + log.debug("master id to delete " + i.next()); + + } + + int j=0; + for(Iterator i = masterIdLIFO.listIterator();i.hasNext();j++) { + + sqlBuffer.append(deleteTempMaster( masterIdLIFO.get(j),level)); + masterIdLIFO.remove(j); + } + + } + return new String[] { sql, maxPanelNum}; + } + + public String getQueryDefinitionRequestXml(String itemKey) throws I2B2DAOException { + + + DAOFactoryHelper helper = new DAOFactoryHelper(dataSourceLookup.getDomainId(), dataSourceLookup.getProjectPath(), + dataSourceLookup.getProjectPath()); + SetFinderDAOFactory sfDaoFactory = helper.getDAOFactory() + .getSetFinderDAOFactory(); + + //get master id + String masterId = itemKey.substring(9); + //get query definition + QtQueryMaster queryMaster = sfDaoFactory.getQueryMasterDAO().getQueryDefinition(masterId); + return queryMaster.getI2b2RequestXml(); + } + + + + public String copyDxToMaster(String masterId, String queryTiming, String masterQueryTiming, boolean selectEncounterFlag, boolean selectInstanceFlag, + String maxPanelNum, int level) { + String selectFields = " "; + String joinTableName = tempTableNameMap.getTempTableName(); + String joinColumnName = "patient_num"; + if (selectInstanceFlag) { + selectFields = " encounter_num, instance_num, patient_num, concept_cd, start_date, provider_id, "; + } else if (selectEncounterFlag) { + selectFields = "encounter_num, patient_num, "; + } else { + selectFields = " patient_num, "; + } + + if (queryTiming != null && masterQueryTiming != null) { + if (!queryTiming.equalsIgnoreCase(masterQueryTiming)) { + QueryTimingHandler queryTimingHandler = new QueryTimingHandler(); + if (queryTimingHandler.isSameVisit(queryTiming) && queryTimingHandler.isAny(masterQueryTiming)) { + joinTableName = "visit_dimension"; + joinColumnName = "patient_num"; + selectFields = "encounter_num, patient_num, "; + } else if (queryTimingHandler.isSameInstanceNum(queryTiming) && queryTimingHandler.isAny(masterQueryTiming)) { + joinTableName = "observation_fact"; + joinColumnName = "patient_num"; + selectFields = " encounter_num, instance_num, patient_num, concept_cd, start_date, provider_id, "; + } else if (queryTimingHandler.isSameInstanceNum(queryTiming) && queryTimingHandler.isSameVisit(masterQueryTiming)) { + joinTableName = "observation_fact"; + joinColumnName = "encounter_num"; + selectFields = " encounter_num, instance_num, patient_num, concept_cd, start_date, provider_id, "; + } + } + } + //return " insert into " + this.getDbSchemaName() + tempTableNameMap.getTempMasterTable() + "(master_id, " + selectFields + " level_no) " + + // "select '" + masterId + "', " + selectFields + level + " from " + this.getDbSchemaName() + tempTableNameMap.getTempTableName() +" where panel_count = " + maxPanelNum; + + return " insert into " + this.getDbSchemaName() + tempTableNameMap.getTempMasterTable() + "(master_id, " + selectFields + " level_no) " + + "select '" + masterId + "', " + selectFields + level + " from " + this.getDbSchemaName() + joinTableName + " where " + joinColumnName + " IN ( " + + "select " + joinColumnName + " from " + this.getDbSchemaName() + tempTableNameMap.getTempTableName() +" where panel_count = " + maxPanelNum + " ) "; + + + } + + public String deleteTempTable() { + + return " delete "+ this.getDbSchemaName() + tempTableNameMap.getTempDxTableName() + " \n<*>\n delete " + this.getDbSchemaName()+ tempTableNameMap.getTempTableName(); + + } + + + public String deleteTempMaster(String masterId,int level) { + return "\n <*> \n delete " + this.getDbSchemaName() + tempTableNameMap.getTempMasterTable() +" where master_id = '" + masterId + "' and level_no >= " + level + "\n<*>"; + } + + + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/ResultEntry.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/ResultEntry.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/ResultEntry.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/ResultEntry.java index 709896b6..84828188 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/ResultEntry.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/ResultEntry.java @@ -1,60 +1,60 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Chris - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; - -/** - * Implement comparator for ResultEntry - * $Id: ResultEntry.java,v 1.4 2008/07/21 20:04:21 rk903 Exp $ - * @author chris - */ -public class ResultEntry { - public int Enct_Panels; - public int Invert; - public long EstPanelSize; - public int Items; - public int AllShort; - public int ForInsert; - public int FirstPanel; - public Integer Panel; - public String TableName; - public String FieldName; - public long EstItemSize; - public int SqlX; - public String Sql0; - public String Sql1; - public int totalItemOccurrences = 0; - public String totalItemoccurrencesOperator = ""; - - public ResultEntry(int enct_panels, IdentityPanelEntry p, ItemEntry v) { - this.AllShort = p.AllShort; - this.Enct_Panels = enct_panels; - this.EstItemSize = v.EstItemSize; - this.EstPanelSize = p.EstPanelSize; - this.FieldName = v.FieldName; - this.FirstPanel = p.FirstPanel; - this.ForInsert = p.ForInsert; - this.Invert = p.Invert; - this.Items = p.Items; - this.Panel = p.Panel; - totalItemOccurrences = p.totalItemOccurrences; - totalItemoccurrencesOperator = p.totalItemOccurrencesOperator; - this.Sql0 = v.Sql0; - this.Sql1 = v.Sql1; - this.SqlX = v.SqlX; - this.TableName = v.TableName; - } -} - +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Chris + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; + +/** + * Implement comparator for ResultEntry + * $Id: ResultEntry.java,v 1.4 2008/07/21 20:04:21 rk903 Exp $ + * @author chris + */ +public class ResultEntry { + public int Enct_Panels; + public int Invert; + public long EstPanelSize; + public int Items; + public int AllShort; + public int ForInsert; + public int FirstPanel; + public Integer Panel; + public String TableName; + public String FieldName; + public long EstItemSize; + public int SqlX; + public String Sql0; + public String Sql1; + public int totalItemOccurrences = 0; + public String totalItemoccurrencesOperator = ""; + + public ResultEntry(int enct_panels, IdentityPanelEntry p, ItemEntry v) { + this.AllShort = p.AllShort; + this.Enct_Panels = enct_panels; + this.EstItemSize = v.EstItemSize; + this.EstPanelSize = p.EstPanelSize; + this.FieldName = v.FieldName; + this.FirstPanel = p.FirstPanel; + this.ForInsert = p.ForInsert; + this.Invert = p.Invert; + this.Items = p.Items; + this.Panel = p.Panel; + totalItemOccurrences = p.totalItemOccurrences; + totalItemoccurrencesOperator = p.totalItemOccurrencesOperator; + this.Sql0 = v.Sql0; + this.Sql1 = v.Sql1; + this.SqlX = v.SqlX; + this.TableName = v.TableName; + } +} + diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/ResultEntryComparator.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/ResultEntryComparator.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/ResultEntryComparator.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/ResultEntryComparator.java index 9308db37..ed69d8a9 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/ResultEntryComparator.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/ResultEntryComparator.java @@ -1,88 +1,88 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Chris - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; - -import java.util.Comparator; - - -/** - * Implement comparator for ResultEntry - * $Id: ResultEntryComparator.java,v 1.3 2007/08/31 14:46:23 rk903 Exp $ - * @author chris - */ -public class ResultEntryComparator implements Comparator { - private String PATIENT_TABLE = null; - private String ENCOUNTER_TABLE = null; - private String THIRD_TABLE = null; - - public ResultEntryComparator(String patient_table, String encounter_table, - String third_table) { - PATIENT_TABLE = patient_table; - ENCOUNTER_TABLE = encounter_table; - THIRD_TABLE = third_table; - } - - @Override - public int compare(Object element1, Object element2) { - if ((element1.getClass().equals(ResultEntry.class)) && - (element2.getClass().equals((ResultEntry.class)))) { - ResultEntry r1 = (ResultEntry) element1; - ResultEntry r2 = (ResultEntry) element2; - int compare = new Integer(r1.Panel).compareTo(new Integer(r2.Panel)); - - if (compare == 0) { - compare = new Integer(r1.SqlX).compareTo(new Integer(r2.SqlX)) * -1; - - if (compare == 0) { - if (r1.TableName.equals(r2.TableName)) { - compare = new Long(r1.EstItemSize).compareTo(new Long( - r2.EstItemSize)) * -1; - } else { - int r1TblValue = -1; - int r2TblValue = -1; - - if (r1.TableName.equals(PATIENT_TABLE)) { - r1TblValue = 0; - } else if (r1.TableName.equals(ENCOUNTER_TABLE)) { - r1TblValue = 1; - } else if (r1.TableName.equals(THIRD_TABLE)) { - r1TblValue = 2; - } else { - r1TblValue = 3; - } - - if (r2.TableName.equals(PATIENT_TABLE)) { - r2TblValue = 0; - } else if (r2.TableName.equals(ENCOUNTER_TABLE)) { - r2TblValue = 1; - } else if (r2.TableName.equals(THIRD_TABLE)) { - r2TblValue = 2; - } else { - r2TblValue = 3; - } - - compare = new Integer(r1TblValue).compareTo(new Integer( - r2TblValue)); - } - } - } - - return compare; - } else { - return element1.toString().compareTo(element2.toString()); - } - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Chris + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; + +import java.util.Comparator; + + +/** + * Implement comparator for ResultEntry + * $Id: ResultEntryComparator.java,v 1.3 2007/08/31 14:46:23 rk903 Exp $ + * @author chris + */ +public class ResultEntryComparator implements Comparator { + private String PATIENT_TABLE = null; + private String ENCOUNTER_TABLE = null; + private String THIRD_TABLE = null; + + public ResultEntryComparator(String patient_table, String encounter_table, + String third_table) { + PATIENT_TABLE = patient_table; + ENCOUNTER_TABLE = encounter_table; + THIRD_TABLE = third_table; + } + + @Override + public int compare(Object element1, Object element2) { + if ((element1.getClass().equals(ResultEntry.class)) && + (element2.getClass().equals((ResultEntry.class)))) { + ResultEntry r1 = (ResultEntry) element1; + ResultEntry r2 = (ResultEntry) element2; + int compare = new Integer(r1.Panel).compareTo(new Integer(r2.Panel)); + + if (compare == 0) { + compare = new Integer(r1.SqlX).compareTo(new Integer(r2.SqlX)) * -1; + + if (compare == 0) { + if (r1.TableName.equals(r2.TableName)) { + compare = new Long(r1.EstItemSize).compareTo(new Long( + r2.EstItemSize)) * -1; + } else { + int r1TblValue = -1; + int r2TblValue = -1; + + if (r1.TableName.equals(PATIENT_TABLE)) { + r1TblValue = 0; + } else if (r1.TableName.equals(ENCOUNTER_TABLE)) { + r1TblValue = 1; + } else if (r1.TableName.equals(THIRD_TABLE)) { + r1TblValue = 2; + } else { + r1TblValue = 3; + } + + if (r2.TableName.equals(PATIENT_TABLE)) { + r2TblValue = 0; + } else if (r2.TableName.equals(ENCOUNTER_TABLE)) { + r2TblValue = 1; + } else if (r2.TableName.equals(THIRD_TABLE)) { + r2TblValue = 2; + } else { + r2TblValue = 3; + } + + compare = new Integer(r1TblValue).compareTo(new Integer( + r2TblValue)); + } + } + } + + return compare; + } else { + return element1.toString().compareTo(element2.toString()); + } + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/SortPanel.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/SortPanel.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/SortPanel.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/SortPanel.java index fb3b38c6..f059de95 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/SortPanel.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/SortPanel.java @@ -1,168 +1,168 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.xml.stream.XMLStreamException; - -import org.apache.axis2.AxisFault; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.exception.StackTraceUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; -import edu.harvard.i2b2.crc.datavo.ontology.ConceptType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ItemType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.PanelType; -import edu.harvard.i2b2.crc.delegate.ontology.CallOntologyUtil; -import edu.harvard.i2b2.crc.util.ItemKeyUtil; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - -public class SortPanel { - /** log **/ - protected final Log log = LogFactory.getLog(getClass()); - - public List sortedPanelList(List panelList, - SecurityType securityType, String projectId) throws I2B2Exception { - - Map panelTotalMap = new HashMap(); - Map invertPanelTotalMap = new HashMap(); - Map panelMap = new HashMap(); - Map invertPanelMap = new HashMap(); - int panelIndex = 0, invertPanelIndex = 0; - List sortedPanelArray = new ArrayList(); - List sortedInvertPanelArray = new ArrayList(); - for (PanelType panelType : panelList) { - - List itemList = panelType.getItem(); - int invert = panelType.getInvert(); - // calculate the total for each item - int panelTotal = 0; - String itemKey = null; - for (ItemType itemType : itemList) { - ConceptType conceptType = null; - - try { - itemKey = itemType.getItemKey(); - if (ItemKeyUtil.isConceptKey(itemKey)) { - //conceptType = ontologyUtil.callOntology(itemKey); - conceptType = CallOntologyUtil.callOntology(itemKey, securityType, projectId, QueryProcessorUtil.getInstance().getOntologyUrl()); - - if (conceptType != null && conceptType.getTotalnum() !=null) { - panelTotal += conceptType.getTotalnum(); - } - } - - } catch (AxisFault e) { - log.error("Error while fetching metadata [" + itemKey - + "] from ontology ", e); - throw new OntologyException( - "Error while fetching metadata [" + itemKey - + "] from ontology " - + StackTraceUtil.getStackTrace(e)); - } catch (XMLStreamException e) { - log.error("Error while fetching metadata [" + itemKey - + "] from ontology ", e); - throw new OntologyException( - "Error while fetching metadata [" + itemKey - + "] from ontology " - + StackTraceUtil.getStackTrace(e)); - } catch (JAXBUtilException e) { - log.error("Error while fetching metadata [" + itemKey - + "] from ontology ", e); - throw new OntologyException( - "Error while fetching metadata [" + itemKey - + "] from ontology " - + StackTraceUtil.getStackTrace(e)); - } - - } - - - - if (invert == 1) { - invertPanelIndex++; - invertPanelTotalMap.put(invertPanelIndex, panelTotal*-1); - invertPanelMap.put(invertPanelIndex, panelType); - //panelTotalMap.put(panelIndex, panelTotal); - } else { - panelIndex++; - panelTotalMap.put(panelIndex, panelTotal); - panelMap.put(panelIndex, panelType); - } - - log.debug("Panel's Total num [" + panelTotal - + "] and the panel index [" + panelIndex + "]"); - - } - - - HashMap yourMap = new HashMap(); - HashMap map = new LinkedHashMap(); - List yourMapKeys = new ArrayList(panelTotalMap.keySet()); - List yourMapValues = new ArrayList(panelTotalMap.values()); - List sortedMapValues = new ArrayList(yourMapValues); - Collections.sort(sortedMapValues); - int size = yourMapValues.size(); - int indexInMapValues = 0; - for (int i = 0; i < size; i++) { - indexInMapValues = yourMapValues.indexOf(sortedMapValues.get(i)); - map.put(yourMapKeys.get(indexInMapValues), sortedMapValues.get(i)); - yourMapValues.set(indexInMapValues, -1); - } - Set ref = map.keySet(); - Iterator it = ref.iterator(); - int panelIndexHash = 0; - while (it.hasNext()) { - panelIndexHash = (Integer) it.next(); - sortedPanelArray.add(panelMap.get(panelIndexHash)); - } - log.debug("size of sorted panel array [" + sortedPanelArray.size() + "]"); - - HashMap yourInvertMap = new HashMap(); - HashMap invertMap = new LinkedHashMap(); - List yourInvertMapKeys = new ArrayList(invertPanelTotalMap.keySet()); - List yourInvertMapValues = new ArrayList(invertPanelTotalMap.values()); - List sortedInvertMapValues = new ArrayList(yourInvertMapValues); - Collections.sort(sortedInvertMapValues); - - size = yourInvertMapValues.size(); - indexInMapValues = 0; - for (int i = 0; i < size; i++) { - indexInMapValues = yourInvertMapValues.indexOf(sortedInvertMapValues.get(i)); - invertMap.put(yourInvertMapKeys.get(indexInMapValues), sortedInvertMapValues.get(i)); - yourInvertMapValues.set(indexInMapValues, -1); - } - Set ref1 = invertMap.keySet(); - Iterator it1 = ref1.iterator(); - panelIndexHash = 0; - while (it1.hasNext()) { - panelIndexHash = (Integer) it1.next(); - sortedInvertPanelArray.add(invertPanelMap.get(panelIndexHash)); - } - - log.debug("size of sorted exclude panel array [" + sortedInvertPanelArray.size() + "]"); - - sortedPanelArray.addAll(sortedInvertPanelArray); - - - return sortedPanelArray; - - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.xml.stream.XMLStreamException; + +import org.apache.axis2.AxisFault; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.exception.StackTraceUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; +import edu.harvard.i2b2.crc.datavo.ontology.ConceptType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ItemType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.PanelType; +import edu.harvard.i2b2.crc.delegate.ontology.CallOntologyUtil; +import edu.harvard.i2b2.crc.util.ItemKeyUtil; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + +public class SortPanel { + /** log **/ + protected final Log log = LogFactory.getLog(getClass()); + + public List sortedPanelList(List panelList, + SecurityType securityType, String projectId) throws I2B2Exception { + + Map panelTotalMap = new HashMap(); + Map invertPanelTotalMap = new HashMap(); + Map panelMap = new HashMap(); + Map invertPanelMap = new HashMap(); + int panelIndex = 0, invertPanelIndex = 0; + List sortedPanelArray = new ArrayList(); + List sortedInvertPanelArray = new ArrayList(); + for (PanelType panelType : panelList) { + + List itemList = panelType.getItem(); + int invert = panelType.getInvert(); + // calculate the total for each item + int panelTotal = 0; + String itemKey = null; + for (ItemType itemType : itemList) { + ConceptType conceptType = null; + + try { + itemKey = itemType.getItemKey(); + if (ItemKeyUtil.isConceptKey(itemKey)) { + //conceptType = ontologyUtil.callOntology(itemKey); + conceptType = CallOntologyUtil.callOntology(itemKey, securityType, projectId, QueryProcessorUtil.getInstance().getOntologyUrl()); + + if (conceptType != null && conceptType.getTotalnum() !=null) { + panelTotal += conceptType.getTotalnum(); + } + } + + } catch (AxisFault e) { + log.error("Error while fetching metadata [" + itemKey + + "] from ontology ", e); + throw new OntologyException( + "Error while fetching metadata [" + itemKey + + "] from ontology " + + StackTraceUtil.getStackTrace(e)); + } catch (XMLStreamException e) { + log.error("Error while fetching metadata [" + itemKey + + "] from ontology ", e); + throw new OntologyException( + "Error while fetching metadata [" + itemKey + + "] from ontology " + + StackTraceUtil.getStackTrace(e)); + } catch (JAXBUtilException e) { + log.error("Error while fetching metadata [" + itemKey + + "] from ontology ", e); + throw new OntologyException( + "Error while fetching metadata [" + itemKey + + "] from ontology " + + StackTraceUtil.getStackTrace(e)); + } + + } + + + + if (invert == 1) { + invertPanelIndex++; + invertPanelTotalMap.put(invertPanelIndex, panelTotal*-1); + invertPanelMap.put(invertPanelIndex, panelType); + //panelTotalMap.put(panelIndex, panelTotal); + } else { + panelIndex++; + panelTotalMap.put(panelIndex, panelTotal); + panelMap.put(panelIndex, panelType); + } + + log.debug("Panel's Total num [" + panelTotal + + "] and the panel index [" + panelIndex + "]"); + + } + + + HashMap yourMap = new HashMap(); + HashMap map = new LinkedHashMap(); + List yourMapKeys = new ArrayList(panelTotalMap.keySet()); + List yourMapValues = new ArrayList(panelTotalMap.values()); + List sortedMapValues = new ArrayList(yourMapValues); + Collections.sort(sortedMapValues); + int size = yourMapValues.size(); + int indexInMapValues = 0; + for (int i = 0; i < size; i++) { + indexInMapValues = yourMapValues.indexOf(sortedMapValues.get(i)); + map.put(yourMapKeys.get(indexInMapValues), sortedMapValues.get(i)); + yourMapValues.set(indexInMapValues, -1); + } + Set ref = map.keySet(); + Iterator it = ref.iterator(); + int panelIndexHash = 0; + while (it.hasNext()) { + panelIndexHash = (Integer) it.next(); + sortedPanelArray.add(panelMap.get(panelIndexHash)); + } + log.debug("size of sorted panel array [" + sortedPanelArray.size() + "]"); + + HashMap yourInvertMap = new HashMap(); + HashMap invertMap = new LinkedHashMap(); + List yourInvertMapKeys = new ArrayList(invertPanelTotalMap.keySet()); + List yourInvertMapValues = new ArrayList(invertPanelTotalMap.values()); + List sortedInvertMapValues = new ArrayList(yourInvertMapValues); + Collections.sort(sortedInvertMapValues); + + size = yourInvertMapValues.size(); + indexInMapValues = 0; + for (int i = 0; i < size; i++) { + indexInMapValues = yourInvertMapValues.indexOf(sortedInvertMapValues.get(i)); + invertMap.put(yourInvertMapKeys.get(indexInMapValues), sortedInvertMapValues.get(i)); + yourInvertMapValues.set(indexInMapValues, -1); + } + Set ref1 = invertMap.keySet(); + Iterator it1 = ref1.iterator(); + panelIndexHash = 0; + while (it1.hasNext()) { + panelIndexHash = (Integer) it1.next(); + sortedInvertPanelArray.add(invertPanelMap.get(panelIndexHash)); + } + + log.debug("size of sorted exclude panel array [" + sortedInvertPanelArray.size() + "]"); + + sortedPanelArray.addAll(sortedInvertPanelArray); + + + return sortedPanelArray; + + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/TempTableNameMap.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/TempTableNameMap.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/TempTableNameMap.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/TempTableNameMap.java index b1eb8404..4655762c --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/TempTableNameMap.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/TempTableNameMap.java @@ -1,50 +1,50 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; - -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; - -public class TempTableNameMap { - - private String tempTableName = ""; - private String tempDxTableName = ""; - private String tempMasterTableName = ""; - private String noLockSqlServer = " "; - - - public TempTableNameMap(String serverType) { - if (serverType.equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER) ) { - tempTableName = "#global_temp_table"; - tempDxTableName = "#dx"; - tempMasterTableName = "#master_global_temp_table"; - } else if (serverType.equalsIgnoreCase( - DAOFactoryHelper.ORACLE) || serverType.equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) { - tempTableName = "QUERY_GLOBAL_TEMP"; - tempDxTableName = "DX"; - tempMasterTableName = "MASTER_QUERY_GLOBAL_TEMP"; - - } - } - - public String getTempTableName() { - return this.tempTableName; - } - - public String getTempDxTableName() { - return this.tempDxTableName; - } - - public String getTempMasterTable() { - return this.tempMasterTableName; - } - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; + +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; + +public class TempTableNameMap { + + private String tempTableName = ""; + private String tempDxTableName = ""; + private String tempMasterTableName = ""; + private String noLockSqlServer = " "; + + + public TempTableNameMap(String serverType) { + if (serverType.equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER) ) { + tempTableName = "#global_temp_table"; + tempDxTableName = "#dx"; + tempMasterTableName = "#master_global_temp_table"; + } else if (serverType.equalsIgnoreCase( + DAOFactoryHelper.ORACLE) || serverType.equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) { + tempTableName = "QUERY_GLOBAL_TEMP"; + tempDxTableName = "DX"; + tempMasterTableName = "MASTER_QUERY_GLOBAL_TEMP"; + + } + } + + public String getTempTableName() { + return this.tempTableName; + } + + public String getTempDxTableName() { + return this.tempDxTableName; + } + + public String getTempMasterTable() { + return this.tempMasterTableName; + } + + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/TotalItemOccurrenceHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/TotalItemOccurrenceHandler.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/TotalItemOccurrenceHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/TotalItemOccurrenceHandler.java index 26781cd2..9ba3f98b --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/TotalItemOccurrenceHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/TotalItemOccurrenceHandler.java @@ -1,41 +1,41 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; - -import edu.harvard.i2b2.common.util.xml.XMLOperatorLookup; -import edu.harvard.i2b2.crc.datavo.setfinder.query.TotOccuranceOperatorType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.PanelType.TotalItemOccurrences; - -public class TotalItemOccurrenceHandler { - - public String buildTotalItemOccurrenceClause( - TotalItemOccurrences totalItemOccurances) { - String totalItemOccuranceStr = null; - - int totalItemOccurrenceValue = 1; - String totalItemOccurrenceOperator = ">="; - if (totalItemOccurances != null) { - totalItemOccurrenceValue = totalItemOccurances.getValue(); - TotOccuranceOperatorType totalOccuranceOperator = totalItemOccurances - .getOperator(); - if (totalOccuranceOperator == null) { - totalItemOccurrenceOperator = ">="; - } else { - totalItemOccurrenceOperator = XMLOperatorLookup - .getComparisonOperatorFromAcronum(totalOccuranceOperator - .toString()); - } - } - totalItemOccuranceStr = totalItemOccurrenceOperator + " " - + totalItemOccurrenceValue; - return totalItemOccuranceStr; - - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; + +import edu.harvard.i2b2.common.util.xml.XMLOperatorLookup; +import edu.harvard.i2b2.crc.datavo.setfinder.query.TotOccuranceOperatorType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.PanelType.TotalItemOccurrences; + +public class TotalItemOccurrenceHandler { + + public String buildTotalItemOccurrenceClause( + TotalItemOccurrences totalItemOccurances) { + String totalItemOccuranceStr = null; + + int totalItemOccurrenceValue = 1; + String totalItemOccurrenceOperator = ">="; + if (totalItemOccurances != null) { + totalItemOccurrenceValue = totalItemOccurances.getValue(); + TotOccuranceOperatorType totalOccuranceOperator = totalItemOccurances + .getOperator(); + if (totalOccuranceOperator == null) { + totalItemOccurrenceOperator = ">="; + } else { + totalItemOccurrenceOperator = XMLOperatorLookup + .getComparisonOperatorFromAcronum(totalOccuranceOperator + .toString()); + } + } + totalItemOccuranceStr = totalItemOccurrenceOperator + " " + + totalItemOccurrenceValue; + return totalItemOccuranceStr; + + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/UnitConverstionUtil.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/UnitConverstionUtil.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/UnitConverstionUtil.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/UnitConverstionUtil.java index c7cc4504..0f0e77d5 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/UnitConverstionUtil.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/UnitConverstionUtil.java @@ -1,143 +1,143 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; - -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; - -public class UnitConverstionUtil { - - - public String buildUnitCdInClause(Element rootElement,String tableNamePrefix ) throws I2B2DAOException { - if (rootElement == null) { - return " " ; - } - - NodeList normalUnitNodeList = rootElement.getElementsByTagName("NormalUnits"); - String normalUnitCd = "", equalUnitCd = ""; - if (normalUnitNodeList != null && normalUnitNodeList.getLength()>0 && normalUnitNodeList.item(0)!= null) { - normalUnitCd = normalUnitNodeList.item(0).getTextContent(); - if (normalUnitCd != null) { - normalUnitCd = "'" + normalUnitCd.replaceAll("'", "''") + "'"; - } - } - - NodeList equalUnitNodeList = rootElement.getElementsByTagName("EqualUnits"); - int nodeLength = equalUnitNodeList.getLength(); - int i = 0 ; - Node unitNode = null; - String unitNodeContent = "" ; - while (i0) { - equalUnitCd += "'" + unitNodeContent.replaceAll("'", "''") + "'"; - if (i+1 0 || normalUnitCd.length() > 0) { - if (normalUnitCd != null && equalUnitCd != null) { - comma = " , "; - } - unitNodeInClause = " " + " ( " + normalUnitCd + comma + equalUnitCd +" ) " ; - //case when 'a' in ('a','b') then 1 else 0 end =1 - } - - return unitNodeInClause; - } - - public String buildUnitCdSwitchClause(Element rootElement, boolean selectFlag, String tableNamePrefix) throws I2B2DAOException { - if (rootElement == null) { - return " " ; - } - - NodeList convertingUnitNodeList = rootElement.getElementsByTagName("ConvertingUnits"); - - - int nodeLength = convertingUnitNodeList.getLength(); - int i=0; - NodeList childList = null; - String singleUnitCd = "", singleMultiplyingFactor = ""; - String multiplyingFactor = ""; - while (i0 && singleMultiplyingFactor.trim().length()>0 ) { - multiplyingFactor += "\n when " + tableNamePrefix + "units_cd = '" + singleUnitCd + "' then " + tableNamePrefix + "nval_num * " + singleMultiplyingFactor; - } - - i++; - } - - - NodeList normalUnitNodeList = rootElement.getElementsByTagName("NormalUnits"); - String normalUnitCd = "", equalUnitCd = ""; - if (normalUnitNodeList != null && normalUnitNodeList.getLength()>0 && normalUnitNodeList.item(0)!= null) { - normalUnitCd = normalUnitNodeList.item(0).getTextContent(); - if (normalUnitCd != null && normalUnitCd.trim().length()>0) { - multiplyingFactor += "\n when " + tableNamePrefix + "units_cd = '" + normalUnitCd + "' then " + tableNamePrefix + "nval_num " ; - } - } - - NodeList equalUnitNodeList = rootElement.getElementsByTagName("EqualUnits"); - nodeLength = equalUnitNodeList.getLength(); - i = 0 ; - Node unitNode = null; - String unitNodeContent = "" ; - while (i0) { - multiplyingFactor += "\n when " + tableNamePrefix + "units_cd = '" + unitNodeContent + "' then " + tableNamePrefix + "nval_num " ; - } - } - i++; - } - - if (multiplyingFactor.length()>0) { - //" else " + tableNamePrefix + "nval_num end" removed else - multiplyingFactor = " case " + multiplyingFactor + " end "; - if ( selectFlag) { - multiplyingFactor += " " + tableNamePrefix + "nval_num " ; - } - } - - - return multiplyingFactor; - } - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; + +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; + +public class UnitConverstionUtil { + + + public String buildUnitCdInClause(Element rootElement,String tableNamePrefix ) throws I2B2DAOException { + if (rootElement == null) { + return " " ; + } + + NodeList normalUnitNodeList = rootElement.getElementsByTagName("NormalUnits"); + String normalUnitCd = "", equalUnitCd = ""; + if (normalUnitNodeList != null && normalUnitNodeList.getLength()>0 && normalUnitNodeList.item(0)!= null) { + normalUnitCd = normalUnitNodeList.item(0).getTextContent(); + if (normalUnitCd != null) { + normalUnitCd = "'" + normalUnitCd.replaceAll("'", "''") + "'"; + } + } + + NodeList equalUnitNodeList = rootElement.getElementsByTagName("EqualUnits"); + int nodeLength = equalUnitNodeList.getLength(); + int i = 0 ; + Node unitNode = null; + String unitNodeContent = "" ; + while (i0) { + equalUnitCd += "'" + unitNodeContent.replaceAll("'", "''") + "'"; + if (i+1 0 || normalUnitCd.length() > 0) { + if (normalUnitCd != null && equalUnitCd != null) { + comma = " , "; + } + unitNodeInClause = " " + " ( " + normalUnitCd + comma + equalUnitCd +" ) " ; + //case when 'a' in ('a','b') then 1 else 0 end =1 + } + + return unitNodeInClause; + } + + public String buildUnitCdSwitchClause(Element rootElement, boolean selectFlag, String tableNamePrefix) throws I2B2DAOException { + if (rootElement == null) { + return " " ; + } + + NodeList convertingUnitNodeList = rootElement.getElementsByTagName("ConvertingUnits"); + + + int nodeLength = convertingUnitNodeList.getLength(); + int i=0; + NodeList childList = null; + String singleUnitCd = "", singleMultiplyingFactor = ""; + String multiplyingFactor = ""; + while (i0 && singleMultiplyingFactor.trim().length()>0 ) { + multiplyingFactor += "\n when " + tableNamePrefix + "units_cd = '" + singleUnitCd + "' then " + tableNamePrefix + "nval_num * " + singleMultiplyingFactor; + } + + i++; + } + + + NodeList normalUnitNodeList = rootElement.getElementsByTagName("NormalUnits"); + String normalUnitCd = "", equalUnitCd = ""; + if (normalUnitNodeList != null && normalUnitNodeList.getLength()>0 && normalUnitNodeList.item(0)!= null) { + normalUnitCd = normalUnitNodeList.item(0).getTextContent(); + if (normalUnitCd != null && normalUnitCd.trim().length()>0) { + multiplyingFactor += "\n when " + tableNamePrefix + "units_cd = '" + normalUnitCd + "' then " + tableNamePrefix + "nval_num " ; + } + } + + NodeList equalUnitNodeList = rootElement.getElementsByTagName("EqualUnits"); + nodeLength = equalUnitNodeList.getLength(); + i = 0 ; + Node unitNode = null; + String unitNodeContent = "" ; + while (i0) { + multiplyingFactor += "\n when " + tableNamePrefix + "units_cd = '" + unitNodeContent + "' then " + tableNamePrefix + "nval_num " ; + } + } + i++; + } + + if (multiplyingFactor.length()>0) { + //" else " + tableNamePrefix + "nval_num end" removed else + multiplyingFactor = " case " + multiplyingFactor + " end "; + if ( selectFlag) { + multiplyingFactor += " " + tableNamePrefix + "nval_num " ; + } + } + + + return multiplyingFactor; + } + + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/ValueConstrainsHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/ValueConstrainsHandler.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/ValueConstrainsHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/ValueConstrainsHandler.java index d1fb5890..b58ea8d0 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/ValueConstrainsHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/ValueConstrainsHandler.java @@ -1,421 +1,421 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - * Christopher Herrick - */ -package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; - -import java.util.List; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.exception.StackTraceUtil; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ConstrainOperatorType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ConstrainValueType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ItemType; -import edu.harvard.i2b2.crc.util.ContainsUtil; -import edu.harvard.i2b2.crc.util.RegExUtil; -import edu.harvard.i2b2.crc.util.SqlClauseUtil; - -/** - * Class to handle value constrains. Generates sql where clause based on the - * list of value constrains. - * - * @author rkuttan - */ -public class ValueConstrainsHandler { - /** log **/ - protected final Log log = LogFactory.getLog(getClass()); - - private boolean unitCdConverstionFlag = false; - private String unitCdInClause = "", unitCdSwitchClause = ""; - - // ch@0013012 - The decision was made that modifier_cd needs to have a - // default value when querying for concept value (numeric, text, large text) - - // if a default value is not specified for modifier_cd, a concept value - // constraint could bring back rows that match the values on modifier and not - // on the main concept value - this would be an error. To get around this, - // we need to include a default modifier_cd constraint on all non-modifier - // value constraints. After careful consideration, it was determined that - // the default value for modifier_cd should be '@'. This could present - // problems at sites where no non-modifier row was created for a concept - // or where an alternative modifier_cd was specified as the default. To make - // customization easier in these cases, the modifier constraint is - // defined here and included in the appropriate sql statements below. Additionally, - // I've maintained the old constructValueConstainClause so 1.6 queries work the same - private String defaultModifierConstraint = " modifier_cd = '@' "; - - - public void setUnitCdConversionFlag(boolean unitCdConverstionFlag, - String unitCdInClause, String unitCdSwitchClause) { - this.unitCdConverstionFlag = unitCdConverstionFlag; - this.unitCdInClause = unitCdInClause; - this.unitCdSwitchClause = unitCdSwitchClause; - } - - public String[] constructValueConstainClause( - List valueConstrainList, - String dbServerType, String dbSchemaName, int panelAccuracyScale) throws I2B2DAOException{ - //used for backward compatibility - defaultModifierConstraint = ""; - return constructValueConstainClause(valueConstrainList, dbServerType, dbSchemaName, panelAccuracyScale, false); - } - - - public String[] constructValueConstainClause( - List valueConstrainList, - String dbServerType, String dbSchemaName, int panelAccuracyScale, - boolean useDefaultModifier) - throws I2B2DAOException { - String fullConstrainSql = "", containsJoinSql = ""; - log.debug("panel accuracy scale" + panelAccuracyScale); - panelAccuracyScale = 0; - - boolean oracleFlag = false; - if (dbServerType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { - oracleFlag = true; - } - - int j = 0; - for (ItemType.ConstrainByValue valueConstrain : valueConstrainList) { - ConstrainValueType valueType = valueConstrain.getValueType(); - ConstrainOperatorType operatorType = valueConstrain - .getValueOperator(); - String value = valueConstrain.getValueConstraint(); - String unitCd = valueConstrain.getValueUnitOfMeasure(); - - String constraintSql = ""; - // check if value type is not null - if (valueType == null || operatorType == null) { - continue; - } - if (valueType.equals(ConstrainValueType.LARGETEXT)) { - ContainsUtil containsUtil = new ContainsUtil(); - String containsSql = ""; - if (operatorType.value().equalsIgnoreCase( - ConstrainOperatorType.CONTAINS.value())) { - containsSql = containsUtil.formatValue(value, dbServerType); - } else if (operatorType.value().equalsIgnoreCase( - ConstrainOperatorType.CONTAINS_DATABASE.value())) { - containsSql = containsUtil.formatValue("[" + value + "]", - dbServerType); - } else { - log.debug("LARGETEXT : Invalid operator skipped [" - + operatorType.value() + "]"); - continue; - } - // panelAccuracyScale = 100 - panelAccuracyScale; - if (useDefaultModifier - && defaultModifierConstraint != null - && defaultModifierConstraint.trim().length() > 0) - constraintSql += defaultModifierConstraint + " AND "; - - // constraintSql += " AND valtype_cd = 'B' AND " ; - constraintSql += " valtype_cd = 'B' AND "; - // constrainSql = " valtype_cd = 'B' AND " ; - if (oracleFlag == true) { - constraintSql += " ( "; - for (String str: containsSql.split("\\s+")) { - constraintSql += " contains(observation_blob,'{" - + str + "}') "; - - if (panelAccuracyScale > 0) { - constraintSql += " >= " + panelAccuracyScale + " "; - } else { - constraintSql += " > 0 "; - } - constraintSql += " OR "; - } - constraintSql += " 1=0 ) "; - - } else { - if (panelAccuracyScale > 0) { - panelAccuracyScale = panelAccuracyScale * 10; - j++; - containsJoinSql += " INNER JOIN freetexttable(" - + dbSchemaName - + "observation_fact,observation_blob,'" - + containsSql + "') " + " AS ft" + j - + " ON text_search_index = ft" + j + ".[KEY] "; - - constraintSql += " ft" + j + ".[RANK] >= " - + panelAccuracyScale + " "; - - } else { - if (dbServerType.equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) - constraintSql += " observation_blob @@ to_tsquery('english', '" - + containsSql + "') "; - else - constraintSql += " CONTAINS(observation_blob,'" - + containsSql + "') "; - } - } - log.debug("LARGETEXT where clause " + constraintSql); - - } else if (valueType.equals(ConstrainValueType.TEXT)) { - // check if operator and value not null - if (operatorType == null || value == null) { - continue; - } - - boolean notLikeFlag = false; - - if (useDefaultModifier - && defaultModifierConstraint != null - && defaultModifierConstraint.trim().length() > 0) - constraintSql += defaultModifierConstraint + " AND "; - - if (operatorType.value().startsWith( - ConstrainOperatorType.LIKE.value())) { - // call the utility to find the like operation - String operatorOption = RegExUtil - .getOperatorOption(operatorType.value()); - if (operatorOption == null) { - operatorOption = "[begin]"; - } - String likeValueFormat = ""; - if (operatorOption.equalsIgnoreCase("[begin]")) { - likeValueFormat = "'" + value.replaceAll("'", "''") - + "%'"; - } else if (operatorOption.equalsIgnoreCase("[end]")) { - likeValueFormat = "'%" + value.replaceAll("'", "''") - + "'"; - } else if (operatorOption.equalsIgnoreCase("[contains]")) { - likeValueFormat = "'%" + value.replaceAll("'", "''") - + "%'"; - } else if (operatorOption.equalsIgnoreCase("[exact]")) { - likeValueFormat = "'" + value.replaceAll("'", "''") - + "'"; - if (oracleFlag) { - constraintSql += " valtype_cd = 'T' AND upper(tval_char) = " - + " upper(" + likeValueFormat + ")"; - } else { - constraintSql += " valtype_cd = 'T' AND tval_char = " - + likeValueFormat; - } - notLikeFlag = true; - } - if (notLikeFlag == false) { - if (oracleFlag) { - constraintSql += " valtype_cd = 'T' AND upper(tval_char) LIKE " - + " upper(" + likeValueFormat + ")"; - } else { - constraintSql += " valtype_cd = 'T' AND tval_char LIKE " - + likeValueFormat; - } - } - } else if (operatorType.value().equalsIgnoreCase( - ConstrainOperatorType.EQ.value())) { - constraintSql += " valtype_cd = 'T' AND tval_char = '" - + value.replaceAll("'", "''") + "' "; - } else if (operatorType.value().equalsIgnoreCase( - ConstrainOperatorType.IN.value())) { - value = SqlClauseUtil.buildINClause(value, true); - constraintSql += " valtype_cd = 'T' AND tval_char IN (" - + value + ")"; - } else if (operatorType.value().equalsIgnoreCase( - ConstrainOperatorType.BETWEEN.value())) { - throw new I2B2DAOException( - "Error in value constrain, BETWEEN operator not supported in TEXT value type [" - + value + "]"); - /* - * try { value = SqlClauseUtil.buildBetweenClause(value); } - * catch (I2B2Exception e) { throw new - * I2B2DAOException("Error in BETWEEN Clause" + - * e.getMessage() + StackTraceUtil.getStackTrace(e)); } - * constrainSql = - * " valtype_cd = 'T' AND tval_char BETWEEN " + value; - */ - } else if (operatorType.value().equalsIgnoreCase( - ConstrainOperatorType.NE.value())) { - String emptyStringCheck = " "; - if (oracleFlag == false) { - emptyStringCheck = " AND tval_char <> '' "; - } - constraintSql += " valtype_cd = 'T' AND tval_char <> '" - + value.replaceAll("'", "''") + "' " - + emptyStringCheck; - } else { - throw new I2B2DAOException( - "Error TEXT value constrain because operator(" - + operatorType.toString() + ")is invalid"); - } - } else if (valueType.equals(ConstrainValueType.NUMBER)) { - // check if operator and value not null - if (operatorType == null || value == null) { - continue; - } - value.replaceAll("'", "''"); - - String nvalNum = " nval_num ", unitsCdInClause = " "; - if (this.unitCdConverstionFlag) { - nvalNum = unitCdSwitchClause; - // unitsCdInClause = this.unitCdInClause + " AND "; - - // commented not needed - // if (unitCd != null) { - // unitCd = unitCd.replace("'", "''"); - // unitsCdInClause = " case when '" + unitCd + "' in " + - // this.unitCdInClause + " then 1 else 0 end =1 AND "; - // } - unitsCdInClause = " "; - } - - if (useDefaultModifier - && defaultModifierConstraint != null - && defaultModifierConstraint.trim().length() > 0) - constraintSql += defaultModifierConstraint + " AND "; - - if (operatorType.value().equalsIgnoreCase( - ConstrainOperatorType.GT.value())) { - constraintSql += unitsCdInClause - + " (( valtype_cd = 'N' AND " - + nvalNum - + " > " - + value - + " AND tval_char IN ('E','GE')) OR ( valtype_cd = 'N' AND " - + nvalNum + " >= " + value - + " AND tval_char = 'G' )) "; - } else if (operatorType.value().equalsIgnoreCase( - ConstrainOperatorType.GE.value())) { - constraintSql += unitsCdInClause - + " valtype_cd = 'N' AND " + nvalNum + " >= " - + value + " AND tval_char IN ('E','GE','G') "; - } else if (operatorType.value().equalsIgnoreCase( - ConstrainOperatorType.LT.value())) { - constraintSql += unitsCdInClause - + " (( valtype_cd = 'N' AND " - + nvalNum - + " < " - + value - + " AND tval_char IN ('E','LE')) OR ( valtype_cd = 'N' AND " - + nvalNum + " <= " + value - + " AND tval_char = 'L' )) "; - } else if (operatorType.value().equalsIgnoreCase( - ConstrainOperatorType.LE.value())) { - constraintSql += unitsCdInClause - + " valtype_cd = 'N' AND " + nvalNum + " <= " - + value + " AND tval_char IN ('E','LE','L') "; - } else if (operatorType.value().equalsIgnoreCase( - ConstrainOperatorType.EQ.value())) { - constraintSql += unitsCdInClause - + " valtype_cd = 'N' AND " + nvalNum + " = " - + value + " AND tval_char='E' "; - } else if (operatorType.value().equalsIgnoreCase( - ConstrainOperatorType.BETWEEN.value())) { - try { - value = SqlClauseUtil.buildBetweenClause(value); - } catch (I2B2Exception e) { - throw new I2B2DAOException("Error in BETWEEN Clause" - + e.getMessage() - + StackTraceUtil.getStackTrace(e)); - } - constraintSql += unitsCdInClause - + " valtype_cd = 'N' AND " + nvalNum - + " BETWEEN " + value + " AND tval_char ='E' "; - } else if (operatorType.value().equalsIgnoreCase( - ConstrainOperatorType.NE.value())) { - constraintSql += unitsCdInClause - + " (( valtype_cd = 'N' AND " - + nvalNum - + " <> " - + value - + " AND tval_char <> 'NE') OR ( valtype_cd = 'N' AND " - + nvalNum + " = " + value - + " AND tval_char ='NE' )) "; - } else { - throw new I2B2DAOException( - "Error NUMBER value constrain because operator(" - + operatorType.toString() + ")is invalid"); - } - } else if (valueType.equals(ConstrainValueType.FLAG)) { - // check if operator and value not null - if (operatorType == null || value == null) { - continue; - } - - if (useDefaultModifier - && defaultModifierConstraint != null - && defaultModifierConstraint.trim().length() > 0) - constraintSql += defaultModifierConstraint + " AND "; - - if (operatorType.value().equalsIgnoreCase( - ConstrainOperatorType.EQ.value())) { - constraintSql += " valueflag_cd = '" - + value.replaceAll("'", "''") + "' "; - } else if (operatorType.value().equalsIgnoreCase( - ConstrainOperatorType.NE.value())) { - String emptyStringCheck = " "; - if (oracleFlag == false) { - emptyStringCheck = " AND valueflag_cd <> '' "; - } - constraintSql += " valueflag_cd <> '" - + value.replaceAll("'", "''") + "' " - + emptyStringCheck; - } else if (operatorType.value().equalsIgnoreCase( - ConstrainOperatorType.IN.value())) { - value = SqlClauseUtil.buildINClause(value, true); - constraintSql += " valueflag_cd IN (" + value + ")"; - } else { - throw new I2B2DAOException( - "Error FLAG value constrain because operator(" - + operatorType.toString() + ")is invalid"); - } - } else if (valueType.equals(ConstrainValueType.MODIFIER)) { - // check if operator and value not null - if (operatorType == null || value == null) { - continue; - } - if (value != null) { - if (operatorType.value().equalsIgnoreCase( - ConstrainOperatorType.EQ.value())) { - constraintSql = " valtype_cd = 'M' and tval_char = '" - + value.replaceAll("'", "''") + "' "; - } else if (operatorType.value().equalsIgnoreCase( - ConstrainOperatorType.NE.value())) { - constraintSql = " valtype_cd = 'M' and tval_char <> '" - + value.replaceAll("'", "''") - + "' and tval_char <> ''"; - } else if (operatorType.value().equalsIgnoreCase( - ConstrainOperatorType.IN.value())) { - value = SqlClauseUtil.buildINClause(value, true); - constraintSql = " valtype_cd = 'M' and tval_char IN (" - + value + ") "; - } - - } - - } else { - throw new I2B2DAOException( - "Error value constrain, invalid value type (" - + valueType.toString() + ")"); - } - - if (constraintSql != null && constraintSql.trim().length() > 0) { - if (fullConstrainSql.length() > 0) { - fullConstrainSql += " AND "; - } - - fullConstrainSql += constraintSql; - } - } - - return new String[] { fullConstrainSql, containsJoinSql }; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + * Christopher Herrick + */ +package edu.harvard.i2b2.crc.dao.setfinder.querybuilder; + +import java.util.List; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.exception.StackTraceUtil; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ConstrainOperatorType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ConstrainValueType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ItemType; +import edu.harvard.i2b2.crc.util.ContainsUtil; +import edu.harvard.i2b2.crc.util.RegExUtil; +import edu.harvard.i2b2.crc.util.SqlClauseUtil; + +/** + * Class to handle value constrains. Generates sql where clause based on the + * list of value constrains. + * + * @author rkuttan + */ +public class ValueConstrainsHandler { + /** log **/ + protected final Log log = LogFactory.getLog(getClass()); + + private boolean unitCdConverstionFlag = false; + private String unitCdInClause = "", unitCdSwitchClause = ""; + + // ch@0013012 - The decision was made that modifier_cd needs to have a + // default value when querying for concept value (numeric, text, large text) - + // if a default value is not specified for modifier_cd, a concept value + // constraint could bring back rows that match the values on modifier and not + // on the main concept value - this would be an error. To get around this, + // we need to include a default modifier_cd constraint on all non-modifier + // value constraints. After careful consideration, it was determined that + // the default value for modifier_cd should be '@'. This could present + // problems at sites where no non-modifier row was created for a concept + // or where an alternative modifier_cd was specified as the default. To make + // customization easier in these cases, the modifier constraint is + // defined here and included in the appropriate sql statements below. Additionally, + // I've maintained the old constructValueConstainClause so 1.6 queries work the same + private String defaultModifierConstraint = " modifier_cd = '@' "; + + + public void setUnitCdConversionFlag(boolean unitCdConverstionFlag, + String unitCdInClause, String unitCdSwitchClause) { + this.unitCdConverstionFlag = unitCdConverstionFlag; + this.unitCdInClause = unitCdInClause; + this.unitCdSwitchClause = unitCdSwitchClause; + } + + public String[] constructValueConstainClause( + List valueConstrainList, + String dbServerType, String dbSchemaName, int panelAccuracyScale) throws I2B2DAOException{ + //used for backward compatibility + defaultModifierConstraint = ""; + return constructValueConstainClause(valueConstrainList, dbServerType, dbSchemaName, panelAccuracyScale, false); + } + + + public String[] constructValueConstainClause( + List valueConstrainList, + String dbServerType, String dbSchemaName, int panelAccuracyScale, + boolean useDefaultModifier) + throws I2B2DAOException { + String fullConstrainSql = "", containsJoinSql = ""; + log.debug("panel accuracy scale" + panelAccuracyScale); + panelAccuracyScale = 0; + + boolean oracleFlag = false; + if (dbServerType.equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { + oracleFlag = true; + } + + int j = 0; + for (ItemType.ConstrainByValue valueConstrain : valueConstrainList) { + ConstrainValueType valueType = valueConstrain.getValueType(); + ConstrainOperatorType operatorType = valueConstrain + .getValueOperator(); + String value = valueConstrain.getValueConstraint(); + String unitCd = valueConstrain.getValueUnitOfMeasure(); + + String constraintSql = ""; + // check if value type is not null + if (valueType == null || operatorType == null) { + continue; + } + if (valueType.equals(ConstrainValueType.LARGETEXT)) { + ContainsUtil containsUtil = new ContainsUtil(); + String containsSql = ""; + if (operatorType.value().equalsIgnoreCase( + ConstrainOperatorType.CONTAINS.value())) { + containsSql = containsUtil.formatValue(value, dbServerType); + } else if (operatorType.value().equalsIgnoreCase( + ConstrainOperatorType.CONTAINS_DATABASE.value())) { + containsSql = containsUtil.formatValue("[" + value + "]", + dbServerType); + } else { + log.debug("LARGETEXT : Invalid operator skipped [" + + operatorType.value() + "]"); + continue; + } + // panelAccuracyScale = 100 - panelAccuracyScale; + if (useDefaultModifier + && defaultModifierConstraint != null + && defaultModifierConstraint.trim().length() > 0) + constraintSql += defaultModifierConstraint + " AND "; + + // constraintSql += " AND valtype_cd = 'B' AND " ; + constraintSql += " valtype_cd = 'B' AND "; + // constrainSql = " valtype_cd = 'B' AND " ; + if (oracleFlag == true) { + constraintSql += " ( "; + for (String str: containsSql.split("\\s+")) { + constraintSql += " contains(observation_blob,'{" + + str + "}') "; + + if (panelAccuracyScale > 0) { + constraintSql += " >= " + panelAccuracyScale + " "; + } else { + constraintSql += " > 0 "; + } + constraintSql += " OR "; + } + constraintSql += " 1=0 ) "; + + } else { + if (panelAccuracyScale > 0) { + panelAccuracyScale = panelAccuracyScale * 10; + j++; + containsJoinSql += " INNER JOIN freetexttable(" + + dbSchemaName + + "observation_fact,observation_blob,'" + + containsSql + "') " + " AS ft" + j + + " ON text_search_index = ft" + j + ".[KEY] "; + + constraintSql += " ft" + j + ".[RANK] >= " + + panelAccuracyScale + " "; + + } else { + if (dbServerType.equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) + constraintSql += " observation_blob @@ to_tsquery('english', '" + + containsSql + "') "; + else + constraintSql += " CONTAINS(observation_blob,'" + + containsSql + "') "; + } + } + log.debug("LARGETEXT where clause " + constraintSql); + + } else if (valueType.equals(ConstrainValueType.TEXT)) { + // check if operator and value not null + if (operatorType == null || value == null) { + continue; + } + + boolean notLikeFlag = false; + + if (useDefaultModifier + && defaultModifierConstraint != null + && defaultModifierConstraint.trim().length() > 0) + constraintSql += defaultModifierConstraint + " AND "; + + if (operatorType.value().startsWith( + ConstrainOperatorType.LIKE.value())) { + // call the utility to find the like operation + String operatorOption = RegExUtil + .getOperatorOption(operatorType.value()); + if (operatorOption == null) { + operatorOption = "[begin]"; + } + String likeValueFormat = ""; + if (operatorOption.equalsIgnoreCase("[begin]")) { + likeValueFormat = "'" + value.replaceAll("'", "''") + + "%'"; + } else if (operatorOption.equalsIgnoreCase("[end]")) { + likeValueFormat = "'%" + value.replaceAll("'", "''") + + "'"; + } else if (operatorOption.equalsIgnoreCase("[contains]")) { + likeValueFormat = "'%" + value.replaceAll("'", "''") + + "%'"; + } else if (operatorOption.equalsIgnoreCase("[exact]")) { + likeValueFormat = "'" + value.replaceAll("'", "''") + + "'"; + if (oracleFlag) { + constraintSql += " valtype_cd = 'T' AND upper(tval_char) = " + + " upper(" + likeValueFormat + ")"; + } else { + constraintSql += " valtype_cd = 'T' AND tval_char = " + + likeValueFormat; + } + notLikeFlag = true; + } + if (notLikeFlag == false) { + if (oracleFlag) { + constraintSql += " valtype_cd = 'T' AND upper(tval_char) LIKE " + + " upper(" + likeValueFormat + ")"; + } else { + constraintSql += " valtype_cd = 'T' AND tval_char LIKE " + + likeValueFormat; + } + } + } else if (operatorType.value().equalsIgnoreCase( + ConstrainOperatorType.EQ.value())) { + constraintSql += " valtype_cd = 'T' AND tval_char = '" + + value.replaceAll("'", "''") + "' "; + } else if (operatorType.value().equalsIgnoreCase( + ConstrainOperatorType.IN.value())) { + value = SqlClauseUtil.buildINClause(value, true); + constraintSql += " valtype_cd = 'T' AND tval_char IN (" + + value + ")"; + } else if (operatorType.value().equalsIgnoreCase( + ConstrainOperatorType.BETWEEN.value())) { + throw new I2B2DAOException( + "Error in value constrain, BETWEEN operator not supported in TEXT value type [" + + value + "]"); + /* + * try { value = SqlClauseUtil.buildBetweenClause(value); } + * catch (I2B2Exception e) { throw new + * I2B2DAOException("Error in BETWEEN Clause" + + * e.getMessage() + StackTraceUtil.getStackTrace(e)); } + * constrainSql = + * " valtype_cd = 'T' AND tval_char BETWEEN " + value; + */ + } else if (operatorType.value().equalsIgnoreCase( + ConstrainOperatorType.NE.value())) { + String emptyStringCheck = " "; + if (oracleFlag == false) { + emptyStringCheck = " AND tval_char <> '' "; + } + constraintSql += " valtype_cd = 'T' AND tval_char <> '" + + value.replaceAll("'", "''") + "' " + + emptyStringCheck; + } else { + throw new I2B2DAOException( + "Error TEXT value constrain because operator(" + + operatorType.toString() + ")is invalid"); + } + } else if (valueType.equals(ConstrainValueType.NUMBER)) { + // check if operator and value not null + if (operatorType == null || value == null) { + continue; + } + value.replaceAll("'", "''"); + + String nvalNum = " nval_num ", unitsCdInClause = " "; + if (this.unitCdConverstionFlag) { + nvalNum = unitCdSwitchClause; + // unitsCdInClause = this.unitCdInClause + " AND "; + + // commented not needed + // if (unitCd != null) { + // unitCd = unitCd.replace("'", "''"); + // unitsCdInClause = " case when '" + unitCd + "' in " + + // this.unitCdInClause + " then 1 else 0 end =1 AND "; + // } + unitsCdInClause = " "; + } + + if (useDefaultModifier + && defaultModifierConstraint != null + && defaultModifierConstraint.trim().length() > 0) + constraintSql += defaultModifierConstraint + " AND "; + + if (operatorType.value().equalsIgnoreCase( + ConstrainOperatorType.GT.value())) { + constraintSql += unitsCdInClause + + " (( valtype_cd = 'N' AND " + + nvalNum + + " > " + + value + + " AND tval_char IN ('E','GE')) OR ( valtype_cd = 'N' AND " + + nvalNum + " >= " + value + + " AND tval_char = 'G' )) "; + } else if (operatorType.value().equalsIgnoreCase( + ConstrainOperatorType.GE.value())) { + constraintSql += unitsCdInClause + + " valtype_cd = 'N' AND " + nvalNum + " >= " + + value + " AND tval_char IN ('E','GE','G') "; + } else if (operatorType.value().equalsIgnoreCase( + ConstrainOperatorType.LT.value())) { + constraintSql += unitsCdInClause + + " (( valtype_cd = 'N' AND " + + nvalNum + + " < " + + value + + " AND tval_char IN ('E','LE')) OR ( valtype_cd = 'N' AND " + + nvalNum + " <= " + value + + " AND tval_char = 'L' )) "; + } else if (operatorType.value().equalsIgnoreCase( + ConstrainOperatorType.LE.value())) { + constraintSql += unitsCdInClause + + " valtype_cd = 'N' AND " + nvalNum + " <= " + + value + " AND tval_char IN ('E','LE','L') "; + } else if (operatorType.value().equalsIgnoreCase( + ConstrainOperatorType.EQ.value())) { + constraintSql += unitsCdInClause + + " valtype_cd = 'N' AND " + nvalNum + " = " + + value + " AND tval_char='E' "; + } else if (operatorType.value().equalsIgnoreCase( + ConstrainOperatorType.BETWEEN.value())) { + try { + value = SqlClauseUtil.buildBetweenClause(value); + } catch (I2B2Exception e) { + throw new I2B2DAOException("Error in BETWEEN Clause" + + e.getMessage() + + StackTraceUtil.getStackTrace(e)); + } + constraintSql += unitsCdInClause + + " valtype_cd = 'N' AND " + nvalNum + + " BETWEEN " + value + " AND tval_char ='E' "; + } else if (operatorType.value().equalsIgnoreCase( + ConstrainOperatorType.NE.value())) { + constraintSql += unitsCdInClause + + " (( valtype_cd = 'N' AND " + + nvalNum + + " <> " + + value + + " AND tval_char <> 'NE') OR ( valtype_cd = 'N' AND " + + nvalNum + " = " + value + + " AND tval_char ='NE' )) "; + } else { + throw new I2B2DAOException( + "Error NUMBER value constrain because operator(" + + operatorType.toString() + ")is invalid"); + } + } else if (valueType.equals(ConstrainValueType.FLAG)) { + // check if operator and value not null + if (operatorType == null || value == null) { + continue; + } + + if (useDefaultModifier + && defaultModifierConstraint != null + && defaultModifierConstraint.trim().length() > 0) + constraintSql += defaultModifierConstraint + " AND "; + + if (operatorType.value().equalsIgnoreCase( + ConstrainOperatorType.EQ.value())) { + constraintSql += " valueflag_cd = '" + + value.replaceAll("'", "''") + "' "; + } else if (operatorType.value().equalsIgnoreCase( + ConstrainOperatorType.NE.value())) { + String emptyStringCheck = " "; + if (oracleFlag == false) { + emptyStringCheck = " AND valueflag_cd <> '' "; + } + constraintSql += " valueflag_cd <> '" + + value.replaceAll("'", "''") + "' " + + emptyStringCheck; + } else if (operatorType.value().equalsIgnoreCase( + ConstrainOperatorType.IN.value())) { + value = SqlClauseUtil.buildINClause(value, true); + constraintSql += " valueflag_cd IN (" + value + ")"; + } else { + throw new I2B2DAOException( + "Error FLAG value constrain because operator(" + + operatorType.toString() + ")is invalid"); + } + } else if (valueType.equals(ConstrainValueType.MODIFIER)) { + // check if operator and value not null + if (operatorType == null || value == null) { + continue; + } + if (value != null) { + if (operatorType.value().equalsIgnoreCase( + ConstrainOperatorType.EQ.value())) { + constraintSql = " valtype_cd = 'M' and tval_char = '" + + value.replaceAll("'", "''") + "' "; + } else if (operatorType.value().equalsIgnoreCase( + ConstrainOperatorType.NE.value())) { + constraintSql = " valtype_cd = 'M' and tval_char <> '" + + value.replaceAll("'", "''") + + "' and tval_char <> ''"; + } else if (operatorType.value().equalsIgnoreCase( + ConstrainOperatorType.IN.value())) { + value = SqlClauseUtil.buildINClause(value, true); + constraintSql = " valtype_cd = 'M' and tval_char IN (" + + value + ") "; + } + + } + + } else { + throw new I2B2DAOException( + "Error value constrain, invalid value type (" + + valueType.toString() + ")"); + } + + if (constraintSql != null && constraintSql.trim().length() > 0) { + if (fullConstrainSql.length() > 0) { + fullConstrainSql += " AND "; + } + + fullConstrainSql += constraintSql; + } + } + + return new String[] { fullConstrainSql, containsJoinSql }; + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalPanel.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalPanel.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalPanel.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalPanel.java index 67b21dba..c51f6b19 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalPanel.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalPanel.java @@ -1,2319 +1,2319 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Christopher Herrick - */ - -package edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Hashtable; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import javax.xml.stream.XMLStreamException; - -import org.apache.axis2.AxisFault; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.exception.StackTraceUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.ConceptNotFoundException; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.DateConstrainUtil; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.OntologyException; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.QueryTimingHandler; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.TotalItemOccurrenceHandler; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal.TemporalQueryOptions.InvertedConstraintStrategy; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal.TemporalQueryOptions.QueryConstraintStrategy; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; -import edu.harvard.i2b2.crc.datavo.ontology.DerivedFactColumnsType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ItemType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.PanelType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.PanelType.TotalItemOccurrences; -import edu.harvard.i2b2.crc.delegate.ontology.CallOntologyUtil; -import edu.harvard.i2b2.crc.datavo.setfinder.query.TotOccuranceOperatorType; -import edu.harvard.i2b2.crc.util.ItemKeyUtil; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - -/** - * Temporal Panel Object - * - *

    - * Panel query object that wraps the panel tag found in the query definition - * xml. It roughly corresponds to a panel in the query UI. Panel is responsible - * for organizing the sql that comes back from individual panel items - sql from - * items should be logically or'd together. It is also the container that holds - * the panel constraint types - occurrence, dates, and exclude. - * - * @author Christopher Herrick - * - */ -public class TemporalPanel implements Comparable { - - protected final Log log = LogFactory.getLog(getClass()); - - /* - * Max Timing Score - max score a panel can get when ordering based on items - * and timing - */ - private final int MAXTIMINGSCORE = 5; - - private TemporalSubQuery parent; - private PanelType basePanel; - private int estimatedPanelSize = 0; - private List panelItemList = null; - private int missingItemTotals = 0; - - protected class TemporalPanelItemSql{ - protected String itemSql = null; - protected String factTable = null; - protected String joinTable = null; - protected boolean valueConstraint = false; - protected boolean textConstraint = false; - } - /** - * Constructor - * - * @param parent - * reference to the temporal panel group to which this panel - * belongs - * @param panel - * i2b2 instantiation of the panel xml object found in the query - * definition - * @throws I2B2Exception - * thrown when an i2b2 specific error is found - */ - public TemporalPanel(TemporalSubQuery parent, PanelType panel) - throws I2B2Exception { - this.parent = parent; - this.basePanel = panel; - - parsePanel(); - } - - /** - * Parse Panel - * - * Parses through the paneltype object passed in through the constructor. - * Evaluates each panel item and casts them to the appropriate type. - * Calculates the estimated return size of the times in the panel which will - * then be used when sorting panel items - * - * @throws I2B2Exception - * thrown when an i2b2 specific error is found - */ - private void parsePanel() throws I2B2Exception { - panelItemList = new ArrayList(); - - List itemList = basePanel.getItem(); - - for (ItemType itemType : itemList) { - TemporalPanelItem panelItem = null; - try{ - if (itemType.getItemKey().toLowerCase() - .startsWith(ItemKeyUtil.ITEM_KEY_PATIENT_SET)) { - panelItem = new TemporalPanelPatientSetItem(this, itemType); - } else if (itemType.getItemKey().toLowerCase() - .startsWith(ItemKeyUtil.ITEM_KEY_PATIENT_ENCOUNTER_SET)) { - panelItem = new TemporalPanelPatientEncounterSetItem(this, - itemType); - } else if (itemType.getItemKey().toLowerCase() - .startsWith(ItemKeyUtil.ITEM_KEY_MASTERID)) { - panelItem = new TemporalPanelEmbeddedQueryItem(this, itemType); - } else if (itemType.getItemKey().toLowerCase() - .startsWith(ItemKeyUtil.ITEM_KEY_PATIENT)) { - panelItem = new TemporalPanelPatientItem(this, itemType); - } else if (itemType.getItemKey().toLowerCase() - .startsWith(ItemKeyUtil.ITEM_KEY_ENCOUNTER)) { - panelItem = new TemporalPanelEncounterItem(this, itemType); - } else { - panelItem = new TemporalPanelConceptItem(this, itemType); - if(panelItem.getConceptType() == null) - panelItem.getConceptType(); - if (panelItem != null - && panelItem.getConceptType() != null - && panelItem.getConceptType().getDimcode() != null - && panelItem.getConceptType().getDimcode() - .toLowerCase().trim() - .startsWith(ItemKeyUtil.ITEM_KEY_CELLID)) { - panelItem = new TemporalPanelCellQueryItem(this, itemType, - panelItem.getConceptType()); - - } - if (parent.isProtectedQuery() == false) - parent.setProtectedQuery(panelItem.getConceptType().getProtectedAccess().equalsIgnoreCase("Y")?true:false); - /* - * check for derived table parameter and look for other views for this item. - * ... i.e. item is found in multiple views. - * ... if others found, then add them to the panel item list individually. - */ - if (this.parent.getQueryOptions()!=null&&this.parent.getQueryOptions().useDerivedFactTable()) - { - if(panelItem.getConceptType().getFacttablecolumn().contains(".")) - { - String baseItemFactColumn = panelItem.getConceptType().getFacttablecolumn(); - DerivedFactColumnsType columns = getFactColumnsFromOntologyCell(itemType.getItemKey()); - if(columns.getDerivedFactTableColumn().size() > 1) { - - for (String column : columns.getDerivedFactTableColumn()) { - // look for non-null fact table columns that are not equal to the base item's column - if((column != null) && !(column.equals(baseItemFactColumn))){ - if(column.contains(".")){ - TemporalPanelItem derivedPanelItem = new TemporalPanelConceptItem(this, itemType); - if(derivedPanelItem.getConceptType() == null) - derivedPanelItem.getConceptType(); - - if (derivedPanelItem != null - && derivedPanelItem.getConceptType() != null - && derivedPanelItem.getConceptType().getDimcode() != null - && derivedPanelItem.getConceptType().getDimcode() - .toLowerCase().trim() - .startsWith(ItemKeyUtil.ITEM_KEY_CELLID)) { - derivedPanelItem = new TemporalPanelCellQueryItem(this, itemType, - derivedPanelItem.getConceptType()); - } - log.debug("setting a new fact column: " + column); - derivedPanelItem.parseFactColumn(column); - panelItemList.add(derivedPanelItem); - } - } - } - } - - } - } - } - Integer conceptTotal = panelItem.getConceptTotal(); - if (conceptTotal != null) { - estimatedPanelSize += conceptTotal; - } else - missingItemTotals++; - panelItemList.add(panelItem); - - - } - catch (ConceptNotFoundException ce){ - log.debug("Concept not found error: " + ce.getMessage()); - parent.addIgnoredMessage(ce.getMessage() + " panel#" + parent.getPanelIndex(this)); - } - } - } - - protected DerivedFactColumnsType getFactColumnsFromOntologyCell(String itemKey) - throws ConceptNotFoundException, OntologyException { - DerivedFactColumnsType factColumns = new DerivedFactColumnsType(); - try { - - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - String ontologyUrl = qpUtil - .getCRCPropertyValue(QueryProcessorUtil.ONTOLOGYCELL_ROOT_WS_URL_PROPERTIES); - - factColumns = CallOntologyUtil.callGetFactColumns(itemKey, - parent.getSecurityType(), parent.getProjectId(), - ontologyUrl +"/getDerivedFactColumns"); - } catch (JAXBUtilException e) { - - log.error("Error while fetching metadata [" + itemKey - + "] from ontology ", e); - throw new OntologyException("Error while fetching metadata [" - + itemKey + "] from ontology " - + StackTraceUtil.getStackTrace(e)); - } catch (I2B2Exception e) { - log.error("Error while fetching metadata from ontology ", e); - throw new OntologyException("Error while fetching metadata [" - + itemKey + "] from ontology " - + StackTraceUtil.getStackTrace(e)); - } catch (AxisFault e) { - log.error("Error while fetching metadata from ontology ", e); - throw new OntologyException("Error while fetching metadata [" - + itemKey + "] from ontology " - + StackTraceUtil.getStackTrace(e)); - } catch (XMLStreamException e) { - log.error("Error while fetching metadata from ontology ", e); - throw new OntologyException("Error while fetching metadata [" - + itemKey + "] from ontology " - + StackTraceUtil.getStackTrace(e)); - } - -// if (factColumns.isEmpty()) { -// throw new ConceptNotFoundException("[" + itemKey + "] "); - -// } - - return factColumns; - } - - /** - * Build Sql - * - * Main method for generating the sql string that will be run on the - * database for this panel item. Iterates through each item contained in the - * panel and appends sql together to form sql string for all items in the - * panel - * - * @param currentIndex - * int value that represents the panel position in the query - * @return String sql representation of the items in the query - * @throws I2B2DAOException - * thrown when a data related i2b2 issue is encountered - */ - public String buildSql(int currentIndex) throws I2B2DAOException { - boolean firstPanel = this.isFirstPanelInQuery(); - StringBuilder panelSqlBuffer = new StringBuilder(); - - boolean addDelimiter = false; - // OMOP WAS... - // List itemSqlList = getItemSql(); - List itemSqlList = getItemSql(); - if (itemSqlList!=null&&itemSqlList.size()>0){ - if (this.hasPanelOccurrenceConstraint() - && this.applyOccurrenceToPanelLevel() - && (this.getItemList().size() > 1 || !this.isPatientOnlyQuery())) { - if (firstPanel) { - panelSqlBuffer - .append(firstPanelItemSqlWithOccurrence(itemSqlList)); - } else { - panelSqlBuffer.append(nonFirstPanelItemSqlWithOccurrence( - currentIndex, itemSqlList)); - } - } else if (firstPanel && this.isPanelInverted()) { - panelSqlBuffer.append(buildFirstPanelInvertSql(itemSqlList)); - } else { - if (firstPanel) { - panelSqlBuffer.append(firstPanelItemSql(itemSqlList)); - } else { - panelSqlBuffer.append(nonFirstPanelItemSql(itemSqlList, - currentIndex)); - } - } - } - else if (this.isPanelInverted()){ - //no items and inverted panel means this is a get everyone query - - String schema = getDatabaseSchema(); - if (schema == null) - schema = ""; - else if (!schema.endsWith(".")) - schema += "."; - - panelSqlBuffer.append("insert into " + parent.getTempTableName() + " (patient_num, panel_count ) " + - "select distinct patient_num, 0 from " + schema + "patient_dimension pat "); - - } - - return panelSqlBuffer.toString(); - } - - /** - * Get Item Sql - * - * Gets the sql for each of the items in the panel and returns the results - * in an List - * - * @return List list of sql statements for all the times contained in the panel - * @throws I2B2DAOException - */ - //OMOP WAS.. -/* private List getItemSql() throws I2B2DAOException { - List itemList = null; - if (panelItemList.size() > 0) { - itemList = new ArrayList(panelItemList.size()); - for (TemporalPanelItem item : panelItemList) { - try { - itemList.add(item.buildSql()); - } - catch (ConceptNotFoundException ce){ - parent.addIgnoredMessage(ce.getMessage() + " panel#" + parent.getPanelIndex(this)); - } - } - } - return itemList; - } - */ - private List getItemSql() throws I2B2DAOException { - List itemList = null; - if (panelItemList.size() > 0) { - itemList = new ArrayList(panelItemList.size()); - for (TemporalPanelItem item : panelItemList) { - try { - TemporalPanelItemSql itemSql = new TemporalPanelItemSql(); - itemSql.itemSql = item.buildSql(); - itemSql.factTable = item.factTable; - itemSql.joinTable = item.tableName; - itemList.add(itemSql); - } - catch (ConceptNotFoundException ce){ - parent.addIgnoredMessage(ce.getMessage() + " panel#" + parent.getPanelIndex(this)); - } - } - } - return itemList; - } - - /** - * Union Item Sql - * - * Takes the list of individual sql statements and constructs one sql statement by unioning - * individual statements together. Submitted statements are assumed to have the same select list - * - * @param itemSqlList List of individual sql statements - * @return String one sql statement that unions individual statement together - */ - //OMOP WAS.. - // private String unionItemSql(List itemSqlList) { - private String unionItemSql(List itemSqlList) { - StringBuilder unionSql = new StringBuilder(); - - boolean first = true; - // OMOP WAS... - //for (String itemSql : itemSqlList) { - for (TemporalPanelItemSql itemSqlItem : itemSqlList) { - String itemSql = itemSqlItem.itemSql; - if (!first) - unionSql.append("\n union all \n"); - else - first = false; - - unionSql.append(itemSql); - } - - return unionSql.toString(); - } - - /** - * Consolidate Item Sql - * - * Takes in list of individual sql statements and combines them by consolidating statements with the same from clause - * into one statement with multiple constraints. Statements with different from clauses are unioned together - * - * @param itemSql List of individual sql statements - * @return String one sql statement that combines all statements from the individual list - */ - //OMOP WAS.. -// private String consolidateItemSql(List itemSql) { - private String consolidateItemSql(List itemSqlList) { - StringBuilder itemSqlBuffer = new StringBuilder(); - - HashMap> tableMatch = new HashMap>(); - int index = 0; - //OMOP WAS.. - // for (String sql : itemSql) { - for (TemporalPanelItemSql itemSql : itemSqlList) { - String sql = itemSql.itemSql; - TemporalQuerySimpleSqlParser simpleSql = new TemporalQuerySimpleSqlParser( - sql); - - String selectClause = simpleSql.getSelectClause(); - String fromClause = simpleSql.getFromClause(); - String groupByClause = simpleSql.getGroupByClause(); - String havingClause = simpleSql.getHavingClause(); - - String consolidatedKey = selectClause - + "|" - + fromClause - + "|" - + (groupByClause != null - && groupByClause.trim().length() > 0 ? "|" - + groupByClause : ""); - - if (havingClause != null && havingClause.trim().length() > 0) { - consolidatedKey += "|" + String.valueOf(index); - } - - List sqlList = null; - if (tableMatch.containsKey(consolidatedKey)) { - sqlList = tableMatch.get(consolidatedKey); - } else { - sqlList = new ArrayList(); - } - - sqlList.add(simpleSql); - tableMatch.put(consolidatedKey, sqlList); - index++; - } - - boolean firstKey = true; - for (String consolidatedKey : tableMatch.keySet()) { - List sqlList = tableMatch - .get(consolidatedKey); - - boolean firstItem = true; - - String selectClause = ""; - String fromClause = ""; - String whereClause = ""; - String groupByClause = ""; - String havingClause = ""; - for (TemporalQuerySimpleSqlParser simpleSql : sqlList) { - if (firstItem) { - selectClause = "select " + simpleSql.getSelectClause() - + " "; - fromClause = "from " + simpleSql.getFromClause() + " "; - if (simpleSql.getGroupByClause() != null - && simpleSql.getGroupByClause().trim().length() > 0) - groupByClause = "group by " - + simpleSql.getGroupByClause() + " "; - if (simpleSql.getHavingClause() != null - && simpleSql.getHavingClause().trim().length() > 0) - havingClause = "having " + simpleSql.getHavingClause() - + " "; - } - - if (simpleSql.getWhereClause() != null - && simpleSql.getWhereClause().trim().length() > 0) { - if (whereClause.length() == 0) { - whereClause = "where (" + simpleSql.getWhereClause() - + ") "; - } else { - whereClause += "or (" + simpleSql.getWhereClause() - + ") "; - } - } - - firstItem = false; - } - - if (!firstKey) { - itemSqlBuffer.append("\nunion all \n"); - } - - itemSqlBuffer.append(selectClause); - itemSqlBuffer.append(fromClause); - if (whereClause != null && whereClause.trim().length() > 0) - itemSqlBuffer.append(whereClause); - if (groupByClause != null && groupByClause.trim().length() > 0) - itemSqlBuffer.append(groupByClause); - if (havingClause != null && havingClause.trim().length() > 0) - itemSqlBuffer.append(havingClause); - - firstKey = false; - } - - return itemSqlBuffer.toString(); - } - - /** - * Build Item Union Sql - * - * Used to return the proper sql syntax for unioning two sql statements - * together - * - * @return String with sql building block used to union to sql statements - * together - * @throws I2B2DAOException - * thrown when an i2b2 related data error is encountered - */ - private String buildItemUnionSql() throws I2B2DAOException { - StringBuilder itemSqlBuffer = new StringBuilder(); - - int currentIndex = 0; - for (TemporalPanelItem item : panelItemList) { - String itemSql = item.buildSql(); - if (currentIndex > 0) { - itemSqlBuffer.append("\n union all \n"); - } - - itemSqlBuffer.append(itemSql); - currentIndex++; - } - - return itemSqlBuffer.toString(); - } - - /** - * First Panel Item Sql - * - * Processes an item from the first panel of a panel group. First panel - * items are processed as an insert statement into a temporary table rather - * than an update - * - * @param itemSqlList - * List of individual sql statements found in this panel - * @return String sql representation that joins the item sql to the panel - * sql - */ - //OMOP WAS... - // private String firstPanelItemSql(List itemSqlList) { - private String firstPanelItemSql(List itemSqlList) { - StringBuilder panelSql = new StringBuilder(); - boolean addDelimiter = false; - - //OMOP WAS.. - // for (String itemSql : itemSqlList) { - for (TemporalPanelItemSql itemSqlItem : itemSqlList) { - String itemSql = itemSqlItem.itemSql; - String insertValuesClause = buildInsertValuesClause(); - - StringBuilder withItemSql = new StringBuilder(); - - String firstPanelItemSql = ""; - - String innerSelectClause = buildInnerSelectClause(); - String innerGroupByClause = buildInnerGroupByClause(); - - String itemStatement = ""; - StringBuilder tableStatement = new StringBuilder(itemSql); - - boolean useTempTables = false; - if (parent.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER) - && parent.getQueryOptions().getQueryConstraintLogic() == QueryConstraintStrategy.TEMP_TABLES) { - useTempTables = true; - } - - // String suffix = getPanelId(); - String suffix = ""; - - String tSelect = "select " + innerSelectClause + " " + "from " - + (useTempTables ? "#t" + suffix + " " : "") + "t "; - - String schema = getDatabaseSchema(); - if (schema == null) - schema = ""; - else if (!schema.endsWith(".")) - schema += "."; - - if (getPanelTiming().equals(QueryTimingHandler.ANY)) { - // this means there are negation panels behind this one - if (returnInstanceToParent()) { - itemStatement = itemSql; - innerSelectClause = buildInnerSelectClause("f"); - innerGroupByClause = buildInnerGroupByClause("f"); - tableStatement = new StringBuilder(); - tableStatement.append("select " + innerSelectClause + " " - + "from " + schema + "observation_fact f, "); - if (useTempTables) { - tableStatement.append("#i" + suffix + " "); - } else if (parent.getQueryOptions().getQueryConstraintLogic() == QueryConstraintStrategy.DERIVED_TABLES) { - tableStatement.append("(" + itemSql + ") "); - } - tableStatement - .append(" i where i.patient_num = f.patient_num "); - if (innerGroupByClause != null - && innerGroupByClause.trim().length() > 0 - && parent.getQueryOptions().useItemGroupByStatement()) { - tableStatement.append("group by " + innerGroupByClause); - } - } else if (returnEncounterToParent()) { - itemStatement = itemSql; - innerSelectClause = buildInnerSelectClause("v"); - innerGroupByClause = buildInnerGroupByClause("v"); - tableStatement = new StringBuilder(); - tableStatement.append("select " + innerSelectClause + " " - + "from " + schema + "visit_dimension v, "); - if (useTempTables) { - tableStatement.append("#i" + suffix + " "); - } else if (parent.getQueryOptions().getQueryConstraintLogic() == QueryConstraintStrategy.DERIVED_TABLES) { - tableStatement.append("(" + itemSql + ") "); - } - tableStatement - .append(" i where i.patient_num = v.patient_num "); - if (innerGroupByClause != null - && innerGroupByClause.trim().length() > 0 - && parent.getQueryOptions().useItemGroupByStatement()) { - tableStatement.append("group by " + innerGroupByClause); - } - } - } else if (getPanelTiming().equals(QueryTimingHandler.SAME) - || getPanelTiming().equals(QueryTimingHandler.SAMEVISIT)) { - if (returnInstanceToParent()) { - itemStatement = itemSql; - innerSelectClause = buildInnerSelectClause("f"); - innerGroupByClause = buildInnerGroupByClause("f"); - tableStatement = new StringBuilder(); - tableStatement.append("select " + innerSelectClause + " " - + "from " + schema + "observation_fact f, "); - if (useTempTables) { - tableStatement.append("#i" + suffix + " "); - } else if (parent.getQueryOptions().getQueryConstraintLogic() == QueryConstraintStrategy.DERIVED_TABLES) { - tableStatement.append("(" + itemSql + ") "); - } - tableStatement.append(" i " - + "where i.patient_num = f.patient_num " - + "and i.encounter_num = f.encounter_num "); - if (innerGroupByClause != null - && innerGroupByClause.trim().length() > 0 - && parent.getQueryOptions().useItemGroupByStatement()) { - tableStatement.append("group by " + innerGroupByClause); - } - } - } - - if (useTempTables) { - if (itemStatement != null - && itemStatement.trim().length() > 0) { - withItemSql - .append(parent.buildTempTableCheckDrop("i" + suffix)); - withItemSql.append(parent.getSqlDelimiter()); - withItemSql.append(buildSelectIntoStatement( - itemStatement, "i" + suffix)); - withItemSql.append(parent.getSqlDelimiter()); - withItemSql - .append(parent.buildTempTableCheckDrop("t" + suffix)); - withItemSql.append(parent.getSqlDelimiter()); - withItemSql.append(buildSelectIntoStatement( - tableStatement.toString(), "t" + suffix)); - withItemSql.append(parent.getSqlDelimiter()); - withItemSql.append("drop table #i" + suffix); - withItemSql.append(parent.getSqlDelimiter()); - } else { - withItemSql - .append(parent.buildTempTableCheckDrop("t" + suffix)); - withItemSql.append(parent.getSqlDelimiter()); - withItemSql.append(buildSelectIntoStatement( - tableStatement.toString(), "t" + suffix)); - withItemSql.append(parent.getSqlDelimiter()); - } - } else if (parent.getQueryOptions().getQueryConstraintLogic() == QueryConstraintStrategy.DERIVED_TABLES) { - withItemSql = new StringBuilder(); - innerSelectClause = buildInnerSelectClause(); - tSelect = "select " + innerSelectClause + " " + "from (" - + tableStatement.toString() + ") t "; - } else { - if (itemStatement != null - && itemStatement.trim().length() > 0) { - withItemSql.append("with i as ( " + "\n" - + itemStatement + "\n" + " ) " + "\n"); - withItemSql.append(", t as ( " + "\n" - + tableStatement.toString() + "\n" + " ) " - + "\n"); - } else { - withItemSql.append("with t as ( " + "\n" - + tableStatement.toString() + "\n" + " ) " - + "\n"); - } - } - - if (parent.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE) || parent.getServerType() - .equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { - firstPanelItemSql = "insert into " - + parent.getTempTableName() + " (" - + insertValuesClause + ")" + "\n" - + withItemSql.toString() + tSelect; - } else { - firstPanelItemSql = withItemSql.toString() + "insert into " - + parent.getTempTableName() + " (" - + insertValuesClause + ")" + "\n" + tSelect; - } - - if (useTempTables) { - firstPanelItemSql += parent.getSqlDelimiter(); - firstPanelItemSql += "drop table #t" + suffix + ""; - } - - if (addDelimiter) { - panelSql.append(parent.getSqlDelimiter()); - } - - panelSql.append(firstPanelItemSql); - - addDelimiter = true; - } - - return panelSql.toString(); - } - - /** - * Build Select Into Statement - * - * Takes a sql statement and creates sql statement that selects the results into a temporary table. This method should only be used on - * Sql Server or other database that supports the select into sybntax - * - * @param sqlStatement String that contains the sql statements to be saved into a temporary table - * @param tempTableName String that contains the name of the temporary table - * @return String properly formated sql statement that stores the result of the select statement into a temporary table - */ - private String buildSelectIntoStatement(String sqlStatement, - String tempTableName) { - TemporalQuerySimpleSqlParser sqlParser = new TemporalQuerySimpleSqlParser( - sqlStatement); - String select = sqlParser.getSelectClause(); - String into = " into #" + tempTableName; - String from = sqlParser.getFromClause(); - String where = sqlParser.getWhereClause(); - String groupBy = sqlParser.getGroupByClause(); - String having = sqlParser.getHavingClause(); - String orderBy = sqlParser.getOrderByClause(); - String selectIntoSql = "select " - + select - + " \n" - + into - + " \n" - + "from " - + from - + " \n" - + (where != null && where.trim().length() > 0 ? "where " - + where + " \n" : "") - + (groupBy != null && groupBy.trim().length() > 0 ? "group by " - + groupBy + " \n" : "") - + (having != null && having.trim().length() > 0 ? "having " - + having + " \n" : "") - + (orderBy != null && orderBy.trim().length() > 0 ? "order by " - + orderBy + " \n" : ""); - return selectIntoSql; - } - - /** - * Build First Panel Invert Sql - * - * Take in the list of individual sql statements from this panel and creates a sql statement that is inverted. Current invert options are - * limited to either using a minus/except syntax or a not exists/not in syntax. - * - * @param itemSqlList List of individual sql statements for all items in this panel - * @return String sql statement that applies invert clause to all items in first panel - */ - //OMOP WAS... - // private String buildFirstPanelInvertSql(List itemSqlList) { - private String buildFirstPanelInvertSql(List itemSqlList) { - - String insertValuesClause = buildInsertValuesClause(); - StringBuilder withItemSql = new StringBuilder(); - String invertSql = ""; - String replaceString = ""; - - String innerSelectClause = buildInnerSelectClause(); - String innerGroupByClause = buildInnerGroupByClause(); - String itemSql = unionItemSql(itemSqlList); - String itemStatement = ""; - StringBuilder tableStatement = new StringBuilder(itemSql); - - List factTables = null; - if (this.parent.getQueryOptions()!=null&&this.parent.getQueryOptions().useDerivedFactTable()) - { - factTables = buildFactTableList(itemSqlList); - } - - - boolean useTempTables = false; - if (parent.getServerType().equalsIgnoreCase(DAOFactoryHelper.SQLSERVER) - && parent.getQueryOptions().getQueryConstraintLogic() == QueryConstraintStrategy.TEMP_TABLES) { - useTempTables = true; - } - - String schema = getDatabaseSchema(); - if (schema == null) - schema = ""; - else if (!schema.endsWith(".")) - schema += "."; - - // String suffix = getPanelId(); - String suffix = ""; - - String tSelect = "select " + innerSelectClause + " " + "from " - + (useTempTables ? "#t" + suffix + " " : "") + " t"; - - if (getPanelTiming().equals(QueryTimingHandler.ANY)) { - // this means there are negation panels behind this one - if (returnInstanceToParent()) { - itemStatement = itemSql; - innerSelectClause = buildInnerSelectClause("f"); - innerGroupByClause = buildInnerGroupByClause("f"); - tableStatement = new StringBuilder(); - if(factTables == null){ - tableStatement.append("select " + innerSelectClause + " " - + "from " + schema + "observation_fact f, "); - } - else{ - if(factTables.size() == 1) { - tableStatement.append("select " + innerSelectClause + " " - + "from " + schema + factTables.get(0) +" f, "); - } - else { - Iterator i = factTables.iterator(); - while (i.hasNext()){ - tableStatement.append("select " + innerSelectClause + " " - + "from " + schema + i.next() +" f, "); - if(i.hasNext()){ - tableStatement.append(" union all "); - } - } - } - } - - if (useTempTables) { - tableStatement.append("#i" + suffix + " "); - } else if (parent.getQueryOptions().getQueryConstraintLogic() == QueryConstraintStrategy.DERIVED_TABLES) { - tableStatement.append("(" + replaceString + ") "); - } - tableStatement.append(" i " - + "where i.patient_num = f.patient_num "); - if (innerGroupByClause != null - && innerGroupByClause.trim().length() > 0 - && parent.getQueryOptions().useItemGroupByStatement()) { - tableStatement.append("group by " + innerGroupByClause); - } - } else if (returnEncounterToParent()) { - itemStatement = itemSql; - innerSelectClause = buildInnerSelectClause("v"); - innerGroupByClause = buildInnerGroupByClause("v"); - tableStatement = new StringBuilder(); - tableStatement.append("select " + innerSelectClause + " " - + "from " + schema + "visit_dimension v, "); - if (useTempTables) { - tableStatement.append("#i" + suffix + " "); - } else if (parent.getQueryOptions().getQueryConstraintLogic() == QueryConstraintStrategy.DERIVED_TABLES) { - tableStatement.append("(" + replaceString + ") "); - } - tableStatement.append(" i " - + "where i.patient_num = v.patient_num "); - if (innerGroupByClause != null - && innerGroupByClause.trim().length() > 0 - && parent.getQueryOptions().useItemGroupByStatement()) { - tableStatement.append("group by " + innerGroupByClause); - } - } - } else if (getPanelTiming().equals(QueryTimingHandler.SAME) - || getPanelTiming().equals(QueryTimingHandler.SAMEVISIT)) { - if (returnInstanceToParent()) { - itemStatement = itemSql; - innerSelectClause = buildInnerSelectClause("f"); - innerGroupByClause = buildInnerGroupByClause("f"); - tableStatement = new StringBuilder(); - if(factTables == null){ - tableStatement.append("select " + innerSelectClause + " " - + "from " + schema + "observation_fact f, "); - } - else{ - if(factTables.size() == 1) { - tableStatement.append("select " + innerSelectClause + " " - + "from " + schema + factTables.get(0) +" f, "); - } - else { - Iterator i = factTables.iterator(); - while (i.hasNext()){ - tableStatement.append("select " + innerSelectClause + " " - + "from " + schema + i.next() +" f, "); - if(i.hasNext()){ - tableStatement.append(" union all "); - } - } - } - } - - if (useTempTables) { - tableStatement.append("#i" + suffix + " "); - } else if (parent.getQueryOptions().getQueryConstraintLogic() == QueryConstraintStrategy.DERIVED_TABLES) { - tableStatement.append("(" + replaceString + ") "); - } - tableStatement.append(" i " - + "where i.patient_num = f.patient_num " - + "and i.encounter_num = f.encounter_num "); - if (innerGroupByClause != null - && innerGroupByClause.trim().length() > 0 - && parent.getQueryOptions().useItemGroupByStatement()) { - tableStatement.append("group by " + innerGroupByClause); - } - } - } - - if (useTempTables) { - if (itemStatement != null && itemStatement.trim().length() > 0) { - withItemSql.append(parent.buildTempTableCheckDrop("y" + suffix)); - withItemSql.append(parent.getSqlDelimiter()); - withItemSql.append(buildSelectIntoStatement(itemStatement, "y" - + suffix)); - withItemSql.append(parent.getSqlDelimiter()); - - String invertClause = ""; - if (parent.getQueryOptions().getInvertedConstraintLogic()==InvertedConstraintStrategy.MINUS_CLAUSE){ - invertClause = buildInvertExceptSql("#y" + suffix); - } - else { - invertClause = buildInvertNotExistsSql("#y" + suffix); - } - withItemSql.append(parent.buildTempTableCheckDrop("i" + suffix)); - withItemSql.append(parent.getSqlDelimiter()); - withItemSql.append(buildSelectIntoStatement(invertClause, "i" - + suffix)); - withItemSql.append(parent.getSqlDelimiter()); - withItemSql.append("drop table #y" + suffix + ""); - withItemSql.append(parent.getSqlDelimiter()); - - withItemSql.append(parent.buildTempTableCheckDrop("t" + suffix)); - withItemSql.append(parent.getSqlDelimiter()); - withItemSql.append(buildSelectIntoStatement( - tableStatement.toString(), "t" + suffix)); - withItemSql.append(parent.getSqlDelimiter()); - withItemSql.append("drop table #i" + suffix); - withItemSql.append(parent.getSqlDelimiter()); - } else { - - withItemSql.append(parent.buildTempTableCheckDrop("y" + suffix)); - withItemSql.append(parent.getSqlDelimiter()); - withItemSql.append(buildSelectIntoStatement(itemSql, "y" - + suffix)); - withItemSql.append(parent.getSqlDelimiter()); - - String invertClause = ""; - if (parent.getQueryOptions().getInvertedConstraintLogic()==InvertedConstraintStrategy.MINUS_CLAUSE){ - invertClause = buildInvertExceptSql("#y" + suffix); - } - else { - invertClause = buildInvertNotExistsSql("#y" + suffix); - } - withItemSql.append(parent.buildTempTableCheckDrop("i" + suffix)); - withItemSql.append(parent.getSqlDelimiter()); - withItemSql.append(buildSelectIntoStatement(invertClause, "i" - + suffix)); - withItemSql.append(parent.getSqlDelimiter()); - withItemSql.append("drop table #y" + suffix); - withItemSql.append(parent.getSqlDelimiter()); - - String invertInsertSql = buildInvertInsertSelectSql("i"); - withItemSql.append(parent.buildTempTableCheckDrop("t" + suffix)); - withItemSql.append(parent.getSqlDelimiter()); - withItemSql - .append("select " + invertInsertSql + " " + "into #t" - + suffix + " " + "from #i" + suffix + " i "); - withItemSql.append(parent.getSqlDelimiter()); - withItemSql.append("drop table #i" + suffix); - withItemSql.append(parent.getSqlDelimiter()); - } - - invertSql = withItemSql.toString() + "insert into " - + parent.getTempTableName() + " (" + insertValuesClause - + ")" + "\n" + tSelect + parent.getSqlDelimiter() - + "drop table #t" + suffix; - } else if (parent.getQueryOptions().getQueryConstraintLogic()==QueryConstraintStrategy.DERIVED_TABLES){ - if (itemStatement != null && itemStatement.trim().length() > 0) { - String invertClause = ""; - if (parent.getQueryOptions().getInvertedConstraintLogic()==InvertedConstraintStrategy.MINUS_CLAUSE){ - invertClause = buildInvertExceptSql("y"); - } - else { - invertClause = buildInvertNotExistsSql(itemStatement, "y"); - } - String derivedSql = tableStatement.toString().replace(replaceString, invertClause); - withItemSql.append(derivedSql); - } else { - String invertClause = ""; - if (parent.getQueryOptions().getInvertedConstraintLogic()==InvertedConstraintStrategy.MINUS_CLAUSE){ - invertClause = buildInvertExceptSql("y"); - } - else { - invertClause = buildInvertNotExistsSql(itemSql, "y"); - } - String invertInsertSql = buildInvertInsertSelectSql("i"); - withItemSql.append(" select " + - invertInsertSql + " from (" + - invertClause + - ") i \n"); - } - - innerSelectClause = buildInnerSelectClause(); - tSelect = "select " + innerSelectClause + " " + "from (" - + withItemSql.toString() + ") t "; - - if (parent.getServerType() - .equalsIgnoreCase(DAOFactoryHelper.ORACLE) || parent.getServerType() - .equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { - invertSql = "insert into " + parent.getTempTableName() + " (" - + insertValuesClause + ")" + "\n" - + tSelect; - } else { - invertSql = "insert into " - + parent.getTempTableName() + " (" + insertValuesClause - + ")" + "\n" + tSelect; - } - } else { - if (itemStatement != null && itemStatement.trim().length() > 0) { - withItemSql.append("with y as ( " + "\n" + itemStatement + "\n" - + " ) " + "\n"); - - String invertClause = ""; - if (parent.getQueryOptions().getInvertedConstraintLogic()==InvertedConstraintStrategy.MINUS_CLAUSE){ - invertClause = buildInvertExceptSql("y"); - } - else { - invertClause = buildInvertNotExistsSql("y"); - } - withItemSql.append(", i as ( " + "\n" + invertClause + "\n" - + " ) " + "\n"); - withItemSql.append(", t as ( " + "\n" - + tableStatement.toString() + "\n" + " ) " + "\n"); - } else { - withItemSql.append("with y as ( " + "\n" + itemSql + "\n" - + " ) " + "\n"); - String invertClause = ""; - if (parent.getQueryOptions().getInvertedConstraintLogic()==InvertedConstraintStrategy.MINUS_CLAUSE){ - invertClause = buildInvertExceptSql("y"); - } - else { - invertClause = buildInvertNotExistsSql("y"); - } - withItemSql.append(", i as ( " + "\n" + invertClause + "\n" - + " ) " + "\n"); - String invertInsertSql = buildInvertInsertSelectSql("i"); - withItemSql.append(", t as ( " + "\n" + " select " - + invertInsertSql + " from i " + "\n" + " ) " + "\n"); - } - - if (parent.getServerType() - .equalsIgnoreCase(DAOFactoryHelper.ORACLE) || parent.getServerType() - .equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { - invertSql = "insert into " + parent.getTempTableName() + " (" - + insertValuesClause + ")" + "\n" - + withItemSql.toString() + tSelect; - } else { - invertSql = withItemSql.toString() + "insert into " - + parent.getTempTableName() + " (" + insertValuesClause - + ")" + "\n" + tSelect; - } - - } - - return invertSql; - } - - - /** - * First Panel Item Sql With Occurrence - * - * This method returns the sql representation of all items in a panel when - * the panel is the first panel in a query. This method is only accessed - * when usePanelLevelOccurrence flag is set to true - in which case the - * occurrence is processed on the panel level instead of in an item by item - * basis - * - * @param itemSqlList List of individual sql statements for all items in this panel - * @return String sql representation for the first panel in the query - * @throws I2B2DAOException - * thrown when an i2b2 data related error is encountered - */ - //OMOP WAS.. - // private String firstPanelItemSqlWithOccurrence(List itemSqlList) - private String firstPanelItemSqlWithOccurrence(List itemSqlList) - throws I2B2DAOException { - - String itemSql = consolidateItemSql(itemSqlList); - - String insertValuesClause = buildInsertValuesClause(); - - String innerSelectClause = buildInnerSelectClause(""); - String innerGroupByClause = buildInnerGroupByClause(); - - TotalItemOccurrenceHandler totalItemOccurrencHandler = new TotalItemOccurrenceHandler(); - String totalItemOccurrenceClause = totalItemOccurrencHandler - .buildTotalItemOccurrenceClause(this.getTotalOccurrences()); - - StringBuilder withItemSql = new StringBuilder(); - - String firstPanelItemSql = ""; - - String schema = getDatabaseSchema(); - if (schema == null) - schema = ""; - else if (!schema.endsWith(".")) - schema += "."; - - String tSelect = "select " + innerSelectClause + " " + "from t"; - - if (getPanelTiming().equals(QueryTimingHandler.ANY)) { - // this means there are negation panels behind this one - if (returnInstanceToParent()) { - withItemSql - .append("with sub_t as ( " - + "\n" - + itemSql - + "\n" - + " ), " - + "\n" - + "y as (" - + "select " - + innerSelectClause - + " " - + "from sub_t " - + "where patient_num in (select patient_num from sub_t group by patient_num having sum(fact_count) " - + totalItemOccurrenceClause + ") " + ") \n"); - - innerSelectClause = buildInnerSelectClause("f"); - innerGroupByClause = buildInnerGroupByClause("f"); - withItemSql - .append(", t as (" - + "\n" - + "select " - + innerSelectClause - + " " - + "from " - + schema - + "observation_fact f " - + "where exists (" - + "select 1 " - + "from y " - + "where y.patient_num = f.patient_num) " - + (innerGroupByClause != null - && innerGroupByClause.trim().length() > 0 - && parent.getQueryOptions().useItemGroupByStatement() ? "group by " - + innerGroupByClause - : "") + ") " + "\n"); - } else if (returnEncounterToParent()) { - - withItemSql - .append("with sub_t as ( " - + "\n" - + itemSql - + "\n" - + " ), " - + "\n" - + "y as (" - + "select " - + innerSelectClause - + " " - + "from sub_t " - + "where patient_num in (select patient_num from sub_t group by patient_num having sum(fact_count) " - + totalItemOccurrenceClause + ") " + ") \n"); - - innerSelectClause = buildInnerSelectClause("v"); - innerGroupByClause = buildInnerGroupByClause("v"); - withItemSql - .append(", t as (" - + "\n" - + "select " - + innerSelectClause - + " " - + "from " - + schema - + "visit_dimension v " - + "where exists (" - + "select 1 " - + "from y " - + "where y.patient_num = v.patient_num) " - + (innerGroupByClause != null - && innerGroupByClause.trim().length() > 0 - && parent.getQueryOptions().useItemGroupByStatement() ? "group by " - + innerGroupByClause - : "") + ") " + "\n"); - } - } else if (getPanelTiming().equals(QueryTimingHandler.SAME) - || getPanelTiming().equals(QueryTimingHandler.SAMEVISIT)) { - if (returnInstanceToParent()) { - withItemSql - .append("with sub_t as ( " - + "\n" - + itemSql - + "\n" - + " ), " - + "\n" - + "y as (" - + "select " - + innerSelectClause - + " " - + "from sub_t " - + "where patient_num in (select patient_num from sub_t group by patient_num having sum(fact_count) " - + totalItemOccurrenceClause + ") " + ") \n"); - - innerSelectClause = buildInnerSelectClause("f"); - innerGroupByClause = buildInnerGroupByClause("f"); - withItemSql - .append(", t as (" - + "\n" - + "select " - + innerSelectClause - + " " - + "from " - + schema - + "observation_fact f " - + "where exists (" - + "select 1 " - + "from y " - + "where y.patient_num = f.patient_num " - + "and y.encounter_num = f.encounter_num) " - + (innerGroupByClause != null - && innerGroupByClause.trim().length() > 0 - && parent.getQueryOptions().useItemGroupByStatement() ? "group by " - + innerGroupByClause - : "") + ") " + "\n"); - } - } else { - withItemSql - .append("with sub_t as ( " - + "\n" - + itemSql - + "\n" - + " ), " - + "\n" - + "t as (" - + "select " - + innerSelectClause - + " " - + "from sub_t " - + "where patient_num in (select patient_num from sub_t group by patient_num having sum(fact_count) " - + totalItemOccurrenceClause + ") " + ") \n"); - } - - if (parent.getServerType().equalsIgnoreCase(DAOFactoryHelper.ORACLE) || parent.getServerType() - .equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { - firstPanelItemSql = "insert into " + parent.getTempTableName() - + " (" + insertValuesClause + ")" + "\n" + withItemSql - + tSelect; - } else { - firstPanelItemSql = withItemSql + "insert into " - + parent.getTempTableName() + " (" + insertValuesClause - + ")" + "\n" + tSelect; - } - - return firstPanelItemSql; - } - - /** - * Build Insert Values Clause - * - * Returns a list of columns from the temporary table that will be populated - * in an insert - * - * @return String sql list of columns from temporary table that will be - * inserted into - */ - public String buildInsertValuesClause() { - String insertValuesClause = ""; - - if (returnInstanceToParent() - || getPanelTiming().equalsIgnoreCase( - QueryTimingHandler.SAMEINSTANCENUM)) { - insertValuesClause = "provider_id, start_date, concept_cd, instance_num, encounter_num, patient_num"; - } else if (returnEncounterToParent() - || getPanelTiming().equalsIgnoreCase(QueryTimingHandler.SAME) - || getPanelTiming().equalsIgnoreCase( - QueryTimingHandler.SAMEVISIT)) { - insertValuesClause = "encounter_num, patient_num"; - } else { - insertValuesClause = "patient_num"; - } - - insertValuesClause += ", panel_count"; - - return insertValuesClause; - } - - /** - * Build Inner Select Clause - * - * Returns a list of columns that will be inserted into the temporary table - * for each item - * - * @return String sql statement that specifies the columns that should be - * returned from the item sql - */ - public String buildInnerSelectClause() { - return buildInnerSelectClause("t"); - } - - /** - * Build Inner Select Clause - * - * Returns a list of columns that will be inserted into the temporary table - * for each item - * - * @param tableAlias - * String that specifies the table alias to use when building sql - * string - * @return String sql statement that specifies the columns that should be - * returned from the item sql - */ - public String buildInnerSelectClause(String tableAlias) { - - if (tableAlias != null && tableAlias.trim().length() > 0 - && !tableAlias.trim().endsWith(".")) - tableAlias += "."; - - String innerSelectClause = " "; - if (!isFirstPanelInQuery()) { - innerSelectClause = " 1 as panel_count "; - } else { - if (returnInstanceToParent() - || getPanelTiming().equalsIgnoreCase( - QueryTimingHandler.SAMEINSTANCENUM)) { - innerSelectClause = "" + tableAlias + "provider_id, " - + tableAlias + "start_date, " + tableAlias - + "concept_cd, " + tableAlias + "instance_num, " - + tableAlias + "encounter_num, "; - } else if (returnEncounterToParent() - || getPanelTiming().equalsIgnoreCase( - QueryTimingHandler.SAME) - || getPanelTiming().equalsIgnoreCase( - QueryTimingHandler.SAMEVISIT)) { - innerSelectClause = "" + tableAlias + "encounter_num, "; - } - innerSelectClause += "" + tableAlias - + "patient_num, 0 as panel_count "; - } - return innerSelectClause; - } - - /** - * Build Inner Group By Clause - * - * Returns a list of columns that will be used to group the results of the panel sql statement - * - * @return String sql statement that specifies the columns that should be used to group the results - */ - public String buildInnerGroupByClause() { - return buildInnerGroupByClause("t"); - } - - /** - * Build Inner Group By Clause - * - * Returns a list of columns that will be used to group the results of the panel sql statement - * - * @param tableAlias - * String that specifies the table alias to use when building sql - * string - * @return String sql statement that specifies the columns that should be used to group the results - */ - public String buildInnerGroupByClause(String tableAlias) { - - if (tableAlias != null && tableAlias.trim().length() > 0 - && !tableAlias.trim().endsWith(".")) - tableAlias += "."; - - String innerSelectClause = " "; - if (!isFirstPanelInQuery()) { - innerSelectClause = " 1 as panel_count "; - } else { - if (returnInstanceToParent() - || getPanelTiming().equalsIgnoreCase( - QueryTimingHandler.SAMEINSTANCENUM)) { - innerSelectClause = "" + tableAlias + "provider_id, " - + tableAlias + "start_date, " + tableAlias - + "concept_cd, " + tableAlias + "instance_num, " - + tableAlias + "encounter_num, "; - } else if (returnEncounterToParent() - || getPanelTiming().equalsIgnoreCase( - QueryTimingHandler.SAME) - || getPanelTiming().equalsIgnoreCase( - QueryTimingHandler.SAMEVISIT)) { - innerSelectClause = "" + tableAlias + "encounter_num, "; - } - innerSelectClause += "" + tableAlias + "patient_num "; - } - return innerSelectClause; - } - - /** - * Non First Panel Item Sql With Occurrence - * - * This method returns the sql representation of all items in a panel when - * the panel is not the first panel in a query. This method is only accessed - * when usePanelLevelOccurrence flag is set to true - in which case the - * occurrence is processed on the panel level instead of in an item by item - * basis - * - * @param panelIndex - * int update index for the given panel - * @param itemSqlList - * List of individual sql statements for all items in this panel - * @return String sql representation for updating temporary table with panel - * information - * @throws I2B2DAOException - * thrown when an i2b2 data related error is encountered - */ - private String nonFirstPanelItemSqlWithOccurrence(int panelIndex, - List itemSqlList) throws I2B2DAOException { - String encounterNumClause = " ", instanceNumClause = " "; - String tempTableName = parent.getTempTableName(); - int oldPanelIndex = panelIndex - 1; - - if (getPanelTiming().equalsIgnoreCase( - QueryTimingHandler.SAMEINSTANCENUM)) { - instanceNumClause = " and " // + parent.getDatabaseSchema() - + tempTableName - + ".encounter_num = t.encounter_num and " - + tempTableName - + ".instance_num = t.instance_num and " - + tempTableName - + ".start_date = t.start_date and " - + tempTableName - + ".concept_cd = t.concept_cd and " - + tempTableName + ".provider_id = t.provider_id "; - } else if (getPanelTiming().equalsIgnoreCase(QueryTimingHandler.SAME) - || getPanelTiming().equalsIgnoreCase( - QueryTimingHandler.SAMEVISIT)) { - encounterNumClause = " and " + tempTableName - + ".encounter_num = t.encounter_num "; - } - - String itemSql = consolidateItemSql(itemSqlList); - - String nonFirstPanelItemSql = ""; - - if (this.isPanelInverted()) { - oldPanelIndex = 0; - panelIndex = -1; - } - - TotalItemOccurrenceHandler totalItemOccurrencHandler = new TotalItemOccurrenceHandler(); - String totalItemOccurrenceClause = totalItemOccurrencHandler - .buildTotalItemOccurrenceClause(this.getTotalOccurrences()); - - String withItemSql = "with sub_t as ( " + "\n" + itemSql + "\n" - + " ) \n"; - - if (parent.getServerType().equalsIgnoreCase(DAOFactoryHelper.ORACLE) || parent.getServerType() - .equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { - nonFirstPanelItemSql += "update " - + tempTableName - + " set panel_count =" - + panelIndex - + " where " - + tempTableName - + ".panel_count = " - + oldPanelIndex - + " and exists ( " - + withItemSql - + "select 1 " - + "from (" - + "select * " - + "from sub_t " - + "where patient_num in (select patient_num from sub_t group by patient_num having sum(fact_count) " - + totalItemOccurrenceClause + ") " + ") t " + "where " - + tempTableName + ".patient_num = t.patient_num " - + encounterNumClause + instanceNumClause + " ) "; - } else { - nonFirstPanelItemSql += withItemSql - + "update " - + tempTableName - + " set panel_count =" - + panelIndex - + " where " - + tempTableName - + ".panel_count = " - + oldPanelIndex - + " and exists ( " - + "select 1 " - + "from (" - + "select * " - + "from sub_t " - + "where patient_num in (select patient_num from sub_t group by patient_num having sum(fact_count) " - + totalItemOccurrenceClause + ") " + ") t " + "where " - + tempTableName + ".patient_num = t.patient_num " - + encounterNumClause + instanceNumClause + " ) "; - } - - return nonFirstPanelItemSql; - - } - - /** - * Non First Panel Item Sql - * - * Processes item sql from all items in panel that is not the first panel in a subquery. - * Non first panel items are processed as an update statement to the - * temporary table rather than an insert - * - * @param itemSqlList List of individual sql statements for all items in this panel - * @param panelIndex - * int update index for the given panel - * @return String sql representation that joins the item sql to the panel - * sql - */ - private String nonFirstPanelItemSql(List itemSqlList, int panelIndex) { - - StringBuilder panelSql = new StringBuilder(); - boolean addDelimiter = false; - StringBuilder tempItemSql = new StringBuilder(); - - boolean useTempTables = false; - if (parent.getServerType().equalsIgnoreCase(DAOFactoryHelper.SQLSERVER) - && parent.getQueryOptions().getQueryConstraintLogic() == QueryConstraintStrategy.TEMP_TABLES) { - useTempTables = true; - } - - // OMOP WAS.. - //for (String itemSql : itemSqlList) { - for (TemporalPanelItemSql itemSqlItem : itemSqlList) { - String itemSql = itemSqlItem.itemSql; - - String encounterNumClause = " ", instanceNumClause = " "; - String tempTableName = parent.getTempTableName(); - int oldPanelIndex = panelIndex - 1; - - if (getPanelTiming().equalsIgnoreCase( - QueryTimingHandler.SAMEINSTANCENUM)) { - instanceNumClause = " and " // + parent.getDatabaseSchema() - + tempTableName - + ".encounter_num = t.encounter_num and " - + tempTableName - + ".instance_num = t.instance_num and " - + tempTableName - + ".start_date = t.start_date and " - + tempTableName - + ".concept_cd = t.concept_cd and " - + tempTableName + ".provider_id = t.provider_id "; - } else if (getPanelTiming().equalsIgnoreCase( - QueryTimingHandler.SAME) - || getPanelTiming().equalsIgnoreCase( - QueryTimingHandler.SAMEVISIT)) { - encounterNumClause = " and " + tempTableName - + ".encounter_num = t.encounter_num "; - } - - String nonFirstPanelItemSql = ""; - /* - * "with t as ( " + "\n" + itemSql + "\n" + " ) " + "\n" + "\n"; - */ - - if (this.isPanelInverted()) { - if (oldPanelIndex<0) - oldPanelIndex = 0; - - if (useTempTables){ - String suffix = ""; - - nonFirstPanelItemSql += parent.buildTempTableCheckDrop("t" + suffix); - nonFirstPanelItemSql += parent.getSqlDelimiter(); - - nonFirstPanelItemSql += buildSelectIntoStatement(itemSql, "t"); - nonFirstPanelItemSql += parent.getSqlDelimiter(); - - nonFirstPanelItemSql += " update " + tempTableName - + " set panel_count = -1 " + " where " + tempTableName - + ".panel_count = " + oldPanelIndex + " and exists ( " - + "select 1 " + "from #t t " + "where " - + tempTableName + ".patient_num = t.patient_num " - + encounterNumClause + instanceNumClause + " ) "; - - nonFirstPanelItemSql += parent.getSqlDelimiter(); - nonFirstPanelItemSql += parent.buildTempTableCheckDrop("t" + suffix); - - } - else { - nonFirstPanelItemSql += " update " + tempTableName - + " set panel_count = -1 " + " where " + tempTableName - + ".panel_count = " + oldPanelIndex + " and exists ( " - + "select 1 " + "from (" + itemSql + ") t " + "where " - + tempTableName + ".patient_num = t.patient_num " - + encounterNumClause + instanceNumClause + " ) "; - } - - } else { - - if (useTempTables){ - String suffix = ""; - - nonFirstPanelItemSql += parent.buildTempTableCheckDrop("t" + suffix); - nonFirstPanelItemSql += parent.getSqlDelimiter(); - - nonFirstPanelItemSql += buildSelectIntoStatement(itemSql, "t"); - nonFirstPanelItemSql += parent.getSqlDelimiter(); - - nonFirstPanelItemSql += "update " + tempTableName - + " set panel_count =" + panelIndex + " where " - + tempTableName + ".panel_count = " + oldPanelIndex - + " and exists ( " + "select 1 " + "from #t" - + " t " + "where " + tempTableName - + ".patient_num = t.patient_num " + encounterNumClause - + instanceNumClause + " ) "; - - nonFirstPanelItemSql += parent.getSqlDelimiter(); - nonFirstPanelItemSql += parent.buildTempTableCheckDrop("t" + suffix); - - } - else { - nonFirstPanelItemSql += "update " + tempTableName - + " set panel_count =" + panelIndex + " where " - + tempTableName + ".panel_count = " + oldPanelIndex - + " and exists ( " + "select 1 " + "from (" + itemSql - + ") t " + "where " + tempTableName - + ".patient_num = t.patient_num " + encounterNumClause - + instanceNumClause + " ) "; - } - } - if (addDelimiter) { - panelSql.append(parent.getSqlDelimiter()); - } - - panelSql.append(nonFirstPanelItemSql); - - addDelimiter = true; - } - - return panelSql.toString(); - } - - /** - * Build Invert Main Table Sql - * - * Constructs sql statement that selects the correct columns from the superset of items from which - * an invert can be applied - through either a minus/except or not in/not exists clause - * - * @return String sql statement that contains sql for accessing main table sql - */ - public String buildInvertMainTableSql() { - String selectClause = ""; - String whereClause = ""; - String groupByClause = ""; - - String patientTable = "patient_dimension p "; - String instanceTable = "observation_fact f "; - String visitTable = "visit_dimension v "; - - List factTables = null; - List itemSqlList = null; - try { - itemSqlList = getItemSql(); - } catch (I2B2DAOException e) { - return null; - } - if (this.parent.getQueryOptions()!=null&&this.parent.getQueryOptions().useDerivedFactTable()) - { - factTables = buildFactTableList(itemSqlList); - } - - - String invertTableName = patientTable; - - if (getPanelTiming().equalsIgnoreCase( - QueryTimingHandler.SAMEINSTANCENUM)) { - selectClause = "f.provider_id, f.start_date, f.concept_cd, f.instance_num, f.encounter_num, f.patient_num"; - invertTableName = instanceTable; - } else if (getPanelTiming().equalsIgnoreCase(QueryTimingHandler.SAME) - || getPanelTiming().equalsIgnoreCase( - QueryTimingHandler.SAMEVISIT)) { - invertTableName = visitTable; - selectClause = "v.encounter_num, v.patient_num"; - } else { - selectClause = "p.patient_num"; - } - - String invertSql = "select " + selectClause + ", 0 panel_count" - + " from " + parent.getDatabaseSchema() + invertTableName - + whereClause + groupByClause; - /* - if(factTables != null){ - if((factTables.size() == 1)) { - - invertSql = "select " + selectClause + ", 0 panel_count" - + " from " + parent.getDatabaseSchema() + factTables.get(0) + " f " - + whereClause + groupByClause; - } - else { - invertSql = ""; - Iterator i = factTables.iterator(); - while (i.hasNext()){ - - invertSql += "select " + selectClause + ", 0 panel_count" - + " from " + parent.getDatabaseSchema() + i.next() + " f " - + whereClause + groupByClause; - if(i.hasNext()){ - invertSql += "\n union all \n"; - } - } - } - } -*/ - - return invertSql; - - } - - /** - * Build Invert Insert Select Sql - * - * Constructs select clause for use in a larger statement. Clause contains the correct columns - * based on panel and query timing models - * - * @param tableAlias String alias for table referenced in from clause - * @return String select clause for inclusion in larger statement - */ - protected String buildInvertInsertSelectSql(String tableAlias) { - if (tableAlias != null && tableAlias.trim().length() > 0) - tableAlias = tableAlias + "."; - else - tableAlias = ""; - - String insertSelectClause = ""; - - if (getPanelTiming().equalsIgnoreCase( - QueryTimingHandler.SAMEINSTANCENUM)) { - insertSelectClause = tableAlias + "provider_id, " + tableAlias - + "start_date, " + tableAlias + "concept_cd, " + tableAlias - + "instance_num, " + tableAlias + "encounter_num, " - + tableAlias + "patient_num"; - } else if (getPanelTiming().equalsIgnoreCase(QueryTimingHandler.SAME) - || getPanelTiming().equalsIgnoreCase( - QueryTimingHandler.SAMEVISIT)) { - insertSelectClause = " " + tableAlias + "encounter_num, " - + tableAlias + "patient_num"; - } else { - insertSelectClause = " " + tableAlias + "patient_num"; - } - - insertSelectClause += ", 0 as panel_count"; - - return insertSelectClause; - - } - - /** - * Build Invert Not Except Sql - * - * Constructs with clause for use in larger invert statement. Clause contains proper minus/except - * constraints based on the panel timing - * - * @param withAlias String alias of table or with clause for use in referencing column names - * @return String not exists clause for use in larger sql invert statement - */ - protected String buildInvertExceptSql(String withAlias) { - if (withAlias == null) - withAlias = "y"; - - String minusOperator = "minus"; - if (!parent.getServerType().equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { - minusOperator = "except"; - } - - StringBuilder exceptClause = new StringBuilder(); - - exceptClause.append(buildInvertMainTableSql() + "\n"); - - exceptClause.append(" " + minusOperator + "\n"); - String invertInsertSql = buildInvertInsertSelectSql(withAlias); - exceptClause.append("select " + invertInsertSql + " from " + withAlias - + " "); - return exceptClause.toString(); - } - - /** - * Build Invert Not Exists Sql - * - * Constructs with clause for use in larger invert statement. Clause contains proper - * constraints based on the panel timing - * - * @param withAlias String alias of table or with clause for use in referencing column names - * @return String not exists clause for use in larger sql invert statement - */ - protected String buildInvertNotExistsSql(String withAlias){ - return buildInvertNotExistsSql("", withAlias); - } - - /** - * Build Invert Not Exists Sql - * - * Constructs with clause for use in larger invert statement. Clause contains proper not in/not exists - * constraints based on the panel timing - * - * @param withTable String name of table or with clause name - * @param withAlias String alias of table or with clause for use in referencing column names - * @return String not exists clause for use in larger sql invert statement - */ - protected String buildInvertNotExistsSql(String withTable, String withAlias) { - if (withAlias == null) - withAlias = "y"; - - StringBuilder notExistsClause = new StringBuilder(); - notExistsClause.append(buildInvertMainTableSql() + "\n"); - notExistsClause.append("where not exists (\n"); - notExistsClause.append("select 1 from " + - (withTable!=null&&withTable.trim().length()>0 ? withTable + " " : "") + - withAlias + " \n"); - if (getPanelTiming().equalsIgnoreCase( - QueryTimingHandler.SAMEINSTANCENUM)) { - notExistsClause.append("where " + withAlias - + ".patient_num = f.patient_num "); - notExistsClause.append("and " + withAlias - + ".encounter_num = f.encounter_num "); - notExistsClause.append("and " + withAlias - + ".start_date = f.start_date "); - notExistsClause.append("and " + withAlias - + ".concept_cd = f.concept_cd "); - notExistsClause.append("and " + withAlias - + ".instance_num = f.instance_num "); - notExistsClause.append("and " + withAlias - + ".provider_id = f.provider_id) "); - } else if (getPanelTiming().equalsIgnoreCase(QueryTimingHandler.SAME) - || getPanelTiming().equalsIgnoreCase( - QueryTimingHandler.SAMEVISIT)) { - notExistsClause.append("where " + withAlias - + ".patient_num = v.patient_num "); - notExistsClause.append("and " + withAlias - + ".encounter_num = v.encounter_num) "); - } else { - notExistsClause.append("where " + withAlias - + ".patient_num = p.patient_num) "); - } - - return notExistsClause.toString(); - } - - @Override - public int compareTo(Object element) { - if (element.getClass().equals((TemporalPanel.class))) { - TemporalPanel tp2 = (TemporalPanel) element; - - Integer tp1Score = this.getTimingScore(); - Integer tp2Score = tp2.getTimingScore(); - - int compare = tp1Score.compareTo(tp2Score); - if (compare == 0) { - tp1Score = this.getEstimatedTotal(); - tp2Score = tp2.getEstimatedTotal(); - compare = tp1Score.compareTo(tp2Score); - if (compare == 0) { - tp1Score = this.basePanel.getPanelNumber(); - tp2Score = tp2.basePanel.getPanelNumber(); - compare = tp1Score.compareTo(tp2Score); - if (compare == 0) { - return this.toString().compareTo(tp2.toString()); - } else - return compare; - - } else - return compare; - } else - return compare; - - } else { - return this.toString().compareTo(element.toString()); - } - } - - /** - * Get Timing Score - * - * Calculates the timing score of the panel. Timing scores are used to - * properly sort panels so query processing can be optimized - * - * @return int represents the timing score of the panel - */ - private int getTimingScore() { - String timing = getPanelTiming(); - int score = 0; - if (timing == null || timing.trim().length() == 0) - return MAXTIMINGSCORE; - else if (timing.equalsIgnoreCase(QueryTimingHandler.ANY)) - score = MAXTIMINGSCORE - 1; - else if (timing.equalsIgnoreCase(QueryTimingHandler.SAME)) - score = MAXTIMINGSCORE - 2; - else if (timing.equalsIgnoreCase(QueryTimingHandler.SAMEVISIT)) - score = MAXTIMINGSCORE - 2; - else if (timing.equalsIgnoreCase(QueryTimingHandler.SAMEINSTANCENUM)) - score = MAXTIMINGSCORE - 3; - else - score = MAXTIMINGSCORE - 4; - - if (isPanelInverted()) - return (MAXTIMINGSCORE * 2) - (MAXTIMINGSCORE - score); - else - return score; - } - - /** - * Get Estimated Total - * - * Calculate the estimated number of patients that will be returned by this - * panel. This method accounts for missing values and inverted panels when - * estimated the number of patients returned. Estimated counts are used to - * help sort panels in a way that optimizes query performance - * - * @return int estimated count of patients returned by this panel - */ - private int getEstimatedTotal() { - int totalCount = getSumOfPanelItemCounts(); - double missingCount = getMissingItemTotals(); - - if (missingCount > 0) { - double size = getItemList().size(); - double knownSize = size - missingCount; - if (knownSize == 0) - return Integer.MAX_VALUE; - - // estimate total size by averaging known items and applying it to - // all items - - double dblTotal = totalCount; - totalCount = (int) ((dblTotal / knownSize) * size); - } - - if (this.isPanelInverted()) - totalCount = Integer.MAX_VALUE - totalCount; - - return totalCount; - } - - /** - * Is Panel Inverted - * - * @return boolean true if the panel has the inverted flag set, otherwise - * false - */ - public boolean isPanelInverted() { - return basePanel.getInvert() == 1; - } - - /** - * Get Sum Of Patient Item Counts - * - * Sum the estimated patient counts for all items in the panel - * - * @return int total of estimated counts from items within the panel - */ - public int getSumOfPanelItemCounts() { - return estimatedPanelSize; - } - - /** - * Get Panel Timing - * - * Return timing to use for this panel. If no timing is specified on the - * panel level, than the timing for the query is used. - * - * @return String representation of the timing used for this panel - */ - public String getPanelTiming() { - if (basePanel.getPanelTiming() == null - || basePanel.getPanelTiming().trim().length() == 0) - return parent.getQueryTiming(); - else - return basePanel.getPanelTiming(); - } - - /** - * Return Encounter To Parent - * - * @return boolean true if panel is needs to return encounter num - * results to parent query - */ - private boolean returnEncounterToParent() { - return parent.returnEncounterNum(); - } - - /** - * Return Instance to Parent - * - * @return boolean true if panel is needs to return instance based columns - * results to parent query - */ - private boolean returnInstanceToParent() { - return parent.returnInstanceNum(); - } - - /** - * Get Accuracy Scale - * - * @return int accuracy as included in the original query xml - */ - public int getAccuracyScale() { - return basePanel.getPanelAccuracyScale(); - } - - /** - * Get Item List - * - * @return List list of items in this panel - */ - public List getItemList() { - return panelItemList; - } - - /** - * Get Security Type - * - * @return SecurityType returns security to use for this query - */ - protected SecurityType getSecurityType() { - return parent.getSecurityType(); - } - - - /** - * Get Requestor Security Type - * - * @return SecurityType returns security used by requestor when submitting - * this query - */ - protected SecurityType getRequestorSecurityType() { - return parent.getRequestorSecurityType(); - } - - /** - * Get Project Id - * - * @return String project id used for this query - */ - protected String getProjectId() { - return parent.getProjectId(); - } - - /** - * Get Data Source Lookup - * - * @return DataSourceLookup data source information used for submitting - * query to database - */ - protected DataSourceLookup getDataSourceLookup() { - return parent.getDataSourceLookup(); - } - - /** - * Get Database Schema - * - * @return String name of schema to use when referencing tables - */ - protected String getDatabaseSchema() { - return parent.getDatabaseSchema(); - } - - /** - * Build Date Constraint Sql - * - * Builds string sql statement that contains the date constraint from the panel leve - * - * @return String sql statement that contains the date constraint from the panel level - */ - public String buildDateConstraintSql() { - return buildDateConstraintSql(""); - } - - /** - * Build Date Constraint Sql - * - * Builds string sql statement that contains the date constraint from the panel leve - * - * @param tableAlias String alias of the table to use when reference columns - * @return String sql statement that contains the date constraint from the panel level - */ - public String buildDateConstraintSql(String tableAlias) { - DateConstrainUtil dateConstrainUtil = new DateConstrainUtil( - parent.getDataSourceLookup()); - - return dateConstrainUtil.buildPanelDateSql(basePanel, tableAlias); - } - - /** - * Get Server Type - * - * Returns name of the underlying database type. Currently, only Oracle and SqlServer are supported - * - * @return String name of the database server type - */ - public String getServerType() { - return parent.getServerType(); - } - - /** - * Get Project Parameter Map - * - * Returns the Map of project parameter values passed in when the query was created - * - * @return Map the project parameter map that was passed into the query - */ - protected Map getProjectParameterMap() { - return parent.getProjectParameterMap(); - } - - public int getMissingItemTotals() { - return missingItemTotals; - } - - - /** - * Has Panel Date Constraint - * - * Returns whether or not this panel has a panel level date constraint: date from, date to, or both - * - * @return Boolean true if this panel has a panel level date constraint - */ - public boolean hasPanelDateConstraint() { - if (basePanel.getPanelDateFrom() != null - || basePanel.getPanelDateTo() != null) - return true; - else - return false; - } - - /** - * Has Panel Occurrence Constraint - * - * Returns whether or not this panel has an occurrence constraint other than the default - * - * @return Boolean true if the panel has an occurrence constraint > 1, else false - */ - public boolean hasPanelOccurrenceConstraint() { - if (this.basePanel.getTotalItemOccurrences() != null - && this.basePanel.getTotalItemOccurrences().getOperator() != null) { - if ((this.basePanel.getTotalItemOccurrences().getOperator() == TotOccuranceOperatorType.GE) - && (this.basePanel.getTotalItemOccurrences().getValue() == 1)) - return false; - else - return true; - } else - return false; - } - - /** - * Is First Panel In Query - * - * Determines whether this panel is the first panel in the query - * - * @return Boolean true if panel is first panel in query, otherwise false - */ - public boolean isFirstPanelInQuery() { - return parent.getPanelIndex(this) == 0; - } - - /** - * Get Total Occurrences - * - * Gets the total occurrences constraint for this panel - * - * @return TotalItemOccurrences occurrence constraint from main query - */ - public TotalItemOccurrences getTotalOccurrences() { - return this.basePanel.getTotalItemOccurrences(); - } - - /** - * Get Total Occurrences Operator - * - * Get the operator for the total occurrences constraint for this panel - * - * @return String operator for total occurrences constraint - */ - public String getTotalOccurrenceOperator() { - if (this.basePanel.getTotalItemOccurrences() != null) - return this.basePanel.getTotalItemOccurrences().getOperator() - .toString(); - else - return ""; - } - - /** - * Allow Large Text Value Constrain Flag - * - * Return whether or not constraints on large text values are allowed - * - * @return Boolean true if large text constraints are allowed, otherwise false - */ - protected boolean allowLargeTextValueConstrainFlag() { - return parent.allowLargeTextValueConstrainFlag(); - } - - protected List getUserRoles() { - return parent.getUserRoles(); - } - - /** - * Appply Occurrence to Panel Level - * - * Return whether or not occurrences should be applied on the panel level instead of on each item **NOTE: This is experimental funcationality and not current supported** - * - * @return Boolean true if occurrence should be applied over all items in a query instead of on an item by item basis, otherwise false - */ - protected boolean applyOccurrenceToPanelLevel() { - return parent.getQueryOptions().usePanelLevelOccurrence(); - } - - /** - * Get Processing Level - * - * Returns the processing level of the current query. Default value is 1, when processing an embedded query, processing level is incremented - * - * @return int Processing level of current query - */ - protected int getProcessingLevel() { - return parent.getProcessingLevel(); - } - - /** - * Add Pre Processing Sql - * - * Add sql statement to run before main sql statement is run - * - * @param sql String sql statement to be processed before main sql statement has been run - */ - protected void addPreProcessingSql(String sql) { - parent.addPreProcessingSql(sql); - } - - /** - * Add Post Processing Sql - * - * Add sql statement to run after main sql statement has run - * - * @param sql String sql statement to processed after main sql statement has been run - */ - protected void addPostProcessingSql(String sql) { - parent.addPostProcessingSql(sql); - } - - /** - * Search For Query In Request Definition - * - * Looks for query defintion with the specified query id in the parent query xml definition - * - * @param subQueryId String specified the query id for the query to look for - * @return QueryDefinitionType if query is found, otherwise returns null - */ - protected QueryDefinitionType searchForQueryInRequestDefinition(String subQueryId){ - return parent.searchForQueryInRequestDefinition(subQueryId); - } - - - /** - * Is Patient Only Query - * - * @return true if only patient num is required to be returned by this panel - */ - protected boolean isPatientOnlyQuery() { - if (this.returnEncounterToParent() - || this.returnInstanceToParent() - || this.getPanelTiming().equalsIgnoreCase( - QueryTimingHandler.SAME) - || this.getPanelTiming().equalsIgnoreCase( - QueryTimingHandler.SAMEVISIT) - || this.getPanelTiming().equalsIgnoreCase( - QueryTimingHandler.SAMEINSTANCENUM)) - return false; - else - return true; - } - - /** - * Add Ignored Message - * - * @param errorMessage String error m - */ - public void addIgnoredMessage(String errorMessage) { - parent.addIgnoredMessage(errorMessage); - } - - /** - * Get Query Options - * - * @return TemporalQueryOptions that are valid for this query - */ - protected TemporalQueryOptions getQueryOptions() { - return parent.getQueryOptions(); - } - - private List buildFactTableList(List itemSqlList) { - List factTableList = new ArrayList(); - - for (TemporalPanelItemSql itemSqlItem : itemSqlList) { - String itemSql = itemSqlItem.itemSql; - factTableList.add(itemSqlItem.factTable); - } - return factTableList; - - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Christopher Herrick + */ + +package edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Hashtable; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import javax.xml.stream.XMLStreamException; + +import org.apache.axis2.AxisFault; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.exception.StackTraceUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.ConceptNotFoundException; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.DateConstrainUtil; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.OntologyException; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.QueryTimingHandler; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.TotalItemOccurrenceHandler; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal.TemporalQueryOptions.InvertedConstraintStrategy; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal.TemporalQueryOptions.QueryConstraintStrategy; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; +import edu.harvard.i2b2.crc.datavo.ontology.DerivedFactColumnsType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ItemType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.PanelType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.PanelType.TotalItemOccurrences; +import edu.harvard.i2b2.crc.delegate.ontology.CallOntologyUtil; +import edu.harvard.i2b2.crc.datavo.setfinder.query.TotOccuranceOperatorType; +import edu.harvard.i2b2.crc.util.ItemKeyUtil; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + +/** + * Temporal Panel Object + * + *

    + * Panel query object that wraps the panel tag found in the query definition + * xml. It roughly corresponds to a panel in the query UI. Panel is responsible + * for organizing the sql that comes back from individual panel items - sql from + * items should be logically or'd together. It is also the container that holds + * the panel constraint types - occurrence, dates, and exclude. + * + * @author Christopher Herrick + * + */ +public class TemporalPanel implements Comparable { + + protected final Log log = LogFactory.getLog(getClass()); + + /* + * Max Timing Score - max score a panel can get when ordering based on items + * and timing + */ + private final int MAXTIMINGSCORE = 5; + + private TemporalSubQuery parent; + private PanelType basePanel; + private int estimatedPanelSize = 0; + private List panelItemList = null; + private int missingItemTotals = 0; + + protected class TemporalPanelItemSql{ + protected String itemSql = null; + protected String factTable = null; + protected String joinTable = null; + protected boolean valueConstraint = false; + protected boolean textConstraint = false; + } + /** + * Constructor + * + * @param parent + * reference to the temporal panel group to which this panel + * belongs + * @param panel + * i2b2 instantiation of the panel xml object found in the query + * definition + * @throws I2B2Exception + * thrown when an i2b2 specific error is found + */ + public TemporalPanel(TemporalSubQuery parent, PanelType panel) + throws I2B2Exception { + this.parent = parent; + this.basePanel = panel; + + parsePanel(); + } + + /** + * Parse Panel + * + * Parses through the paneltype object passed in through the constructor. + * Evaluates each panel item and casts them to the appropriate type. + * Calculates the estimated return size of the times in the panel which will + * then be used when sorting panel items + * + * @throws I2B2Exception + * thrown when an i2b2 specific error is found + */ + private void parsePanel() throws I2B2Exception { + panelItemList = new ArrayList(); + + List itemList = basePanel.getItem(); + + for (ItemType itemType : itemList) { + TemporalPanelItem panelItem = null; + try{ + if (itemType.getItemKey().toLowerCase() + .startsWith(ItemKeyUtil.ITEM_KEY_PATIENT_SET)) { + panelItem = new TemporalPanelPatientSetItem(this, itemType); + } else if (itemType.getItemKey().toLowerCase() + .startsWith(ItemKeyUtil.ITEM_KEY_PATIENT_ENCOUNTER_SET)) { + panelItem = new TemporalPanelPatientEncounterSetItem(this, + itemType); + } else if (itemType.getItemKey().toLowerCase() + .startsWith(ItemKeyUtil.ITEM_KEY_MASTERID)) { + panelItem = new TemporalPanelEmbeddedQueryItem(this, itemType); + } else if (itemType.getItemKey().toLowerCase() + .startsWith(ItemKeyUtil.ITEM_KEY_PATIENT)) { + panelItem = new TemporalPanelPatientItem(this, itemType); + } else if (itemType.getItemKey().toLowerCase() + .startsWith(ItemKeyUtil.ITEM_KEY_ENCOUNTER)) { + panelItem = new TemporalPanelEncounterItem(this, itemType); + } else { + panelItem = new TemporalPanelConceptItem(this, itemType); + if(panelItem.getConceptType() == null) + panelItem.getConceptType(); + if (panelItem != null + && panelItem.getConceptType() != null + && panelItem.getConceptType().getDimcode() != null + && panelItem.getConceptType().getDimcode() + .toLowerCase().trim() + .startsWith(ItemKeyUtil.ITEM_KEY_CELLID)) { + panelItem = new TemporalPanelCellQueryItem(this, itemType, + panelItem.getConceptType()); + + } + if (parent.isProtectedQuery() == false) + parent.setProtectedQuery(panelItem.getConceptType().getProtectedAccess().equalsIgnoreCase("Y")?true:false); + /* + * check for derived table parameter and look for other views for this item. + * ... i.e. item is found in multiple views. + * ... if others found, then add them to the panel item list individually. + */ + if (this.parent.getQueryOptions()!=null&&this.parent.getQueryOptions().useDerivedFactTable()) + { + if(panelItem.getConceptType().getFacttablecolumn().contains(".")) + { + String baseItemFactColumn = panelItem.getConceptType().getFacttablecolumn(); + DerivedFactColumnsType columns = getFactColumnsFromOntologyCell(itemType.getItemKey()); + if(columns.getDerivedFactTableColumn().size() > 1) { + + for (String column : columns.getDerivedFactTableColumn()) { + // look for non-null fact table columns that are not equal to the base item's column + if((column != null) && !(column.equals(baseItemFactColumn))){ + if(column.contains(".")){ + TemporalPanelItem derivedPanelItem = new TemporalPanelConceptItem(this, itemType); + if(derivedPanelItem.getConceptType() == null) + derivedPanelItem.getConceptType(); + + if (derivedPanelItem != null + && derivedPanelItem.getConceptType() != null + && derivedPanelItem.getConceptType().getDimcode() != null + && derivedPanelItem.getConceptType().getDimcode() + .toLowerCase().trim() + .startsWith(ItemKeyUtil.ITEM_KEY_CELLID)) { + derivedPanelItem = new TemporalPanelCellQueryItem(this, itemType, + derivedPanelItem.getConceptType()); + } + log.debug("setting a new fact column: " + column); + derivedPanelItem.parseFactColumn(column); + panelItemList.add(derivedPanelItem); + } + } + } + } + + } + } + } + Integer conceptTotal = panelItem.getConceptTotal(); + if (conceptTotal != null) { + estimatedPanelSize += conceptTotal; + } else + missingItemTotals++; + panelItemList.add(panelItem); + + + } + catch (ConceptNotFoundException ce){ + log.debug("Concept not found error: " + ce.getMessage()); + parent.addIgnoredMessage(ce.getMessage() + " panel#" + parent.getPanelIndex(this)); + } + } + } + + protected DerivedFactColumnsType getFactColumnsFromOntologyCell(String itemKey) + throws ConceptNotFoundException, OntologyException { + DerivedFactColumnsType factColumns = new DerivedFactColumnsType(); + try { + + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + String ontologyUrl = qpUtil + .getCRCPropertyValue(QueryProcessorUtil.ONTOLOGYCELL_ROOT_WS_URL_PROPERTIES); + + factColumns = CallOntologyUtil.callGetFactColumns(itemKey, + parent.getSecurityType(), parent.getProjectId(), + ontologyUrl +"/getDerivedFactColumns"); + } catch (JAXBUtilException e) { + + log.error("Error while fetching metadata [" + itemKey + + "] from ontology ", e); + throw new OntologyException("Error while fetching metadata [" + + itemKey + "] from ontology " + + StackTraceUtil.getStackTrace(e)); + } catch (I2B2Exception e) { + log.error("Error while fetching metadata from ontology ", e); + throw new OntologyException("Error while fetching metadata [" + + itemKey + "] from ontology " + + StackTraceUtil.getStackTrace(e)); + } catch (AxisFault e) { + log.error("Error while fetching metadata from ontology ", e); + throw new OntologyException("Error while fetching metadata [" + + itemKey + "] from ontology " + + StackTraceUtil.getStackTrace(e)); + } catch (XMLStreamException e) { + log.error("Error while fetching metadata from ontology ", e); + throw new OntologyException("Error while fetching metadata [" + + itemKey + "] from ontology " + + StackTraceUtil.getStackTrace(e)); + } + +// if (factColumns.isEmpty()) { +// throw new ConceptNotFoundException("[" + itemKey + "] "); + +// } + + return factColumns; + } + + /** + * Build Sql + * + * Main method for generating the sql string that will be run on the + * database for this panel item. Iterates through each item contained in the + * panel and appends sql together to form sql string for all items in the + * panel + * + * @param currentIndex + * int value that represents the panel position in the query + * @return String sql representation of the items in the query + * @throws I2B2DAOException + * thrown when a data related i2b2 issue is encountered + */ + public String buildSql(int currentIndex) throws I2B2DAOException { + boolean firstPanel = this.isFirstPanelInQuery(); + StringBuilder panelSqlBuffer = new StringBuilder(); + + boolean addDelimiter = false; + // OMOP WAS... + // List itemSqlList = getItemSql(); + List itemSqlList = getItemSql(); + if (itemSqlList!=null&&itemSqlList.size()>0){ + if (this.hasPanelOccurrenceConstraint() + && this.applyOccurrenceToPanelLevel() + && (this.getItemList().size() > 1 || !this.isPatientOnlyQuery())) { + if (firstPanel) { + panelSqlBuffer + .append(firstPanelItemSqlWithOccurrence(itemSqlList)); + } else { + panelSqlBuffer.append(nonFirstPanelItemSqlWithOccurrence( + currentIndex, itemSqlList)); + } + } else if (firstPanel && this.isPanelInverted()) { + panelSqlBuffer.append(buildFirstPanelInvertSql(itemSqlList)); + } else { + if (firstPanel) { + panelSqlBuffer.append(firstPanelItemSql(itemSqlList)); + } else { + panelSqlBuffer.append(nonFirstPanelItemSql(itemSqlList, + currentIndex)); + } + } + } + else if (this.isPanelInverted()){ + //no items and inverted panel means this is a get everyone query + + String schema = getDatabaseSchema(); + if (schema == null) + schema = ""; + else if (!schema.endsWith(".")) + schema += "."; + + panelSqlBuffer.append("insert into " + parent.getTempTableName() + " (patient_num, panel_count ) " + + "select distinct patient_num, 0 from " + schema + "patient_dimension pat "); + + } + + return panelSqlBuffer.toString(); + } + + /** + * Get Item Sql + * + * Gets the sql for each of the items in the panel and returns the results + * in an List + * + * @return List list of sql statements for all the times contained in the panel + * @throws I2B2DAOException + */ + //OMOP WAS.. +/* private List getItemSql() throws I2B2DAOException { + List itemList = null; + if (panelItemList.size() > 0) { + itemList = new ArrayList(panelItemList.size()); + for (TemporalPanelItem item : panelItemList) { + try { + itemList.add(item.buildSql()); + } + catch (ConceptNotFoundException ce){ + parent.addIgnoredMessage(ce.getMessage() + " panel#" + parent.getPanelIndex(this)); + } + } + } + return itemList; + } + */ + private List getItemSql() throws I2B2DAOException { + List itemList = null; + if (panelItemList.size() > 0) { + itemList = new ArrayList(panelItemList.size()); + for (TemporalPanelItem item : panelItemList) { + try { + TemporalPanelItemSql itemSql = new TemporalPanelItemSql(); + itemSql.itemSql = item.buildSql(); + itemSql.factTable = item.factTable; + itemSql.joinTable = item.tableName; + itemList.add(itemSql); + } + catch (ConceptNotFoundException ce){ + parent.addIgnoredMessage(ce.getMessage() + " panel#" + parent.getPanelIndex(this)); + } + } + } + return itemList; + } + + /** + * Union Item Sql + * + * Takes the list of individual sql statements and constructs one sql statement by unioning + * individual statements together. Submitted statements are assumed to have the same select list + * + * @param itemSqlList List of individual sql statements + * @return String one sql statement that unions individual statement together + */ + //OMOP WAS.. + // private String unionItemSql(List itemSqlList) { + private String unionItemSql(List itemSqlList) { + StringBuilder unionSql = new StringBuilder(); + + boolean first = true; + // OMOP WAS... + //for (String itemSql : itemSqlList) { + for (TemporalPanelItemSql itemSqlItem : itemSqlList) { + String itemSql = itemSqlItem.itemSql; + if (!first) + unionSql.append("\n union all \n"); + else + first = false; + + unionSql.append(itemSql); + } + + return unionSql.toString(); + } + + /** + * Consolidate Item Sql + * + * Takes in list of individual sql statements and combines them by consolidating statements with the same from clause + * into one statement with multiple constraints. Statements with different from clauses are unioned together + * + * @param itemSql List of individual sql statements + * @return String one sql statement that combines all statements from the individual list + */ + //OMOP WAS.. +// private String consolidateItemSql(List itemSql) { + private String consolidateItemSql(List itemSqlList) { + StringBuilder itemSqlBuffer = new StringBuilder(); + + HashMap> tableMatch = new HashMap>(); + int index = 0; + //OMOP WAS.. + // for (String sql : itemSql) { + for (TemporalPanelItemSql itemSql : itemSqlList) { + String sql = itemSql.itemSql; + TemporalQuerySimpleSqlParser simpleSql = new TemporalQuerySimpleSqlParser( + sql); + + String selectClause = simpleSql.getSelectClause(); + String fromClause = simpleSql.getFromClause(); + String groupByClause = simpleSql.getGroupByClause(); + String havingClause = simpleSql.getHavingClause(); + + String consolidatedKey = selectClause + + "|" + + fromClause + + "|" + + (groupByClause != null + && groupByClause.trim().length() > 0 ? "|" + + groupByClause : ""); + + if (havingClause != null && havingClause.trim().length() > 0) { + consolidatedKey += "|" + String.valueOf(index); + } + + List sqlList = null; + if (tableMatch.containsKey(consolidatedKey)) { + sqlList = tableMatch.get(consolidatedKey); + } else { + sqlList = new ArrayList(); + } + + sqlList.add(simpleSql); + tableMatch.put(consolidatedKey, sqlList); + index++; + } + + boolean firstKey = true; + for (String consolidatedKey : tableMatch.keySet()) { + List sqlList = tableMatch + .get(consolidatedKey); + + boolean firstItem = true; + + String selectClause = ""; + String fromClause = ""; + String whereClause = ""; + String groupByClause = ""; + String havingClause = ""; + for (TemporalQuerySimpleSqlParser simpleSql : sqlList) { + if (firstItem) { + selectClause = "select " + simpleSql.getSelectClause() + + " "; + fromClause = "from " + simpleSql.getFromClause() + " "; + if (simpleSql.getGroupByClause() != null + && simpleSql.getGroupByClause().trim().length() > 0) + groupByClause = "group by " + + simpleSql.getGroupByClause() + " "; + if (simpleSql.getHavingClause() != null + && simpleSql.getHavingClause().trim().length() > 0) + havingClause = "having " + simpleSql.getHavingClause() + + " "; + } + + if (simpleSql.getWhereClause() != null + && simpleSql.getWhereClause().trim().length() > 0) { + if (whereClause.length() == 0) { + whereClause = "where (" + simpleSql.getWhereClause() + + ") "; + } else { + whereClause += "or (" + simpleSql.getWhereClause() + + ") "; + } + } + + firstItem = false; + } + + if (!firstKey) { + itemSqlBuffer.append("\nunion all \n"); + } + + itemSqlBuffer.append(selectClause); + itemSqlBuffer.append(fromClause); + if (whereClause != null && whereClause.trim().length() > 0) + itemSqlBuffer.append(whereClause); + if (groupByClause != null && groupByClause.trim().length() > 0) + itemSqlBuffer.append(groupByClause); + if (havingClause != null && havingClause.trim().length() > 0) + itemSqlBuffer.append(havingClause); + + firstKey = false; + } + + return itemSqlBuffer.toString(); + } + + /** + * Build Item Union Sql + * + * Used to return the proper sql syntax for unioning two sql statements + * together + * + * @return String with sql building block used to union to sql statements + * together + * @throws I2B2DAOException + * thrown when an i2b2 related data error is encountered + */ + private String buildItemUnionSql() throws I2B2DAOException { + StringBuilder itemSqlBuffer = new StringBuilder(); + + int currentIndex = 0; + for (TemporalPanelItem item : panelItemList) { + String itemSql = item.buildSql(); + if (currentIndex > 0) { + itemSqlBuffer.append("\n union all \n"); + } + + itemSqlBuffer.append(itemSql); + currentIndex++; + } + + return itemSqlBuffer.toString(); + } + + /** + * First Panel Item Sql + * + * Processes an item from the first panel of a panel group. First panel + * items are processed as an insert statement into a temporary table rather + * than an update + * + * @param itemSqlList + * List of individual sql statements found in this panel + * @return String sql representation that joins the item sql to the panel + * sql + */ + //OMOP WAS... + // private String firstPanelItemSql(List itemSqlList) { + private String firstPanelItemSql(List itemSqlList) { + StringBuilder panelSql = new StringBuilder(); + boolean addDelimiter = false; + + //OMOP WAS.. + // for (String itemSql : itemSqlList) { + for (TemporalPanelItemSql itemSqlItem : itemSqlList) { + String itemSql = itemSqlItem.itemSql; + String insertValuesClause = buildInsertValuesClause(); + + StringBuilder withItemSql = new StringBuilder(); + + String firstPanelItemSql = ""; + + String innerSelectClause = buildInnerSelectClause(); + String innerGroupByClause = buildInnerGroupByClause(); + + String itemStatement = ""; + StringBuilder tableStatement = new StringBuilder(itemSql); + + boolean useTempTables = false; + if (parent.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER) + && parent.getQueryOptions().getQueryConstraintLogic() == QueryConstraintStrategy.TEMP_TABLES) { + useTempTables = true; + } + + // String suffix = getPanelId(); + String suffix = ""; + + String tSelect = "select " + innerSelectClause + " " + "from " + + (useTempTables ? "#t" + suffix + " " : "") + "t "; + + String schema = getDatabaseSchema(); + if (schema == null) + schema = ""; + else if (!schema.endsWith(".")) + schema += "."; + + if (getPanelTiming().equals(QueryTimingHandler.ANY)) { + // this means there are negation panels behind this one + if (returnInstanceToParent()) { + itemStatement = itemSql; + innerSelectClause = buildInnerSelectClause("f"); + innerGroupByClause = buildInnerGroupByClause("f"); + tableStatement = new StringBuilder(); + tableStatement.append("select " + innerSelectClause + " " + + "from " + schema + "observation_fact f, "); + if (useTempTables) { + tableStatement.append("#i" + suffix + " "); + } else if (parent.getQueryOptions().getQueryConstraintLogic() == QueryConstraintStrategy.DERIVED_TABLES) { + tableStatement.append("(" + itemSql + ") "); + } + tableStatement + .append(" i where i.patient_num = f.patient_num "); + if (innerGroupByClause != null + && innerGroupByClause.trim().length() > 0 + && parent.getQueryOptions().useItemGroupByStatement()) { + tableStatement.append("group by " + innerGroupByClause); + } + } else if (returnEncounterToParent()) { + itemStatement = itemSql; + innerSelectClause = buildInnerSelectClause("v"); + innerGroupByClause = buildInnerGroupByClause("v"); + tableStatement = new StringBuilder(); + tableStatement.append("select " + innerSelectClause + " " + + "from " + schema + "visit_dimension v, "); + if (useTempTables) { + tableStatement.append("#i" + suffix + " "); + } else if (parent.getQueryOptions().getQueryConstraintLogic() == QueryConstraintStrategy.DERIVED_TABLES) { + tableStatement.append("(" + itemSql + ") "); + } + tableStatement + .append(" i where i.patient_num = v.patient_num "); + if (innerGroupByClause != null + && innerGroupByClause.trim().length() > 0 + && parent.getQueryOptions().useItemGroupByStatement()) { + tableStatement.append("group by " + innerGroupByClause); + } + } + } else if (getPanelTiming().equals(QueryTimingHandler.SAME) + || getPanelTiming().equals(QueryTimingHandler.SAMEVISIT)) { + if (returnInstanceToParent()) { + itemStatement = itemSql; + innerSelectClause = buildInnerSelectClause("f"); + innerGroupByClause = buildInnerGroupByClause("f"); + tableStatement = new StringBuilder(); + tableStatement.append("select " + innerSelectClause + " " + + "from " + schema + "observation_fact f, "); + if (useTempTables) { + tableStatement.append("#i" + suffix + " "); + } else if (parent.getQueryOptions().getQueryConstraintLogic() == QueryConstraintStrategy.DERIVED_TABLES) { + tableStatement.append("(" + itemSql + ") "); + } + tableStatement.append(" i " + + "where i.patient_num = f.patient_num " + + "and i.encounter_num = f.encounter_num "); + if (innerGroupByClause != null + && innerGroupByClause.trim().length() > 0 + && parent.getQueryOptions().useItemGroupByStatement()) { + tableStatement.append("group by " + innerGroupByClause); + } + } + } + + if (useTempTables) { + if (itemStatement != null + && itemStatement.trim().length() > 0) { + withItemSql + .append(parent.buildTempTableCheckDrop("i" + suffix)); + withItemSql.append(parent.getSqlDelimiter()); + withItemSql.append(buildSelectIntoStatement( + itemStatement, "i" + suffix)); + withItemSql.append(parent.getSqlDelimiter()); + withItemSql + .append(parent.buildTempTableCheckDrop("t" + suffix)); + withItemSql.append(parent.getSqlDelimiter()); + withItemSql.append(buildSelectIntoStatement( + tableStatement.toString(), "t" + suffix)); + withItemSql.append(parent.getSqlDelimiter()); + withItemSql.append("drop table #i" + suffix); + withItemSql.append(parent.getSqlDelimiter()); + } else { + withItemSql + .append(parent.buildTempTableCheckDrop("t" + suffix)); + withItemSql.append(parent.getSqlDelimiter()); + withItemSql.append(buildSelectIntoStatement( + tableStatement.toString(), "t" + suffix)); + withItemSql.append(parent.getSqlDelimiter()); + } + } else if (parent.getQueryOptions().getQueryConstraintLogic() == QueryConstraintStrategy.DERIVED_TABLES) { + withItemSql = new StringBuilder(); + innerSelectClause = buildInnerSelectClause(); + tSelect = "select " + innerSelectClause + " " + "from (" + + tableStatement.toString() + ") t "; + } else { + if (itemStatement != null + && itemStatement.trim().length() > 0) { + withItemSql.append("with i as ( " + "\n" + + itemStatement + "\n" + " ) " + "\n"); + withItemSql.append(", t as ( " + "\n" + + tableStatement.toString() + "\n" + " ) " + + "\n"); + } else { + withItemSql.append("with t as ( " + "\n" + + tableStatement.toString() + "\n" + " ) " + + "\n"); + } + } + + if (parent.getServerType().equalsIgnoreCase( + DAOFactoryHelper.ORACLE) || parent.getServerType() + .equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { + firstPanelItemSql = "insert into " + + parent.getTempTableName() + " (" + + insertValuesClause + ")" + "\n" + + withItemSql.toString() + tSelect; + } else { + firstPanelItemSql = withItemSql.toString() + "insert into " + + parent.getTempTableName() + " (" + + insertValuesClause + ")" + "\n" + tSelect; + } + + if (useTempTables) { + firstPanelItemSql += parent.getSqlDelimiter(); + firstPanelItemSql += "drop table #t" + suffix + ""; + } + + if (addDelimiter) { + panelSql.append(parent.getSqlDelimiter()); + } + + panelSql.append(firstPanelItemSql); + + addDelimiter = true; + } + + return panelSql.toString(); + } + + /** + * Build Select Into Statement + * + * Takes a sql statement and creates sql statement that selects the results into a temporary table. This method should only be used on + * Sql Server or other database that supports the select into sybntax + * + * @param sqlStatement String that contains the sql statements to be saved into a temporary table + * @param tempTableName String that contains the name of the temporary table + * @return String properly formated sql statement that stores the result of the select statement into a temporary table + */ + private String buildSelectIntoStatement(String sqlStatement, + String tempTableName) { + TemporalQuerySimpleSqlParser sqlParser = new TemporalQuerySimpleSqlParser( + sqlStatement); + String select = sqlParser.getSelectClause(); + String into = " into #" + tempTableName; + String from = sqlParser.getFromClause(); + String where = sqlParser.getWhereClause(); + String groupBy = sqlParser.getGroupByClause(); + String having = sqlParser.getHavingClause(); + String orderBy = sqlParser.getOrderByClause(); + String selectIntoSql = "select " + + select + + " \n" + + into + + " \n" + + "from " + + from + + " \n" + + (where != null && where.trim().length() > 0 ? "where " + + where + " \n" : "") + + (groupBy != null && groupBy.trim().length() > 0 ? "group by " + + groupBy + " \n" : "") + + (having != null && having.trim().length() > 0 ? "having " + + having + " \n" : "") + + (orderBy != null && orderBy.trim().length() > 0 ? "order by " + + orderBy + " \n" : ""); + return selectIntoSql; + } + + /** + * Build First Panel Invert Sql + * + * Take in the list of individual sql statements from this panel and creates a sql statement that is inverted. Current invert options are + * limited to either using a minus/except syntax or a not exists/not in syntax. + * + * @param itemSqlList List of individual sql statements for all items in this panel + * @return String sql statement that applies invert clause to all items in first panel + */ + //OMOP WAS... + // private String buildFirstPanelInvertSql(List itemSqlList) { + private String buildFirstPanelInvertSql(List itemSqlList) { + + String insertValuesClause = buildInsertValuesClause(); + StringBuilder withItemSql = new StringBuilder(); + String invertSql = ""; + String replaceString = ""; + + String innerSelectClause = buildInnerSelectClause(); + String innerGroupByClause = buildInnerGroupByClause(); + String itemSql = unionItemSql(itemSqlList); + String itemStatement = ""; + StringBuilder tableStatement = new StringBuilder(itemSql); + + List factTables = null; + if (this.parent.getQueryOptions()!=null&&this.parent.getQueryOptions().useDerivedFactTable()) + { + factTables = buildFactTableList(itemSqlList); + } + + + boolean useTempTables = false; + if (parent.getServerType().equalsIgnoreCase(DAOFactoryHelper.SQLSERVER) + && parent.getQueryOptions().getQueryConstraintLogic() == QueryConstraintStrategy.TEMP_TABLES) { + useTempTables = true; + } + + String schema = getDatabaseSchema(); + if (schema == null) + schema = ""; + else if (!schema.endsWith(".")) + schema += "."; + + // String suffix = getPanelId(); + String suffix = ""; + + String tSelect = "select " + innerSelectClause + " " + "from " + + (useTempTables ? "#t" + suffix + " " : "") + " t"; + + if (getPanelTiming().equals(QueryTimingHandler.ANY)) { + // this means there are negation panels behind this one + if (returnInstanceToParent()) { + itemStatement = itemSql; + innerSelectClause = buildInnerSelectClause("f"); + innerGroupByClause = buildInnerGroupByClause("f"); + tableStatement = new StringBuilder(); + if(factTables == null){ + tableStatement.append("select " + innerSelectClause + " " + + "from " + schema + "observation_fact f, "); + } + else{ + if(factTables.size() == 1) { + tableStatement.append("select " + innerSelectClause + " " + + "from " + schema + factTables.get(0) +" f, "); + } + else { + Iterator i = factTables.iterator(); + while (i.hasNext()){ + tableStatement.append("select " + innerSelectClause + " " + + "from " + schema + i.next() +" f, "); + if(i.hasNext()){ + tableStatement.append(" union all "); + } + } + } + } + + if (useTempTables) { + tableStatement.append("#i" + suffix + " "); + } else if (parent.getQueryOptions().getQueryConstraintLogic() == QueryConstraintStrategy.DERIVED_TABLES) { + tableStatement.append("(" + replaceString + ") "); + } + tableStatement.append(" i " + + "where i.patient_num = f.patient_num "); + if (innerGroupByClause != null + && innerGroupByClause.trim().length() > 0 + && parent.getQueryOptions().useItemGroupByStatement()) { + tableStatement.append("group by " + innerGroupByClause); + } + } else if (returnEncounterToParent()) { + itemStatement = itemSql; + innerSelectClause = buildInnerSelectClause("v"); + innerGroupByClause = buildInnerGroupByClause("v"); + tableStatement = new StringBuilder(); + tableStatement.append("select " + innerSelectClause + " " + + "from " + schema + "visit_dimension v, "); + if (useTempTables) { + tableStatement.append("#i" + suffix + " "); + } else if (parent.getQueryOptions().getQueryConstraintLogic() == QueryConstraintStrategy.DERIVED_TABLES) { + tableStatement.append("(" + replaceString + ") "); + } + tableStatement.append(" i " + + "where i.patient_num = v.patient_num "); + if (innerGroupByClause != null + && innerGroupByClause.trim().length() > 0 + && parent.getQueryOptions().useItemGroupByStatement()) { + tableStatement.append("group by " + innerGroupByClause); + } + } + } else if (getPanelTiming().equals(QueryTimingHandler.SAME) + || getPanelTiming().equals(QueryTimingHandler.SAMEVISIT)) { + if (returnInstanceToParent()) { + itemStatement = itemSql; + innerSelectClause = buildInnerSelectClause("f"); + innerGroupByClause = buildInnerGroupByClause("f"); + tableStatement = new StringBuilder(); + if(factTables == null){ + tableStatement.append("select " + innerSelectClause + " " + + "from " + schema + "observation_fact f, "); + } + else{ + if(factTables.size() == 1) { + tableStatement.append("select " + innerSelectClause + " " + + "from " + schema + factTables.get(0) +" f, "); + } + else { + Iterator i = factTables.iterator(); + while (i.hasNext()){ + tableStatement.append("select " + innerSelectClause + " " + + "from " + schema + i.next() +" f, "); + if(i.hasNext()){ + tableStatement.append(" union all "); + } + } + } + } + + if (useTempTables) { + tableStatement.append("#i" + suffix + " "); + } else if (parent.getQueryOptions().getQueryConstraintLogic() == QueryConstraintStrategy.DERIVED_TABLES) { + tableStatement.append("(" + replaceString + ") "); + } + tableStatement.append(" i " + + "where i.patient_num = f.patient_num " + + "and i.encounter_num = f.encounter_num "); + if (innerGroupByClause != null + && innerGroupByClause.trim().length() > 0 + && parent.getQueryOptions().useItemGroupByStatement()) { + tableStatement.append("group by " + innerGroupByClause); + } + } + } + + if (useTempTables) { + if (itemStatement != null && itemStatement.trim().length() > 0) { + withItemSql.append(parent.buildTempTableCheckDrop("y" + suffix)); + withItemSql.append(parent.getSqlDelimiter()); + withItemSql.append(buildSelectIntoStatement(itemStatement, "y" + + suffix)); + withItemSql.append(parent.getSqlDelimiter()); + + String invertClause = ""; + if (parent.getQueryOptions().getInvertedConstraintLogic()==InvertedConstraintStrategy.MINUS_CLAUSE){ + invertClause = buildInvertExceptSql("#y" + suffix); + } + else { + invertClause = buildInvertNotExistsSql("#y" + suffix); + } + withItemSql.append(parent.buildTempTableCheckDrop("i" + suffix)); + withItemSql.append(parent.getSqlDelimiter()); + withItemSql.append(buildSelectIntoStatement(invertClause, "i" + + suffix)); + withItemSql.append(parent.getSqlDelimiter()); + withItemSql.append("drop table #y" + suffix + ""); + withItemSql.append(parent.getSqlDelimiter()); + + withItemSql.append(parent.buildTempTableCheckDrop("t" + suffix)); + withItemSql.append(parent.getSqlDelimiter()); + withItemSql.append(buildSelectIntoStatement( + tableStatement.toString(), "t" + suffix)); + withItemSql.append(parent.getSqlDelimiter()); + withItemSql.append("drop table #i" + suffix); + withItemSql.append(parent.getSqlDelimiter()); + } else { + + withItemSql.append(parent.buildTempTableCheckDrop("y" + suffix)); + withItemSql.append(parent.getSqlDelimiter()); + withItemSql.append(buildSelectIntoStatement(itemSql, "y" + + suffix)); + withItemSql.append(parent.getSqlDelimiter()); + + String invertClause = ""; + if (parent.getQueryOptions().getInvertedConstraintLogic()==InvertedConstraintStrategy.MINUS_CLAUSE){ + invertClause = buildInvertExceptSql("#y" + suffix); + } + else { + invertClause = buildInvertNotExistsSql("#y" + suffix); + } + withItemSql.append(parent.buildTempTableCheckDrop("i" + suffix)); + withItemSql.append(parent.getSqlDelimiter()); + withItemSql.append(buildSelectIntoStatement(invertClause, "i" + + suffix)); + withItemSql.append(parent.getSqlDelimiter()); + withItemSql.append("drop table #y" + suffix); + withItemSql.append(parent.getSqlDelimiter()); + + String invertInsertSql = buildInvertInsertSelectSql("i"); + withItemSql.append(parent.buildTempTableCheckDrop("t" + suffix)); + withItemSql.append(parent.getSqlDelimiter()); + withItemSql + .append("select " + invertInsertSql + " " + "into #t" + + suffix + " " + "from #i" + suffix + " i "); + withItemSql.append(parent.getSqlDelimiter()); + withItemSql.append("drop table #i" + suffix); + withItemSql.append(parent.getSqlDelimiter()); + } + + invertSql = withItemSql.toString() + "insert into " + + parent.getTempTableName() + " (" + insertValuesClause + + ")" + "\n" + tSelect + parent.getSqlDelimiter() + + "drop table #t" + suffix; + } else if (parent.getQueryOptions().getQueryConstraintLogic()==QueryConstraintStrategy.DERIVED_TABLES){ + if (itemStatement != null && itemStatement.trim().length() > 0) { + String invertClause = ""; + if (parent.getQueryOptions().getInvertedConstraintLogic()==InvertedConstraintStrategy.MINUS_CLAUSE){ + invertClause = buildInvertExceptSql("y"); + } + else { + invertClause = buildInvertNotExistsSql(itemStatement, "y"); + } + String derivedSql = tableStatement.toString().replace(replaceString, invertClause); + withItemSql.append(derivedSql); + } else { + String invertClause = ""; + if (parent.getQueryOptions().getInvertedConstraintLogic()==InvertedConstraintStrategy.MINUS_CLAUSE){ + invertClause = buildInvertExceptSql("y"); + } + else { + invertClause = buildInvertNotExistsSql(itemSql, "y"); + } + String invertInsertSql = buildInvertInsertSelectSql("i"); + withItemSql.append(" select " + + invertInsertSql + " from (" + + invertClause + + ") i \n"); + } + + innerSelectClause = buildInnerSelectClause(); + tSelect = "select " + innerSelectClause + " " + "from (" + + withItemSql.toString() + ") t "; + + if (parent.getServerType() + .equalsIgnoreCase(DAOFactoryHelper.ORACLE) || parent.getServerType() + .equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { + invertSql = "insert into " + parent.getTempTableName() + " (" + + insertValuesClause + ")" + "\n" + + tSelect; + } else { + invertSql = "insert into " + + parent.getTempTableName() + " (" + insertValuesClause + + ")" + "\n" + tSelect; + } + } else { + if (itemStatement != null && itemStatement.trim().length() > 0) { + withItemSql.append("with y as ( " + "\n" + itemStatement + "\n" + + " ) " + "\n"); + + String invertClause = ""; + if (parent.getQueryOptions().getInvertedConstraintLogic()==InvertedConstraintStrategy.MINUS_CLAUSE){ + invertClause = buildInvertExceptSql("y"); + } + else { + invertClause = buildInvertNotExistsSql("y"); + } + withItemSql.append(", i as ( " + "\n" + invertClause + "\n" + + " ) " + "\n"); + withItemSql.append(", t as ( " + "\n" + + tableStatement.toString() + "\n" + " ) " + "\n"); + } else { + withItemSql.append("with y as ( " + "\n" + itemSql + "\n" + + " ) " + "\n"); + String invertClause = ""; + if (parent.getQueryOptions().getInvertedConstraintLogic()==InvertedConstraintStrategy.MINUS_CLAUSE){ + invertClause = buildInvertExceptSql("y"); + } + else { + invertClause = buildInvertNotExistsSql("y"); + } + withItemSql.append(", i as ( " + "\n" + invertClause + "\n" + + " ) " + "\n"); + String invertInsertSql = buildInvertInsertSelectSql("i"); + withItemSql.append(", t as ( " + "\n" + " select " + + invertInsertSql + " from i " + "\n" + " ) " + "\n"); + } + + if (parent.getServerType() + .equalsIgnoreCase(DAOFactoryHelper.ORACLE) || parent.getServerType() + .equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { + invertSql = "insert into " + parent.getTempTableName() + " (" + + insertValuesClause + ")" + "\n" + + withItemSql.toString() + tSelect; + } else { + invertSql = withItemSql.toString() + "insert into " + + parent.getTempTableName() + " (" + insertValuesClause + + ")" + "\n" + tSelect; + } + + } + + return invertSql; + } + + + /** + * First Panel Item Sql With Occurrence + * + * This method returns the sql representation of all items in a panel when + * the panel is the first panel in a query. This method is only accessed + * when usePanelLevelOccurrence flag is set to true - in which case the + * occurrence is processed on the panel level instead of in an item by item + * basis + * + * @param itemSqlList List of individual sql statements for all items in this panel + * @return String sql representation for the first panel in the query + * @throws I2B2DAOException + * thrown when an i2b2 data related error is encountered + */ + //OMOP WAS.. + // private String firstPanelItemSqlWithOccurrence(List itemSqlList) + private String firstPanelItemSqlWithOccurrence(List itemSqlList) + throws I2B2DAOException { + + String itemSql = consolidateItemSql(itemSqlList); + + String insertValuesClause = buildInsertValuesClause(); + + String innerSelectClause = buildInnerSelectClause(""); + String innerGroupByClause = buildInnerGroupByClause(); + + TotalItemOccurrenceHandler totalItemOccurrencHandler = new TotalItemOccurrenceHandler(); + String totalItemOccurrenceClause = totalItemOccurrencHandler + .buildTotalItemOccurrenceClause(this.getTotalOccurrences()); + + StringBuilder withItemSql = new StringBuilder(); + + String firstPanelItemSql = ""; + + String schema = getDatabaseSchema(); + if (schema == null) + schema = ""; + else if (!schema.endsWith(".")) + schema += "."; + + String tSelect = "select " + innerSelectClause + " " + "from t"; + + if (getPanelTiming().equals(QueryTimingHandler.ANY)) { + // this means there are negation panels behind this one + if (returnInstanceToParent()) { + withItemSql + .append("with sub_t as ( " + + "\n" + + itemSql + + "\n" + + " ), " + + "\n" + + "y as (" + + "select " + + innerSelectClause + + " " + + "from sub_t " + + "where patient_num in (select patient_num from sub_t group by patient_num having sum(fact_count) " + + totalItemOccurrenceClause + ") " + ") \n"); + + innerSelectClause = buildInnerSelectClause("f"); + innerGroupByClause = buildInnerGroupByClause("f"); + withItemSql + .append(", t as (" + + "\n" + + "select " + + innerSelectClause + + " " + + "from " + + schema + + "observation_fact f " + + "where exists (" + + "select 1 " + + "from y " + + "where y.patient_num = f.patient_num) " + + (innerGroupByClause != null + && innerGroupByClause.trim().length() > 0 + && parent.getQueryOptions().useItemGroupByStatement() ? "group by " + + innerGroupByClause + : "") + ") " + "\n"); + } else if (returnEncounterToParent()) { + + withItemSql + .append("with sub_t as ( " + + "\n" + + itemSql + + "\n" + + " ), " + + "\n" + + "y as (" + + "select " + + innerSelectClause + + " " + + "from sub_t " + + "where patient_num in (select patient_num from sub_t group by patient_num having sum(fact_count) " + + totalItemOccurrenceClause + ") " + ") \n"); + + innerSelectClause = buildInnerSelectClause("v"); + innerGroupByClause = buildInnerGroupByClause("v"); + withItemSql + .append(", t as (" + + "\n" + + "select " + + innerSelectClause + + " " + + "from " + + schema + + "visit_dimension v " + + "where exists (" + + "select 1 " + + "from y " + + "where y.patient_num = v.patient_num) " + + (innerGroupByClause != null + && innerGroupByClause.trim().length() > 0 + && parent.getQueryOptions().useItemGroupByStatement() ? "group by " + + innerGroupByClause + : "") + ") " + "\n"); + } + } else if (getPanelTiming().equals(QueryTimingHandler.SAME) + || getPanelTiming().equals(QueryTimingHandler.SAMEVISIT)) { + if (returnInstanceToParent()) { + withItemSql + .append("with sub_t as ( " + + "\n" + + itemSql + + "\n" + + " ), " + + "\n" + + "y as (" + + "select " + + innerSelectClause + + " " + + "from sub_t " + + "where patient_num in (select patient_num from sub_t group by patient_num having sum(fact_count) " + + totalItemOccurrenceClause + ") " + ") \n"); + + innerSelectClause = buildInnerSelectClause("f"); + innerGroupByClause = buildInnerGroupByClause("f"); + withItemSql + .append(", t as (" + + "\n" + + "select " + + innerSelectClause + + " " + + "from " + + schema + + "observation_fact f " + + "where exists (" + + "select 1 " + + "from y " + + "where y.patient_num = f.patient_num " + + "and y.encounter_num = f.encounter_num) " + + (innerGroupByClause != null + && innerGroupByClause.trim().length() > 0 + && parent.getQueryOptions().useItemGroupByStatement() ? "group by " + + innerGroupByClause + : "") + ") " + "\n"); + } + } else { + withItemSql + .append("with sub_t as ( " + + "\n" + + itemSql + + "\n" + + " ), " + + "\n" + + "t as (" + + "select " + + innerSelectClause + + " " + + "from sub_t " + + "where patient_num in (select patient_num from sub_t group by patient_num having sum(fact_count) " + + totalItemOccurrenceClause + ") " + ") \n"); + } + + if (parent.getServerType().equalsIgnoreCase(DAOFactoryHelper.ORACLE) || parent.getServerType() + .equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { + firstPanelItemSql = "insert into " + parent.getTempTableName() + + " (" + insertValuesClause + ")" + "\n" + withItemSql + + tSelect; + } else { + firstPanelItemSql = withItemSql + "insert into " + + parent.getTempTableName() + " (" + insertValuesClause + + ")" + "\n" + tSelect; + } + + return firstPanelItemSql; + } + + /** + * Build Insert Values Clause + * + * Returns a list of columns from the temporary table that will be populated + * in an insert + * + * @return String sql list of columns from temporary table that will be + * inserted into + */ + public String buildInsertValuesClause() { + String insertValuesClause = ""; + + if (returnInstanceToParent() + || getPanelTiming().equalsIgnoreCase( + QueryTimingHandler.SAMEINSTANCENUM)) { + insertValuesClause = "provider_id, start_date, concept_cd, instance_num, encounter_num, patient_num"; + } else if (returnEncounterToParent() + || getPanelTiming().equalsIgnoreCase(QueryTimingHandler.SAME) + || getPanelTiming().equalsIgnoreCase( + QueryTimingHandler.SAMEVISIT)) { + insertValuesClause = "encounter_num, patient_num"; + } else { + insertValuesClause = "patient_num"; + } + + insertValuesClause += ", panel_count"; + + return insertValuesClause; + } + + /** + * Build Inner Select Clause + * + * Returns a list of columns that will be inserted into the temporary table + * for each item + * + * @return String sql statement that specifies the columns that should be + * returned from the item sql + */ + public String buildInnerSelectClause() { + return buildInnerSelectClause("t"); + } + + /** + * Build Inner Select Clause + * + * Returns a list of columns that will be inserted into the temporary table + * for each item + * + * @param tableAlias + * String that specifies the table alias to use when building sql + * string + * @return String sql statement that specifies the columns that should be + * returned from the item sql + */ + public String buildInnerSelectClause(String tableAlias) { + + if (tableAlias != null && tableAlias.trim().length() > 0 + && !tableAlias.trim().endsWith(".")) + tableAlias += "."; + + String innerSelectClause = " "; + if (!isFirstPanelInQuery()) { + innerSelectClause = " 1 as panel_count "; + } else { + if (returnInstanceToParent() + || getPanelTiming().equalsIgnoreCase( + QueryTimingHandler.SAMEINSTANCENUM)) { + innerSelectClause = "" + tableAlias + "provider_id, " + + tableAlias + "start_date, " + tableAlias + + "concept_cd, " + tableAlias + "instance_num, " + + tableAlias + "encounter_num, "; + } else if (returnEncounterToParent() + || getPanelTiming().equalsIgnoreCase( + QueryTimingHandler.SAME) + || getPanelTiming().equalsIgnoreCase( + QueryTimingHandler.SAMEVISIT)) { + innerSelectClause = "" + tableAlias + "encounter_num, "; + } + innerSelectClause += "" + tableAlias + + "patient_num, 0 as panel_count "; + } + return innerSelectClause; + } + + /** + * Build Inner Group By Clause + * + * Returns a list of columns that will be used to group the results of the panel sql statement + * + * @return String sql statement that specifies the columns that should be used to group the results + */ + public String buildInnerGroupByClause() { + return buildInnerGroupByClause("t"); + } + + /** + * Build Inner Group By Clause + * + * Returns a list of columns that will be used to group the results of the panel sql statement + * + * @param tableAlias + * String that specifies the table alias to use when building sql + * string + * @return String sql statement that specifies the columns that should be used to group the results + */ + public String buildInnerGroupByClause(String tableAlias) { + + if (tableAlias != null && tableAlias.trim().length() > 0 + && !tableAlias.trim().endsWith(".")) + tableAlias += "."; + + String innerSelectClause = " "; + if (!isFirstPanelInQuery()) { + innerSelectClause = " 1 as panel_count "; + } else { + if (returnInstanceToParent() + || getPanelTiming().equalsIgnoreCase( + QueryTimingHandler.SAMEINSTANCENUM)) { + innerSelectClause = "" + tableAlias + "provider_id, " + + tableAlias + "start_date, " + tableAlias + + "concept_cd, " + tableAlias + "instance_num, " + + tableAlias + "encounter_num, "; + } else if (returnEncounterToParent() + || getPanelTiming().equalsIgnoreCase( + QueryTimingHandler.SAME) + || getPanelTiming().equalsIgnoreCase( + QueryTimingHandler.SAMEVISIT)) { + innerSelectClause = "" + tableAlias + "encounter_num, "; + } + innerSelectClause += "" + tableAlias + "patient_num "; + } + return innerSelectClause; + } + + /** + * Non First Panel Item Sql With Occurrence + * + * This method returns the sql representation of all items in a panel when + * the panel is not the first panel in a query. This method is only accessed + * when usePanelLevelOccurrence flag is set to true - in which case the + * occurrence is processed on the panel level instead of in an item by item + * basis + * + * @param panelIndex + * int update index for the given panel + * @param itemSqlList + * List of individual sql statements for all items in this panel + * @return String sql representation for updating temporary table with panel + * information + * @throws I2B2DAOException + * thrown when an i2b2 data related error is encountered + */ + private String nonFirstPanelItemSqlWithOccurrence(int panelIndex, + List itemSqlList) throws I2B2DAOException { + String encounterNumClause = " ", instanceNumClause = " "; + String tempTableName = parent.getTempTableName(); + int oldPanelIndex = panelIndex - 1; + + if (getPanelTiming().equalsIgnoreCase( + QueryTimingHandler.SAMEINSTANCENUM)) { + instanceNumClause = " and " // + parent.getDatabaseSchema() + + tempTableName + + ".encounter_num = t.encounter_num and " + + tempTableName + + ".instance_num = t.instance_num and " + + tempTableName + + ".start_date = t.start_date and " + + tempTableName + + ".concept_cd = t.concept_cd and " + + tempTableName + ".provider_id = t.provider_id "; + } else if (getPanelTiming().equalsIgnoreCase(QueryTimingHandler.SAME) + || getPanelTiming().equalsIgnoreCase( + QueryTimingHandler.SAMEVISIT)) { + encounterNumClause = " and " + tempTableName + + ".encounter_num = t.encounter_num "; + } + + String itemSql = consolidateItemSql(itemSqlList); + + String nonFirstPanelItemSql = ""; + + if (this.isPanelInverted()) { + oldPanelIndex = 0; + panelIndex = -1; + } + + TotalItemOccurrenceHandler totalItemOccurrencHandler = new TotalItemOccurrenceHandler(); + String totalItemOccurrenceClause = totalItemOccurrencHandler + .buildTotalItemOccurrenceClause(this.getTotalOccurrences()); + + String withItemSql = "with sub_t as ( " + "\n" + itemSql + "\n" + + " ) \n"; + + if (parent.getServerType().equalsIgnoreCase(DAOFactoryHelper.ORACLE) || parent.getServerType() + .equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)) { + nonFirstPanelItemSql += "update " + + tempTableName + + " set panel_count =" + + panelIndex + + " where " + + tempTableName + + ".panel_count = " + + oldPanelIndex + + " and exists ( " + + withItemSql + + "select 1 " + + "from (" + + "select * " + + "from sub_t " + + "where patient_num in (select patient_num from sub_t group by patient_num having sum(fact_count) " + + totalItemOccurrenceClause + ") " + ") t " + "where " + + tempTableName + ".patient_num = t.patient_num " + + encounterNumClause + instanceNumClause + " ) "; + } else { + nonFirstPanelItemSql += withItemSql + + "update " + + tempTableName + + " set panel_count =" + + panelIndex + + " where " + + tempTableName + + ".panel_count = " + + oldPanelIndex + + " and exists ( " + + "select 1 " + + "from (" + + "select * " + + "from sub_t " + + "where patient_num in (select patient_num from sub_t group by patient_num having sum(fact_count) " + + totalItemOccurrenceClause + ") " + ") t " + "where " + + tempTableName + ".patient_num = t.patient_num " + + encounterNumClause + instanceNumClause + " ) "; + } + + return nonFirstPanelItemSql; + + } + + /** + * Non First Panel Item Sql + * + * Processes item sql from all items in panel that is not the first panel in a subquery. + * Non first panel items are processed as an update statement to the + * temporary table rather than an insert + * + * @param itemSqlList List of individual sql statements for all items in this panel + * @param panelIndex + * int update index for the given panel + * @return String sql representation that joins the item sql to the panel + * sql + */ + private String nonFirstPanelItemSql(List itemSqlList, int panelIndex) { + + StringBuilder panelSql = new StringBuilder(); + boolean addDelimiter = false; + StringBuilder tempItemSql = new StringBuilder(); + + boolean useTempTables = false; + if (parent.getServerType().equalsIgnoreCase(DAOFactoryHelper.SQLSERVER) + && parent.getQueryOptions().getQueryConstraintLogic() == QueryConstraintStrategy.TEMP_TABLES) { + useTempTables = true; + } + + // OMOP WAS.. + //for (String itemSql : itemSqlList) { + for (TemporalPanelItemSql itemSqlItem : itemSqlList) { + String itemSql = itemSqlItem.itemSql; + + String encounterNumClause = " ", instanceNumClause = " "; + String tempTableName = parent.getTempTableName(); + int oldPanelIndex = panelIndex - 1; + + if (getPanelTiming().equalsIgnoreCase( + QueryTimingHandler.SAMEINSTANCENUM)) { + instanceNumClause = " and " // + parent.getDatabaseSchema() + + tempTableName + + ".encounter_num = t.encounter_num and " + + tempTableName + + ".instance_num = t.instance_num and " + + tempTableName + + ".start_date = t.start_date and " + + tempTableName + + ".concept_cd = t.concept_cd and " + + tempTableName + ".provider_id = t.provider_id "; + } else if (getPanelTiming().equalsIgnoreCase( + QueryTimingHandler.SAME) + || getPanelTiming().equalsIgnoreCase( + QueryTimingHandler.SAMEVISIT)) { + encounterNumClause = " and " + tempTableName + + ".encounter_num = t.encounter_num "; + } + + String nonFirstPanelItemSql = ""; + /* + * "with t as ( " + "\n" + itemSql + "\n" + " ) " + "\n" + "\n"; + */ + + if (this.isPanelInverted()) { + if (oldPanelIndex<0) + oldPanelIndex = 0; + + if (useTempTables){ + String suffix = ""; + + nonFirstPanelItemSql += parent.buildTempTableCheckDrop("t" + suffix); + nonFirstPanelItemSql += parent.getSqlDelimiter(); + + nonFirstPanelItemSql += buildSelectIntoStatement(itemSql, "t"); + nonFirstPanelItemSql += parent.getSqlDelimiter(); + + nonFirstPanelItemSql += " update " + tempTableName + + " set panel_count = -1 " + " where " + tempTableName + + ".panel_count = " + oldPanelIndex + " and exists ( " + + "select 1 " + "from #t t " + "where " + + tempTableName + ".patient_num = t.patient_num " + + encounterNumClause + instanceNumClause + " ) "; + + nonFirstPanelItemSql += parent.getSqlDelimiter(); + nonFirstPanelItemSql += parent.buildTempTableCheckDrop("t" + suffix); + + } + else { + nonFirstPanelItemSql += " update " + tempTableName + + " set panel_count = -1 " + " where " + tempTableName + + ".panel_count = " + oldPanelIndex + " and exists ( " + + "select 1 " + "from (" + itemSql + ") t " + "where " + + tempTableName + ".patient_num = t.patient_num " + + encounterNumClause + instanceNumClause + " ) "; + } + + } else { + + if (useTempTables){ + String suffix = ""; + + nonFirstPanelItemSql += parent.buildTempTableCheckDrop("t" + suffix); + nonFirstPanelItemSql += parent.getSqlDelimiter(); + + nonFirstPanelItemSql += buildSelectIntoStatement(itemSql, "t"); + nonFirstPanelItemSql += parent.getSqlDelimiter(); + + nonFirstPanelItemSql += "update " + tempTableName + + " set panel_count =" + panelIndex + " where " + + tempTableName + ".panel_count = " + oldPanelIndex + + " and exists ( " + "select 1 " + "from #t" + + " t " + "where " + tempTableName + + ".patient_num = t.patient_num " + encounterNumClause + + instanceNumClause + " ) "; + + nonFirstPanelItemSql += parent.getSqlDelimiter(); + nonFirstPanelItemSql += parent.buildTempTableCheckDrop("t" + suffix); + + } + else { + nonFirstPanelItemSql += "update " + tempTableName + + " set panel_count =" + panelIndex + " where " + + tempTableName + ".panel_count = " + oldPanelIndex + + " and exists ( " + "select 1 " + "from (" + itemSql + + ") t " + "where " + tempTableName + + ".patient_num = t.patient_num " + encounterNumClause + + instanceNumClause + " ) "; + } + } + if (addDelimiter) { + panelSql.append(parent.getSqlDelimiter()); + } + + panelSql.append(nonFirstPanelItemSql); + + addDelimiter = true; + } + + return panelSql.toString(); + } + + /** + * Build Invert Main Table Sql + * + * Constructs sql statement that selects the correct columns from the superset of items from which + * an invert can be applied - through either a minus/except or not in/not exists clause + * + * @return String sql statement that contains sql for accessing main table sql + */ + public String buildInvertMainTableSql() { + String selectClause = ""; + String whereClause = ""; + String groupByClause = ""; + + String patientTable = "patient_dimension p "; + String instanceTable = "observation_fact f "; + String visitTable = "visit_dimension v "; + + List factTables = null; + List itemSqlList = null; + try { + itemSqlList = getItemSql(); + } catch (I2B2DAOException e) { + return null; + } + if (this.parent.getQueryOptions()!=null&&this.parent.getQueryOptions().useDerivedFactTable()) + { + factTables = buildFactTableList(itemSqlList); + } + + + String invertTableName = patientTable; + + if (getPanelTiming().equalsIgnoreCase( + QueryTimingHandler.SAMEINSTANCENUM)) { + selectClause = "f.provider_id, f.start_date, f.concept_cd, f.instance_num, f.encounter_num, f.patient_num"; + invertTableName = instanceTable; + } else if (getPanelTiming().equalsIgnoreCase(QueryTimingHandler.SAME) + || getPanelTiming().equalsIgnoreCase( + QueryTimingHandler.SAMEVISIT)) { + invertTableName = visitTable; + selectClause = "v.encounter_num, v.patient_num"; + } else { + selectClause = "p.patient_num"; + } + + String invertSql = "select " + selectClause + ", 0 panel_count" + + " from " + parent.getDatabaseSchema() + invertTableName + + whereClause + groupByClause; + /* + if(factTables != null){ + if((factTables.size() == 1)) { + + invertSql = "select " + selectClause + ", 0 panel_count" + + " from " + parent.getDatabaseSchema() + factTables.get(0) + " f " + + whereClause + groupByClause; + } + else { + invertSql = ""; + Iterator i = factTables.iterator(); + while (i.hasNext()){ + + invertSql += "select " + selectClause + ", 0 panel_count" + + " from " + parent.getDatabaseSchema() + i.next() + " f " + + whereClause + groupByClause; + if(i.hasNext()){ + invertSql += "\n union all \n"; + } + } + } + } +*/ + + return invertSql; + + } + + /** + * Build Invert Insert Select Sql + * + * Constructs select clause for use in a larger statement. Clause contains the correct columns + * based on panel and query timing models + * + * @param tableAlias String alias for table referenced in from clause + * @return String select clause for inclusion in larger statement + */ + protected String buildInvertInsertSelectSql(String tableAlias) { + if (tableAlias != null && tableAlias.trim().length() > 0) + tableAlias = tableAlias + "."; + else + tableAlias = ""; + + String insertSelectClause = ""; + + if (getPanelTiming().equalsIgnoreCase( + QueryTimingHandler.SAMEINSTANCENUM)) { + insertSelectClause = tableAlias + "provider_id, " + tableAlias + + "start_date, " + tableAlias + "concept_cd, " + tableAlias + + "instance_num, " + tableAlias + "encounter_num, " + + tableAlias + "patient_num"; + } else if (getPanelTiming().equalsIgnoreCase(QueryTimingHandler.SAME) + || getPanelTiming().equalsIgnoreCase( + QueryTimingHandler.SAMEVISIT)) { + insertSelectClause = " " + tableAlias + "encounter_num, " + + tableAlias + "patient_num"; + } else { + insertSelectClause = " " + tableAlias + "patient_num"; + } + + insertSelectClause += ", 0 as panel_count"; + + return insertSelectClause; + + } + + /** + * Build Invert Not Except Sql + * + * Constructs with clause for use in larger invert statement. Clause contains proper minus/except + * constraints based on the panel timing + * + * @param withAlias String alias of table or with clause for use in referencing column names + * @return String not exists clause for use in larger sql invert statement + */ + protected String buildInvertExceptSql(String withAlias) { + if (withAlias == null) + withAlias = "y"; + + String minusOperator = "minus"; + if (!parent.getServerType().equalsIgnoreCase(DAOFactoryHelper.ORACLE)) { + minusOperator = "except"; + } + + StringBuilder exceptClause = new StringBuilder(); + + exceptClause.append(buildInvertMainTableSql() + "\n"); + + exceptClause.append(" " + minusOperator + "\n"); + String invertInsertSql = buildInvertInsertSelectSql(withAlias); + exceptClause.append("select " + invertInsertSql + " from " + withAlias + + " "); + return exceptClause.toString(); + } + + /** + * Build Invert Not Exists Sql + * + * Constructs with clause for use in larger invert statement. Clause contains proper + * constraints based on the panel timing + * + * @param withAlias String alias of table or with clause for use in referencing column names + * @return String not exists clause for use in larger sql invert statement + */ + protected String buildInvertNotExistsSql(String withAlias){ + return buildInvertNotExistsSql("", withAlias); + } + + /** + * Build Invert Not Exists Sql + * + * Constructs with clause for use in larger invert statement. Clause contains proper not in/not exists + * constraints based on the panel timing + * + * @param withTable String name of table or with clause name + * @param withAlias String alias of table or with clause for use in referencing column names + * @return String not exists clause for use in larger sql invert statement + */ + protected String buildInvertNotExistsSql(String withTable, String withAlias) { + if (withAlias == null) + withAlias = "y"; + + StringBuilder notExistsClause = new StringBuilder(); + notExistsClause.append(buildInvertMainTableSql() + "\n"); + notExistsClause.append("where not exists (\n"); + notExistsClause.append("select 1 from " + + (withTable!=null&&withTable.trim().length()>0 ? withTable + " " : "") + + withAlias + " \n"); + if (getPanelTiming().equalsIgnoreCase( + QueryTimingHandler.SAMEINSTANCENUM)) { + notExistsClause.append("where " + withAlias + + ".patient_num = f.patient_num "); + notExistsClause.append("and " + withAlias + + ".encounter_num = f.encounter_num "); + notExistsClause.append("and " + withAlias + + ".start_date = f.start_date "); + notExistsClause.append("and " + withAlias + + ".concept_cd = f.concept_cd "); + notExistsClause.append("and " + withAlias + + ".instance_num = f.instance_num "); + notExistsClause.append("and " + withAlias + + ".provider_id = f.provider_id) "); + } else if (getPanelTiming().equalsIgnoreCase(QueryTimingHandler.SAME) + || getPanelTiming().equalsIgnoreCase( + QueryTimingHandler.SAMEVISIT)) { + notExistsClause.append("where " + withAlias + + ".patient_num = v.patient_num "); + notExistsClause.append("and " + withAlias + + ".encounter_num = v.encounter_num) "); + } else { + notExistsClause.append("where " + withAlias + + ".patient_num = p.patient_num) "); + } + + return notExistsClause.toString(); + } + + @Override + public int compareTo(Object element) { + if (element.getClass().equals((TemporalPanel.class))) { + TemporalPanel tp2 = (TemporalPanel) element; + + Integer tp1Score = this.getTimingScore(); + Integer tp2Score = tp2.getTimingScore(); + + int compare = tp1Score.compareTo(tp2Score); + if (compare == 0) { + tp1Score = this.getEstimatedTotal(); + tp2Score = tp2.getEstimatedTotal(); + compare = tp1Score.compareTo(tp2Score); + if (compare == 0) { + tp1Score = this.basePanel.getPanelNumber(); + tp2Score = tp2.basePanel.getPanelNumber(); + compare = tp1Score.compareTo(tp2Score); + if (compare == 0) { + return this.toString().compareTo(tp2.toString()); + } else + return compare; + + } else + return compare; + } else + return compare; + + } else { + return this.toString().compareTo(element.toString()); + } + } + + /** + * Get Timing Score + * + * Calculates the timing score of the panel. Timing scores are used to + * properly sort panels so query processing can be optimized + * + * @return int represents the timing score of the panel + */ + private int getTimingScore() { + String timing = getPanelTiming(); + int score = 0; + if (timing == null || timing.trim().length() == 0) + return MAXTIMINGSCORE; + else if (timing.equalsIgnoreCase(QueryTimingHandler.ANY)) + score = MAXTIMINGSCORE - 1; + else if (timing.equalsIgnoreCase(QueryTimingHandler.SAME)) + score = MAXTIMINGSCORE - 2; + else if (timing.equalsIgnoreCase(QueryTimingHandler.SAMEVISIT)) + score = MAXTIMINGSCORE - 2; + else if (timing.equalsIgnoreCase(QueryTimingHandler.SAMEINSTANCENUM)) + score = MAXTIMINGSCORE - 3; + else + score = MAXTIMINGSCORE - 4; + + if (isPanelInverted()) + return (MAXTIMINGSCORE * 2) - (MAXTIMINGSCORE - score); + else + return score; + } + + /** + * Get Estimated Total + * + * Calculate the estimated number of patients that will be returned by this + * panel. This method accounts for missing values and inverted panels when + * estimated the number of patients returned. Estimated counts are used to + * help sort panels in a way that optimizes query performance + * + * @return int estimated count of patients returned by this panel + */ + private int getEstimatedTotal() { + int totalCount = getSumOfPanelItemCounts(); + double missingCount = getMissingItemTotals(); + + if (missingCount > 0) { + double size = getItemList().size(); + double knownSize = size - missingCount; + if (knownSize == 0) + return Integer.MAX_VALUE; + + // estimate total size by averaging known items and applying it to + // all items + + double dblTotal = totalCount; + totalCount = (int) ((dblTotal / knownSize) * size); + } + + if (this.isPanelInverted()) + totalCount = Integer.MAX_VALUE - totalCount; + + return totalCount; + } + + /** + * Is Panel Inverted + * + * @return boolean true if the panel has the inverted flag set, otherwise + * false + */ + public boolean isPanelInverted() { + return basePanel.getInvert() == 1; + } + + /** + * Get Sum Of Patient Item Counts + * + * Sum the estimated patient counts for all items in the panel + * + * @return int total of estimated counts from items within the panel + */ + public int getSumOfPanelItemCounts() { + return estimatedPanelSize; + } + + /** + * Get Panel Timing + * + * Return timing to use for this panel. If no timing is specified on the + * panel level, than the timing for the query is used. + * + * @return String representation of the timing used for this panel + */ + public String getPanelTiming() { + if (basePanel.getPanelTiming() == null + || basePanel.getPanelTiming().trim().length() == 0) + return parent.getQueryTiming(); + else + return basePanel.getPanelTiming(); + } + + /** + * Return Encounter To Parent + * + * @return boolean true if panel is needs to return encounter num + * results to parent query + */ + private boolean returnEncounterToParent() { + return parent.returnEncounterNum(); + } + + /** + * Return Instance to Parent + * + * @return boolean true if panel is needs to return instance based columns + * results to parent query + */ + private boolean returnInstanceToParent() { + return parent.returnInstanceNum(); + } + + /** + * Get Accuracy Scale + * + * @return int accuracy as included in the original query xml + */ + public int getAccuracyScale() { + return basePanel.getPanelAccuracyScale(); + } + + /** + * Get Item List + * + * @return List list of items in this panel + */ + public List getItemList() { + return panelItemList; + } + + /** + * Get Security Type + * + * @return SecurityType returns security to use for this query + */ + protected SecurityType getSecurityType() { + return parent.getSecurityType(); + } + + + /** + * Get Requestor Security Type + * + * @return SecurityType returns security used by requestor when submitting + * this query + */ + protected SecurityType getRequestorSecurityType() { + return parent.getRequestorSecurityType(); + } + + /** + * Get Project Id + * + * @return String project id used for this query + */ + protected String getProjectId() { + return parent.getProjectId(); + } + + /** + * Get Data Source Lookup + * + * @return DataSourceLookup data source information used for submitting + * query to database + */ + protected DataSourceLookup getDataSourceLookup() { + return parent.getDataSourceLookup(); + } + + /** + * Get Database Schema + * + * @return String name of schema to use when referencing tables + */ + protected String getDatabaseSchema() { + return parent.getDatabaseSchema(); + } + + /** + * Build Date Constraint Sql + * + * Builds string sql statement that contains the date constraint from the panel leve + * + * @return String sql statement that contains the date constraint from the panel level + */ + public String buildDateConstraintSql() { + return buildDateConstraintSql(""); + } + + /** + * Build Date Constraint Sql + * + * Builds string sql statement that contains the date constraint from the panel leve + * + * @param tableAlias String alias of the table to use when reference columns + * @return String sql statement that contains the date constraint from the panel level + */ + public String buildDateConstraintSql(String tableAlias) { + DateConstrainUtil dateConstrainUtil = new DateConstrainUtil( + parent.getDataSourceLookup()); + + return dateConstrainUtil.buildPanelDateSql(basePanel, tableAlias); + } + + /** + * Get Server Type + * + * Returns name of the underlying database type. Currently, only Oracle and SqlServer are supported + * + * @return String name of the database server type + */ + public String getServerType() { + return parent.getServerType(); + } + + /** + * Get Project Parameter Map + * + * Returns the Map of project parameter values passed in when the query was created + * + * @return Map the project parameter map that was passed into the query + */ + protected Map getProjectParameterMap() { + return parent.getProjectParameterMap(); + } + + public int getMissingItemTotals() { + return missingItemTotals; + } + + + /** + * Has Panel Date Constraint + * + * Returns whether or not this panel has a panel level date constraint: date from, date to, or both + * + * @return Boolean true if this panel has a panel level date constraint + */ + public boolean hasPanelDateConstraint() { + if (basePanel.getPanelDateFrom() != null + || basePanel.getPanelDateTo() != null) + return true; + else + return false; + } + + /** + * Has Panel Occurrence Constraint + * + * Returns whether or not this panel has an occurrence constraint other than the default + * + * @return Boolean true if the panel has an occurrence constraint > 1, else false + */ + public boolean hasPanelOccurrenceConstraint() { + if (this.basePanel.getTotalItemOccurrences() != null + && this.basePanel.getTotalItemOccurrences().getOperator() != null) { + if ((this.basePanel.getTotalItemOccurrences().getOperator() == TotOccuranceOperatorType.GE) + && (this.basePanel.getTotalItemOccurrences().getValue() == 1)) + return false; + else + return true; + } else + return false; + } + + /** + * Is First Panel In Query + * + * Determines whether this panel is the first panel in the query + * + * @return Boolean true if panel is first panel in query, otherwise false + */ + public boolean isFirstPanelInQuery() { + return parent.getPanelIndex(this) == 0; + } + + /** + * Get Total Occurrences + * + * Gets the total occurrences constraint for this panel + * + * @return TotalItemOccurrences occurrence constraint from main query + */ + public TotalItemOccurrences getTotalOccurrences() { + return this.basePanel.getTotalItemOccurrences(); + } + + /** + * Get Total Occurrences Operator + * + * Get the operator for the total occurrences constraint for this panel + * + * @return String operator for total occurrences constraint + */ + public String getTotalOccurrenceOperator() { + if (this.basePanel.getTotalItemOccurrences() != null) + return this.basePanel.getTotalItemOccurrences().getOperator() + .toString(); + else + return ""; + } + + /** + * Allow Large Text Value Constrain Flag + * + * Return whether or not constraints on large text values are allowed + * + * @return Boolean true if large text constraints are allowed, otherwise false + */ + protected boolean allowLargeTextValueConstrainFlag() { + return parent.allowLargeTextValueConstrainFlag(); + } + + protected List getUserRoles() { + return parent.getUserRoles(); + } + + /** + * Appply Occurrence to Panel Level + * + * Return whether or not occurrences should be applied on the panel level instead of on each item **NOTE: This is experimental funcationality and not current supported** + * + * @return Boolean true if occurrence should be applied over all items in a query instead of on an item by item basis, otherwise false + */ + protected boolean applyOccurrenceToPanelLevel() { + return parent.getQueryOptions().usePanelLevelOccurrence(); + } + + /** + * Get Processing Level + * + * Returns the processing level of the current query. Default value is 1, when processing an embedded query, processing level is incremented + * + * @return int Processing level of current query + */ + protected int getProcessingLevel() { + return parent.getProcessingLevel(); + } + + /** + * Add Pre Processing Sql + * + * Add sql statement to run before main sql statement is run + * + * @param sql String sql statement to be processed before main sql statement has been run + */ + protected void addPreProcessingSql(String sql) { + parent.addPreProcessingSql(sql); + } + + /** + * Add Post Processing Sql + * + * Add sql statement to run after main sql statement has run + * + * @param sql String sql statement to processed after main sql statement has been run + */ + protected void addPostProcessingSql(String sql) { + parent.addPostProcessingSql(sql); + } + + /** + * Search For Query In Request Definition + * + * Looks for query defintion with the specified query id in the parent query xml definition + * + * @param subQueryId String specified the query id for the query to look for + * @return QueryDefinitionType if query is found, otherwise returns null + */ + protected QueryDefinitionType searchForQueryInRequestDefinition(String subQueryId){ + return parent.searchForQueryInRequestDefinition(subQueryId); + } + + + /** + * Is Patient Only Query + * + * @return true if only patient num is required to be returned by this panel + */ + protected boolean isPatientOnlyQuery() { + if (this.returnEncounterToParent() + || this.returnInstanceToParent() + || this.getPanelTiming().equalsIgnoreCase( + QueryTimingHandler.SAME) + || this.getPanelTiming().equalsIgnoreCase( + QueryTimingHandler.SAMEVISIT) + || this.getPanelTiming().equalsIgnoreCase( + QueryTimingHandler.SAMEINSTANCENUM)) + return false; + else + return true; + } + + /** + * Add Ignored Message + * + * @param errorMessage String error m + */ + public void addIgnoredMessage(String errorMessage) { + parent.addIgnoredMessage(errorMessage); + } + + /** + * Get Query Options + * + * @return TemporalQueryOptions that are valid for this query + */ + protected TemporalQueryOptions getQueryOptions() { + return parent.getQueryOptions(); + } + + private List buildFactTableList(List itemSqlList) { + List factTableList = new ArrayList(); + + for (TemporalPanelItemSql itemSqlItem : itemSqlList) { + String itemSql = itemSqlItem.itemSql; + factTableList.add(itemSqlItem.factTable); + } + return factTableList; + + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalPanelCellQueryItem.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalPanelCellQueryItem.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalPanelCellQueryItem.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalPanelCellQueryItem.java index b38da88e..21cd8460 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalPanelCellQueryItem.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalPanelCellQueryItem.java @@ -1,330 +1,330 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Christopher Herrick - */ -package edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal; - -import java.io.StringReader; -import java.io.StringWriter; - -import javax.xml.XMLConstants; -import jakarta.xml.bind.JAXBElement; -import javax.xml.stream.XMLInputFactory; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamReader; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.TransformerFactoryConfigurationError; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; - -import org.apache.axiom.om.OMElement; -import org.apache.axiom.om.OMXMLBuilderFactory; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.w3c.dom.Element; -import org.w3c.dom.Node; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.exception.StackTraceUtil; -import edu.harvard.i2b2.common.util.axis2.ServiceClient; -import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.i2b2message.FacilityType; -import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.ontology.ConceptType; -import edu.harvard.i2b2.crc.datavo.ontology.XmlValueType; -import edu.harvard.i2b2.crc.datavo.pdo.PatientDataType; -import edu.harvard.i2b2.crc.datavo.pdo.PatientSet; -import edu.harvard.i2b2.crc.datavo.pdo.PatientType; -import edu.harvard.i2b2.crc.datavo.pdo.query.PatientDataResponseType; -import edu.harvard.i2b2.crc.datavo.pm.GetUserConfigurationType; -import edu.harvard.i2b2.crc.datavo.pm.ProjectType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ItemType; -import edu.harvard.i2b2.crc.util.ItemKeyUtil; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - -/** - * Temporal Panel Cell Query Item - * - *

    - * Cell Query query object that wraps the item tag found in the query definition - * xml for cell query items. It roughly corresponds to a panel in the query UI. Panel is responsible - * for organizing the sql that comes back from individual panel items - sql from - * items should be logically or'd together. It is also the container that holds - * the panel constraint types - occurrence, dates, and exclude. - * - * @author Christopher Herrick - * - */ -public class TemporalPanelCellQueryItem extends TemporalPanelItem { - - private JAXBUtil jaxbUtil = null; - private static Log log = LogFactory.getLog(TemporalPanelCellQueryItem.class); - private XmlValueType requestXml = null; - private String cellUrl = null; - private String patientNums = null; - - public TemporalPanelCellQueryItem(TemporalPanel parent, ItemType item, ConceptType conceptType) - throws I2B2Exception { - super(parent, item, conceptType); - parseCellItem(); - } - - protected void parseCellItem() throws I2B2Exception { - super.parseItem(); - - cellUrl = conceptType.getDimcode(); - if (cellUrl!=null&&cellUrl.toLowerCase().startsWith(ItemKeyUtil.ITEM_KEY_CELLID)) - cellUrl = cellUrl.substring(ItemKeyUtil.ITEM_KEY_CELLID.length()); - - if (conceptType.getMetadataxml()!=null){ - requestXml = conceptType.getMetadataxml(); - } - - jaxbUtil = CRCJAXBUtil.getJAXBUtil(); - } - - - @Override - protected String buildSql() throws I2B2DAOException { - try { - this.callCellUrlWithRequest(); - this.dimCode = patientNums; - } catch (Exception e) { - log.debug(e.getStackTrace()); - e.printStackTrace(); - return ""; - } - - if (returnEncounterNum()|| - returnInstanceNum()|| - this.hasItemDateConstraint()|| - this.hasModiferConstraint()|| - this.hasPanelDateConstraint()|| - this.hasPanelOccurrenceConstraint()|| - this.hasValueConstraint() - //||parent.isTimingQuery() - ){ - return super.buildSql(); - } - else{ - return "select " - + this.factTableColumn + " from " + noLockSqlServer - + parent.getDatabaseSchema() + this.tableName - + " " + " where " + this.columnName + " " - + this.operator + " " + this.dimCode - + ""; - } - } - - @Override - protected String getJoinTable() { - if (returnInstanceNum()|| - hasItemDateConstraint()|| - hasPanelDateConstraint()|| - hasValueConstraint()|| - hasPanelOccurrenceConstraint()) { - return "observation_fact"; - } else if (returnEncounterNum() - //||parent.isTimingQuery() - ) { - return "visit_dimension"; - } else { - return "patient_dimension"; - } - } - - - public PatientSet getPatientSetFromResponseXML(String responseXML) - throws Exception { - JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); - - @SuppressWarnings("rawtypes") - JAXBElement jaxbElement = jaxbUtil.unMashallFromString(responseXML); - ResponseMessageType messageType = (ResponseMessageType) jaxbElement - .getValue(); - BodyType bodyType = messageType.getMessageBody(); - PatientDataResponseType responseType = (PatientDataResponseType) new JAXBUnWrapHelper() - .getObjectByClass(bodyType.getAny(), - PatientDataResponseType.class); - PatientDataType patientDataType = responseType.getPatientData(); - - PatientSet patientSet = patientDataType.getPatientSet(); - - return patientSet; - } - - public ProjectType callCellUrlWithRequest() throws Exception { - RequestMessageType requestMessageType = getI2B2RequestMessage(parent.getRequestorSecurityType(), parent.getProjectId()); - OMElement requestElement = null; - ProjectType projectType = null; - try { - - String requestXmlString = createRequestXmlString(); - requestElement = buildOMElement(requestMessageType, requestXmlString); - log.debug("call cell request xml " + requestElement); - - String response = ServiceClient.sendREST(cellUrl, requestElement); - - log.debug("Got Response"); - - PatientSet pSet = getPatientSetFromResponseXML(response); - - if (pSet!=null){ - StringBuffer patientList = new StringBuffer(); - patientList.append("("); - boolean first = true; - for (PatientType patient : pSet.getPatient()){ - if (!first){ - patientList.append(", "); - } - else - first = false; - - if (patient.getPatientId()!=null&&patient.getPatientId().getValue()!=null) - patientList.append(patient.getPatientId().getValue()); - } - patientList.append(")"); - - patientNums = patientList.toString(); - } - } catch (XMLStreamException e) { - e.printStackTrace(); - throw new I2B2Exception("" + StackTraceUtil.getStackTrace(e)); - } catch (Exception e) { - e.printStackTrace(); - throw new I2B2Exception("" + StackTraceUtil.getStackTrace(e)); - } - - log.debug("Returning ProjectType"); - return projectType; - } - - private OMElement buildOMElement(RequestMessageType requestMessageType, String requestXml) - throws XMLStreamException, JAXBUtilException { - StringWriter strWriter = new StringWriter(); - edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory hiveof = new edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory(); - jaxbUtil.marshaller(hiveof.createRequest(requestMessageType), strWriter); - - //insert request - String msgBody = ""; - String xmlrequest = strWriter.toString(); - int index = xmlrequest.indexOf(msgBody); - if (index>=0){ - xmlrequest = xmlrequest.substring(0, index) + "" + requestXml + "" + xmlrequest.substring(index + msgBody.length()+1); - } - - StringReader strReader = new StringReader(xmlrequest); - XMLInputFactory xif = XMLInputFactory.newInstance(); - XMLStreamReader reader = xif.createXMLStreamReader(strReader); - OMElement request = OMXMLBuilderFactory.createStAXOMBuilder(reader).getDocumentElement(); - - return request; - } - - private RequestMessageType getI2B2RequestMessage(SecurityType securityType, String projectId) throws Exception { - QueryProcessorUtil queryUtil = QueryProcessorUtil.getInstance(); - MessageHeaderType messageHeaderType = queryUtil.getMessageHeader(); - messageHeaderType.setSecurity(securityType); - messageHeaderType.setProjectId(projectId); - - messageHeaderType.setReceivingApplication(messageHeaderType - .getSendingApplication()); - FacilityType facilityType = new FacilityType(); - facilityType.setFacilityName("sample"); - messageHeaderType.setSendingFacility(facilityType); - messageHeaderType.setReceivingFacility(facilityType); - // build message body - // GetUserInfoType getUserInfoType = null; - GetUserConfigurationType userConfig = new GetUserConfigurationType(); - userConfig.getProject().add(projectId); - - RequestMessageType requestMessageType = new RequestMessageType(); - - BodyType bodyType = new BodyType(); - requestMessageType.setMessageBody(bodyType); - - requestMessageType.setMessageHeader(messageHeaderType); - - RequestHeaderType requestHeader = new RequestHeaderType(); - requestHeader.setResultWaittimeMs(180000); - requestMessageType.setRequestHeader(requestHeader); - - return requestMessageType; - - } - - private String createRequestXmlString(){ - String xmlRootString = ""; - StringBuffer requestXmlString= new StringBuffer(); - if (requestXml!=null){ - if (requestXml.getAny().size()>0&&requestXml.getAny().get(0).getNodeName().toLowerCase().equals("cellrequest")){ - Element request = requestXml.getAny().get(0); - for (int i = 0; i < request.getChildNodes().getLength(); i++){ - String nodeString = convertNodeToString(request.getChildNodes().item(i)); - if (nodeString.startsWith(xmlRootString)){ - nodeString = nodeString.substring(xmlRootString.length()).trim(); - } - - if (nodeString.length()>0) { - requestXmlString.append(nodeString); - } - } - } - } - return requestXmlString.toString(); - } - - - private String convertNodeToString(Node request) { - StringWriter writer = new StringWriter(); - Transformer transformer; - try { - System.setProperty("javax.xml.transform.TransformerFactory","com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl"); - - TransformerFactory tf = TransformerFactory.newInstance(); - try { - tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); - tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, ""); - } catch (IllegalArgumentException e) { - //jaxp 1.5 feature not supported - } - - - transformer = tf.newTransformer(); - transformer.transform(new DOMSource(request), new StreamResult(writer)); - } catch (TransformerConfigurationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (TransformerFactoryConfigurationError e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (TransformerException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - return writer.toString(); - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Christopher Herrick + */ +package edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal; + +import java.io.StringReader; +import java.io.StringWriter; + +import javax.xml.XMLConstants; +import jakarta.xml.bind.JAXBElement; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.TransformerFactoryConfigurationError; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.apache.axiom.om.OMElement; +import org.apache.axiom.om.OMXMLBuilderFactory; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.w3c.dom.Element; +import org.w3c.dom.Node; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.exception.StackTraceUtil; +import edu.harvard.i2b2.common.util.axis2.ServiceClient; +import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; +import edu.harvard.i2b2.crc.datavo.i2b2message.FacilityType; +import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.ontology.ConceptType; +import edu.harvard.i2b2.crc.datavo.ontology.XmlValueType; +import edu.harvard.i2b2.crc.datavo.pdo.PatientDataType; +import edu.harvard.i2b2.crc.datavo.pdo.PatientSet; +import edu.harvard.i2b2.crc.datavo.pdo.PatientType; +import edu.harvard.i2b2.crc.datavo.pdo.query.PatientDataResponseType; +import edu.harvard.i2b2.crc.datavo.pm.GetUserConfigurationType; +import edu.harvard.i2b2.crc.datavo.pm.ProjectType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ItemType; +import edu.harvard.i2b2.crc.util.ItemKeyUtil; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + +/** + * Temporal Panel Cell Query Item + * + *

    + * Cell Query query object that wraps the item tag found in the query definition + * xml for cell query items. It roughly corresponds to a panel in the query UI. Panel is responsible + * for organizing the sql that comes back from individual panel items - sql from + * items should be logically or'd together. It is also the container that holds + * the panel constraint types - occurrence, dates, and exclude. + * + * @author Christopher Herrick + * + */ +public class TemporalPanelCellQueryItem extends TemporalPanelItem { + + private JAXBUtil jaxbUtil = null; + private static Log log = LogFactory.getLog(TemporalPanelCellQueryItem.class); + private XmlValueType requestXml = null; + private String cellUrl = null; + private String patientNums = null; + + public TemporalPanelCellQueryItem(TemporalPanel parent, ItemType item, ConceptType conceptType) + throws I2B2Exception { + super(parent, item, conceptType); + parseCellItem(); + } + + protected void parseCellItem() throws I2B2Exception { + super.parseItem(); + + cellUrl = conceptType.getDimcode(); + if (cellUrl!=null&&cellUrl.toLowerCase().startsWith(ItemKeyUtil.ITEM_KEY_CELLID)) + cellUrl = cellUrl.substring(ItemKeyUtil.ITEM_KEY_CELLID.length()); + + if (conceptType.getMetadataxml()!=null){ + requestXml = conceptType.getMetadataxml(); + } + + jaxbUtil = CRCJAXBUtil.getJAXBUtil(); + } + + + @Override + protected String buildSql() throws I2B2DAOException { + try { + this.callCellUrlWithRequest(); + this.dimCode = patientNums; + } catch (Exception e) { + log.debug(e.getStackTrace()); + e.printStackTrace(); + return ""; + } + + if (returnEncounterNum()|| + returnInstanceNum()|| + this.hasItemDateConstraint()|| + this.hasModiferConstraint()|| + this.hasPanelDateConstraint()|| + this.hasPanelOccurrenceConstraint()|| + this.hasValueConstraint() + //||parent.isTimingQuery() + ){ + return super.buildSql(); + } + else{ + return "select " + + this.factTableColumn + " from " + noLockSqlServer + + parent.getDatabaseSchema() + this.tableName + + " " + " where " + this.columnName + " " + + this.operator + " " + this.dimCode + + ""; + } + } + + @Override + protected String getJoinTable() { + if (returnInstanceNum()|| + hasItemDateConstraint()|| + hasPanelDateConstraint()|| + hasValueConstraint()|| + hasPanelOccurrenceConstraint()) { + return "observation_fact"; + } else if (returnEncounterNum() + //||parent.isTimingQuery() + ) { + return "visit_dimension"; + } else { + return "patient_dimension"; + } + } + + + public PatientSet getPatientSetFromResponseXML(String responseXML) + throws Exception { + JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); + + @SuppressWarnings("rawtypes") + JAXBElement jaxbElement = jaxbUtil.unMashallFromString(responseXML); + ResponseMessageType messageType = (ResponseMessageType) jaxbElement + .getValue(); + BodyType bodyType = messageType.getMessageBody(); + PatientDataResponseType responseType = (PatientDataResponseType) new JAXBUnWrapHelper() + .getObjectByClass(bodyType.getAny(), + PatientDataResponseType.class); + PatientDataType patientDataType = responseType.getPatientData(); + + PatientSet patientSet = patientDataType.getPatientSet(); + + return patientSet; + } + + public ProjectType callCellUrlWithRequest() throws Exception { + RequestMessageType requestMessageType = getI2B2RequestMessage(parent.getRequestorSecurityType(), parent.getProjectId()); + OMElement requestElement = null; + ProjectType projectType = null; + try { + + String requestXmlString = createRequestXmlString(); + requestElement = buildOMElement(requestMessageType, requestXmlString); + log.debug("call cell request xml " + requestElement); + + String response = ServiceClient.sendREST(cellUrl, requestElement); + + log.debug("Got Response"); + + PatientSet pSet = getPatientSetFromResponseXML(response); + + if (pSet!=null){ + StringBuffer patientList = new StringBuffer(); + patientList.append("("); + boolean first = true; + for (PatientType patient : pSet.getPatient()){ + if (!first){ + patientList.append(", "); + } + else + first = false; + + if (patient.getPatientId()!=null&&patient.getPatientId().getValue()!=null) + patientList.append(patient.getPatientId().getValue()); + } + patientList.append(")"); + + patientNums = patientList.toString(); + } + } catch (XMLStreamException e) { + e.printStackTrace(); + throw new I2B2Exception("" + StackTraceUtil.getStackTrace(e)); + } catch (Exception e) { + e.printStackTrace(); + throw new I2B2Exception("" + StackTraceUtil.getStackTrace(e)); + } + + log.debug("Returning ProjectType"); + return projectType; + } + + private OMElement buildOMElement(RequestMessageType requestMessageType, String requestXml) + throws XMLStreamException, JAXBUtilException { + StringWriter strWriter = new StringWriter(); + edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory hiveof = new edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory(); + jaxbUtil.marshaller(hiveof.createRequest(requestMessageType), strWriter); + + //insert request + String msgBody = ""; + String xmlrequest = strWriter.toString(); + int index = xmlrequest.indexOf(msgBody); + if (index>=0){ + xmlrequest = xmlrequest.substring(0, index) + "" + requestXml + "" + xmlrequest.substring(index + msgBody.length()+1); + } + + StringReader strReader = new StringReader(xmlrequest); + XMLInputFactory xif = XMLInputFactory.newInstance(); + XMLStreamReader reader = xif.createXMLStreamReader(strReader); + OMElement request = OMXMLBuilderFactory.createStAXOMBuilder(reader).getDocumentElement(); + + return request; + } + + private RequestMessageType getI2B2RequestMessage(SecurityType securityType, String projectId) throws Exception { + QueryProcessorUtil queryUtil = QueryProcessorUtil.getInstance(); + MessageHeaderType messageHeaderType = queryUtil.getMessageHeader(); + messageHeaderType.setSecurity(securityType); + messageHeaderType.setProjectId(projectId); + + messageHeaderType.setReceivingApplication(messageHeaderType + .getSendingApplication()); + FacilityType facilityType = new FacilityType(); + facilityType.setFacilityName("sample"); + messageHeaderType.setSendingFacility(facilityType); + messageHeaderType.setReceivingFacility(facilityType); + // build message body + // GetUserInfoType getUserInfoType = null; + GetUserConfigurationType userConfig = new GetUserConfigurationType(); + userConfig.getProject().add(projectId); + + RequestMessageType requestMessageType = new RequestMessageType(); + + BodyType bodyType = new BodyType(); + requestMessageType.setMessageBody(bodyType); + + requestMessageType.setMessageHeader(messageHeaderType); + + RequestHeaderType requestHeader = new RequestHeaderType(); + requestHeader.setResultWaittimeMs(180000); + requestMessageType.setRequestHeader(requestHeader); + + return requestMessageType; + + } + + private String createRequestXmlString(){ + String xmlRootString = ""; + StringBuffer requestXmlString= new StringBuffer(); + if (requestXml!=null){ + if (requestXml.getAny().size()>0&&requestXml.getAny().get(0).getNodeName().toLowerCase().equals("cellrequest")){ + Element request = requestXml.getAny().get(0); + for (int i = 0; i < request.getChildNodes().getLength(); i++){ + String nodeString = convertNodeToString(request.getChildNodes().item(i)); + if (nodeString.startsWith(xmlRootString)){ + nodeString = nodeString.substring(xmlRootString.length()).trim(); + } + + if (nodeString.length()>0) { + requestXmlString.append(nodeString); + } + } + } + } + return requestXmlString.toString(); + } + + + private String convertNodeToString(Node request) { + StringWriter writer = new StringWriter(); + Transformer transformer; + try { + System.setProperty("javax.xml.transform.TransformerFactory","com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl"); + + TransformerFactory tf = TransformerFactory.newInstance(); + try { + tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); + tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, ""); + } catch (IllegalArgumentException e) { + //jaxp 1.5 feature not supported + } + + + transformer = tf.newTransformer(); + transformer.transform(new DOMSource(request), new StreamResult(writer)); + } catch (TransformerConfigurationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (TransformerFactoryConfigurationError e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (TransformerException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return writer.toString(); + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalPanelConceptItem.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalPanelConceptItem.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalPanelConceptItem.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalPanelConceptItem.java index 511f56ec..5b344b6e --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalPanelConceptItem.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalPanelConceptItem.java @@ -1,96 +1,96 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Christopher Herrick - */ -package edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.crc.datavo.ontology.ConceptType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ItemType; - -public class TemporalPanelConceptItem extends TemporalPanelItem { - - public TemporalPanelConceptItem(TemporalPanel parent, ItemType item) - throws I2B2Exception { - super(parent, item); - } - - public TemporalPanelConceptItem(TemporalPanel parent, ItemType item, ConceptType concept) - throws I2B2Exception { - super(parent, item, concept); - } - - - @Override - protected String buildSqlHintClause() { - if (parent.getServerType().equalsIgnoreCase("ORACLE")&& - parent.getQueryOptions().useSqlHints()){ - String joinTable = getJoinTable(); - if (joinTable.equalsIgnoreCase("observation_fact")){ - if (tableName.equalsIgnoreCase("provider_dimension")) { - return " /*+ index(observation_fact observation_fact_pk) */ "; - } else { - return " /*+ index(f fact_cnpt_pat_enct_idx) */ "; - } - } - return ""; - } - else - return " "; - } - - @Override - protected String getJoinTable() { - //OMOP WAS.. - //String joinTableName = "observation_fact"; - - String joinFact = this.factTable; - if ((joinFact==null)||(joinFact.trim().isEmpty())){ - joinFact = "observation_fact"; - } - String joinTableName = joinFact; - if (tableName.equalsIgnoreCase("patient_dimension")) { - joinTableName = "patient_dimension"; - if (parent.hasPanelOccurrenceConstraint()) { - //OMOP WAS.. - //joinTableName = "observation_fact"; - joinTableName = joinFact; - } - else if (returnInstanceNum()) { - //OMOP WAS.. - //joinTableName = "observation_fact"; - joinTableName = joinFact; - } - else if (returnEncounterNum()) { - joinTableName = "visit_dimension"; - } - else if (parent.hasPanelDateConstraint()){ - joinTableName = "visit_dimension"; - } - } else if (tableName.equalsIgnoreCase( - "visit_dimension")) { - joinTableName = "visit_dimension"; - if (returnInstanceNum() - ||parent.hasPanelOccurrenceConstraint()) { - //OMOP WAS.. - //joinTableName = "observation_fact"; - joinTableName = joinFact; - } - } - - return joinTableName; - } - - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Christopher Herrick + */ +package edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.crc.datavo.ontology.ConceptType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ItemType; + +public class TemporalPanelConceptItem extends TemporalPanelItem { + + public TemporalPanelConceptItem(TemporalPanel parent, ItemType item) + throws I2B2Exception { + super(parent, item); + } + + public TemporalPanelConceptItem(TemporalPanel parent, ItemType item, ConceptType concept) + throws I2B2Exception { + super(parent, item, concept); + } + + + @Override + protected String buildSqlHintClause() { + if (parent.getServerType().equalsIgnoreCase("ORACLE")&& + parent.getQueryOptions().useSqlHints()){ + String joinTable = getJoinTable(); + if (joinTable.equalsIgnoreCase("observation_fact")){ + if (tableName.equalsIgnoreCase("provider_dimension")) { + return " /*+ index(observation_fact observation_fact_pk) */ "; + } else { + return " /*+ index(f fact_cnpt_pat_enct_idx) */ "; + } + } + return ""; + } + else + return " "; + } + + @Override + protected String getJoinTable() { + //OMOP WAS.. + //String joinTableName = "observation_fact"; + + String joinFact = this.factTable; + if ((joinFact==null)||(joinFact.trim().isEmpty())){ + joinFact = "observation_fact"; + } + String joinTableName = joinFact; + if (tableName.equalsIgnoreCase("patient_dimension")) { + joinTableName = "patient_dimension"; + if (parent.hasPanelOccurrenceConstraint()) { + //OMOP WAS.. + //joinTableName = "observation_fact"; + joinTableName = joinFact; + } + else if (returnInstanceNum()) { + //OMOP WAS.. + //joinTableName = "observation_fact"; + joinTableName = joinFact; + } + else if (returnEncounterNum()) { + joinTableName = "visit_dimension"; + } + else if (parent.hasPanelDateConstraint()){ + joinTableName = "visit_dimension"; + } + } else if (tableName.equalsIgnoreCase( + "visit_dimension")) { + joinTableName = "visit_dimension"; + if (returnInstanceNum() + ||parent.hasPanelOccurrenceConstraint()) { + //OMOP WAS.. + //joinTableName = "observation_fact"; + joinTableName = joinFact; + } + } + + return joinTableName; + } + + + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalPanelEmbeddedQueryItem.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalPanelEmbeddedQueryItem.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalPanelEmbeddedQueryItem.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalPanelEmbeddedQueryItem.java index 1acba23c..43423645 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalPanelEmbeddedQueryItem.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalPanelEmbeddedQueryItem.java @@ -1,318 +1,318 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Christopher Herrick - */ -package edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.ConceptNotFoundException; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.OntologyException; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.QueryTimingHandler; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.TempTableNameMap; -import edu.harvard.i2b2.crc.datavo.db.QtQueryMaster; -import edu.harvard.i2b2.crc.datavo.ontology.ConceptType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ItemType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionType; - -public class TemporalPanelEmbeddedQueryItem extends TemporalPanelItem { - - private String masterQueryTiming = null; - - public TemporalPanelEmbeddedQueryItem(TemporalPanel parent, ItemType item) - throws I2B2Exception { - super(parent, item); - parseEmbeddedItem(); - } - - protected void parseEmbeddedItem() throws I2B2Exception { - // TODO Auto-generated method stub - super.parseItem(); - - TemporalQuery masterQuery = null; - - //first look at query defintion to see if it was sent in the request - QueryDefinitionType queryDef = parent.searchForQueryInRequestDefinition(baseItem.getItemKey()); - if (queryDef!=null){ - try { - masterQuery = new TemporalQuery(parent.getDataSourceLookup(), parent.getProjectParameterMap(), queryDef, parent.allowLargeTextValueConstrainFlag(), parent.getUserRoles(), parent.getProcessingLevel() + 1, - parent.getProjectId(), parent.getRequestorSecurityType(), parent.getSecurityType()); - } catch (JAXBUtilException e) { - e.printStackTrace(); - throw new I2B2Exception("Error processing embedded query: " + e.getMessage()); - } - } - else { - String requestXml = getQueryDefinitionRequestXml(baseItem.getItemKey()); - try { - masterQuery = new TemporalQuery(parent.getDataSourceLookup(), parent.getProjectParameterMap(), requestXml, parent.allowLargeTextValueConstrainFlag(), parent.getUserRoles(), parent.getProcessingLevel() + 1); - } catch (JAXBUtilException e) { - e.printStackTrace(); - throw new I2B2Exception("Error processing embedded query: " + e.getMessage()); - } - } - - parent.addPreProcessingSql(masterQuery.buildSql()); - masterQueryTiming = masterQuery.getQueryTiming(); - - parent.addPreProcessingSql(copyDxTempToMaster(baseItem.getItemKey(), masterQueryTiming, String.valueOf(masterQuery.getMaxPanelIndex()), - masterQuery.getDxTempTableName(), masterQuery.getMasterTempTableName())); - - parent.addPreProcessingSql(deleteDxTempTable(masterQuery.getDxTempTableName())); - parent.addPreProcessingSql(deleteTempTable(masterQuery.getTempTableName())); - - parent.addPostProcessingSql(deleteMasterTempTable(baseItem.getItemKey(), parent.getProcessingLevel(), masterQuery.getMasterTempTableName())); - } - - - public String getQueryDefinitionRequestXml(String itemKey) - throws I2B2DAOException { - - DAOFactoryHelper helper = new DAOFactoryHelper( - parent.getDataSourceLookup().getDomainId(), - parent.getDataSourceLookup().getProjectPath(), - parent.getDataSourceLookup().getProjectPath()); - - SetFinderDAOFactory sfDaoFactory = helper.getDAOFactory() - .getSetFinderDAOFactory(); - - String masterId = itemKey.substring(9); - QtQueryMaster queryMaster = sfDaoFactory.getQueryMasterDAO().getQueryDefinition(masterId); - return queryMaster.getI2b2RequestXml(); - } - - - @Override - protected String buildSql() throws I2B2DAOException { - if (this.returnEncounterNum()|| - this.returnInstanceNum()|| - this.hasItemDateConstraint()|| - this.hasModiferConstraint()|| - this.hasPanelDateConstraint()|| - this.hasPanelOccurrenceConstraint()|| - this.hasValueConstraint() - //||parent.isTimingQuery() - ){ - return super.buildSql(); - } - else{ - return "select " - + this.factTableColumn + " from " + noLockSqlServer - + (parent.getServerType().equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL) ? "" : parent.getDatabaseSchema() ) - + this.tableName - + " " + " where " + this.columnName + " " - + this.operator + " " + this.dimCode - + ""; - } - } - - - @Override - protected ConceptType getConceptType() throws ConceptNotFoundException, - OntologyException { - if (conceptType==null){ - - TempTableNameMap tempTableNameMap = new TempTableNameMap( - parent.getServerType()); - String masterTableName = tempTableNameMap.getTempMasterTable(); - - String itemKey = baseItem.getItemKey(); - - if (itemKey != null) { - conceptType = new ConceptType(); - conceptType.setColumnname(" master_id "); - conceptType.setOperator(" = "); - conceptType.setColumndatatype("T"); - conceptType.setFacttablecolumn(" patient_num "); - conceptType.setTablename(masterTableName); - conceptType.setDimcode("'" + itemKey + "'"); - } - } - - return conceptType; - } - - - @Override - protected String getJoinTable() { - if (this.returnInstanceNum()|| - hasItemDateConstraint()|| - hasPanelDateConstraint()|| - hasValueConstraint()|| - hasPanelOccurrenceConstraint()) { - return "observation_fact"; - } else if (this.returnEncounterNum() - //||parent.isTimingQuery() - ) { - return "visit_dimension"; - } else { - - TempTableNameMap tempTableNameMap = new TempTableNameMap( - parent.getServerType()); - String masterTableName = tempTableNameMap.getTempMasterTable(); - return masterTableName; - } - } - - @Override - protected String buildDimensionJoinSql(String tableAlias) { - String dimensionSql = ""; - - if (tableAlias!=null&&tableAlias.trim().length()>0) - tableAlias += "."; - - if (masterQueryTiming==null||masterQueryTiming.trim().length()==0) - masterQueryTiming="ANY"; - - String dbSchema = parent.getDatabaseSchema(); - if (parent.getServerType().equalsIgnoreCase(DAOFactoryHelper.SQLSERVER)){ - dbSchema = ""; - } - - if (masterQueryTiming.equals(QueryTimingHandler.SAMEINSTANCENUM)){ - //we have all columns in the master table to join to - if (parent.getPanelTiming().equals(QueryTimingHandler.SAMEINSTANCENUM)||parent.hasPanelOccurrenceConstraint()){ - dimensionSql = "exists (select 1 " - + "from " + noLockSqlServer - + (parent.getServerType().equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL) ? "" : dbSchema ) - + this.tableName + " mqt " - + "where mqt.patient_num = " + tableAlias + "patient_num " - + "and mqt.encounter_num = " + tableAlias + "encounter_num " - + "and mqt.provider_id = " + tableAlias + "provider_id " - + "and mqt.start_date = " + tableAlias + "start_date " - + "and mqt.concept_cd = " + tableAlias + "concept_cd " - + "and mqt.instance_num = " + tableAlias + "instance_num " - + "and mqt.master_id = " + this.dimCode - + ")"; - } - else if (parent.getPanelTiming().equals(QueryTimingHandler.SAME)||parent.getPanelTiming().equals(QueryTimingHandler.SAMEVISIT)||parent.hasPanelDateConstraint()||this.hasItemDateConstraint()){ - dimensionSql = "exists (select 1 " - + "from " + noLockSqlServer - + (parent.getServerType().equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL) ? "" : dbSchema ) - + this.tableName + " mqt " - + "where mqt.patient_num = " + tableAlias + "patient_num " - + "and mqt.encounter_num = " + tableAlias + "encounter_num " - + "and mqt.master_id = " + this.dimCode - + ")"; - } - else { - dimensionSql = "exists (select 1 " - + "from " + noLockSqlServer - + (parent.getServerType().equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL) ? "" : dbSchema ) - + this.tableName + " mqt " - + "where mqt.patient_num = " + tableAlias + "patient_num " - + "and mqt.master_id = " + this.dimCode - + ")"; - } - } - else if (masterQueryTiming.equals(QueryTimingHandler.SAME)||masterQueryTiming.equals(QueryTimingHandler.SAMEVISIT)){ - if (parent.getPanelTiming().equals(QueryTimingHandler.SAMEINSTANCENUM)||parent.hasPanelOccurrenceConstraint()|| - parent.getPanelTiming().equals(QueryTimingHandler.SAME)||parent.getPanelTiming().equals(QueryTimingHandler.SAMEVISIT)|| - parent.hasPanelDateConstraint()||this.hasItemDateConstraint()){ - dimensionSql = "exists (select 1 " - + "from " + noLockSqlServer - + (parent.getServerType().equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL) ? "" : dbSchema ) - + this.tableName + " mqt " - + "where mqt.patient_num = " + tableAlias + "patient_num " - + "and mqt.encounter_num = " + tableAlias + "encounter_num " - + "and mqt.master_id = " + this.dimCode - + ")"; - } - else { - dimensionSql = "exists (select 1 " - + "from " + noLockSqlServer - + (parent.getServerType().equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL) ? "" : dbSchema ) - + this.tableName + " mqt " - + "where mqt.patient_num = " + tableAlias + "patient_num " - + "and mqt.master_id = " + this.dimCode - + ")"; - } - } - else { - dimensionSql = "exists (select 1 " - + "from " + noLockSqlServer - + (parent.getServerType().equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL) ? "" : dbSchema ) - + this.tableName + " mqt " - + "where mqt.patient_num = " + tableAlias + "patient_num " - + "and mqt.master_id = " + this.dimCode - + ")"; - } - - return dimensionSql; - } - - - public String copyDxTempToMaster(String masterId, String masterQueryTiming, String maxPanelNum, String dxTempTableName, String masterTempTableName) { - String selectFields = " "; - String joinTableName = dxTempTableName; - String joinColumnName = "patient_num"; - if (this.returnInstanceNum()) { - selectFields = " encounter_num, instance_num, patient_num, concept_cd, start_date, provider_id, "; - } else if (this.returnEncounterNum()) { - selectFields = "encounter_num, patient_num, "; - } else { - selectFields = " patient_num, "; - } - - if (masterQueryTiming != null) { - QueryTimingHandler queryTimingHandler = new QueryTimingHandler(); - - if (queryTimingHandler.isSameInstanceNum(masterQueryTiming)) { - selectFields = " encounter_num, instance_num, patient_num, concept_cd, start_date, provider_id, "; - } else if (queryTimingHandler.isSameVisit(masterQueryTiming)) { - selectFields = "encounter_num, patient_num, "; - } else { - selectFields = " patient_num, "; - } - } - - if (joinTableName.equals(dxTempTableName)){ - return " insert into " + masterTempTableName + "(master_id, " - + selectFields + " level_no) " + "select '" + masterId + "', " - + selectFields + parent.getProcessingLevel() + " from " - + dxTempTableName; - } - else { - return " insert into " + masterTempTableName + "(master_id, " - + selectFields + " level_no) " + "select '" + masterId + "', " - + selectFields + parent.getProcessingLevel() + " from " - + joinTableName + " where " + joinColumnName + " IN ( " - + "select " + joinColumnName + " from " - + dxTempTableName + " ) "; - } - } - - public String deleteDxTempTable(String dxTempTableName){ - return " delete " + - (parent.getServerType().equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)? " from " : "") + - dxTempTableName; - } - - public String deleteTempTable(String tempTableName) { - return " delete " + - (parent.getServerType().equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)? " from " : "") + - tempTableName; - } - - public String deleteMasterTempTable(String masterId, int level, String masterTempTableName) { - return "delete " + - (parent.getServerType().equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)? " from " : "") + - masterTempTableName - + " where master_id = '" + masterId + "' and level_no >= " - + level; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Christopher Herrick + */ +package edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.ConceptNotFoundException; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.OntologyException; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.QueryTimingHandler; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.TempTableNameMap; +import edu.harvard.i2b2.crc.datavo.db.QtQueryMaster; +import edu.harvard.i2b2.crc.datavo.ontology.ConceptType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ItemType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionType; + +public class TemporalPanelEmbeddedQueryItem extends TemporalPanelItem { + + private String masterQueryTiming = null; + + public TemporalPanelEmbeddedQueryItem(TemporalPanel parent, ItemType item) + throws I2B2Exception { + super(parent, item); + parseEmbeddedItem(); + } + + protected void parseEmbeddedItem() throws I2B2Exception { + // TODO Auto-generated method stub + super.parseItem(); + + TemporalQuery masterQuery = null; + + //first look at query defintion to see if it was sent in the request + QueryDefinitionType queryDef = parent.searchForQueryInRequestDefinition(baseItem.getItemKey()); + if (queryDef!=null){ + try { + masterQuery = new TemporalQuery(parent.getDataSourceLookup(), parent.getProjectParameterMap(), queryDef, parent.allowLargeTextValueConstrainFlag(), parent.getUserRoles(), parent.getProcessingLevel() + 1, + parent.getProjectId(), parent.getRequestorSecurityType(), parent.getSecurityType()); + } catch (JAXBUtilException e) { + e.printStackTrace(); + throw new I2B2Exception("Error processing embedded query: " + e.getMessage()); + } + } + else { + String requestXml = getQueryDefinitionRequestXml(baseItem.getItemKey()); + try { + masterQuery = new TemporalQuery(parent.getDataSourceLookup(), parent.getProjectParameterMap(), requestXml, parent.allowLargeTextValueConstrainFlag(), parent.getUserRoles(), parent.getProcessingLevel() + 1); + } catch (JAXBUtilException e) { + e.printStackTrace(); + throw new I2B2Exception("Error processing embedded query: " + e.getMessage()); + } + } + + parent.addPreProcessingSql(masterQuery.buildSql()); + masterQueryTiming = masterQuery.getQueryTiming(); + + parent.addPreProcessingSql(copyDxTempToMaster(baseItem.getItemKey(), masterQueryTiming, String.valueOf(masterQuery.getMaxPanelIndex()), + masterQuery.getDxTempTableName(), masterQuery.getMasterTempTableName())); + + parent.addPreProcessingSql(deleteDxTempTable(masterQuery.getDxTempTableName())); + parent.addPreProcessingSql(deleteTempTable(masterQuery.getTempTableName())); + + parent.addPostProcessingSql(deleteMasterTempTable(baseItem.getItemKey(), parent.getProcessingLevel(), masterQuery.getMasterTempTableName())); + } + + + public String getQueryDefinitionRequestXml(String itemKey) + throws I2B2DAOException { + + DAOFactoryHelper helper = new DAOFactoryHelper( + parent.getDataSourceLookup().getDomainId(), + parent.getDataSourceLookup().getProjectPath(), + parent.getDataSourceLookup().getProjectPath()); + + SetFinderDAOFactory sfDaoFactory = helper.getDAOFactory() + .getSetFinderDAOFactory(); + + String masterId = itemKey.substring(9); + QtQueryMaster queryMaster = sfDaoFactory.getQueryMasterDAO().getQueryDefinition(masterId); + return queryMaster.getI2b2RequestXml(); + } + + + @Override + protected String buildSql() throws I2B2DAOException { + if (this.returnEncounterNum()|| + this.returnInstanceNum()|| + this.hasItemDateConstraint()|| + this.hasModiferConstraint()|| + this.hasPanelDateConstraint()|| + this.hasPanelOccurrenceConstraint()|| + this.hasValueConstraint() + //||parent.isTimingQuery() + ){ + return super.buildSql(); + } + else{ + return "select " + + this.factTableColumn + " from " + noLockSqlServer + + (parent.getServerType().equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL) ? "" : parent.getDatabaseSchema() ) + + this.tableName + + " " + " where " + this.columnName + " " + + this.operator + " " + this.dimCode + + ""; + } + } + + + @Override + protected ConceptType getConceptType() throws ConceptNotFoundException, + OntologyException { + if (conceptType==null){ + + TempTableNameMap tempTableNameMap = new TempTableNameMap( + parent.getServerType()); + String masterTableName = tempTableNameMap.getTempMasterTable(); + + String itemKey = baseItem.getItemKey(); + + if (itemKey != null) { + conceptType = new ConceptType(); + conceptType.setColumnname(" master_id "); + conceptType.setOperator(" = "); + conceptType.setColumndatatype("T"); + conceptType.setFacttablecolumn(" patient_num "); + conceptType.setTablename(masterTableName); + conceptType.setDimcode("'" + itemKey + "'"); + } + } + + return conceptType; + } + + + @Override + protected String getJoinTable() { + if (this.returnInstanceNum()|| + hasItemDateConstraint()|| + hasPanelDateConstraint()|| + hasValueConstraint()|| + hasPanelOccurrenceConstraint()) { + return "observation_fact"; + } else if (this.returnEncounterNum() + //||parent.isTimingQuery() + ) { + return "visit_dimension"; + } else { + + TempTableNameMap tempTableNameMap = new TempTableNameMap( + parent.getServerType()); + String masterTableName = tempTableNameMap.getTempMasterTable(); + return masterTableName; + } + } + + @Override + protected String buildDimensionJoinSql(String tableAlias) { + String dimensionSql = ""; + + if (tableAlias!=null&&tableAlias.trim().length()>0) + tableAlias += "."; + + if (masterQueryTiming==null||masterQueryTiming.trim().length()==0) + masterQueryTiming="ANY"; + + String dbSchema = parent.getDatabaseSchema(); + if (parent.getServerType().equalsIgnoreCase(DAOFactoryHelper.SQLSERVER)){ + dbSchema = ""; + } + + if (masterQueryTiming.equals(QueryTimingHandler.SAMEINSTANCENUM)){ + //we have all columns in the master table to join to + if (parent.getPanelTiming().equals(QueryTimingHandler.SAMEINSTANCENUM)||parent.hasPanelOccurrenceConstraint()){ + dimensionSql = "exists (select 1 " + + "from " + noLockSqlServer + + (parent.getServerType().equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL) ? "" : dbSchema ) + + this.tableName + " mqt " + + "where mqt.patient_num = " + tableAlias + "patient_num " + + "and mqt.encounter_num = " + tableAlias + "encounter_num " + + "and mqt.provider_id = " + tableAlias + "provider_id " + + "and mqt.start_date = " + tableAlias + "start_date " + + "and mqt.concept_cd = " + tableAlias + "concept_cd " + + "and mqt.instance_num = " + tableAlias + "instance_num " + + "and mqt.master_id = " + this.dimCode + + ")"; + } + else if (parent.getPanelTiming().equals(QueryTimingHandler.SAME)||parent.getPanelTiming().equals(QueryTimingHandler.SAMEVISIT)||parent.hasPanelDateConstraint()||this.hasItemDateConstraint()){ + dimensionSql = "exists (select 1 " + + "from " + noLockSqlServer + + (parent.getServerType().equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL) ? "" : dbSchema ) + + this.tableName + " mqt " + + "where mqt.patient_num = " + tableAlias + "patient_num " + + "and mqt.encounter_num = " + tableAlias + "encounter_num " + + "and mqt.master_id = " + this.dimCode + + ")"; + } + else { + dimensionSql = "exists (select 1 " + + "from " + noLockSqlServer + + (parent.getServerType().equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL) ? "" : dbSchema ) + + this.tableName + " mqt " + + "where mqt.patient_num = " + tableAlias + "patient_num " + + "and mqt.master_id = " + this.dimCode + + ")"; + } + } + else if (masterQueryTiming.equals(QueryTimingHandler.SAME)||masterQueryTiming.equals(QueryTimingHandler.SAMEVISIT)){ + if (parent.getPanelTiming().equals(QueryTimingHandler.SAMEINSTANCENUM)||parent.hasPanelOccurrenceConstraint()|| + parent.getPanelTiming().equals(QueryTimingHandler.SAME)||parent.getPanelTiming().equals(QueryTimingHandler.SAMEVISIT)|| + parent.hasPanelDateConstraint()||this.hasItemDateConstraint()){ + dimensionSql = "exists (select 1 " + + "from " + noLockSqlServer + + (parent.getServerType().equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL) ? "" : dbSchema ) + + this.tableName + " mqt " + + "where mqt.patient_num = " + tableAlias + "patient_num " + + "and mqt.encounter_num = " + tableAlias + "encounter_num " + + "and mqt.master_id = " + this.dimCode + + ")"; + } + else { + dimensionSql = "exists (select 1 " + + "from " + noLockSqlServer + + (parent.getServerType().equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL) ? "" : dbSchema ) + + this.tableName + " mqt " + + "where mqt.patient_num = " + tableAlias + "patient_num " + + "and mqt.master_id = " + this.dimCode + + ")"; + } + } + else { + dimensionSql = "exists (select 1 " + + "from " + noLockSqlServer + + (parent.getServerType().equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL) ? "" : dbSchema ) + + this.tableName + " mqt " + + "where mqt.patient_num = " + tableAlias + "patient_num " + + "and mqt.master_id = " + this.dimCode + + ")"; + } + + return dimensionSql; + } + + + public String copyDxTempToMaster(String masterId, String masterQueryTiming, String maxPanelNum, String dxTempTableName, String masterTempTableName) { + String selectFields = " "; + String joinTableName = dxTempTableName; + String joinColumnName = "patient_num"; + if (this.returnInstanceNum()) { + selectFields = " encounter_num, instance_num, patient_num, concept_cd, start_date, provider_id, "; + } else if (this.returnEncounterNum()) { + selectFields = "encounter_num, patient_num, "; + } else { + selectFields = " patient_num, "; + } + + if (masterQueryTiming != null) { + QueryTimingHandler queryTimingHandler = new QueryTimingHandler(); + + if (queryTimingHandler.isSameInstanceNum(masterQueryTiming)) { + selectFields = " encounter_num, instance_num, patient_num, concept_cd, start_date, provider_id, "; + } else if (queryTimingHandler.isSameVisit(masterQueryTiming)) { + selectFields = "encounter_num, patient_num, "; + } else { + selectFields = " patient_num, "; + } + } + + if (joinTableName.equals(dxTempTableName)){ + return " insert into " + masterTempTableName + "(master_id, " + + selectFields + " level_no) " + "select '" + masterId + "', " + + selectFields + parent.getProcessingLevel() + " from " + + dxTempTableName; + } + else { + return " insert into " + masterTempTableName + "(master_id, " + + selectFields + " level_no) " + "select '" + masterId + "', " + + selectFields + parent.getProcessingLevel() + " from " + + joinTableName + " where " + joinColumnName + " IN ( " + + "select " + joinColumnName + " from " + + dxTempTableName + " ) "; + } + } + + public String deleteDxTempTable(String dxTempTableName){ + return " delete " + + (parent.getServerType().equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)? " from " : "") + + dxTempTableName; + } + + public String deleteTempTable(String tempTableName) { + return " delete " + + (parent.getServerType().equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)? " from " : "") + + tempTableName; + } + + public String deleteMasterTempTable(String masterId, int level, String masterTempTableName) { + return "delete " + + (parent.getServerType().equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)? " from " : "") + + masterTempTableName + + " where master_id = '" + masterId + "' and level_no >= " + + level; + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalPanelEncounterItem.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalPanelEncounterItem.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalPanelEncounterItem.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalPanelEncounterItem.java index 24a9c399..554b4dd1 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalPanelEncounterItem.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalPanelEncounterItem.java @@ -1,116 +1,116 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Christopher Herrick - */ -package edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.ConceptNotFoundException; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.OntologyException; -import edu.harvard.i2b2.crc.datavo.ontology.ConceptType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ItemType; - -public class TemporalPanelEncounterItem extends TemporalPanelItem { - - public TemporalPanelEncounterItem(TemporalPanel parent, ItemType item) - throws I2B2Exception { - super(parent, item); - } - - - @Override - protected String buildSql() throws I2B2DAOException { - if (this.returnInstanceNum()|| - this.hasItemDateConstraint()|| - this.hasModiferConstraint()|| - this.hasPanelDateConstraint()|| - this.hasPanelOccurrenceConstraint()|| - this.hasValueConstraint() - ){ - return super.buildSql(); - } - else{ - String selectClause = "select patient_num "; - if (this.returnEncounterNum()) - selectClause = "select encounter_num, patient_num "; - return selectClause + " from " + noLockSqlServer - + parent.getDatabaseSchema() + this.tableName - + " " + " where " + this.columnName + " " - + this.operator + " " + this.dimCode - + ""; - } - } - - - @Override - protected ConceptType getConceptType() throws ConceptNotFoundException, - OntologyException { - if (conceptType==null){ - String itemKey = baseItem.getItemKey(); - - String[] encounterId = itemKey.split(":"); - if (encounterId[1] != null) { - String encounterNum = encounterId[1]; - conceptType = new ConceptType(); - conceptType.setColumnname(" encounter_num "); - conceptType.setOperator(" = "); - conceptType.setFacttablecolumn(" encounter_num "); - conceptType.setTablename("visit_dimension "); - conceptType.setDimcode(encounterNum); - } - } - - return conceptType; - } - - @Override - protected String getJoinTable() { - if (this.returnInstanceNum()|| - hasItemDateConstraint()|| - hasPanelDateConstraint()|| - hasValueConstraint()|| - hasPanelOccurrenceConstraint()) { - return "observation_fact"; - } else { - return "visit_dimension"; - } - } - - - @Override - protected String buildDimensionJoinSql(String tableAlias) { - String dimensionSql = ""; - - if (tableAlias!=null&&tableAlias.trim().length()>0) - tableAlias += "."; - - String itemKey = baseItem.getItemKey(); - - String[] encounterId = itemKey.split(":"); - if (encounterId.length > 2 && - encounterId[1] != null && - encounterId[2] != null) { - - dimensionSql = tableAlias + this.factTableColumn + " IN (select " - + "encounter_num from " + noLockSqlServer - + parent.getDatabaseSchema() + "encounter_mapping " - + "where encounter_ide_source = '" + encounterId[1] + "' " - + "and encounter_ide = '" + encounterId[2] + "' " - + ")"; - } - - return dimensionSql; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Christopher Herrick + */ +package edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.ConceptNotFoundException; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.OntologyException; +import edu.harvard.i2b2.crc.datavo.ontology.ConceptType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ItemType; + +public class TemporalPanelEncounterItem extends TemporalPanelItem { + + public TemporalPanelEncounterItem(TemporalPanel parent, ItemType item) + throws I2B2Exception { + super(parent, item); + } + + + @Override + protected String buildSql() throws I2B2DAOException { + if (this.returnInstanceNum()|| + this.hasItemDateConstraint()|| + this.hasModiferConstraint()|| + this.hasPanelDateConstraint()|| + this.hasPanelOccurrenceConstraint()|| + this.hasValueConstraint() + ){ + return super.buildSql(); + } + else{ + String selectClause = "select patient_num "; + if (this.returnEncounterNum()) + selectClause = "select encounter_num, patient_num "; + return selectClause + " from " + noLockSqlServer + + parent.getDatabaseSchema() + this.tableName + + " " + " where " + this.columnName + " " + + this.operator + " " + this.dimCode + + ""; + } + } + + + @Override + protected ConceptType getConceptType() throws ConceptNotFoundException, + OntologyException { + if (conceptType==null){ + String itemKey = baseItem.getItemKey(); + + String[] encounterId = itemKey.split(":"); + if (encounterId[1] != null) { + String encounterNum = encounterId[1]; + conceptType = new ConceptType(); + conceptType.setColumnname(" encounter_num "); + conceptType.setOperator(" = "); + conceptType.setFacttablecolumn(" encounter_num "); + conceptType.setTablename("visit_dimension "); + conceptType.setDimcode(encounterNum); + } + } + + return conceptType; + } + + @Override + protected String getJoinTable() { + if (this.returnInstanceNum()|| + hasItemDateConstraint()|| + hasPanelDateConstraint()|| + hasValueConstraint()|| + hasPanelOccurrenceConstraint()) { + return "observation_fact"; + } else { + return "visit_dimension"; + } + } + + + @Override + protected String buildDimensionJoinSql(String tableAlias) { + String dimensionSql = ""; + + if (tableAlias!=null&&tableAlias.trim().length()>0) + tableAlias += "."; + + String itemKey = baseItem.getItemKey(); + + String[] encounterId = itemKey.split(":"); + if (encounterId.length > 2 && + encounterId[1] != null && + encounterId[2] != null) { + + dimensionSql = tableAlias + this.factTableColumn + " IN (select " + + "encounter_num from " + noLockSqlServer + + parent.getDatabaseSchema() + "encounter_mapping " + + "where encounter_ide_source = '" + encounterId[1] + "' " + + "and encounter_ide = '" + encounterId[2] + "' " + + ")"; + } + + return dimensionSql; + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalPanelItem.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalPanelItem.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalPanelItem.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalPanelItem.java index a646a08d..47712fbb --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalPanelItem.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalPanelItem.java @@ -1,1023 +1,1023 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Christopher Herrick - */ -package edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import javax.xml.stream.XMLStreamException; - -import org.apache.axis2.AxisFault; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.w3c.dom.Element; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.exception.StackTraceUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.ConceptNotFoundException; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.DateConstrainUtil; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.OntologyException; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.QueryTimingHandler; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.TotalItemOccurrenceHandler; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.UnitConverstionUtil; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.ValueConstrainsHandler; -import edu.harvard.i2b2.crc.datavo.ontology.ConceptType; -import edu.harvard.i2b2.crc.datavo.ontology.ModifierType; -import edu.harvard.i2b2.crc.datavo.ontology.XmlValueType; -import edu.harvard.i2b2.crc.datavo.pdo.query.TotOccuranceOperatorType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ConstrainValueType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ItemType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ItemType.ConstrainByDate; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ItemType.ConstrainByValue; -import edu.harvard.i2b2.crc.datavo.setfinder.query.PanelType.TotalItemOccurrences; -import edu.harvard.i2b2.crc.delegate.ontology.CallOntologyUtil; -import edu.harvard.i2b2.crc.util.ParamUtil; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; -import edu.harvard.i2b2.crc.util.SqlClauseUtil; -import edu.harvard.i2b2.crc.util.StringUtil; - - -/** - ** - * Temporal Panel Item - * - *

    - * Panel Item query object that wraps the item tag found in the query definition - * xml for panel items. It roughly corresponds to an item dropped into a panel in the query UI. PanelItem is responsible - * for generating the sql for an individual panel item. It implements the logic for the sql query - * and takes into account item value constraints, modifier constraints, item and panel based date constraints, - * and panel occurrences. This class is an abstract class and must be implemented by class dedicated to - * specific panel item types. - * - * @author Christopher Herrick - * - */ -public abstract class TemporalPanelItem { - - protected final Log log = LogFactory.getLog(getClass()); - protected final Log logesapi = LogFactory.getLog(getClass()); - - protected TemporalPanel parent = null; - - protected ItemType baseItem = null; - protected ConceptType conceptType = null; - protected ModifierType modifierType = null; - protected Integer conceptTotal; - protected String noLockSqlServer = " "; - - //Concept Type fields - protected String factTableColumn = null; - protected String tableName = null; - protected String dimCode = null; - protected String operator = null; - protected String columnName = null; - protected XmlValueType metaDataXml = null; - protected String factTable = "observation_fact"; - protected boolean isProtected = false; - protected String ontologyProtection = null; - - /** - * Constructor - * - * @param parent - TemporalPanel object to which this panle item belongs - * @param item - object representation of the xml from panel item contained in query definition xml - * @throws I2B2Exception - thrown when an i2b2 specific error is found - */ - public TemporalPanelItem(TemporalPanel parent, ItemType item) - throws I2B2Exception { - this.parent = parent; - this.baseItem = item; - parseItem(); - } - - /** - * Constructor - * - * @param parent - TemporalPanel object to which this panle item belongs - * @param item - object representation of the xml from panel item contained in query definition xml - * @param conceptType - object representation of the item obtained from the Ontology cell - * @throws I2B2Exception - thrown when an i2b2 specific error is found - */ - public TemporalPanelItem(TemporalPanel parent, ItemType item, ConceptType conceptType) - throws I2B2Exception { - this.parent = parent; - this.baseItem = item; - this.conceptType = conceptType; - parseItem(); - } - - /** - * Parse Item - * - * Parses through the item and/or concept type object and assigns key fields - * to the corresponding properties of the class. ParseItem is called from the constructor - * and must be executed before trying to build sql on the item. - * - * @throws I2B2Exception - thrown when an i2b2 specific error is found - */ - protected void parseItem() throws I2B2Exception { - if (conceptType==null){ - conceptType = getConceptType(); - } - if (conceptType != null) { - if (conceptType.getTotalnum() != null) { - conceptTotal = conceptType.getTotalnum(); - } - factTableColumn = conceptType.getFacttablecolumn(); - tableName = conceptType.getTablename(); - dimCode = conceptType.getDimcode(); - operator = conceptType.getOperator(); - columnName = conceptType.getColumnname(); - metaDataXml = conceptType.getMetadataxml(); - ontologyProtection = conceptType.getOntologyProtection(); - if (conceptType.getProtectedAccess() != null) - isProtected = (conceptType.getProtectedAccess().equalsIgnoreCase("Y")?true:false); - - // If protected check roles - if (isProtected) - { - Boolean protectedAccess = false; - String[] dataProt = {"DATA_PROT"}; - List ontologyProtection = Arrays.asList(conceptType.getOntologyProtection() == null || conceptType.getOntologyProtection().equals("")?dataProt:conceptType.getOntologyProtection().split(",")); - for (String s: parent.getUserRoles()) { - if (ontologyProtection.contains(s)) - protectedAccess = true; - - } - - if (protectedAccess == false) - throw new I2B2DAOException("This query contains protected."); - } - //OMOP addition - parseFactColumn(factTableColumn); - } - } - - /** - * Build Sql - * - * Main method for generating the sql string that will be run on the - * database for this item. Constructs sql based on logic for main item, value constraints, - * modifier constraints, date constraints, and occurrence constraints - * - * @return String - sql logic for querying based on the constraints represented in this item - * @throws I2B2DAOException - thrown when an i2b2 specific data or database error occurs - */ - protected String buildSql() throws I2B2DAOException { - - checkLargeTextConstrainPermission(); - - String sqlHintClause = buildSqlHintClause(); - String selectSql = buildSelectSql(); - String fromSql = buildFromSql(); - String dimensionJoinSql = buildDimensionJoinSql(); - String modifierConstraintSql = buildModifierConstraintSql(); - String[] modifierValueConstrainSql = buildModifierValueConstraintSql(); - String dateConstraintSql = buildItemDateConstraintSql(); - String[] valueConstraintSql = buildValueConstraintSql(); - String panelDateConstraintSql = buildPanelDateConstraintSql(); - String groupbyClause = buildGroupBySql(); - String havingClause = buildHavingSql(); - - if (parent.getAccuracyScale()>0&& - valueConstraintSql[1]!=null&& - valueConstraintSql[1].trim().length()>0) { - fromSql += valueConstraintSql[1]; - } - - if (parent.getAccuracyScale() >0& - modifierValueConstrainSql[1]!=null&& - modifierValueConstrainSql[1].trim().length()>0) { - fromSql += modifierValueConstrainSql[1]; - } - - String derivedTableSql = " select " + sqlHintClause - + selectSql - + " \nfrom " + fromSql - + " \nwhere " - + formatSql(dimensionJoinSql) + " " - + formatSql(modifierConstraintSql) - + formatSql(modifierValueConstrainSql[0]) - + formatSql(valueConstraintSql[0]) - + formatSql(dateConstraintSql) - + formatSql(panelDateConstraintSql) - + " \ngroup by " + groupbyClause - + formatSql(havingClause); - logesapi.debug("Derived table sql [" + derivedTableSql + "]"); - - return derivedTableSql; - } - - /** - * Format Sql - * - * Method for adding carriage returns into sql so statements are more - * readable when output to error and logs - * - * @param sql String to be formatted - * @return String formatted sql string - */ - private String formatSql(String sql){ - if (sql!=null&&sql.trim().length()>0) - return "\n" + sql; - else - return ""; - } - - - /** - * Build Select Sql - * - * Construct the sql SELECT clause for this item. Determines which columns should be - * returned by the query - * - * @return String sql SELECT clause for use in larger statement - */ - protected String buildSelectSql(){ - return buildSelectSql(getPrimaryTableAlias()); - } - - /** - * Build Select Sql - * - * Construct the sql SELECT clause for this item. Determines which columns should be - * returned by the query - * - * @param tableAlias String used to alias all columns contained in the select statement - * @return String sql SELECT clause for use in larger statement - */ - protected String buildSelectSql(String tableAlias){ - - if (tableAlias!=null&&tableAlias.trim().length()>0) - tableAlias += "."; - - String selectClause = tableAlias + "patient_num "; - - if (this.returnInstanceNum()) { - selectClause = " " + tableAlias + "provider_id, " - + tableAlias + "start_date, " - + tableAlias + "concept_cd, " - + tableAlias + "instance_num, " - + tableAlias + "encounter_num, " - + selectClause; - } else if (this.returnEncounterNum()) { - selectClause = " " + tableAlias + "encounter_num, " - + selectClause; - } - - if (parent.hasPanelOccurrenceConstraint() && - parent.applyOccurrenceToPanelLevel() && - (parent.getItemList().size()>1 || - !parent.isPatientOnlyQuery())){ - selectClause += ", " + buildFactCountSql(tableAlias) + " "; - } - - return selectClause; - } - - /** - * Build Sql Hint Clause - * - * Returns any database specific sql syntax used to guid the database optimizer in - * choosing an execution plan or index to use - * - * @return String sql clause that contains database specific parameters for passing sql hints to optimizer - */ - protected String buildSqlHintClause(){ - return " "; - } - - /** - * Build From Sql - * - * Construct the sql FROM clause for this item. Determines which tables should be - * referenced and joined to in the item query - * - * @return String sql FROM clause that contains tables used in this item query - */ - protected String buildFromSql(){ - return buildFromSql(getPrimaryTableAlias()); - } - - /** - * Build From Sql - * - * Construct the sql FROM clause for this item. Determines which tables should be - * referenced and joined to in the item query - * - * @param tableAlias String used to alias the table in the from clause - * @return String sql FROM clause that contains tables used in this item query - */ - protected String buildFromSql(String tableAlias){ - String joinTableName = parent.getDatabaseSchema() + getJoinTable(); - - if (tableAlias!=null&&tableAlias.trim().length()>0) - joinTableName += " " + tableAlias; - - return joinTableName; - } - - - /** - * Build Dimension Join Sql - * - * Construct the sql FROM clause for this item. Determines which tables should be - * referenced and joined to in the item query. Use the default table alias. - * - * @return String sql FROM clause that contains tables used in this item query - */ - protected String buildDimensionJoinSql(){ - return buildDimensionJoinSql(getPrimaryTableAlias()); - } - - /** - * Build Dimension Join Sql - * - * Construct the sql FROM clause for this item. Determines which tables should be - * referenced and joined to in the item query - * - * @param tableAlias String used to alias the table in the from clause - * @return String sql FROM clause that contains tables used in this item query - */ - protected String buildDimensionJoinSql(String tableAlias) { - String dimensionSql = ""; - - if (tableAlias!=null&&tableAlias.trim().length()>0) - tableAlias += "."; - - if ((this.operator!=null)&& - (this.operator.toUpperCase().equals("LIKE"))&& - (this.dimCode!=null) && (parent.getServerType().equalsIgnoreCase("POSTGRESQL"))) - { - this.dimCode = this.dimCode.replaceAll("\\\\", "\\\\\\\\"); - - } - dimensionSql = tableAlias + this.factTableColumn + " IN (select " - + this.factTableColumn + " from " + noLockSqlServer - + parent.getDatabaseSchema() + this.tableName - + " " + " where " + this.columnName + " " - + this.operator + " " + this.dimCode; - - if ((this.operator!=null)&& - (this.operator.toUpperCase().equals("LIKE"))&& - (this.dimCode!=null)&& - (this.dimCode.contains("?"))) - { - dimensionSql += (!parent.getDataSourceLookup().getServerType().toUpperCase().equals("POSTGRESQL") ? " {ESCAPE '?'} " : "" ) ; - } - dimensionSql += ")"; - return dimensionSql; - } - - /** - * Build Item Date Constraint Sql - * - * Construct sql WHERE constraint statements that constrain this item by date. These date constraints orignate - * at the item level and not at the panel level. - * - * @return String sql constraint clause to be appended to the WHERE clause generated by this item - */ - protected String buildItemDateConstraintSql() { - return buildItemDateConstraintSql(getPrimaryTableAlias()); - } - - - /** - * Build Item Date Constraint Sql - * - * Construct sql WHERE constraint statements that constrain this item by date. These date constraints orignate - * at the item level and not at the panel level. - * - * @param tableAlias String used to alias the table that is being constrained - * @return String sql constraint clause to be appended to the WHERE clause generated by this item - */ - protected String buildItemDateConstraintSql(String tableAlias) { - // generate sql for item date constrain - DateConstrainUtil dateConstrainUtil = new DateConstrainUtil( - parent.getDataSourceLookup()); - String itemDateConstrainSql = dateConstrainUtil - .buildItemDateSql(baseItem, tableAlias); - if (itemDateConstrainSql != null - && itemDateConstrainSql.trim().length() > 0) { - log.info("Item date constrain sql" + itemDateConstrainSql); - itemDateConstrainSql = " AND ( " + itemDateConstrainSql + " ) "; - } else { - itemDateConstrainSql = ""; - } - return itemDateConstrainSql; - } - - protected String[] buildValueConstraintSql() - throws I2B2DAOException { - - // generate sql for unit_cd conversion - String unitCdSwitchClause = "", unitCdInClause = ""; - - if (parent.getProjectParameterMap() != null - && parent.getProjectParameterMap().get(ParamUtil.CRC_ENABLE_UNITCD_CONVERSION) != null) { - String unitCdConversionFlag = (String) parent.getProjectParameterMap().get(ParamUtil.CRC_ENABLE_UNITCD_CONVERSION); - if (unitCdConversionFlag != null - && unitCdConversionFlag.equalsIgnoreCase("ON")) { - if (metaDataXml != null - && metaDataXml.getAny().get(0) != null) { - Element valueMetadataElement = metaDataXml.getAny().get(0); - UnitConverstionUtil unitConverstionUtil = new UnitConverstionUtil(); - unitCdSwitchClause = unitConverstionUtil - .buildUnitCdSwitchClause(valueMetadataElement, - false, ""); - log.debug("concept unit Conversion sql " - + unitCdSwitchClause); - unitCdInClause = unitConverstionUtil.buildUnitCdInClause( - valueMetadataElement, ""); - - } - } - } - - ValueConstrainsHandler valueConstrainHandler = new ValueConstrainsHandler(); - if (unitCdSwitchClause.length() > 0) { - valueConstrainHandler.setUnitCdConversionFlag(true, unitCdInClause, - unitCdSwitchClause); - } - - String[] itemValueConstrainSql = valueConstrainHandler - .constructValueConstainClause(baseItem.getConstrainByValue(), - parent.getServerType(), parent.getDatabaseSchema(), - parent.getAccuracyScale(), true); - log.info("Item value constrain sql " + itemValueConstrainSql); - - if (itemValueConstrainSql != null - && itemValueConstrainSql[0].trim().length() > 0) { - - itemValueConstrainSql[0] = " AND ( " + itemValueConstrainSql[0] - + " )"; - } else { - itemValueConstrainSql[0] = ""; - } - return itemValueConstrainSql; - } - - protected String[] buildModifierValueConstraintSql() - throws I2B2DAOException { - - if (modifierType==null){ - modifierType = getModifierMetadataFromOntology(); - } - - if (modifierType==null) - return new String[] { "", "" }; - - String modifierUnitCdSwitchClause = "", modifierUnitCdInClause = ""; - - if (parent.getProjectParameterMap() != null - && parent.getProjectParameterMap().get( - ParamUtil.CRC_ENABLE_UNITCD_CONVERSION) != null) { - String unitCdConversionFlag = (String) parent - .getProjectParameterMap().get( - ParamUtil.CRC_ENABLE_UNITCD_CONVERSION); - if (unitCdConversionFlag != null - && unitCdConversionFlag.equalsIgnoreCase("ON")) { - if (modifierType != null - && modifierType.getMetadataxml() != null - && modifierType.getMetadataxml().getAny().get(0) != null) { - Element valueMetadataElement = modifierType - .getMetadataxml().getAny().get(0); - UnitConverstionUtil unitConverstionUtil = new UnitConverstionUtil(); - modifierUnitCdSwitchClause = unitConverstionUtil - .buildUnitCdSwitchClause(valueMetadataElement, - false, ""); - log.debug("modifier unit Conversion sql " - + modifierUnitCdSwitchClause); - modifierUnitCdInClause = unitConverstionUtil - .buildUnitCdInClause(valueMetadataElement, ""); - - } - } - } - - ValueConstrainsHandler valueConstrainHandler = new ValueConstrainsHandler(); - if (modifierUnitCdSwitchClause.length() > 0) { - valueConstrainHandler.setUnitCdConversionFlag(true, - modifierUnitCdInClause, modifierUnitCdSwitchClause); - } - - - String itemModifierValueConstrainSql[] = new String[] { "", "" }; - - if (baseItem.getConstrainByModifier() != null - && baseItem.getConstrainByModifier().getConstrainByValue() != null) { - List itemValueConstrainList = getModifierItemValueConstrain(baseItem.getConstrainByModifier().getConstrainByValue()); - itemModifierValueConstrainSql = valueConstrainHandler - .constructValueConstainClause(itemValueConstrainList, - parent.getServerType(), parent.getDatabaseSchema(), - parent.getAccuracyScale(), false); - if (itemModifierValueConstrainSql != null - && itemModifierValueConstrainSql[0].length() > 0) { - log.info("Modifier constrian value constrain sql " - + itemModifierValueConstrainSql); - } - } - - if (itemModifierValueConstrainSql[0] != null - && itemModifierValueConstrainSql[0].trim().length() > 0) { - - itemModifierValueConstrainSql[0] = " AND ( " - + itemModifierValueConstrainSql[0] + " )"; - } else { - itemModifierValueConstrainSql[0] = ""; - } - return itemModifierValueConstrainSql; - } - - protected String buildModifierConstraintSql() throws I2B2DAOException { - return buildModifierConstraintSql(getPrimaryTableAlias()); - } - - protected String buildModifierConstraintSql(String tableAlias) throws I2B2DAOException { - if (modifierType==null) - modifierType = getModifierMetadataFromOntology(); - - if (modifierType==null) - return ""; - - if (tableAlias!=null&&tableAlias.trim().length()>0) - tableAlias += "."; - - String dimPath = "", dimColumnName = "", dimCode = "", dimOperator = "", dimTableName = "", factTableColumn = ""; - - String itemModifierConstrainSql = null; - if (modifierType != null) { - dimPath = modifierType.getFullname(); - dimColumnName = modifierType.getColumnname(); - dimCode = modifierType.getDimcode(); - dimOperator = modifierType.getOperator(); - dimTableName = modifierType.getTablename(); - factTableColumn = modifierType.getFacttablecolumn(); - - if (dimPath == null || dimColumnName == null || dimCode == null - || dimOperator == null || dimTableName == null - || factTableColumn == null) { - throw new I2B2DAOException( - "Error modifier constrain information has null value path [" - + dimPath + "] column name [" + dimColumnName - + "] dim code [" + dimCode - + "] dim operator [ " + dimOperator - + "] dim table name [" + dimTableName - + "] fact table column [" + factTableColumn - + "]"); - } - } - - dimPath.replaceAll("'", "''"); - - if ((dimOperator != null) && (dimOperator.toUpperCase().equals("LIKE") - && (parent.getDataSourceLookup().getServerType().toUpperCase().equals("POSTGRESQL")))) - dimCode = dimCode.replaceAll("\\\\", "\\\\\\\\"); - - - - itemModifierConstrainSql = " (" + tableAlias + factTableColumn + " IN " - + "(select " + factTableColumn - + " from " + parent.getDatabaseSchema() + dimTableName - + " where " + dimColumnName + " " + dimOperator + " " + dimCode; - - if ((dimOperator != null) && (dimOperator.toUpperCase().equals("LIKE")) - && (dimCode != null) && (dimCode.contains("?"))) { - itemModifierConstrainSql += (!parent.getDataSourceLookup().getServerType().toUpperCase().equals("POSTGRESQL") ? " {ESCAPE '?'} " : "" ) ; - } - itemModifierConstrainSql += ")) "; - - if (itemModifierConstrainSql != null - && itemModifierConstrainSql.trim().length() > 0) { - log.info("Item modifier constrain sql" + itemModifierConstrainSql); - itemModifierConstrainSql = " AND " + itemModifierConstrainSql; - } else { - itemModifierConstrainSql = " "; - } - - return itemModifierConstrainSql; - } - - protected String buildPanelDateConstraintSql(){ - return buildPanelDateConstraintSql(getPrimaryTableAlias()); - } - - protected String buildPanelDateConstraintSql(String tableAlias){ - String panelDateConstraintSql = parent.buildDateConstraintSql(tableAlias); - if (panelDateConstraintSql!=null&&panelDateConstraintSql.trim().length() > 0) { - panelDateConstraintSql = " AND ( " + panelDateConstraintSql + " )"; - } - - return panelDateConstraintSql; - } - - protected String buildGroupBySql(){ - return buildGroupBySql(getPrimaryTableAlias()); - } - - protected String buildGroupBySql(String tableAlias){ - // check if the dimensionJoinSql is query in query with fact constrains - String groupbyClause = ""; - - if (tableAlias!=null&&tableAlias.trim().length()>0) - tableAlias += "."; - - if (this.returnInstanceNum()) { - groupbyClause = " " + tableAlias + "encounter_num ," - + tableAlias + "instance_num, " - + tableAlias + "concept_cd," + tableAlias - + "start_date," + tableAlias + "provider_id,"; - } - else if (this.returnEncounterNum()){ - groupbyClause = " " + tableAlias + "encounter_num ,"; - } - - groupbyClause += " " + tableAlias + "patient_num "; - - return groupbyClause; - } - - protected String buildFactCountSql(String tableAlias){ - TotalItemOccurrences totalOccur = parent.getTotalOccurrences(); - - if (tableAlias!=null&&tableAlias.trim().length()>0&&!tableAlias.endsWith(".")) - tableAlias += "."; - - if (totalOccur != null) { - if ((totalOccur.getOperator() != null - && totalOccur.getOperator().value() != null - && totalOccur.getOperator().value().equalsIgnoreCase(TotOccuranceOperatorType.GE.value())) - && totalOccur.getValue() == 1) { - } else { - String countDistinct = "*"; - if (parent.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER) ) { - countDistinct = " distinct cast(" + tableAlias + "patient_num as varchar) + '|' + cast(" + tableAlias + "encounter_num as varchar) + '|' + " - + " " + tableAlias + "provider_id + '|' + cast(" + tableAlias + "start_date as varchar) + '|' + cast(" + tableAlias + "instance_num as varchar) + '|' + " + tableAlias + "concept_cd"; - } else if (parent.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE) || parent.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) { - countDistinct = " distinct " + tableAlias + "patient_num || '|' || " + tableAlias + "encounter_num || '|' || " - + tableAlias + "provider_id || '|' || " + tableAlias + "instance_num || '|' ||" + tableAlias + "concept_cd || '|' ||cast(" + tableAlias + "start_date as varchar(50))"; - } - - return "count(" + countDistinct + ") as fact_count"; - } - } - - return ""; - } - - protected String buildHavingSql(){ - return buildHavingSql(getPrimaryTableAlias()); - } - - protected String buildHavingSql(String tableAlias){ - TotalItemOccurrences totalOccur = parent.getTotalOccurrences(); - - TotalItemOccurrenceHandler totalItemOccurrencHandler = new TotalItemOccurrenceHandler(); - String totalItemOccurrenceClause = totalItemOccurrencHandler.buildTotalItemOccurrenceClause(totalOccur); - - String havingSql = " "; - - if (tableAlias!=null&&tableAlias.trim().length()>0) - tableAlias += "."; - - if ((!parent.applyOccurrenceToPanelLevel()||parent.getItemList().size()==1) && totalOccur != null) { - if ((totalOccur.getOperator() != null - && totalOccur.getOperator().value() != null - && totalOccur.getOperator().value().equalsIgnoreCase(TotOccuranceOperatorType.GE.value())) - && totalOccur.getValue() == 1) { - } else { - log.debug("Setfinder query total occurrences operator value [" - + totalOccur.getOperator().value() + "]"); - String countDistinct = "*"; - if (parent.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER) ) { - countDistinct = " distinct cast(" + tableAlias + "patient_num as varchar) + '|' + cast(" + tableAlias + "encounter_num as varchar) + '|' + " - + " " + tableAlias + "provider_id + '|' + cast(" + tableAlias + "start_date as varchar) + '|' + cast(" + tableAlias + "instance_num as varchar) + '|' + " + tableAlias + "concept_cd"; - } else if (parent.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE) || parent.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) { - countDistinct = " distinct " + tableAlias + "patient_num || '|' || " + tableAlias + "encounter_num || '|' || " - + tableAlias + "provider_id || '|' || " + tableAlias + "instance_num || '|' ||" + tableAlias + "concept_cd || '|' ||cast(" + tableAlias + "start_date as varchar(50))"; - } - havingSql = " having count(" + countDistinct + ") " - + totalItemOccurrenceClause; - } - } - - return havingSql; - } - - public void parseFactColumn(String factColumnName){ - this.factTable= "observation_fact"; - this.factTableColumn = factColumnName; - if (this.parent.getQueryOptions()!=null&&this.parent.getQueryOptions().useDerivedFactTable()) - { - if (factColumnName!=null&&factColumnName.contains(".")){ - int lastIndex = factColumnName.lastIndexOf("."); - this.factTable= factColumnName.substring(0, lastIndex); - if ((lastIndex+1) getModifierItemValueConstrain( - List modifierConstrainList) { - List itemValueConstrainList = new ArrayList(); - for (ItemType.ConstrainByModifier.ConstrainByValue modifierValueConstrain : modifierConstrainList) { - ItemType.ConstrainByValue constrainByValue = new ItemType.ConstrainByValue(); - constrainByValue.setValueConstraint(modifierValueConstrain - .getValueConstraint()); - constrainByValue.setValueOperator(modifierValueConstrain - .getValueOperator()); - constrainByValue - .setValueType(modifierValueConstrain.getValueType()); - constrainByValue.setValueUnitOfMeasure(modifierValueConstrain - .getValueUnitOfMeasure()); - itemValueConstrainList.add(constrainByValue); - } - return itemValueConstrainList; - } - - protected ConceptType getConceptType() throws ConceptNotFoundException, - OntologyException { - if (conceptType==null){ - conceptType = getMetaDataFromOntologyCell(baseItem.getItemKey()); - } - - return conceptType; - } - - protected ConceptType getMetaDataFromOntologyCell(String itemKey) - throws ConceptNotFoundException, OntologyException { - ConceptType conceptType = null; - try { - conceptType = CallOntologyUtil.callOntology(itemKey, - parent.getSecurityType(), parent.getProjectId(), - QueryProcessorUtil.getInstance().getOntologyUrl()); - } catch (JAXBUtilException e) { - - log.error("Error while fetching metadata [" + itemKey - + "] from ontology ", e); - throw new OntologyException("Error while fetching metadata [" - + itemKey + "] from ontology " - + StackTraceUtil.getStackTrace(e)); - } catch (I2B2Exception e) { - log.error("Error while fetching metadata from ontology ", e); - throw new OntologyException("Error while fetching metadata [" - + itemKey + "] from ontology " - + StackTraceUtil.getStackTrace(e)); - } catch (AxisFault e) { - log.error("Error while fetching metadata from ontology ", e); - throw new OntologyException("Error while fetching metadata [" - + itemKey + "] from ontology " - + StackTraceUtil.getStackTrace(e)); - } catch (XMLStreamException e) { - log.error("Error while fetching metadata from ontology ", e); - throw new OntologyException("Error while fetching metadata [" - + itemKey + "] from ontology " - + StackTraceUtil.getStackTrace(e)); - } - - if (conceptType == null) { - throw new ConceptNotFoundException("[" + itemKey + "] "); - - } else { - String theData = conceptType.getDimcode(); - if (conceptType.getColumndatatype() != null - && conceptType.getColumndatatype().equalsIgnoreCase("T")) { - - if(parent.getServerType().equalsIgnoreCase(DAOFactoryHelper.SQLSERVER)){ - conceptType.setDimcode(StringUtil.escapeSQLSERVER(conceptType.getDimcode())); - } - else if(parent.getServerType().equalsIgnoreCase(DAOFactoryHelper.ORACLE)){ - conceptType.setDimcode(StringUtil.escapeORACLE(conceptType.getDimcode())); - } - - theData = SqlClauseUtil.handleMetaDataTextValue( - conceptType.getOperator(), conceptType.getDimcode()); - } else if (conceptType.getColumndatatype() != null - && conceptType.getColumndatatype().equalsIgnoreCase("N")) { - theData = SqlClauseUtil.handleMetaDataNumericValue( - conceptType.getOperator(), conceptType.getDimcode()); - } else if (conceptType.getColumndatatype() != null - && conceptType.getColumndatatype().equalsIgnoreCase("D")) { - theData = SqlClauseUtil.handleMetaDataDateValue( - conceptType.getOperator(), conceptType.getDimcode()); - } - conceptType.setDimcode(theData); - } - - return conceptType; - } - - - protected ModifierType getModifierMetadataFromOntology(String modifierKey, - String appliedPath) throws ConceptNotFoundException, - OntologyException { - ModifierType modifierType = null; - try { - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - String ontologyUrl = qpUtil - .getCRCPropertyValue(QueryProcessorUtil.ONTOLOGYCELL_ROOT_WS_URL_PROPERTIES); - String getModifierOperationName = qpUtil - .getCRCPropertyValue(QueryProcessorUtil.ONTOLOGYCELL_GETMODIFIERINFO_URL_PROPERTIES); - String ontologyGetModifierInfoUrl = ontologyUrl - + getModifierOperationName; - log.debug("Ontology getModifierinfo url from property file [" - + ontologyGetModifierInfoUrl + "]"); - - modifierType = CallOntologyUtil.callGetModifierInfo(modifierKey, - appliedPath, parent.getSecurityType(), - parent.getProjectId(), ontologyGetModifierInfoUrl); - - } catch (JAXBUtilException e) { - - log.error("Error while fetching metadata [" + modifierKey - + "] from ontology ", e); - throw new OntologyException("Error while fetching metadata [" - + modifierKey + "] from ontology " - + StackTraceUtil.getStackTrace(e)); - } catch (I2B2Exception e) { - log.error("Error while fetching metadata from ontology ", e); - throw new OntologyException("Error while fetching metadata [" - + modifierKey + "] from ontology " - + StackTraceUtil.getStackTrace(e)); - } catch (AxisFault e) { - log.error("Error while fetching metadata from ontology ", e); - throw new OntologyException("Error while fetching metadata [" - + modifierKey + "] from ontology " - + StackTraceUtil.getStackTrace(e)); - } catch (XMLStreamException e) { - log.error("Error while fetching metadata from ontology ", e); - throw new OntologyException("Error while fetching metadata [" - + modifierKey + "] from ontology " - + StackTraceUtil.getStackTrace(e)); - } - - if (modifierType == null) { - throw new ConceptNotFoundException( - "Error getting modifierinfo for modifier key [" - + modifierKey + "] and appliedPath [" + appliedPath - + "]"); - - } else { - String theData = modifierType.getDimcode(); - if (modifierType.getColumndatatype() != null - && modifierType.getColumndatatype().equalsIgnoreCase("T")) { - theData = SqlClauseUtil.handleMetaDataTextValue( - modifierType.getOperator(), modifierType.getDimcode()); - } else if (modifierType.getColumndatatype() != null - && modifierType.getColumndatatype().equalsIgnoreCase("N")) { - theData = SqlClauseUtil.handleMetaDataNumericValue( - modifierType.getOperator(), modifierType.getDimcode()); - } else if (modifierType.getColumndatatype() != null - && modifierType.getColumndatatype().equalsIgnoreCase("D")) { - theData = SqlClauseUtil.handleMetaDataDateValue( - modifierType.getOperator(), modifierType.getDimcode()); - } - modifierType.setDimcode(theData); - } - - return modifierType; - } - - protected String getPrimaryTableAlias(){ - String joinTableName = getJoinTable(); - - String tableAlias = "f"; - if (joinTableName.equalsIgnoreCase("visit_dimension")) - tableAlias = "e"; - else if (joinTableName.equalsIgnoreCase("patient_dimension")) - tableAlias = "p"; - - return tableAlias; - } - - public ItemType getItemType() { - return baseItem; - } - - public Integer getConceptTotal() { - return conceptTotal; - } - - public boolean isProtected() { - return isProtected; - } - public boolean hasModiferConstraint(){ - ItemType.ConstrainByModifier modifierConstrain = baseItem.getConstrainByModifier(); - if (modifierConstrain != null) { - return true; - } - else - return false; - } - - public boolean hasValueConstraint(){ - List valueConstrainList = baseItem.getConstrainByValue(); - if (valueConstrainList==null||valueConstrainList.size()==0) - return false; - else { - for (ConstrainByValue valueConstrain : valueConstrainList){ - if (valueConstrain!=null&&valueConstrain.getValueType()!=null) - return true; - } - return false; - } - } - - public boolean hasItemDateConstraint(){ - List constrainByDateList = baseItem.getConstrainByDate(); - if (constrainByDateList!=null){ - for (ConstrainByDate constrainByDate : constrainByDateList) { - if (constrainByDate!=null){ - if (constrainByDate.getDateTo()!=null||constrainByDate.getDateFrom()!=null) - return true; - } - } - } - return false; - } - - public boolean hasPanelDateConstraint(){ - return parent.hasPanelDateConstraint(); - } - - public boolean hasPanelOccurrenceConstraint(){ - return parent.hasPanelOccurrenceConstraint(); - } - - public boolean returnEncounterNum(){ - if (parent.getPanelTiming().equalsIgnoreCase(QueryTimingHandler.SAME)|| - parent.getPanelTiming().equalsIgnoreCase(QueryTimingHandler.SAMEVISIT)) - return true; - else - return false; - } - - public boolean returnInstanceNum(){ - if (parent.getPanelTiming().equalsIgnoreCase(QueryTimingHandler.SAMEINSTANCENUM)) - return true; - else - return false; - } - - public void addIgnoredMessage(String errorMessage) { - parent.addIgnoredMessage(errorMessage); - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Christopher Herrick + */ +package edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import javax.xml.stream.XMLStreamException; + +import org.apache.axis2.AxisFault; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.w3c.dom.Element; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.exception.StackTraceUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.ConceptNotFoundException; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.DateConstrainUtil; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.OntologyException; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.QueryTimingHandler; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.TotalItemOccurrenceHandler; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.UnitConverstionUtil; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.ValueConstrainsHandler; +import edu.harvard.i2b2.crc.datavo.ontology.ConceptType; +import edu.harvard.i2b2.crc.datavo.ontology.ModifierType; +import edu.harvard.i2b2.crc.datavo.ontology.XmlValueType; +import edu.harvard.i2b2.crc.datavo.pdo.query.TotOccuranceOperatorType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ConstrainValueType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ItemType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ItemType.ConstrainByDate; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ItemType.ConstrainByValue; +import edu.harvard.i2b2.crc.datavo.setfinder.query.PanelType.TotalItemOccurrences; +import edu.harvard.i2b2.crc.delegate.ontology.CallOntologyUtil; +import edu.harvard.i2b2.crc.util.ParamUtil; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; +import edu.harvard.i2b2.crc.util.SqlClauseUtil; +import edu.harvard.i2b2.crc.util.StringUtil; + + +/** + ** + * Temporal Panel Item + * + *

    + * Panel Item query object that wraps the item tag found in the query definition + * xml for panel items. It roughly corresponds to an item dropped into a panel in the query UI. PanelItem is responsible + * for generating the sql for an individual panel item. It implements the logic for the sql query + * and takes into account item value constraints, modifier constraints, item and panel based date constraints, + * and panel occurrences. This class is an abstract class and must be implemented by class dedicated to + * specific panel item types. + * + * @author Christopher Herrick + * + */ +public abstract class TemporalPanelItem { + + protected final Log log = LogFactory.getLog(getClass()); + protected final Log logesapi = LogFactory.getLog(getClass()); + + protected TemporalPanel parent = null; + + protected ItemType baseItem = null; + protected ConceptType conceptType = null; + protected ModifierType modifierType = null; + protected Integer conceptTotal; + protected String noLockSqlServer = " "; + + //Concept Type fields + protected String factTableColumn = null; + protected String tableName = null; + protected String dimCode = null; + protected String operator = null; + protected String columnName = null; + protected XmlValueType metaDataXml = null; + protected String factTable = "observation_fact"; + protected boolean isProtected = false; + protected String ontologyProtection = null; + + /** + * Constructor + * + * @param parent - TemporalPanel object to which this panle item belongs + * @param item - object representation of the xml from panel item contained in query definition xml + * @throws I2B2Exception - thrown when an i2b2 specific error is found + */ + public TemporalPanelItem(TemporalPanel parent, ItemType item) + throws I2B2Exception { + this.parent = parent; + this.baseItem = item; + parseItem(); + } + + /** + * Constructor + * + * @param parent - TemporalPanel object to which this panle item belongs + * @param item - object representation of the xml from panel item contained in query definition xml + * @param conceptType - object representation of the item obtained from the Ontology cell + * @throws I2B2Exception - thrown when an i2b2 specific error is found + */ + public TemporalPanelItem(TemporalPanel parent, ItemType item, ConceptType conceptType) + throws I2B2Exception { + this.parent = parent; + this.baseItem = item; + this.conceptType = conceptType; + parseItem(); + } + + /** + * Parse Item + * + * Parses through the item and/or concept type object and assigns key fields + * to the corresponding properties of the class. ParseItem is called from the constructor + * and must be executed before trying to build sql on the item. + * + * @throws I2B2Exception - thrown when an i2b2 specific error is found + */ + protected void parseItem() throws I2B2Exception { + if (conceptType==null){ + conceptType = getConceptType(); + } + if (conceptType != null) { + if (conceptType.getTotalnum() != null) { + conceptTotal = conceptType.getTotalnum(); + } + factTableColumn = conceptType.getFacttablecolumn(); + tableName = conceptType.getTablename(); + dimCode = conceptType.getDimcode(); + operator = conceptType.getOperator(); + columnName = conceptType.getColumnname(); + metaDataXml = conceptType.getMetadataxml(); + ontologyProtection = conceptType.getOntologyProtection(); + if (conceptType.getProtectedAccess() != null) + isProtected = (conceptType.getProtectedAccess().equalsIgnoreCase("Y")?true:false); + + // If protected check roles + if (isProtected) + { + Boolean protectedAccess = false; + String[] dataProt = {"DATA_PROT"}; + List ontologyProtection = Arrays.asList(conceptType.getOntologyProtection() == null || conceptType.getOntologyProtection().equals("")?dataProt:conceptType.getOntologyProtection().split(",")); + for (String s: parent.getUserRoles()) { + if (ontologyProtection.contains(s)) + protectedAccess = true; + + } + + if (protectedAccess == false) + throw new I2B2DAOException("This query contains protected."); + } + //OMOP addition + parseFactColumn(factTableColumn); + } + } + + /** + * Build Sql + * + * Main method for generating the sql string that will be run on the + * database for this item. Constructs sql based on logic for main item, value constraints, + * modifier constraints, date constraints, and occurrence constraints + * + * @return String - sql logic for querying based on the constraints represented in this item + * @throws I2B2DAOException - thrown when an i2b2 specific data or database error occurs + */ + protected String buildSql() throws I2B2DAOException { + + checkLargeTextConstrainPermission(); + + String sqlHintClause = buildSqlHintClause(); + String selectSql = buildSelectSql(); + String fromSql = buildFromSql(); + String dimensionJoinSql = buildDimensionJoinSql(); + String modifierConstraintSql = buildModifierConstraintSql(); + String[] modifierValueConstrainSql = buildModifierValueConstraintSql(); + String dateConstraintSql = buildItemDateConstraintSql(); + String[] valueConstraintSql = buildValueConstraintSql(); + String panelDateConstraintSql = buildPanelDateConstraintSql(); + String groupbyClause = buildGroupBySql(); + String havingClause = buildHavingSql(); + + if (parent.getAccuracyScale()>0&& + valueConstraintSql[1]!=null&& + valueConstraintSql[1].trim().length()>0) { + fromSql += valueConstraintSql[1]; + } + + if (parent.getAccuracyScale() >0& + modifierValueConstrainSql[1]!=null&& + modifierValueConstrainSql[1].trim().length()>0) { + fromSql += modifierValueConstrainSql[1]; + } + + String derivedTableSql = " select " + sqlHintClause + + selectSql + + " \nfrom " + fromSql + + " \nwhere " + + formatSql(dimensionJoinSql) + " " + + formatSql(modifierConstraintSql) + + formatSql(modifierValueConstrainSql[0]) + + formatSql(valueConstraintSql[0]) + + formatSql(dateConstraintSql) + + formatSql(panelDateConstraintSql) + + " \ngroup by " + groupbyClause + + formatSql(havingClause); + logesapi.debug("Derived table sql [" + derivedTableSql + "]"); + + return derivedTableSql; + } + + /** + * Format Sql + * + * Method for adding carriage returns into sql so statements are more + * readable when output to error and logs + * + * @param sql String to be formatted + * @return String formatted sql string + */ + private String formatSql(String sql){ + if (sql!=null&&sql.trim().length()>0) + return "\n" + sql; + else + return ""; + } + + + /** + * Build Select Sql + * + * Construct the sql SELECT clause for this item. Determines which columns should be + * returned by the query + * + * @return String sql SELECT clause for use in larger statement + */ + protected String buildSelectSql(){ + return buildSelectSql(getPrimaryTableAlias()); + } + + /** + * Build Select Sql + * + * Construct the sql SELECT clause for this item. Determines which columns should be + * returned by the query + * + * @param tableAlias String used to alias all columns contained in the select statement + * @return String sql SELECT clause for use in larger statement + */ + protected String buildSelectSql(String tableAlias){ + + if (tableAlias!=null&&tableAlias.trim().length()>0) + tableAlias += "."; + + String selectClause = tableAlias + "patient_num "; + + if (this.returnInstanceNum()) { + selectClause = " " + tableAlias + "provider_id, " + + tableAlias + "start_date, " + + tableAlias + "concept_cd, " + + tableAlias + "instance_num, " + + tableAlias + "encounter_num, " + + selectClause; + } else if (this.returnEncounterNum()) { + selectClause = " " + tableAlias + "encounter_num, " + + selectClause; + } + + if (parent.hasPanelOccurrenceConstraint() && + parent.applyOccurrenceToPanelLevel() && + (parent.getItemList().size()>1 || + !parent.isPatientOnlyQuery())){ + selectClause += ", " + buildFactCountSql(tableAlias) + " "; + } + + return selectClause; + } + + /** + * Build Sql Hint Clause + * + * Returns any database specific sql syntax used to guid the database optimizer in + * choosing an execution plan or index to use + * + * @return String sql clause that contains database specific parameters for passing sql hints to optimizer + */ + protected String buildSqlHintClause(){ + return " "; + } + + /** + * Build From Sql + * + * Construct the sql FROM clause for this item. Determines which tables should be + * referenced and joined to in the item query + * + * @return String sql FROM clause that contains tables used in this item query + */ + protected String buildFromSql(){ + return buildFromSql(getPrimaryTableAlias()); + } + + /** + * Build From Sql + * + * Construct the sql FROM clause for this item. Determines which tables should be + * referenced and joined to in the item query + * + * @param tableAlias String used to alias the table in the from clause + * @return String sql FROM clause that contains tables used in this item query + */ + protected String buildFromSql(String tableAlias){ + String joinTableName = parent.getDatabaseSchema() + getJoinTable(); + + if (tableAlias!=null&&tableAlias.trim().length()>0) + joinTableName += " " + tableAlias; + + return joinTableName; + } + + + /** + * Build Dimension Join Sql + * + * Construct the sql FROM clause for this item. Determines which tables should be + * referenced and joined to in the item query. Use the default table alias. + * + * @return String sql FROM clause that contains tables used in this item query + */ + protected String buildDimensionJoinSql(){ + return buildDimensionJoinSql(getPrimaryTableAlias()); + } + + /** + * Build Dimension Join Sql + * + * Construct the sql FROM clause for this item. Determines which tables should be + * referenced and joined to in the item query + * + * @param tableAlias String used to alias the table in the from clause + * @return String sql FROM clause that contains tables used in this item query + */ + protected String buildDimensionJoinSql(String tableAlias) { + String dimensionSql = ""; + + if (tableAlias!=null&&tableAlias.trim().length()>0) + tableAlias += "."; + + if ((this.operator!=null)&& + (this.operator.toUpperCase().equals("LIKE"))&& + (this.dimCode!=null) && (parent.getServerType().equalsIgnoreCase("POSTGRESQL"))) + { + this.dimCode = this.dimCode.replaceAll("\\\\", "\\\\\\\\"); + + } + dimensionSql = tableAlias + this.factTableColumn + " IN (select " + + this.factTableColumn + " from " + noLockSqlServer + + parent.getDatabaseSchema() + this.tableName + + " " + " where " + this.columnName + " " + + this.operator + " " + this.dimCode; + + if ((this.operator!=null)&& + (this.operator.toUpperCase().equals("LIKE"))&& + (this.dimCode!=null)&& + (this.dimCode.contains("?"))) + { + dimensionSql += (!parent.getDataSourceLookup().getServerType().toUpperCase().equals("POSTGRESQL") ? " {ESCAPE '?'} " : "" ) ; + } + dimensionSql += ")"; + return dimensionSql; + } + + /** + * Build Item Date Constraint Sql + * + * Construct sql WHERE constraint statements that constrain this item by date. These date constraints orignate + * at the item level and not at the panel level. + * + * @return String sql constraint clause to be appended to the WHERE clause generated by this item + */ + protected String buildItemDateConstraintSql() { + return buildItemDateConstraintSql(getPrimaryTableAlias()); + } + + + /** + * Build Item Date Constraint Sql + * + * Construct sql WHERE constraint statements that constrain this item by date. These date constraints orignate + * at the item level and not at the panel level. + * + * @param tableAlias String used to alias the table that is being constrained + * @return String sql constraint clause to be appended to the WHERE clause generated by this item + */ + protected String buildItemDateConstraintSql(String tableAlias) { + // generate sql for item date constrain + DateConstrainUtil dateConstrainUtil = new DateConstrainUtil( + parent.getDataSourceLookup()); + String itemDateConstrainSql = dateConstrainUtil + .buildItemDateSql(baseItem, tableAlias); + if (itemDateConstrainSql != null + && itemDateConstrainSql.trim().length() > 0) { + log.info("Item date constrain sql" + itemDateConstrainSql); + itemDateConstrainSql = " AND ( " + itemDateConstrainSql + " ) "; + } else { + itemDateConstrainSql = ""; + } + return itemDateConstrainSql; + } + + protected String[] buildValueConstraintSql() + throws I2B2DAOException { + + // generate sql for unit_cd conversion + String unitCdSwitchClause = "", unitCdInClause = ""; + + if (parent.getProjectParameterMap() != null + && parent.getProjectParameterMap().get(ParamUtil.CRC_ENABLE_UNITCD_CONVERSION) != null) { + String unitCdConversionFlag = (String) parent.getProjectParameterMap().get(ParamUtil.CRC_ENABLE_UNITCD_CONVERSION); + if (unitCdConversionFlag != null + && unitCdConversionFlag.equalsIgnoreCase("ON")) { + if (metaDataXml != null + && metaDataXml.getAny().get(0) != null) { + Element valueMetadataElement = metaDataXml.getAny().get(0); + UnitConverstionUtil unitConverstionUtil = new UnitConverstionUtil(); + unitCdSwitchClause = unitConverstionUtil + .buildUnitCdSwitchClause(valueMetadataElement, + false, ""); + log.debug("concept unit Conversion sql " + + unitCdSwitchClause); + unitCdInClause = unitConverstionUtil.buildUnitCdInClause( + valueMetadataElement, ""); + + } + } + } + + ValueConstrainsHandler valueConstrainHandler = new ValueConstrainsHandler(); + if (unitCdSwitchClause.length() > 0) { + valueConstrainHandler.setUnitCdConversionFlag(true, unitCdInClause, + unitCdSwitchClause); + } + + String[] itemValueConstrainSql = valueConstrainHandler + .constructValueConstainClause(baseItem.getConstrainByValue(), + parent.getServerType(), parent.getDatabaseSchema(), + parent.getAccuracyScale(), true); + log.info("Item value constrain sql " + itemValueConstrainSql); + + if (itemValueConstrainSql != null + && itemValueConstrainSql[0].trim().length() > 0) { + + itemValueConstrainSql[0] = " AND ( " + itemValueConstrainSql[0] + + " )"; + } else { + itemValueConstrainSql[0] = ""; + } + return itemValueConstrainSql; + } + + protected String[] buildModifierValueConstraintSql() + throws I2B2DAOException { + + if (modifierType==null){ + modifierType = getModifierMetadataFromOntology(); + } + + if (modifierType==null) + return new String[] { "", "" }; + + String modifierUnitCdSwitchClause = "", modifierUnitCdInClause = ""; + + if (parent.getProjectParameterMap() != null + && parent.getProjectParameterMap().get( + ParamUtil.CRC_ENABLE_UNITCD_CONVERSION) != null) { + String unitCdConversionFlag = (String) parent + .getProjectParameterMap().get( + ParamUtil.CRC_ENABLE_UNITCD_CONVERSION); + if (unitCdConversionFlag != null + && unitCdConversionFlag.equalsIgnoreCase("ON")) { + if (modifierType != null + && modifierType.getMetadataxml() != null + && modifierType.getMetadataxml().getAny().get(0) != null) { + Element valueMetadataElement = modifierType + .getMetadataxml().getAny().get(0); + UnitConverstionUtil unitConverstionUtil = new UnitConverstionUtil(); + modifierUnitCdSwitchClause = unitConverstionUtil + .buildUnitCdSwitchClause(valueMetadataElement, + false, ""); + log.debug("modifier unit Conversion sql " + + modifierUnitCdSwitchClause); + modifierUnitCdInClause = unitConverstionUtil + .buildUnitCdInClause(valueMetadataElement, ""); + + } + } + } + + ValueConstrainsHandler valueConstrainHandler = new ValueConstrainsHandler(); + if (modifierUnitCdSwitchClause.length() > 0) { + valueConstrainHandler.setUnitCdConversionFlag(true, + modifierUnitCdInClause, modifierUnitCdSwitchClause); + } + + + String itemModifierValueConstrainSql[] = new String[] { "", "" }; + + if (baseItem.getConstrainByModifier() != null + && baseItem.getConstrainByModifier().getConstrainByValue() != null) { + List itemValueConstrainList = getModifierItemValueConstrain(baseItem.getConstrainByModifier().getConstrainByValue()); + itemModifierValueConstrainSql = valueConstrainHandler + .constructValueConstainClause(itemValueConstrainList, + parent.getServerType(), parent.getDatabaseSchema(), + parent.getAccuracyScale(), false); + if (itemModifierValueConstrainSql != null + && itemModifierValueConstrainSql[0].length() > 0) { + log.info("Modifier constrian value constrain sql " + + itemModifierValueConstrainSql); + } + } + + if (itemModifierValueConstrainSql[0] != null + && itemModifierValueConstrainSql[0].trim().length() > 0) { + + itemModifierValueConstrainSql[0] = " AND ( " + + itemModifierValueConstrainSql[0] + " )"; + } else { + itemModifierValueConstrainSql[0] = ""; + } + return itemModifierValueConstrainSql; + } + + protected String buildModifierConstraintSql() throws I2B2DAOException { + return buildModifierConstraintSql(getPrimaryTableAlias()); + } + + protected String buildModifierConstraintSql(String tableAlias) throws I2B2DAOException { + if (modifierType==null) + modifierType = getModifierMetadataFromOntology(); + + if (modifierType==null) + return ""; + + if (tableAlias!=null&&tableAlias.trim().length()>0) + tableAlias += "."; + + String dimPath = "", dimColumnName = "", dimCode = "", dimOperator = "", dimTableName = "", factTableColumn = ""; + + String itemModifierConstrainSql = null; + if (modifierType != null) { + dimPath = modifierType.getFullname(); + dimColumnName = modifierType.getColumnname(); + dimCode = modifierType.getDimcode(); + dimOperator = modifierType.getOperator(); + dimTableName = modifierType.getTablename(); + factTableColumn = modifierType.getFacttablecolumn(); + + if (dimPath == null || dimColumnName == null || dimCode == null + || dimOperator == null || dimTableName == null + || factTableColumn == null) { + throw new I2B2DAOException( + "Error modifier constrain information has null value path [" + + dimPath + "] column name [" + dimColumnName + + "] dim code [" + dimCode + + "] dim operator [ " + dimOperator + + "] dim table name [" + dimTableName + + "] fact table column [" + factTableColumn + + "]"); + } + } + + dimPath.replaceAll("'", "''"); + + if ((dimOperator != null) && (dimOperator.toUpperCase().equals("LIKE") + && (parent.getDataSourceLookup().getServerType().toUpperCase().equals("POSTGRESQL")))) + dimCode = dimCode.replaceAll("\\\\", "\\\\\\\\"); + + + + itemModifierConstrainSql = " (" + tableAlias + factTableColumn + " IN " + + "(select " + factTableColumn + + " from " + parent.getDatabaseSchema() + dimTableName + + " where " + dimColumnName + " " + dimOperator + " " + dimCode; + + if ((dimOperator != null) && (dimOperator.toUpperCase().equals("LIKE")) + && (dimCode != null) && (dimCode.contains("?"))) { + itemModifierConstrainSql += (!parent.getDataSourceLookup().getServerType().toUpperCase().equals("POSTGRESQL") ? " {ESCAPE '?'} " : "" ) ; + } + itemModifierConstrainSql += ")) "; + + if (itemModifierConstrainSql != null + && itemModifierConstrainSql.trim().length() > 0) { + log.info("Item modifier constrain sql" + itemModifierConstrainSql); + itemModifierConstrainSql = " AND " + itemModifierConstrainSql; + } else { + itemModifierConstrainSql = " "; + } + + return itemModifierConstrainSql; + } + + protected String buildPanelDateConstraintSql(){ + return buildPanelDateConstraintSql(getPrimaryTableAlias()); + } + + protected String buildPanelDateConstraintSql(String tableAlias){ + String panelDateConstraintSql = parent.buildDateConstraintSql(tableAlias); + if (panelDateConstraintSql!=null&&panelDateConstraintSql.trim().length() > 0) { + panelDateConstraintSql = " AND ( " + panelDateConstraintSql + " )"; + } + + return panelDateConstraintSql; + } + + protected String buildGroupBySql(){ + return buildGroupBySql(getPrimaryTableAlias()); + } + + protected String buildGroupBySql(String tableAlias){ + // check if the dimensionJoinSql is query in query with fact constrains + String groupbyClause = ""; + + if (tableAlias!=null&&tableAlias.trim().length()>0) + tableAlias += "."; + + if (this.returnInstanceNum()) { + groupbyClause = " " + tableAlias + "encounter_num ," + + tableAlias + "instance_num, " + + tableAlias + "concept_cd," + tableAlias + + "start_date," + tableAlias + "provider_id,"; + } + else if (this.returnEncounterNum()){ + groupbyClause = " " + tableAlias + "encounter_num ,"; + } + + groupbyClause += " " + tableAlias + "patient_num "; + + return groupbyClause; + } + + protected String buildFactCountSql(String tableAlias){ + TotalItemOccurrences totalOccur = parent.getTotalOccurrences(); + + if (tableAlias!=null&&tableAlias.trim().length()>0&&!tableAlias.endsWith(".")) + tableAlias += "."; + + if (totalOccur != null) { + if ((totalOccur.getOperator() != null + && totalOccur.getOperator().value() != null + && totalOccur.getOperator().value().equalsIgnoreCase(TotOccuranceOperatorType.GE.value())) + && totalOccur.getValue() == 1) { + } else { + String countDistinct = "*"; + if (parent.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER) ) { + countDistinct = " distinct cast(" + tableAlias + "patient_num as varchar) + '|' + cast(" + tableAlias + "encounter_num as varchar) + '|' + " + + " " + tableAlias + "provider_id + '|' + cast(" + tableAlias + "start_date as varchar) + '|' + cast(" + tableAlias + "instance_num as varchar) + '|' + " + tableAlias + "concept_cd"; + } else if (parent.getServerType().equalsIgnoreCase( + DAOFactoryHelper.ORACLE) || parent.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) { + countDistinct = " distinct " + tableAlias + "patient_num || '|' || " + tableAlias + "encounter_num || '|' || " + + tableAlias + "provider_id || '|' || " + tableAlias + "instance_num || '|' ||" + tableAlias + "concept_cd || '|' ||cast(" + tableAlias + "start_date as varchar(50))"; + } + + return "count(" + countDistinct + ") as fact_count"; + } + } + + return ""; + } + + protected String buildHavingSql(){ + return buildHavingSql(getPrimaryTableAlias()); + } + + protected String buildHavingSql(String tableAlias){ + TotalItemOccurrences totalOccur = parent.getTotalOccurrences(); + + TotalItemOccurrenceHandler totalItemOccurrencHandler = new TotalItemOccurrenceHandler(); + String totalItemOccurrenceClause = totalItemOccurrencHandler.buildTotalItemOccurrenceClause(totalOccur); + + String havingSql = " "; + + if (tableAlias!=null&&tableAlias.trim().length()>0) + tableAlias += "."; + + if ((!parent.applyOccurrenceToPanelLevel()||parent.getItemList().size()==1) && totalOccur != null) { + if ((totalOccur.getOperator() != null + && totalOccur.getOperator().value() != null + && totalOccur.getOperator().value().equalsIgnoreCase(TotOccuranceOperatorType.GE.value())) + && totalOccur.getValue() == 1) { + } else { + log.debug("Setfinder query total occurrences operator value [" + + totalOccur.getOperator().value() + "]"); + String countDistinct = "*"; + if (parent.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER) ) { + countDistinct = " distinct cast(" + tableAlias + "patient_num as varchar) + '|' + cast(" + tableAlias + "encounter_num as varchar) + '|' + " + + " " + tableAlias + "provider_id + '|' + cast(" + tableAlias + "start_date as varchar) + '|' + cast(" + tableAlias + "instance_num as varchar) + '|' + " + tableAlias + "concept_cd"; + } else if (parent.getServerType().equalsIgnoreCase( + DAOFactoryHelper.ORACLE) || parent.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) { + countDistinct = " distinct " + tableAlias + "patient_num || '|' || " + tableAlias + "encounter_num || '|' || " + + tableAlias + "provider_id || '|' || " + tableAlias + "instance_num || '|' ||" + tableAlias + "concept_cd || '|' ||cast(" + tableAlias + "start_date as varchar(50))"; + } + havingSql = " having count(" + countDistinct + ") " + + totalItemOccurrenceClause; + } + } + + return havingSql; + } + + public void parseFactColumn(String factColumnName){ + this.factTable= "observation_fact"; + this.factTableColumn = factColumnName; + if (this.parent.getQueryOptions()!=null&&this.parent.getQueryOptions().useDerivedFactTable()) + { + if (factColumnName!=null&&factColumnName.contains(".")){ + int lastIndex = factColumnName.lastIndexOf("."); + this.factTable= factColumnName.substring(0, lastIndex); + if ((lastIndex+1) getModifierItemValueConstrain( + List modifierConstrainList) { + List itemValueConstrainList = new ArrayList(); + for (ItemType.ConstrainByModifier.ConstrainByValue modifierValueConstrain : modifierConstrainList) { + ItemType.ConstrainByValue constrainByValue = new ItemType.ConstrainByValue(); + constrainByValue.setValueConstraint(modifierValueConstrain + .getValueConstraint()); + constrainByValue.setValueOperator(modifierValueConstrain + .getValueOperator()); + constrainByValue + .setValueType(modifierValueConstrain.getValueType()); + constrainByValue.setValueUnitOfMeasure(modifierValueConstrain + .getValueUnitOfMeasure()); + itemValueConstrainList.add(constrainByValue); + } + return itemValueConstrainList; + } + + protected ConceptType getConceptType() throws ConceptNotFoundException, + OntologyException { + if (conceptType==null){ + conceptType = getMetaDataFromOntologyCell(baseItem.getItemKey()); + } + + return conceptType; + } + + protected ConceptType getMetaDataFromOntologyCell(String itemKey) + throws ConceptNotFoundException, OntologyException { + ConceptType conceptType = null; + try { + conceptType = CallOntologyUtil.callOntology(itemKey, + parent.getSecurityType(), parent.getProjectId(), + QueryProcessorUtil.getInstance().getOntologyUrl()); + } catch (JAXBUtilException e) { + + log.error("Error while fetching metadata [" + itemKey + + "] from ontology ", e); + throw new OntologyException("Error while fetching metadata [" + + itemKey + "] from ontology " + + StackTraceUtil.getStackTrace(e)); + } catch (I2B2Exception e) { + log.error("Error while fetching metadata from ontology ", e); + throw new OntologyException("Error while fetching metadata [" + + itemKey + "] from ontology " + + StackTraceUtil.getStackTrace(e)); + } catch (AxisFault e) { + log.error("Error while fetching metadata from ontology ", e); + throw new OntologyException("Error while fetching metadata [" + + itemKey + "] from ontology " + + StackTraceUtil.getStackTrace(e)); + } catch (XMLStreamException e) { + log.error("Error while fetching metadata from ontology ", e); + throw new OntologyException("Error while fetching metadata [" + + itemKey + "] from ontology " + + StackTraceUtil.getStackTrace(e)); + } + + if (conceptType == null) { + throw new ConceptNotFoundException("[" + itemKey + "] "); + + } else { + String theData = conceptType.getDimcode(); + if (conceptType.getColumndatatype() != null + && conceptType.getColumndatatype().equalsIgnoreCase("T")) { + + if(parent.getServerType().equalsIgnoreCase(DAOFactoryHelper.SQLSERVER)){ + conceptType.setDimcode(StringUtil.escapeSQLSERVER(conceptType.getDimcode())); + } + else if(parent.getServerType().equalsIgnoreCase(DAOFactoryHelper.ORACLE)){ + conceptType.setDimcode(StringUtil.escapeORACLE(conceptType.getDimcode())); + } + + theData = SqlClauseUtil.handleMetaDataTextValue( + conceptType.getOperator(), conceptType.getDimcode()); + } else if (conceptType.getColumndatatype() != null + && conceptType.getColumndatatype().equalsIgnoreCase("N")) { + theData = SqlClauseUtil.handleMetaDataNumericValue( + conceptType.getOperator(), conceptType.getDimcode()); + } else if (conceptType.getColumndatatype() != null + && conceptType.getColumndatatype().equalsIgnoreCase("D")) { + theData = SqlClauseUtil.handleMetaDataDateValue( + conceptType.getOperator(), conceptType.getDimcode()); + } + conceptType.setDimcode(theData); + } + + return conceptType; + } + + + protected ModifierType getModifierMetadataFromOntology(String modifierKey, + String appliedPath) throws ConceptNotFoundException, + OntologyException { + ModifierType modifierType = null; + try { + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + String ontologyUrl = qpUtil + .getCRCPropertyValue(QueryProcessorUtil.ONTOLOGYCELL_ROOT_WS_URL_PROPERTIES); + String getModifierOperationName = qpUtil + .getCRCPropertyValue(QueryProcessorUtil.ONTOLOGYCELL_GETMODIFIERINFO_URL_PROPERTIES); + String ontologyGetModifierInfoUrl = ontologyUrl + + getModifierOperationName; + log.debug("Ontology getModifierinfo url from property file [" + + ontologyGetModifierInfoUrl + "]"); + + modifierType = CallOntologyUtil.callGetModifierInfo(modifierKey, + appliedPath, parent.getSecurityType(), + parent.getProjectId(), ontologyGetModifierInfoUrl); + + } catch (JAXBUtilException e) { + + log.error("Error while fetching metadata [" + modifierKey + + "] from ontology ", e); + throw new OntologyException("Error while fetching metadata [" + + modifierKey + "] from ontology " + + StackTraceUtil.getStackTrace(e)); + } catch (I2B2Exception e) { + log.error("Error while fetching metadata from ontology ", e); + throw new OntologyException("Error while fetching metadata [" + + modifierKey + "] from ontology " + + StackTraceUtil.getStackTrace(e)); + } catch (AxisFault e) { + log.error("Error while fetching metadata from ontology ", e); + throw new OntologyException("Error while fetching metadata [" + + modifierKey + "] from ontology " + + StackTraceUtil.getStackTrace(e)); + } catch (XMLStreamException e) { + log.error("Error while fetching metadata from ontology ", e); + throw new OntologyException("Error while fetching metadata [" + + modifierKey + "] from ontology " + + StackTraceUtil.getStackTrace(e)); + } + + if (modifierType == null) { + throw new ConceptNotFoundException( + "Error getting modifierinfo for modifier key [" + + modifierKey + "] and appliedPath [" + appliedPath + + "]"); + + } else { + String theData = modifierType.getDimcode(); + if (modifierType.getColumndatatype() != null + && modifierType.getColumndatatype().equalsIgnoreCase("T")) { + theData = SqlClauseUtil.handleMetaDataTextValue( + modifierType.getOperator(), modifierType.getDimcode()); + } else if (modifierType.getColumndatatype() != null + && modifierType.getColumndatatype().equalsIgnoreCase("N")) { + theData = SqlClauseUtil.handleMetaDataNumericValue( + modifierType.getOperator(), modifierType.getDimcode()); + } else if (modifierType.getColumndatatype() != null + && modifierType.getColumndatatype().equalsIgnoreCase("D")) { + theData = SqlClauseUtil.handleMetaDataDateValue( + modifierType.getOperator(), modifierType.getDimcode()); + } + modifierType.setDimcode(theData); + } + + return modifierType; + } + + protected String getPrimaryTableAlias(){ + String joinTableName = getJoinTable(); + + String tableAlias = "f"; + if (joinTableName.equalsIgnoreCase("visit_dimension")) + tableAlias = "e"; + else if (joinTableName.equalsIgnoreCase("patient_dimension")) + tableAlias = "p"; + + return tableAlias; + } + + public ItemType getItemType() { + return baseItem; + } + + public Integer getConceptTotal() { + return conceptTotal; + } + + public boolean isProtected() { + return isProtected; + } + public boolean hasModiferConstraint(){ + ItemType.ConstrainByModifier modifierConstrain = baseItem.getConstrainByModifier(); + if (modifierConstrain != null) { + return true; + } + else + return false; + } + + public boolean hasValueConstraint(){ + List valueConstrainList = baseItem.getConstrainByValue(); + if (valueConstrainList==null||valueConstrainList.size()==0) + return false; + else { + for (ConstrainByValue valueConstrain : valueConstrainList){ + if (valueConstrain!=null&&valueConstrain.getValueType()!=null) + return true; + } + return false; + } + } + + public boolean hasItemDateConstraint(){ + List constrainByDateList = baseItem.getConstrainByDate(); + if (constrainByDateList!=null){ + for (ConstrainByDate constrainByDate : constrainByDateList) { + if (constrainByDate!=null){ + if (constrainByDate.getDateTo()!=null||constrainByDate.getDateFrom()!=null) + return true; + } + } + } + return false; + } + + public boolean hasPanelDateConstraint(){ + return parent.hasPanelDateConstraint(); + } + + public boolean hasPanelOccurrenceConstraint(){ + return parent.hasPanelOccurrenceConstraint(); + } + + public boolean returnEncounterNum(){ + if (parent.getPanelTiming().equalsIgnoreCase(QueryTimingHandler.SAME)|| + parent.getPanelTiming().equalsIgnoreCase(QueryTimingHandler.SAMEVISIT)) + return true; + else + return false; + } + + public boolean returnInstanceNum(){ + if (parent.getPanelTiming().equalsIgnoreCase(QueryTimingHandler.SAMEINSTANCENUM)) + return true; + else + return false; + } + + public void addIgnoredMessage(String errorMessage) { + parent.addIgnoredMessage(errorMessage); + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalPanelPatientEncounterSetItem.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalPanelPatientEncounterSetItem.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalPanelPatientEncounterSetItem.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalPanelPatientEncounterSetItem.java index fe363007..b7a1e087 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalPanelPatientEncounterSetItem.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalPanelPatientEncounterSetItem.java @@ -1,91 +1,91 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Christopher Herrick - */ -package edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.ConceptNotFoundException; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.OntologyException; -import edu.harvard.i2b2.crc.datavo.ontology.ConceptType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ItemType; - -public class TemporalPanelPatientEncounterSetItem extends TemporalPanelItem { - - public TemporalPanelPatientEncounterSetItem(TemporalPanel parent, ItemType item) - throws I2B2Exception { - super(parent, item); - } - - - @Override - protected String buildSql() throws I2B2DAOException { - if (this.returnInstanceNum()|| - this.hasItemDateConstraint()|| - this.hasModiferConstraint()|| - this.hasPanelDateConstraint()|| - this.hasPanelOccurrenceConstraint()|| - this.hasValueConstraint() - ){ - return super.buildSql(); - } - else{ - String selectClause = "select patient_num "; - if (this.returnEncounterNum()) - selectClause = "select encounter_num, patient_num "; - return selectClause + " from " + noLockSqlServer - + parent.getDatabaseSchema() + this.tableName - + " " + " where " + this.columnName + " " - + this.operator + " " + this.dimCode - + ""; - } - } - - - @Override - protected ConceptType getConceptType() throws ConceptNotFoundException, - OntologyException { - if (conceptType==null){ - String itemKey = baseItem.getItemKey(); - - String[] encounterSetId = itemKey.split(":"); - if (encounterSetId[1] != null) { - conceptType = new ConceptType(); - conceptType.setColumnname(" result_instance_id "); - conceptType.setOperator(" = "); - conceptType.setFacttablecolumn(" encounter_num "); - conceptType.setTablename("qt_patient_enc_collection "); - conceptType.setDimcode(encounterSetId[1]); - } - } - - return conceptType; - } - - @Override - protected String getJoinTable() { - if (this.returnInstanceNum()|| - hasItemDateConstraint()|| - hasPanelDateConstraint()|| - hasValueConstraint()|| - hasPanelOccurrenceConstraint()) { - return "observation_fact"; - } else if (this.returnEncounterNum()) { - return "visit_dimension"; - } else { - return "qt_patient_set_collection"; - } - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Christopher Herrick + */ +package edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.ConceptNotFoundException; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.OntologyException; +import edu.harvard.i2b2.crc.datavo.ontology.ConceptType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ItemType; + +public class TemporalPanelPatientEncounterSetItem extends TemporalPanelItem { + + public TemporalPanelPatientEncounterSetItem(TemporalPanel parent, ItemType item) + throws I2B2Exception { + super(parent, item); + } + + + @Override + protected String buildSql() throws I2B2DAOException { + if (this.returnInstanceNum()|| + this.hasItemDateConstraint()|| + this.hasModiferConstraint()|| + this.hasPanelDateConstraint()|| + this.hasPanelOccurrenceConstraint()|| + this.hasValueConstraint() + ){ + return super.buildSql(); + } + else{ + String selectClause = "select patient_num "; + if (this.returnEncounterNum()) + selectClause = "select encounter_num, patient_num "; + return selectClause + " from " + noLockSqlServer + + parent.getDatabaseSchema() + this.tableName + + " " + " where " + this.columnName + " " + + this.operator + " " + this.dimCode + + ""; + } + } + + + @Override + protected ConceptType getConceptType() throws ConceptNotFoundException, + OntologyException { + if (conceptType==null){ + String itemKey = baseItem.getItemKey(); + + String[] encounterSetId = itemKey.split(":"); + if (encounterSetId[1] != null) { + conceptType = new ConceptType(); + conceptType.setColumnname(" result_instance_id "); + conceptType.setOperator(" = "); + conceptType.setFacttablecolumn(" encounter_num "); + conceptType.setTablename("qt_patient_enc_collection "); + conceptType.setDimcode(encounterSetId[1]); + } + } + + return conceptType; + } + + @Override + protected String getJoinTable() { + if (this.returnInstanceNum()|| + hasItemDateConstraint()|| + hasPanelDateConstraint()|| + hasValueConstraint()|| + hasPanelOccurrenceConstraint()) { + return "observation_fact"; + } else if (this.returnEncounterNum()) { + return "visit_dimension"; + } else { + return "qt_patient_set_collection"; + } + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalPanelPatientItem.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalPanelPatientItem.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalPanelPatientItem.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalPanelPatientItem.java index b42bdb14..62ffb92d --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalPanelPatientItem.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalPanelPatientItem.java @@ -1,129 +1,129 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Christopher Herrick - */ -package edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.ConceptNotFoundException; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.OntologyException; -import edu.harvard.i2b2.crc.datavo.ontology.ConceptType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ItemType; - -public class TemporalPanelPatientItem extends TemporalPanelItem { - - public TemporalPanelPatientItem(TemporalPanel parent, ItemType item) - throws I2B2Exception { - super(parent, item); - } - - - @Override - protected String buildSql() throws I2B2DAOException { - if (this.returnEncounterNum()|| - this.returnInstanceNum()|| - this.hasItemDateConstraint()|| - this.hasModiferConstraint()|| - this.hasPanelDateConstraint()|| - this.hasPanelOccurrenceConstraint()|| - this.hasValueConstraint() - ){ - return super.buildSql(); - } - else{ - String itemKey = baseItem.getItemKey(); - - String[] patientId = itemKey.split(":"); - if (patientId.length > 2 && - patientId[1] != null && - patientId[2] != null) { - return "select " - + "patient_num from " + noLockSqlServer - + parent.getDatabaseSchema() + "patient_mapping " - + "where patient_ide_source = '" + patientId[1] + "' " - + "and patient_ide = '" + patientId[2] + "' " - + ""; - } - else - return null; - } - } - - - @Override - protected ConceptType getConceptType() throws ConceptNotFoundException, - OntologyException { - if (conceptType==null){ - String itemKey = baseItem.getItemKey(); - - String[] patientId = itemKey.split(":"); - if (patientId.length > 2 && - patientId[1] != null && - //patientId[1].trim().toUpperCase().equals("HIVE") && - patientId[2] != null) { - String patientNum = patientId[2]; - conceptType = new ConceptType(); - conceptType.setColumnname(" patient_num "); - conceptType.setOperator(" = "); - conceptType.setFacttablecolumn(" patient_num "); - conceptType.setTablename("patient_mapping "); - conceptType.setDimcode(patientNum); - } - } - - return conceptType; - } - - - @Override - protected String buildDimensionJoinSql(String tableAlias) { - String dimensionSql = ""; - - if (tableAlias!=null&&tableAlias.trim().length()>0) - tableAlias += "."; - - String itemKey = baseItem.getItemKey(); - - String[] patientId = itemKey.split(":"); - if (patientId.length > 2 && - patientId[1] != null && - patientId[2] != null) { - - dimensionSql = tableAlias + this.factTableColumn + " IN (select " - + "patient_num from " + noLockSqlServer - + parent.getDatabaseSchema() + "patient_mapping " - + "where patient_ide_source = '" + patientId[1] + "' " - + "and patient_ide = '" + patientId[2] + "' " - + ")"; - } - - return dimensionSql; - } - - - @Override - protected String getJoinTable() { - if (this.returnInstanceNum()|| - hasItemDateConstraint()|| - hasPanelDateConstraint()|| - hasValueConstraint()|| - hasPanelOccurrenceConstraint()) { - return "observation_fact"; - } else if (this.returnEncounterNum()) { - return "visit_dimension"; - } else { - return "patient_dimension"; - } - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Christopher Herrick + */ +package edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.ConceptNotFoundException; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.OntologyException; +import edu.harvard.i2b2.crc.datavo.ontology.ConceptType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ItemType; + +public class TemporalPanelPatientItem extends TemporalPanelItem { + + public TemporalPanelPatientItem(TemporalPanel parent, ItemType item) + throws I2B2Exception { + super(parent, item); + } + + + @Override + protected String buildSql() throws I2B2DAOException { + if (this.returnEncounterNum()|| + this.returnInstanceNum()|| + this.hasItemDateConstraint()|| + this.hasModiferConstraint()|| + this.hasPanelDateConstraint()|| + this.hasPanelOccurrenceConstraint()|| + this.hasValueConstraint() + ){ + return super.buildSql(); + } + else{ + String itemKey = baseItem.getItemKey(); + + String[] patientId = itemKey.split(":"); + if (patientId.length > 2 && + patientId[1] != null && + patientId[2] != null) { + return "select " + + "patient_num from " + noLockSqlServer + + parent.getDatabaseSchema() + "patient_mapping " + + "where patient_ide_source = '" + patientId[1] + "' " + + "and patient_ide = '" + patientId[2] + "' " + + ""; + } + else + return null; + } + } + + + @Override + protected ConceptType getConceptType() throws ConceptNotFoundException, + OntologyException { + if (conceptType==null){ + String itemKey = baseItem.getItemKey(); + + String[] patientId = itemKey.split(":"); + if (patientId.length > 2 && + patientId[1] != null && + //patientId[1].trim().toUpperCase().equals("HIVE") && + patientId[2] != null) { + String patientNum = patientId[2]; + conceptType = new ConceptType(); + conceptType.setColumnname(" patient_num "); + conceptType.setOperator(" = "); + conceptType.setFacttablecolumn(" patient_num "); + conceptType.setTablename("patient_mapping "); + conceptType.setDimcode(patientNum); + } + } + + return conceptType; + } + + + @Override + protected String buildDimensionJoinSql(String tableAlias) { + String dimensionSql = ""; + + if (tableAlias!=null&&tableAlias.trim().length()>0) + tableAlias += "."; + + String itemKey = baseItem.getItemKey(); + + String[] patientId = itemKey.split(":"); + if (patientId.length > 2 && + patientId[1] != null && + patientId[2] != null) { + + dimensionSql = tableAlias + this.factTableColumn + " IN (select " + + "patient_num from " + noLockSqlServer + + parent.getDatabaseSchema() + "patient_mapping " + + "where patient_ide_source = '" + patientId[1] + "' " + + "and patient_ide = '" + patientId[2] + "' " + + ")"; + } + + return dimensionSql; + } + + + @Override + protected String getJoinTable() { + if (this.returnInstanceNum()|| + hasItemDateConstraint()|| + hasPanelDateConstraint()|| + hasValueConstraint()|| + hasPanelOccurrenceConstraint()) { + return "observation_fact"; + } else if (this.returnEncounterNum()) { + return "visit_dimension"; + } else { + return "patient_dimension"; + } + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalPanelPatientSetItem.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalPanelPatientSetItem.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalPanelPatientSetItem.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalPanelPatientSetItem.java index f6f839c5..3eb48a5b --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalPanelPatientSetItem.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalPanelPatientSetItem.java @@ -1,90 +1,90 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Christopher Herrick - */ -package edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.ConceptNotFoundException; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.OntologyException; -import edu.harvard.i2b2.crc.datavo.ontology.ConceptType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ItemType; - -public class TemporalPanelPatientSetItem extends TemporalPanelItem { - - public TemporalPanelPatientSetItem(TemporalPanel parent, ItemType item) - throws I2B2Exception { - super(parent, item); - } - - - @Override - protected String buildSql() throws I2B2DAOException { - if (this.returnEncounterNum()|| - this.returnInstanceNum()|| - this.hasItemDateConstraint()|| - this.hasModiferConstraint()|| - this.hasPanelDateConstraint()|| - this.hasPanelOccurrenceConstraint()|| - this.hasValueConstraint() - ){ - return super.buildSql(); - } - else{ - return "select " - + this.factTableColumn + " from " + noLockSqlServer - + parent.getDatabaseSchema() + this.tableName - + " " + " where " + this.columnName + " " - + this.operator + " " + this.dimCode - + ""; - } - } - - - @Override - protected ConceptType getConceptType() throws ConceptNotFoundException, - OntologyException { - if (conceptType==null){ - String itemKey = baseItem.getItemKey(); - - String[] patientSetId = itemKey.split(":"); - if (patientSetId[1] != null) { - conceptType = new ConceptType(); - conceptType.setColumnname(" result_instance_id "); - conceptType.setOperator(" = "); - conceptType.setFacttablecolumn(" patient_num "); - conceptType.setTablename("qt_patient_set_collection "); - conceptType.setDimcode(patientSetId[1]); - } - } - - return conceptType; - } - - - @Override - protected String getJoinTable() { - if (returnInstanceNum()|| - hasItemDateConstraint()|| - hasPanelDateConstraint()|| - hasValueConstraint()|| - hasPanelOccurrenceConstraint()) { - return "observation_fact"; - } else if (returnEncounterNum()) { - return "visit_dimension"; - } else { - return "qt_patient_set_collection"; - } - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Christopher Herrick + */ +package edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.ConceptNotFoundException; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.OntologyException; +import edu.harvard.i2b2.crc.datavo.ontology.ConceptType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ItemType; + +public class TemporalPanelPatientSetItem extends TemporalPanelItem { + + public TemporalPanelPatientSetItem(TemporalPanel parent, ItemType item) + throws I2B2Exception { + super(parent, item); + } + + + @Override + protected String buildSql() throws I2B2DAOException { + if (this.returnEncounterNum()|| + this.returnInstanceNum()|| + this.hasItemDateConstraint()|| + this.hasModiferConstraint()|| + this.hasPanelDateConstraint()|| + this.hasPanelOccurrenceConstraint()|| + this.hasValueConstraint() + ){ + return super.buildSql(); + } + else{ + return "select " + + this.factTableColumn + " from " + noLockSqlServer + + parent.getDatabaseSchema() + this.tableName + + " " + " where " + this.columnName + " " + + this.operator + " " + this.dimCode + + ""; + } + } + + + @Override + protected ConceptType getConceptType() throws ConceptNotFoundException, + OntologyException { + if (conceptType==null){ + String itemKey = baseItem.getItemKey(); + + String[] patientSetId = itemKey.split(":"); + if (patientSetId[1] != null) { + conceptType = new ConceptType(); + conceptType.setColumnname(" result_instance_id "); + conceptType.setOperator(" = "); + conceptType.setFacttablecolumn(" patient_num "); + conceptType.setTablename("qt_patient_set_collection "); + conceptType.setDimcode(patientSetId[1]); + } + } + + return conceptType; + } + + + @Override + protected String getJoinTable() { + if (returnInstanceNum()|| + hasItemDateConstraint()|| + hasPanelDateConstraint()|| + hasValueConstraint()|| + hasPanelOccurrenceConstraint()) { + return "observation_fact"; + } else if (returnEncounterNum()) { + return "visit_dimension"; + } else { + return "qt_patient_set_collection"; + } + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalQuery.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalQuery.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalQuery.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalQuery.java index 3b0c61d1..70ae13f5 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalQuery.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalQuery.java @@ -1,779 +1,779 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Christopher Herrick - */ - -package edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal; - -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.Hashtable; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -import jakarta.xml.bind.JAXBElement; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.QueryDefinitionUnWrapUtil; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.QueryTimingHandler; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.TempTableNameMap; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal.TemporalQueryOptions.InvertedConstraintStrategy; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal.TemporalQueryOptions.QueryConstraintStrategy; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryConstraintType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionType; -import edu.harvard.i2b2.crc.util.PMServiceAccountUtil; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - -/** - * Temporal Query Object - * - *

    General query object that reads in CRC query requests and converts it into sql that can be run against the database - * This class and the subsequent classes it depends on duplicate much of functionality already found in querybuilder package, but reorganize the - * code in a way that makes it easier to identify sql syntax issues and find the corresponding code snippet that generates it. In addition, - * temporal comparison functionality was added to this set of classes to enable temporal based queries to run in the CRC. - * - * @author Christopher Herrick - * - */ -public class TemporalQuery { - - protected final Log log = LogFactory.getLog(getClass()); - private static QueryTimingHandler timingHandler = null; - - private TempTableNameMap tempTableNameMap = null; - private String queryTiming = "ANY"; - private DataSourceLookup dsLookup = null; - private List subQueryList = null; - private HashMap subQueryMap = null; - private QueryDefinitionType queryDef = null; - private String queryId = null; - private String projectId = null; - private SecurityType securityType = null; - private SecurityType userSecurityType = null; - private Map projectParamMap = null; - private boolean allowLargeTextValueConstrainFlag = false; - private List userRoles = null; - private TemporalQueryConstraintMapping constraintMapping = null; - private int maxPanelIndex = 0; - private int processingLevel = 1; - private StringBuffer ignoredItemMessageBuffer = new StringBuffer(); - private TemporalQueryOptions options = null; - private String lastSubQueryId = null; - private List preProcessingSql = null; - private List postProcessingSql = null; - private boolean isProtectedQuery = false; - - /** - * Constructor - * - * @param dataSourceLookup data source lookup object that contains information about the database and connection used to query against - * @param projectParameterMap map object that contains project parameters used to configure CRC and query logic - * @param queryXml string that contains the query definition xml object received from the query request - * @param allowLargeTextValueConstrainFlag boolean flag that, when set to true, allows text searching against text fields in the database - * @throws JAXBUtilException exception thrown when errors arise from converting string to xml and vice versa - * @throws I2B2Exception exception thrown when i2b2 specific error arises - */ - public TemporalQuery(DataSourceLookup dataSourceLookup, Map projectParameterMap, String queryXml, boolean allowLargeTextValueConstrainFlag, List userRoles) throws JAXBUtilException, I2B2Exception{ - this(dataSourceLookup, projectParameterMap, queryXml, allowLargeTextValueConstrainFlag, userRoles, 1); - } - - /** - * Constructor - * - * @param dataSourceLookup data source lookup object that contains information about the database and connection used to query against - * @param projectParameterMap map object that contains project parameters used to configure CRC and query logic - * @param queryXml string that contains the query definition xml object received from the query request - * @param allowLargeTextValueConstrainFlag boolean flag that, when set to true, allows text searching against text fields in the database - * @throws JAXBUtilException exception thrown when errors arise from converting string to xml and vice versa - * @throws I2B2Exception exception thrown when i2b2 specific error arises - */ - public TemporalQuery(DataSourceLookup dataSourceLookup, Map projectParameterMap, String queryXml, boolean allowLargeTextValueConstrainFlag, List userRoles, int processingLevel) throws JAXBUtilException, I2B2Exception{ - dsLookup = dataSourceLookup; - projectParamMap = projectParameterMap; - - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - String queryConstraintLogic= ""; - try{ - queryConstraintLogic = qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.setfinderquery.constraintlogic"); - }catch (I2B2Exception e) { - // ignore this default will be WITH - } - - - this.allowLargeTextValueConstrainFlag = allowLargeTextValueConstrainFlag; - this.userRoles = userRoles; - this.processingLevel = processingLevel; - options = new TemporalQueryOptions(); - if (getServerType().equalsIgnoreCase(DAOFactoryHelper.SQLSERVER)){ - if (queryConstraintLogic.equalsIgnoreCase("TEMP")||queryConstraintLogic.equalsIgnoreCase("TEMPTABLES")) - options.setQueryConstraintLogic(QueryConstraintStrategy.TEMP_TABLES); - else - options.setQueryConstraintLogic(QueryConstraintStrategy.WITH_STATEMENT); - } - else if (getServerType().equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)){ - options.setQueryConstraintLogic(QueryConstraintStrategy.WITH_STATEMENT); - } - else if (getServerType().equalsIgnoreCase(DAOFactoryHelper.ORACLE)){ - options.setInvertedConstraintLogic(InvertedConstraintStrategy.MINUS_CLAUSE); - } - this.preProcessingSql = new ArrayList(); - this.postProcessingSql = new ArrayList(); - - parseQueryDefinitionXml(queryXml); - } - - - public TemporalQuery(DataSourceLookup dataSourceLookup, Map projectParameterMap, QueryDefinitionType queryDefinition, boolean allowLargeTextValueConstrainFlag, List userRoles, - String queryProjectId, SecurityType userSecurityType, SecurityType querySecurityType) throws JAXBUtilException, I2B2Exception{ - this(dataSourceLookup, projectParameterMap, queryDefinition, allowLargeTextValueConstrainFlag, userRoles, 1, queryProjectId, userSecurityType, querySecurityType); - } - - public TemporalQuery(DataSourceLookup dataSourceLookup, Map projectParameterMap, QueryDefinitionType queryDefinition, boolean allowLargeTextValueConstrainFlag, List userRoles, int processingLevel, - String queryProjectId, SecurityType userSecurityType, SecurityType querySecurityType) throws JAXBUtilException, I2B2Exception{ - dsLookup = dataSourceLookup; - projectParamMap = projectParameterMap; - this.allowLargeTextValueConstrainFlag = allowLargeTextValueConstrainFlag; - this.userRoles = userRoles; - this.processingLevel = processingLevel; - options = new TemporalQueryOptions(); - - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - String queryConstraintLogic= ""; - try{ - queryConstraintLogic = qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.setfinderquery.constraintlogic"); - }catch (I2B2Exception e) { - // ignore this default will be WITH - } - - if (getServerType().equalsIgnoreCase(DAOFactoryHelper.SQLSERVER)){ - //no default options at this time - if (queryConstraintLogic.equalsIgnoreCase("TEMP")||queryConstraintLogic.equalsIgnoreCase("TEMPTABLES")) - options.setQueryConstraintLogic(QueryConstraintStrategy.TEMP_TABLES); - else - options.setQueryConstraintLogic(QueryConstraintStrategy.WITH_STATEMENT); - } - else if (getServerType().equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)){ - //no default options at this time - - options.setQueryConstraintLogic(QueryConstraintStrategy.WITH_STATEMENT); - } - else if (getServerType().equalsIgnoreCase(DAOFactoryHelper.ORACLE)){ - options.setInvertedConstraintLogic(InvertedConstraintStrategy.MINUS_CLAUSE); - } - this.queryDef = queryDefinition; - this.projectId = queryProjectId; - this.userSecurityType = userSecurityType; - this.securityType = querySecurityType; - this.preProcessingSql = new ArrayList(); - this.postProcessingSql = new ArrayList(); - parseQuery(); - } - - - public void parseQueryDefinitionXml(String queryXml) throws JAXBUtilException, I2B2Exception{ - if (queryXml==null) - return; - - //start by converting string object to query definition object - QueryDefinitionUnWrapUtil queryDefUnWrapHelper = new QueryDefinitionUnWrapUtil(); - queryDef = queryDefUnWrapHelper - .getQueryDefinitionType(queryXml); - - //get query timing out - this will be used as the default timing for all groups - //and panels. Panel timing values will override this value - queryTiming = queryDef.getQueryTiming(); - - //extract out project and security information. this will be reused when validating - //panel items with ontology cell - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil() - .unMashallFromString(queryXml); - RequestMessageType request = (RequestMessageType) responseJaxb - .getValue(); - projectId = request.getMessageHeader().getProjectId(); - userSecurityType = request.getMessageHeader() - .getSecurity(); - securityType = PMServiceAccountUtil - .getServiceSecurityType(userSecurityType.getDomain()); - - parseQuery(); - } - - /** - * Parse Query - * - *

    Parses out string representation of query xml object into building blocks that will be used to generate sql statement. - * In particular, this method establishes the processing order of groups, panels, and items when building the query - * - * @param queryXml string that contains the query definition xml object received from the query request - * @throws JAXBUtilException exception thrown when errors arise from converting string to xml and vice versa - * @throws I2B2Exception exception thrown when i2b2 specific error arises - */ - public void parseQuery() throws I2B2Exception { - //get query timing out - this will be used as the default timing for all groups - //and panels. Panel timing values will override this value - - queryTiming = queryDef.getQueryTiming(); - //first step, get the constraints parsed out by groups they reference - //also parse through the columns that need to be returned by each panel group - - constraintMapping = new TemporalQueryConstraintMapping(queryDef); - - HashMap subQuerySet = new HashMap(); - - //second step, treat panel object on the query level as panel group with no temporal component - - if (queryDef.getPanel()!=null&&queryDef.getPanel().size()>0){ - TemporalSubQuery mainQuery = new TemporalSubQuery(this, queryDef.getPanel()); - - //check to see if the main query is an "everyone" query - boolean getEveryoneQuery = false; - if (mainQuery!=null&&mainQuery.getPanelCount()==1){ - TemporalPanel mainPanel = mainQuery.getPanelList().get(0); - if (mainPanel!=null && - mainPanel.isPanelInverted() && - (mainPanel.getItemList()==null||mainPanel.getItemList().size()==0)){ - getEveryoneQuery = true; - } - } - if (isProtectedQuery() == false) - isProtectedQuery = mainQuery.isProtectedQuery(); - - //if there are no subqueries or the main query is not an "everyone" query, include - //the main query as a special subquery - if (queryDef.getSubquery()==null || - queryDef.getSubquery().size()==0 || - !getEveryoneQuery){ - subQuerySet.put("**default**", mainQuery); - } - } - - //third step, check for query objects and create corresponding temporal query panel groups - if (queryDef.getSubquery()!=null&&queryDef.getSubquery().size()>0){ - for (QueryDefinitionType query : queryDef.getSubquery()){ - HashMap> constraints = constraintMapping.getConstraintsForQuery(query.getQueryId()); - EnumSet returnColumns = constraintMapping.getReturnColumnsForQuery(query.getQueryId()); - TemporalSubQuery subQuery = new TemporalSubQuery(this, query, constraints, returnColumns); - subQuerySet.put(query.getQueryId(), subQuery); - } - } - - //last step, group set object established the order of the groups. now copy objects - //into straight list for easier processing - subQueryList = new ArrayList(); - subQueryMap = new HashMap(); - int index = 0; - for(String eventId : constraintMapping.getOrderedQueryList()){ - TemporalSubQuery subQuery = subQuerySet.get(eventId); - if (subQuery!=null){ - subQueryList.add(subQuery); - subQueryMap.put(eventId, index); - index++; - subQuerySet.remove(eventId); - } - } - - if (subQuerySet.size()>0){ - for (TemporalSubQuery grp : subQuerySet.values()){ - subQueryList.add(grp); - subQueryMap.put(grp.getQueryId(), index); - index++; - } - } - - } - - protected QueryDefinitionType searchForSubQuery(String subQueryId){ - if (subQueryId==null||subQueryId.trim().length()==0) - return null; - - String strippedId = ""; - if (subQueryId.startsWith("masterid:")){ - strippedId = subQueryId.replace("masterid:", ""); - } - if (this.queryDef!=null&&this.queryDef.getSubquery()!=null){ - for (QueryDefinitionType query : queryDef.getSubquery()){ - if (query.getQueryId()!=null&&query.getQueryId().trim().length()>0&&query.getQueryId().equalsIgnoreCase(subQueryId)){ - return query; - } - else if (strippedId!=null&&strippedId.trim().length()>0&&strippedId.equalsIgnoreCase(subQueryId)) - return query; - - } - } - return null; - } - - /** - * Build Sql - * - *

    Main call that converts the query object into a sql statement that can be run against the database - * - * @return String sql statement generated from query object - * @throws I2B2DAOException exception generated when encountering an i2b2 specific database error - */ - public String buildSql() throws I2B2DAOException { - StringBuffer querySqlBuffer = new StringBuffer(); - - // iterator through the ordered panel groups, generating a sql - // statement for each - - for (TemporalSubQuery subQuery : subQueryList){ - if (subQuery!=null){ - querySqlBuffer.append(subQuery.buildSql()); - lastSubQueryId = subQuery.getSubQueryId(); - maxPanelIndex = subQuery.getEndPanelIndex(); - } - } - - // finally, add in insert into dx table that will get passed back to - // calling class - - String dxTempTableSql = ""; - if (subQueryList.size()>1){ - dxTempTableSql = buildDxInsertSqlFromMaster(returnEncounterNum(), returnInstanceNum(), lastSubQueryId, 1); - } - else { - dxTempTableSql = buildDxInsertSqlFromTemp(returnEncounterNum(), returnInstanceNum(), maxPanelIndex); - } - querySqlBuffer.append(dxTempTableSql); - - - StringBuffer sqlBuffer = new StringBuffer(); - if (this.preProcessingSql!=null&&this.preProcessingSql.size()>0){ - for(String sql : this.preProcessingSql){ - sqlBuffer.append(sql); - sqlBuffer.append(getSqlDelimiter()); - } - } - sqlBuffer.append(querySqlBuffer.toString()); - if (this.postProcessingSql!=null&&this.postProcessingSql.size()>0){ - for(String sql : this.postProcessingSql){ - sqlBuffer.append(getSqlDelimiter()); - sqlBuffer.append(sql); - } - } - - return sqlBuffer.toString(); - } - - - public String buildDxInsertSqlFromTemp(boolean encounterNumFlag, boolean instanceNumFlag, int maxPanelNum) { - StringBuilder dxInsertSql = new StringBuilder(); - - - String selectEncounterNum = " ", selectPatientNum = " patient_num "; - if (encounterNumFlag) { - selectEncounterNum = " , encounter_num "; - } - - dxInsertSql.append(" insert into " + this.getDxTempTableName() + " ( " + selectPatientNum - + selectEncounterNum + " ) select * from (" - + " select distinct " + selectPatientNum - + selectEncounterNum + "from " + this.getTempTableName() - + " where panel_count = " + maxPanelNum - + " ) q"); - - return dxInsertSql.toString(); - } - - public String buildDxInsertSqlFromMaster(boolean encounterNumFlag, boolean instanceNumFlag, String subQueryId, int levelNo) { - StringBuilder dxInsertSql = new StringBuilder(); - - - String selectEncounterNum = " ", selectPatientNum = " patient_num "; - if (encounterNumFlag) { - selectEncounterNum = " , encounter_num "; - } - - if (useSqlServerTempTables()){ - dxInsertSql.append(" insert into " + this.getDxTempTableName() + " ( " + selectPatientNum - + selectEncounterNum + " ) select * from (" - + " select distinct " + selectPatientNum - + selectEncounterNum + "from #m" + subQueryId - + " where level_no = " + String.valueOf(levelNo)); - } - else { - dxInsertSql.append(" insert into " + this.getDxTempTableName() + " ( " + selectPatientNum - + selectEncounterNum + " ) select * from (" - + " select distinct " + selectPatientNum - + selectEncounterNum + "from " + this.getMasterTempTableName() - + " where level_no = " + String.valueOf(levelNo) - + " and master_id = '" + subQueryId + "'"); - } - - dxInsertSql.append(" ) q"); - - return dxInsertSql.toString(); - } - - - /** - * Get Project Id - * - * @return string that represents the project id for the query that was passed in - */ - protected String getProjectId() { - return projectId; - } - - /** - * Get Security Type - * - * @return security type for the query that was passed in - */ - protected SecurityType getSecurityType() { - return securityType; - } - - /** - * Get Security Type - * - * @return security type for the query that was passed in - */ - protected SecurityType getRequestorSecurityType() { - return userSecurityType; - } - - /** - * Get Panel Group Index - * - * @param grp reference to temporal panel group to test - * @return int that corresponds to the index of this panel group occurs the group list - */ - public int getSubQueryIndex(TemporalSubQuery grp){ - return subQueryList.indexOf(grp); - } - - public int getSubQueryIndex(String subQueryId){ - return subQueryMap.get(subQueryId); - } - - /** - * Is First Group - * - * Test to check if passed in temporal panel group is the first panel group for this query - * - * @param subQuery reference to a temporal panel group to test - * @return true or false depending on if passed in panel group is the first group for this query - */ - public boolean isFirstSubQuery(TemporalSubQuery subQuery){ - return (getSubQueryIndex(subQuery)==0); - } - - /** - * Is Last Group - * - * Test to check if passed in temporal panel group is the last panel group for this query - * - * @param subQuery reference to a temporal panel group to test - * @return true or false depending on if passed in panel group is the last group for this query - */ - public boolean isLastSubQuery(TemporalSubQuery subQuery){ - return (getSubQueryIndex(subQuery)==(subQueryList.size()-1)); - } - - /** - * Get Query Timing - * - * Get the default timing passed in by the query object - * - * @return string containing the query timing constant - */ - public String getQueryTiming() { - return queryTiming; - } - - /** - * Get Data Source Lookup - * - * Returns the data source lookup object passed in in the constructor - * - * @return data source lookup object passed in the constructor - */ - protected DataSourceLookup getDataSourceLookup() { - return dsLookup; - } - public boolean isProtectedQuery() { - return isProtectedQuery; - } - - /** - * Get Database Schema - * - * Returns the name of the schema used to reference the correct table names in the sql syntax - * - * @return string that contains the name of the schema this query should run under - */ - public String getDatabaseSchema() { - String dbSchemaName = dsLookup.getFullSchema(); - if (dbSchemaName != null && dbSchemaName.endsWith(".")) { - return dbSchemaName.trim(); - } - else if (dbSchemaName != null) { - return dbSchemaName.trim() + "."; - } - return dbSchemaName; - } - - /** - * Get Server Type - * - * Returns the type of database server CRC is running against - * - * @return string containing the type of database CRC is running against (Sql Server or Oracle) - */ - protected String getServerType(){ - return dsLookup.getServerType(); - } - - /** - * Get Project Parameter Map - * - * Returns the map that was passed in in the constructor that contains the parameters used for this project - * - * @return map object that contains the project parameters - */ - protected Map getProjectParameterMap(){ - return this.projectParamMap; - } - - /** - * Get Timing Handler - * - * @return query timing handler object that tests timing text from query for various states - */ - protected QueryTimingHandler getTimingHandler(){ - if (timingHandler==null) - timingHandler = new QueryTimingHandler(); - return timingHandler; - } - - /** - * Get Temp Table Name - * - * Return the default name of the temproary table in the database. The temporary table is used to store the results of individual panel items and the joins - * of panel to panel items - * - * @return string containing the name of the default temporary table name in the database - */ - protected String getTempTableName(){ - if (this.tempTableNameMap==null) - this.tempTableNameMap = new TempTableNameMap(this.getServerType()); - String tableName = ""; - if (getServerType().equalsIgnoreCase(DAOFactoryHelper.ORACLE)){ - tableName = getDatabaseSchema(); - } - tableName += tempTableNameMap.getTempTableName(); - - return tableName; - } - - /** - * Get DX Temp Table Name - * - * Return the default name of the dx temporary table in the database. The dx table is used to return the final results of the query from the database to the - * CRC cell - * - * @return string containing the default name of the dx return table in database - */ - protected String getDxTempTableName(){ - if (this.tempTableNameMap==null) - this.tempTableNameMap = new TempTableNameMap(this.getServerType()); - String tableName = ""; - if (getServerType().equalsIgnoreCase(DAOFactoryHelper.ORACLE)){ - tableName = getDatabaseSchema(); - } - tableName += tempTableNameMap.getTempDxTableName(); - - return tableName; - } - - /** - * Get Master Temp Table Name - * - * Return default name of the master table in the database. The master table is used to temporarily store results from embedded query items - * and panel group constraints - * - * @return string containing the default name used for the "master" table in the database - */ - protected String getMasterTempTableName(){ - if (this.tempTableNameMap==null) - this.tempTableNameMap = new TempTableNameMap(this.getServerType()); - String tableName = ""; - if (getServerType().equalsIgnoreCase(DAOFactoryHelper.ORACLE)){ - tableName = getDatabaseSchema(); - } - tableName += tempTableNameMap.getTempMasterTable(); - - return tableName; - } - - /** - * Allow Large Text Value Constrian Flag - * - * @return true if text querying against large text fields is allowed, else false - */ - protected boolean allowLargeTextValueConstrainFlag(){ - return this.allowLargeTextValueConstrainFlag; - } - - protected List getUserRoles() { - return this.userRoles; - } - /** - * Return Encounter Num - * - * @return true if query needs to return encounter information in final results, else false - */ - protected boolean returnEncounterNum(){ - if (getTimingHandler().isSameVisit(queryTiming)) - return true; - else - return false; - } - - /** - * Return Instance Num - * - * @return true if query needs to return instance information is the final results, else false - */ - protected boolean returnInstanceNum(){ - if (getTimingHandler().isSameInstanceNum(queryTiming)) - return true; - else - return false; - } - - /** - * Get Panel Group Count - * - * @return int - the number of panel groups contained in this query - */ - protected int getSubQueryCount(){ - return subQueryList.size(); - } - - /** - * Generate Unique Id - * - * Returns a string with a guaranteed unique value. This method is used specifically to uniquely identify queries and - * panel groups within the context of the query - * - * @return string with a guaranteed unique value - */ - protected String generateUniqueId(){ - UUID uniqueKey = UUID.randomUUID(); - String hexNum = uniqueKey.toString().replace("-", ""); - BigInteger big = new BigInteger(hexNum, 16); - return big.toString(36); - } - - /** - * Get Query Id - * - * @return string containing the unique id of the query that is being run - */ - protected String getQueryId(){ - if (queryId==null) - queryId = generateUniqueId(); - return queryId; - } - - public int getMaxPanelIndex(){ - return this.maxPanelIndex; - } - - /** - * @return the processingLevel - */ - public int getProcessingLevel() { - return processingLevel; - } - - public TemporalQueryOptions getQueryOptions(){ - return options; - } - - /** - * @return the ignoredItemMessageBuffer - */ - public StringBuffer getIgnoredItemMessageBuffer() { - return ignoredItemMessageBuffer; - } - - public void addIgnoredMessage(String errorMessage) { - this.ignoredItemMessageBuffer.append(errorMessage + "\n"); - } - - /** - * @return the lastSubQueryId - */ - protected String getLastProcessedSubQueryId() { - return lastSubQueryId; - } - - protected void addPreProcessingSql(String sql){ - if (sql!=null&&sql.trim().length()>0) - this.preProcessingSql.add(sql); - } - - protected void addPostProcessingSql(String sql){ - if (sql!=null&&sql.trim().length()>0) - this.postProcessingSql.add(sql); - } - - public String getSqlDelimiter() { - return "\n<*>\n"; - } - - - /** - * Build Temp Table Check Drop - * - * Create a Sql Server specific statement to check for the existence of a temporary table and, - * if the table exists, drop it - * - * @param tempTableName String name of the temporary table - * @return String sql statement that checks for temporary table and drops it - */ - protected String buildTempTableCheckDrop(String tempTableName) { - if (tempTableName == null) - return ""; - else if (!tempTableName.startsWith("#")) - tempTableName = "#" + tempTableName; - - return "if (object_id('tempdb.." + tempTableName + "') is not null) \n" - + "begin \n" + "drop table " + tempTableName + " \n" + "end"; - } - - protected boolean useSqlServerTempTables(){ - return ((this.getQueryOptions().getQueryConstraintLogic()==QueryConstraintStrategy.TEMP_TABLES) && - (this.getServerType().equalsIgnoreCase(DAOFactoryHelper.SQLSERVER))); - } - -} - - +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Christopher Herrick + */ + +package edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal; + +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.HashMap; +import java.util.Hashtable; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import jakarta.xml.bind.JAXBElement; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.QueryDefinitionUnWrapUtil; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.QueryTimingHandler; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.TempTableNameMap; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal.TemporalQueryOptions.InvertedConstraintStrategy; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal.TemporalQueryOptions.QueryConstraintStrategy; +import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryConstraintType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionType; +import edu.harvard.i2b2.crc.util.PMServiceAccountUtil; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + +/** + * Temporal Query Object + * + *

    General query object that reads in CRC query requests and converts it into sql that can be run against the database + * This class and the subsequent classes it depends on duplicate much of functionality already found in querybuilder package, but reorganize the + * code in a way that makes it easier to identify sql syntax issues and find the corresponding code snippet that generates it. In addition, + * temporal comparison functionality was added to this set of classes to enable temporal based queries to run in the CRC. + * + * @author Christopher Herrick + * + */ +public class TemporalQuery { + + protected final Log log = LogFactory.getLog(getClass()); + private static QueryTimingHandler timingHandler = null; + + private TempTableNameMap tempTableNameMap = null; + private String queryTiming = "ANY"; + private DataSourceLookup dsLookup = null; + private List subQueryList = null; + private HashMap subQueryMap = null; + private QueryDefinitionType queryDef = null; + private String queryId = null; + private String projectId = null; + private SecurityType securityType = null; + private SecurityType userSecurityType = null; + private Map projectParamMap = null; + private boolean allowLargeTextValueConstrainFlag = false; + private List userRoles = null; + private TemporalQueryConstraintMapping constraintMapping = null; + private int maxPanelIndex = 0; + private int processingLevel = 1; + private StringBuffer ignoredItemMessageBuffer = new StringBuffer(); + private TemporalQueryOptions options = null; + private String lastSubQueryId = null; + private List preProcessingSql = null; + private List postProcessingSql = null; + private boolean isProtectedQuery = false; + + /** + * Constructor + * + * @param dataSourceLookup data source lookup object that contains information about the database and connection used to query against + * @param projectParameterMap map object that contains project parameters used to configure CRC and query logic + * @param queryXml string that contains the query definition xml object received from the query request + * @param allowLargeTextValueConstrainFlag boolean flag that, when set to true, allows text searching against text fields in the database + * @throws JAXBUtilException exception thrown when errors arise from converting string to xml and vice versa + * @throws I2B2Exception exception thrown when i2b2 specific error arises + */ + public TemporalQuery(DataSourceLookup dataSourceLookup, Map projectParameterMap, String queryXml, boolean allowLargeTextValueConstrainFlag, List userRoles) throws JAXBUtilException, I2B2Exception{ + this(dataSourceLookup, projectParameterMap, queryXml, allowLargeTextValueConstrainFlag, userRoles, 1); + } + + /** + * Constructor + * + * @param dataSourceLookup data source lookup object that contains information about the database and connection used to query against + * @param projectParameterMap map object that contains project parameters used to configure CRC and query logic + * @param queryXml string that contains the query definition xml object received from the query request + * @param allowLargeTextValueConstrainFlag boolean flag that, when set to true, allows text searching against text fields in the database + * @throws JAXBUtilException exception thrown when errors arise from converting string to xml and vice versa + * @throws I2B2Exception exception thrown when i2b2 specific error arises + */ + public TemporalQuery(DataSourceLookup dataSourceLookup, Map projectParameterMap, String queryXml, boolean allowLargeTextValueConstrainFlag, List userRoles, int processingLevel) throws JAXBUtilException, I2B2Exception{ + dsLookup = dataSourceLookup; + projectParamMap = projectParameterMap; + + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + String queryConstraintLogic= ""; + try{ + queryConstraintLogic = qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.setfinderquery.constraintlogic"); + }catch (I2B2Exception e) { + // ignore this default will be WITH + } + + + this.allowLargeTextValueConstrainFlag = allowLargeTextValueConstrainFlag; + this.userRoles = userRoles; + this.processingLevel = processingLevel; + options = new TemporalQueryOptions(); + if (getServerType().equalsIgnoreCase(DAOFactoryHelper.SQLSERVER)){ + if (queryConstraintLogic.equalsIgnoreCase("TEMP")||queryConstraintLogic.equalsIgnoreCase("TEMPTABLES")) + options.setQueryConstraintLogic(QueryConstraintStrategy.TEMP_TABLES); + else + options.setQueryConstraintLogic(QueryConstraintStrategy.WITH_STATEMENT); + } + else if (getServerType().equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)){ + options.setQueryConstraintLogic(QueryConstraintStrategy.WITH_STATEMENT); + } + else if (getServerType().equalsIgnoreCase(DAOFactoryHelper.ORACLE)){ + options.setInvertedConstraintLogic(InvertedConstraintStrategy.MINUS_CLAUSE); + } + this.preProcessingSql = new ArrayList(); + this.postProcessingSql = new ArrayList(); + + parseQueryDefinitionXml(queryXml); + } + + + public TemporalQuery(DataSourceLookup dataSourceLookup, Map projectParameterMap, QueryDefinitionType queryDefinition, boolean allowLargeTextValueConstrainFlag, List userRoles, + String queryProjectId, SecurityType userSecurityType, SecurityType querySecurityType) throws JAXBUtilException, I2B2Exception{ + this(dataSourceLookup, projectParameterMap, queryDefinition, allowLargeTextValueConstrainFlag, userRoles, 1, queryProjectId, userSecurityType, querySecurityType); + } + + public TemporalQuery(DataSourceLookup dataSourceLookup, Map projectParameterMap, QueryDefinitionType queryDefinition, boolean allowLargeTextValueConstrainFlag, List userRoles, int processingLevel, + String queryProjectId, SecurityType userSecurityType, SecurityType querySecurityType) throws JAXBUtilException, I2B2Exception{ + dsLookup = dataSourceLookup; + projectParamMap = projectParameterMap; + this.allowLargeTextValueConstrainFlag = allowLargeTextValueConstrainFlag; + this.userRoles = userRoles; + this.processingLevel = processingLevel; + options = new TemporalQueryOptions(); + + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + String queryConstraintLogic= ""; + try{ + queryConstraintLogic = qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.setfinderquery.constraintlogic"); + }catch (I2B2Exception e) { + // ignore this default will be WITH + } + + if (getServerType().equalsIgnoreCase(DAOFactoryHelper.SQLSERVER)){ + //no default options at this time + if (queryConstraintLogic.equalsIgnoreCase("TEMP")||queryConstraintLogic.equalsIgnoreCase("TEMPTABLES")) + options.setQueryConstraintLogic(QueryConstraintStrategy.TEMP_TABLES); + else + options.setQueryConstraintLogic(QueryConstraintStrategy.WITH_STATEMENT); + } + else if (getServerType().equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)){ + //no default options at this time + + options.setQueryConstraintLogic(QueryConstraintStrategy.WITH_STATEMENT); + } + else if (getServerType().equalsIgnoreCase(DAOFactoryHelper.ORACLE)){ + options.setInvertedConstraintLogic(InvertedConstraintStrategy.MINUS_CLAUSE); + } + this.queryDef = queryDefinition; + this.projectId = queryProjectId; + this.userSecurityType = userSecurityType; + this.securityType = querySecurityType; + this.preProcessingSql = new ArrayList(); + this.postProcessingSql = new ArrayList(); + parseQuery(); + } + + + public void parseQueryDefinitionXml(String queryXml) throws JAXBUtilException, I2B2Exception{ + if (queryXml==null) + return; + + //start by converting string object to query definition object + QueryDefinitionUnWrapUtil queryDefUnWrapHelper = new QueryDefinitionUnWrapUtil(); + queryDef = queryDefUnWrapHelper + .getQueryDefinitionType(queryXml); + + //get query timing out - this will be used as the default timing for all groups + //and panels. Panel timing values will override this value + queryTiming = queryDef.getQueryTiming(); + + //extract out project and security information. this will be reused when validating + //panel items with ontology cell + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil() + .unMashallFromString(queryXml); + RequestMessageType request = (RequestMessageType) responseJaxb + .getValue(); + projectId = request.getMessageHeader().getProjectId(); + userSecurityType = request.getMessageHeader() + .getSecurity(); + securityType = PMServiceAccountUtil + .getServiceSecurityType(userSecurityType.getDomain()); + + parseQuery(); + } + + /** + * Parse Query + * + *

    Parses out string representation of query xml object into building blocks that will be used to generate sql statement. + * In particular, this method establishes the processing order of groups, panels, and items when building the query + * + * @param queryXml string that contains the query definition xml object received from the query request + * @throws JAXBUtilException exception thrown when errors arise from converting string to xml and vice versa + * @throws I2B2Exception exception thrown when i2b2 specific error arises + */ + public void parseQuery() throws I2B2Exception { + //get query timing out - this will be used as the default timing for all groups + //and panels. Panel timing values will override this value + + queryTiming = queryDef.getQueryTiming(); + //first step, get the constraints parsed out by groups they reference + //also parse through the columns that need to be returned by each panel group + + constraintMapping = new TemporalQueryConstraintMapping(queryDef); + + HashMap subQuerySet = new HashMap(); + + //second step, treat panel object on the query level as panel group with no temporal component + + if (queryDef.getPanel()!=null&&queryDef.getPanel().size()>0){ + TemporalSubQuery mainQuery = new TemporalSubQuery(this, queryDef.getPanel()); + + //check to see if the main query is an "everyone" query + boolean getEveryoneQuery = false; + if (mainQuery!=null&&mainQuery.getPanelCount()==1){ + TemporalPanel mainPanel = mainQuery.getPanelList().get(0); + if (mainPanel!=null && + mainPanel.isPanelInverted() && + (mainPanel.getItemList()==null||mainPanel.getItemList().size()==0)){ + getEveryoneQuery = true; + } + } + if (isProtectedQuery() == false) + isProtectedQuery = mainQuery.isProtectedQuery(); + + //if there are no subqueries or the main query is not an "everyone" query, include + //the main query as a special subquery + if (queryDef.getSubquery()==null || + queryDef.getSubquery().size()==0 || + !getEveryoneQuery){ + subQuerySet.put("**default**", mainQuery); + } + } + + //third step, check for query objects and create corresponding temporal query panel groups + if (queryDef.getSubquery()!=null&&queryDef.getSubquery().size()>0){ + for (QueryDefinitionType query : queryDef.getSubquery()){ + HashMap> constraints = constraintMapping.getConstraintsForQuery(query.getQueryId()); + EnumSet returnColumns = constraintMapping.getReturnColumnsForQuery(query.getQueryId()); + TemporalSubQuery subQuery = new TemporalSubQuery(this, query, constraints, returnColumns); + subQuerySet.put(query.getQueryId(), subQuery); + } + } + + //last step, group set object established the order of the groups. now copy objects + //into straight list for easier processing + subQueryList = new ArrayList(); + subQueryMap = new HashMap(); + int index = 0; + for(String eventId : constraintMapping.getOrderedQueryList()){ + TemporalSubQuery subQuery = subQuerySet.get(eventId); + if (subQuery!=null){ + subQueryList.add(subQuery); + subQueryMap.put(eventId, index); + index++; + subQuerySet.remove(eventId); + } + } + + if (subQuerySet.size()>0){ + for (TemporalSubQuery grp : subQuerySet.values()){ + subQueryList.add(grp); + subQueryMap.put(grp.getQueryId(), index); + index++; + } + } + + } + + protected QueryDefinitionType searchForSubQuery(String subQueryId){ + if (subQueryId==null||subQueryId.trim().length()==0) + return null; + + String strippedId = ""; + if (subQueryId.startsWith("masterid:")){ + strippedId = subQueryId.replace("masterid:", ""); + } + if (this.queryDef!=null&&this.queryDef.getSubquery()!=null){ + for (QueryDefinitionType query : queryDef.getSubquery()){ + if (query.getQueryId()!=null&&query.getQueryId().trim().length()>0&&query.getQueryId().equalsIgnoreCase(subQueryId)){ + return query; + } + else if (strippedId!=null&&strippedId.trim().length()>0&&strippedId.equalsIgnoreCase(subQueryId)) + return query; + + } + } + return null; + } + + /** + * Build Sql + * + *

    Main call that converts the query object into a sql statement that can be run against the database + * + * @return String sql statement generated from query object + * @throws I2B2DAOException exception generated when encountering an i2b2 specific database error + */ + public String buildSql() throws I2B2DAOException { + StringBuffer querySqlBuffer = new StringBuffer(); + + // iterator through the ordered panel groups, generating a sql + // statement for each + + for (TemporalSubQuery subQuery : subQueryList){ + if (subQuery!=null){ + querySqlBuffer.append(subQuery.buildSql()); + lastSubQueryId = subQuery.getSubQueryId(); + maxPanelIndex = subQuery.getEndPanelIndex(); + } + } + + // finally, add in insert into dx table that will get passed back to + // calling class + + String dxTempTableSql = ""; + if (subQueryList.size()>1){ + dxTempTableSql = buildDxInsertSqlFromMaster(returnEncounterNum(), returnInstanceNum(), lastSubQueryId, 1); + } + else { + dxTempTableSql = buildDxInsertSqlFromTemp(returnEncounterNum(), returnInstanceNum(), maxPanelIndex); + } + querySqlBuffer.append(dxTempTableSql); + + + StringBuffer sqlBuffer = new StringBuffer(); + if (this.preProcessingSql!=null&&this.preProcessingSql.size()>0){ + for(String sql : this.preProcessingSql){ + sqlBuffer.append(sql); + sqlBuffer.append(getSqlDelimiter()); + } + } + sqlBuffer.append(querySqlBuffer.toString()); + if (this.postProcessingSql!=null&&this.postProcessingSql.size()>0){ + for(String sql : this.postProcessingSql){ + sqlBuffer.append(getSqlDelimiter()); + sqlBuffer.append(sql); + } + } + + return sqlBuffer.toString(); + } + + + public String buildDxInsertSqlFromTemp(boolean encounterNumFlag, boolean instanceNumFlag, int maxPanelNum) { + StringBuilder dxInsertSql = new StringBuilder(); + + + String selectEncounterNum = " ", selectPatientNum = " patient_num "; + if (encounterNumFlag) { + selectEncounterNum = " , encounter_num "; + } + + dxInsertSql.append(" insert into " + this.getDxTempTableName() + " ( " + selectPatientNum + + selectEncounterNum + " ) select * from (" + + " select distinct " + selectPatientNum + + selectEncounterNum + "from " + this.getTempTableName() + + " where panel_count = " + maxPanelNum + + " ) q"); + + return dxInsertSql.toString(); + } + + public String buildDxInsertSqlFromMaster(boolean encounterNumFlag, boolean instanceNumFlag, String subQueryId, int levelNo) { + StringBuilder dxInsertSql = new StringBuilder(); + + + String selectEncounterNum = " ", selectPatientNum = " patient_num "; + if (encounterNumFlag) { + selectEncounterNum = " , encounter_num "; + } + + if (useSqlServerTempTables()){ + dxInsertSql.append(" insert into " + this.getDxTempTableName() + " ( " + selectPatientNum + + selectEncounterNum + " ) select * from (" + + " select distinct " + selectPatientNum + + selectEncounterNum + "from #m" + subQueryId + + " where level_no = " + String.valueOf(levelNo)); + } + else { + dxInsertSql.append(" insert into " + this.getDxTempTableName() + " ( " + selectPatientNum + + selectEncounterNum + " ) select * from (" + + " select distinct " + selectPatientNum + + selectEncounterNum + "from " + this.getMasterTempTableName() + + " where level_no = " + String.valueOf(levelNo) + + " and master_id = '" + subQueryId + "'"); + } + + dxInsertSql.append(" ) q"); + + return dxInsertSql.toString(); + } + + + /** + * Get Project Id + * + * @return string that represents the project id for the query that was passed in + */ + protected String getProjectId() { + return projectId; + } + + /** + * Get Security Type + * + * @return security type for the query that was passed in + */ + protected SecurityType getSecurityType() { + return securityType; + } + + /** + * Get Security Type + * + * @return security type for the query that was passed in + */ + protected SecurityType getRequestorSecurityType() { + return userSecurityType; + } + + /** + * Get Panel Group Index + * + * @param grp reference to temporal panel group to test + * @return int that corresponds to the index of this panel group occurs the group list + */ + public int getSubQueryIndex(TemporalSubQuery grp){ + return subQueryList.indexOf(grp); + } + + public int getSubQueryIndex(String subQueryId){ + return subQueryMap.get(subQueryId); + } + + /** + * Is First Group + * + * Test to check if passed in temporal panel group is the first panel group for this query + * + * @param subQuery reference to a temporal panel group to test + * @return true or false depending on if passed in panel group is the first group for this query + */ + public boolean isFirstSubQuery(TemporalSubQuery subQuery){ + return (getSubQueryIndex(subQuery)==0); + } + + /** + * Is Last Group + * + * Test to check if passed in temporal panel group is the last panel group for this query + * + * @param subQuery reference to a temporal panel group to test + * @return true or false depending on if passed in panel group is the last group for this query + */ + public boolean isLastSubQuery(TemporalSubQuery subQuery){ + return (getSubQueryIndex(subQuery)==(subQueryList.size()-1)); + } + + /** + * Get Query Timing + * + * Get the default timing passed in by the query object + * + * @return string containing the query timing constant + */ + public String getQueryTiming() { + return queryTiming; + } + + /** + * Get Data Source Lookup + * + * Returns the data source lookup object passed in in the constructor + * + * @return data source lookup object passed in the constructor + */ + protected DataSourceLookup getDataSourceLookup() { + return dsLookup; + } + public boolean isProtectedQuery() { + return isProtectedQuery; + } + + /** + * Get Database Schema + * + * Returns the name of the schema used to reference the correct table names in the sql syntax + * + * @return string that contains the name of the schema this query should run under + */ + public String getDatabaseSchema() { + String dbSchemaName = dsLookup.getFullSchema(); + if (dbSchemaName != null && dbSchemaName.endsWith(".")) { + return dbSchemaName.trim(); + } + else if (dbSchemaName != null) { + return dbSchemaName.trim() + "."; + } + return dbSchemaName; + } + + /** + * Get Server Type + * + * Returns the type of database server CRC is running against + * + * @return string containing the type of database CRC is running against (Sql Server or Oracle) + */ + protected String getServerType(){ + return dsLookup.getServerType(); + } + + /** + * Get Project Parameter Map + * + * Returns the map that was passed in in the constructor that contains the parameters used for this project + * + * @return map object that contains the project parameters + */ + protected Map getProjectParameterMap(){ + return this.projectParamMap; + } + + /** + * Get Timing Handler + * + * @return query timing handler object that tests timing text from query for various states + */ + protected QueryTimingHandler getTimingHandler(){ + if (timingHandler==null) + timingHandler = new QueryTimingHandler(); + return timingHandler; + } + + /** + * Get Temp Table Name + * + * Return the default name of the temproary table in the database. The temporary table is used to store the results of individual panel items and the joins + * of panel to panel items + * + * @return string containing the name of the default temporary table name in the database + */ + protected String getTempTableName(){ + if (this.tempTableNameMap==null) + this.tempTableNameMap = new TempTableNameMap(this.getServerType()); + String tableName = ""; + if (getServerType().equalsIgnoreCase(DAOFactoryHelper.ORACLE)){ + tableName = getDatabaseSchema(); + } + tableName += tempTableNameMap.getTempTableName(); + + return tableName; + } + + /** + * Get DX Temp Table Name + * + * Return the default name of the dx temporary table in the database. The dx table is used to return the final results of the query from the database to the + * CRC cell + * + * @return string containing the default name of the dx return table in database + */ + protected String getDxTempTableName(){ + if (this.tempTableNameMap==null) + this.tempTableNameMap = new TempTableNameMap(this.getServerType()); + String tableName = ""; + if (getServerType().equalsIgnoreCase(DAOFactoryHelper.ORACLE)){ + tableName = getDatabaseSchema(); + } + tableName += tempTableNameMap.getTempDxTableName(); + + return tableName; + } + + /** + * Get Master Temp Table Name + * + * Return default name of the master table in the database. The master table is used to temporarily store results from embedded query items + * and panel group constraints + * + * @return string containing the default name used for the "master" table in the database + */ + protected String getMasterTempTableName(){ + if (this.tempTableNameMap==null) + this.tempTableNameMap = new TempTableNameMap(this.getServerType()); + String tableName = ""; + if (getServerType().equalsIgnoreCase(DAOFactoryHelper.ORACLE)){ + tableName = getDatabaseSchema(); + } + tableName += tempTableNameMap.getTempMasterTable(); + + return tableName; + } + + /** + * Allow Large Text Value Constrian Flag + * + * @return true if text querying against large text fields is allowed, else false + */ + protected boolean allowLargeTextValueConstrainFlag(){ + return this.allowLargeTextValueConstrainFlag; + } + + protected List getUserRoles() { + return this.userRoles; + } + /** + * Return Encounter Num + * + * @return true if query needs to return encounter information in final results, else false + */ + protected boolean returnEncounterNum(){ + if (getTimingHandler().isSameVisit(queryTiming)) + return true; + else + return false; + } + + /** + * Return Instance Num + * + * @return true if query needs to return instance information is the final results, else false + */ + protected boolean returnInstanceNum(){ + if (getTimingHandler().isSameInstanceNum(queryTiming)) + return true; + else + return false; + } + + /** + * Get Panel Group Count + * + * @return int - the number of panel groups contained in this query + */ + protected int getSubQueryCount(){ + return subQueryList.size(); + } + + /** + * Generate Unique Id + * + * Returns a string with a guaranteed unique value. This method is used specifically to uniquely identify queries and + * panel groups within the context of the query + * + * @return string with a guaranteed unique value + */ + protected String generateUniqueId(){ + UUID uniqueKey = UUID.randomUUID(); + String hexNum = uniqueKey.toString().replace("-", ""); + BigInteger big = new BigInteger(hexNum, 16); + return big.toString(36); + } + + /** + * Get Query Id + * + * @return string containing the unique id of the query that is being run + */ + protected String getQueryId(){ + if (queryId==null) + queryId = generateUniqueId(); + return queryId; + } + + public int getMaxPanelIndex(){ + return this.maxPanelIndex; + } + + /** + * @return the processingLevel + */ + public int getProcessingLevel() { + return processingLevel; + } + + public TemporalQueryOptions getQueryOptions(){ + return options; + } + + /** + * @return the ignoredItemMessageBuffer + */ + public StringBuffer getIgnoredItemMessageBuffer() { + return ignoredItemMessageBuffer; + } + + public void addIgnoredMessage(String errorMessage) { + this.ignoredItemMessageBuffer.append(errorMessage + "\n"); + } + + /** + * @return the lastSubQueryId + */ + protected String getLastProcessedSubQueryId() { + return lastSubQueryId; + } + + protected void addPreProcessingSql(String sql){ + if (sql!=null&&sql.trim().length()>0) + this.preProcessingSql.add(sql); + } + + protected void addPostProcessingSql(String sql){ + if (sql!=null&&sql.trim().length()>0) + this.postProcessingSql.add(sql); + } + + public String getSqlDelimiter() { + return "\n<*>\n"; + } + + + /** + * Build Temp Table Check Drop + * + * Create a Sql Server specific statement to check for the existence of a temporary table and, + * if the table exists, drop it + * + * @param tempTableName String name of the temporary table + * @return String sql statement that checks for temporary table and drops it + */ + protected String buildTempTableCheckDrop(String tempTableName) { + if (tempTableName == null) + return ""; + else if (!tempTableName.startsWith("#")) + tempTableName = "#" + tempTableName; + + return "if (object_id('tempdb.." + tempTableName + "') is not null) \n" + + "begin \n" + "drop table " + tempTableName + " \n" + "end"; + } + + protected boolean useSqlServerTempTables(){ + return ((this.getQueryOptions().getQueryConstraintLogic()==QueryConstraintStrategy.TEMP_TABLES) && + (this.getServerType().equalsIgnoreCase(DAOFactoryHelper.SQLSERVER))); + } + +} + + diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalQueryBuilder.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalQueryBuilder.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalQueryBuilder.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalQueryBuilder.java index 7f0c6d7a..d765a98c --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalQueryBuilder.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalQueryBuilder.java @@ -1,161 +1,161 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Christopher Herrick - */ -package edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal; - -import java.util.List; -import java.util.Map; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.ProcessTimingReportUtil; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.util.LogTimingUtil; -import edu.harvard.i2b2.crc.util.ParamUtil; - -public class TemporalQueryBuilder extends CRCDAO { - - protected final Log logesapi = LogFactory.getLog(getClass()); - - private StringBuffer sqlBuffer = new StringBuffer(); - private StringBuffer ignoredItemBuffer = new StringBuffer(); - private DataSourceLookup dataSourceLookup = null; - private String queryXML = null; - private StringBuffer processTimingMessageBuffer = new StringBuffer(); - private Map projectParamMap = null; - private String processTimingFlag = ""; - private boolean allowLargeTextValueConstrainFlag = true; - private List userRoles = null; - private boolean queryWithoutTempTableFlag = false; - private boolean isTemporalQuery = false; - private boolean isProtectedQuery = false; - - public TemporalQueryBuilder(DataSourceLookup dataSourceLookup, - String queryXML) { - this.dataSourceLookup = dataSourceLookup; - this.queryXML = queryXML; - this.setDbSchemaName(dataSourceLookup.getFullSchema()); - } - - public String getProcessTimingMessage() { - return this.processTimingMessageBuffer.toString(); - } - - public Map getProjectParamMap() { - return this.projectParamMap; - } - - public void setProjectParamMap(Map projectParamMap) { - this.projectParamMap = projectParamMap; - if (projectParamMap != null - && projectParamMap.get(ParamUtil.PM_ENABLE_PROCESS_TIMING) != null) { - this.processTimingFlag = (String) projectParamMap - .get(ParamUtil.PM_ENABLE_PROCESS_TIMING); - } - } - - public void setAllowLargeTextValueConstrainFlag( - boolean allowLargeTextValueConstrainFlag) { - this.allowLargeTextValueConstrainFlag = allowLargeTextValueConstrainFlag; - } - public void setUserRoles( - List userRoles) { - this.userRoles = userRoles; - } - - public String getSql() { - return sqlBuffer.toString(); - } - - public String getIgnoredItemMessage() { - return ignoredItemBuffer.toString(); - } - - public void startSqlBuild() throws JAXBUtilException, I2B2Exception { - LogTimingUtil logTimingUtil = new LogTimingUtil(); - logTimingUtil.setStartTime(); - - execQuery(this.queryXML, null, 0); - - logTimingUtil.setEndTime(); - if (processTimingFlag.equalsIgnoreCase(ProcessTimingReportUtil.INFO) - || processTimingFlag - .equalsIgnoreCase(ProcessTimingReportUtil.DEBUG)) { - ProcessTimingReportUtil ptrUtil = new ProcessTimingReportUtil( - this.dataSourceLookup); - this.processTimingMessageBuffer.append(ptrUtil.buildProcessTiming( - logTimingUtil, "BUILD SQL", null)); - } - } - - private String[] execQuery(String requestXML, String itemName, int level) - throws JAXBUtilException, I2B2Exception { - - TemporalQueryHandler queryTool = null; - queryTool = new TemporalQueryHandler(dataSourceLookup, requestXML, false); - queryTool.setProjectParamMap(this.projectParamMap); - - if (this.processTimingFlag.equalsIgnoreCase(ProcessTimingReportUtil.DEBUG)) { - queryTool.setProcessTimingFlag(this.processTimingFlag); - } - - queryTool.setAllowLargeTextValueConstrainFlag(allowLargeTextValueConstrainFlag); - queryTool.setUserRoles(userRoles); - queryTool.setQueryWithoutTempTableFlag(queryWithoutTempTableFlag); - - String sql = queryTool.buildSql(); - String maxPanelNum = String.valueOf(queryTool.getMaxPanelNumber()); - this.isTemporalQuery = queryTool.isTemporalQuery(); - this.isProtectedQuery = queryTool.isProtectedQuery(); - - ignoredItemBuffer.append(queryTool.getIgnoredItemMessage()); - if (this.processTimingFlag - .equalsIgnoreCase(ProcessTimingReportUtil.DEBUG)) { - processTimingMessageBuffer.append(queryTool - .getProcessTimingMessage()); - } - - logesapi.debug("generated sql " + sql); - sqlBuffer.append(sql); - - return new String[] { sql, maxPanelNum }; - } - - /** - * @return the queryWithoutTempTableFlag - */ - public boolean getQueryWithoutTempTableFlag() { - return queryWithoutTempTableFlag; - } - - /** - * @param queryWithoutTempTableFlag the queryWithoutTempTableFlag to set - */ - public void setQueryWithoutTempTableFlag(boolean queryWithoutTempTableFlag) { - this.queryWithoutTempTableFlag = queryWithoutTempTableFlag; - } - - public boolean isTemporalQuery(){ - return this.isTemporalQuery; - } - - public boolean isProtectedQuery() { - return isProtectedQuery; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Christopher Herrick + */ +package edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal; + +import java.util.List; +import java.util.Map; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.ProcessTimingReportUtil; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.util.LogTimingUtil; +import edu.harvard.i2b2.crc.util.ParamUtil; + +public class TemporalQueryBuilder extends CRCDAO { + + protected final Log logesapi = LogFactory.getLog(getClass()); + + private StringBuffer sqlBuffer = new StringBuffer(); + private StringBuffer ignoredItemBuffer = new StringBuffer(); + private DataSourceLookup dataSourceLookup = null; + private String queryXML = null; + private StringBuffer processTimingMessageBuffer = new StringBuffer(); + private Map projectParamMap = null; + private String processTimingFlag = ""; + private boolean allowLargeTextValueConstrainFlag = true; + private List userRoles = null; + private boolean queryWithoutTempTableFlag = false; + private boolean isTemporalQuery = false; + private boolean isProtectedQuery = false; + + public TemporalQueryBuilder(DataSourceLookup dataSourceLookup, + String queryXML) { + this.dataSourceLookup = dataSourceLookup; + this.queryXML = queryXML; + this.setDbSchemaName(dataSourceLookup.getFullSchema()); + } + + public String getProcessTimingMessage() { + return this.processTimingMessageBuffer.toString(); + } + + public Map getProjectParamMap() { + return this.projectParamMap; + } + + public void setProjectParamMap(Map projectParamMap) { + this.projectParamMap = projectParamMap; + if (projectParamMap != null + && projectParamMap.get(ParamUtil.PM_ENABLE_PROCESS_TIMING) != null) { + this.processTimingFlag = (String) projectParamMap + .get(ParamUtil.PM_ENABLE_PROCESS_TIMING); + } + } + + public void setAllowLargeTextValueConstrainFlag( + boolean allowLargeTextValueConstrainFlag) { + this.allowLargeTextValueConstrainFlag = allowLargeTextValueConstrainFlag; + } + public void setUserRoles( + List userRoles) { + this.userRoles = userRoles; + } + + public String getSql() { + return sqlBuffer.toString(); + } + + public String getIgnoredItemMessage() { + return ignoredItemBuffer.toString(); + } + + public void startSqlBuild() throws JAXBUtilException, I2B2Exception { + LogTimingUtil logTimingUtil = new LogTimingUtil(); + logTimingUtil.setStartTime(); + + execQuery(this.queryXML, null, 0); + + logTimingUtil.setEndTime(); + if (processTimingFlag.equalsIgnoreCase(ProcessTimingReportUtil.INFO) + || processTimingFlag + .equalsIgnoreCase(ProcessTimingReportUtil.DEBUG)) { + ProcessTimingReportUtil ptrUtil = new ProcessTimingReportUtil( + this.dataSourceLookup); + this.processTimingMessageBuffer.append(ptrUtil.buildProcessTiming( + logTimingUtil, "BUILD SQL", null)); + } + } + + private String[] execQuery(String requestXML, String itemName, int level) + throws JAXBUtilException, I2B2Exception { + + TemporalQueryHandler queryTool = null; + queryTool = new TemporalQueryHandler(dataSourceLookup, requestXML, false); + queryTool.setProjectParamMap(this.projectParamMap); + + if (this.processTimingFlag.equalsIgnoreCase(ProcessTimingReportUtil.DEBUG)) { + queryTool.setProcessTimingFlag(this.processTimingFlag); + } + + queryTool.setAllowLargeTextValueConstrainFlag(allowLargeTextValueConstrainFlag); + queryTool.setUserRoles(userRoles); + queryTool.setQueryWithoutTempTableFlag(queryWithoutTempTableFlag); + + String sql = queryTool.buildSql(); + String maxPanelNum = String.valueOf(queryTool.getMaxPanelNumber()); + this.isTemporalQuery = queryTool.isTemporalQuery(); + this.isProtectedQuery = queryTool.isProtectedQuery(); + + ignoredItemBuffer.append(queryTool.getIgnoredItemMessage()); + if (this.processTimingFlag + .equalsIgnoreCase(ProcessTimingReportUtil.DEBUG)) { + processTimingMessageBuffer.append(queryTool + .getProcessTimingMessage()); + } + + logesapi.debug("generated sql " + sql); + sqlBuffer.append(sql); + + return new String[] { sql, maxPanelNum }; + } + + /** + * @return the queryWithoutTempTableFlag + */ + public boolean getQueryWithoutTempTableFlag() { + return queryWithoutTempTableFlag; + } + + /** + * @param queryWithoutTempTableFlag the queryWithoutTempTableFlag to set + */ + public void setQueryWithoutTempTableFlag(boolean queryWithoutTempTableFlag) { + this.queryWithoutTempTableFlag = queryWithoutTempTableFlag; + } + + public boolean isTemporalQuery(){ + return this.isTemporalQuery; + } + + public boolean isProtectedQuery() { + return isProtectedQuery; + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalQueryConstraintMapping.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalQueryConstraintMapping.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalQueryConstraintMapping.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalQueryConstraintMapping.java index b2e76946..db732217 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalQueryConstraintMapping.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalQueryConstraintMapping.java @@ -1,230 +1,230 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Christopher Herrick - */ -package edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal; - -import java.util.ArrayList; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.List; - -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.QueryTimingHandler; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryJoinColumnType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryJoinType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryOperatorType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryAggregateOperatorType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryConstraintType; - -public class TemporalQueryConstraintMapping { - - private HashMap>> constraints = new HashMap>>(); - private HashMap> returnColumns = new HashMap>(); - private ArrayList orderedSet = new ArrayList(); - - public TemporalQueryConstraintMapping(QueryDefinitionType queryDef){ - parseConstraints(queryDef); - } - - public HashMap> getConstraintsForQuery(String eventId){ - if (eventId==null) - return null; - else - return constraints.get(eventId); - } - - public EnumSet getReturnColumnsForQuery(String eventId){ - if (eventId==null) - return null; - else - return returnColumns.get(eventId); - } - - public List getOrderedQueryList(){ - return orderedSet; - } - - private void parseConstraints(QueryDefinitionType queryDef){ - if (queryDef.getSubqueryConstraint()!=null&&queryDef.getSubqueryConstraint().size()>0){ - - //first, preprocess constraints to figure out which queries have the most - HashMap constraintCounts = new HashMap(); - for (QueryConstraintType constraint : queryDef.getSubqueryConstraint()){ - - Integer firstCount = constraintCounts.get(constraint.getFirstQuery().getQueryId()); - if (firstCount==null) - firstCount = 1; - else - firstCount++; - constraintCounts.put(constraint.getFirstQuery().getQueryId(), firstCount); - - Integer secondCount = constraintCounts.get(constraint.getSecondQuery().getQueryId()); - if (secondCount==null) - secondCount = 1; - else - secondCount++; - constraintCounts.put(constraint.getSecondQuery().getQueryId(), secondCount); - } - - for (QueryConstraintType constraint : queryDef.getSubqueryConstraint()){ - - //rule one: process first and last prior to an any - //rule two: query with fewer constraints should be processed first - //rule three: first occurring query in constraint should go first - - String firstQuery = constraint.getFirstQuery().getQueryId(); - String secondQuery = constraint.getSecondQuery().getQueryId(); - if ((constraint.getFirstQuery().getAggregateOperator()==QueryAggregateOperatorType.ANY)&& - ((constraint.getSecondQuery().getAggregateOperator()==QueryAggregateOperatorType.FIRST)|| - (constraint.getSecondQuery().getAggregateOperator()==QueryAggregateOperatorType.LAST))){ - firstQuery = constraint.getSecondQuery().getQueryId(); - secondQuery = constraint.getFirstQuery().getQueryId(); - } - else if ((constraint.getSecondQuery().getAggregateOperator()==QueryAggregateOperatorType.ANY)&& - ((constraint.getFirstQuery().getAggregateOperator()==QueryAggregateOperatorType.FIRST)|| - (constraint.getFirstQuery().getAggregateOperator()==QueryAggregateOperatorType.LAST))){ - firstQuery = constraint.getFirstQuery().getQueryId(); - secondQuery = constraint.getSecondQuery().getQueryId(); - } - else { - Integer firstConstraints = -1; - Integer secondConstraints = -1; - if (constraintCounts.get(firstQuery)!=null) - firstConstraints = constraintCounts.get(firstQuery); - if (constraintCounts.get(secondQuery)!=null) - secondConstraints = constraintCounts.get(secondQuery); - - if (firstConstraints==null) - firstConstraints = -1; - if (secondConstraints==null) - secondConstraints = -1; - - if (firstConstraints=orderedSet.size()) - orderedSet.add(secondQuery); - else - orderedSet.add((firstIndex+1), secondQuery); - } - else if (secondIndex>firstIndex){ - orderedSet.remove(secondIndex); - orderedSet.add(firstIndex, secondQuery); - } - - //attach constraints to event that came last - - HashMap> constraintMapping = constraints.get(secondQuery); - if (constraintMapping==null) - constraintMapping = new HashMap>(); - List constraintList = constraintMapping.get(firstQuery); - if (constraintList==null) - constraintList = new ArrayList(); - constraintList.add(constraint); - constraintMapping.put(firstQuery, constraintList); - constraints.put(secondQuery, constraintMapping); - - parseReturnColumns(constraint.getFirstQuery(), queryDef.getQueryTiming()); - parseReturnColumns(constraint.getSecondQuery(), queryDef.getQueryTiming()); - } - } - } - - private void parseReturnColumns(QueryJoinType eventJoin, String queryTiming){ - String eventId = eventJoin.getQueryId(); - EnumSet columns = returnColumns.get(eventId); - - QueryJoinColumnType joinColumn = eventJoin.getJoinColumn(); - if (joinColumn!=null){ - TemporalSubQuery.TemporalQueryReturnColumns value = null; - if (joinColumn.equals(QueryJoinColumnType.ENCOUNTER)) - value = TemporalSubQuery.TemporalQueryReturnColumns.ENCOUNTER; - else if (joinColumn.equals(QueryJoinColumnType.PATIENT)) - value = TemporalSubQuery.TemporalQueryReturnColumns.PATIENT; - else if (joinColumn.equals(QueryJoinColumnType.INSTANCE)) - value = TemporalSubQuery.TemporalQueryReturnColumns.INSTANCE; - else if (joinColumn.equals(QueryJoinColumnType.STARTDATE)){ - if (eventJoin.getAggregateOperator().equals(QueryAggregateOperatorType.FIRST)) - value = TemporalSubQuery.TemporalQueryReturnColumns.FIRST_START_DATE; - else if (eventJoin.getAggregateOperator().equals(QueryAggregateOperatorType.LAST)) - value = TemporalSubQuery.TemporalQueryReturnColumns.LAST_START_DATE; - else - value = TemporalSubQuery.TemporalQueryReturnColumns.START_DATE; - } - else if (joinColumn.equals(QueryJoinColumnType.ENDDATE)) - if (eventJoin.getAggregateOperator().equals(QueryAggregateOperatorType.FIRST)) - value = TemporalSubQuery.TemporalQueryReturnColumns.FIRST_END_DATE; - else if (eventJoin.getAggregateOperator().equals(QueryAggregateOperatorType.LAST)) - value = TemporalSubQuery.TemporalQueryReturnColumns.LAST_END_DATE; - else - value = TemporalSubQuery.TemporalQueryReturnColumns.END_DATE; - else if (joinColumn.equals(QueryJoinColumnType.ENCOUNTER_STARTDATE)){ - if (eventJoin.getAggregateOperator().equals(QueryAggregateOperatorType.FIRST)) - value = TemporalSubQuery.TemporalQueryReturnColumns.FIRST_ENCOUNTER_START_DATE; - else if (eventJoin.getAggregateOperator().equals(QueryAggregateOperatorType.LAST)) - value = TemporalSubQuery.TemporalQueryReturnColumns.LAST_ENCOUNTER_START_DATE; - else - value = TemporalSubQuery.TemporalQueryReturnColumns.ENCOUNTER_START_DATE; - } - else if (joinColumn.equals(QueryJoinColumnType.ENCOUNTER_ENDDATE)) - if (eventJoin.getAggregateOperator().equals(QueryAggregateOperatorType.FIRST)) - value = TemporalSubQuery.TemporalQueryReturnColumns.FIRST_ENCOUNTER_END_DATE; - else if (eventJoin.getAggregateOperator().equals(QueryAggregateOperatorType.LAST)) - value = TemporalSubQuery.TemporalQueryReturnColumns.LAST_ENCOUNTER_END_DATE; - else - value = TemporalSubQuery.TemporalQueryReturnColumns.ENCOUNTER_START_DATE; - else - value = TemporalSubQuery.TemporalQueryReturnColumns.PATIENT; - - if (columns==null) - columns = EnumSet.of(value); - else - columns.add(value); - } - else - columns = EnumSet.of(TemporalSubQuery.TemporalQueryReturnColumns.PATIENT); - - - if (queryTiming!=null&& - (queryTiming.equalsIgnoreCase(QueryTimingHandler.SAME)|| - queryTiming.equalsIgnoreCase(QueryTimingHandler.SAMEVISIT))){ - columns.add(TemporalSubQuery.TemporalQueryReturnColumns.ENCOUNTER); - } - - returnColumns.put(eventId, columns); - - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Christopher Herrick + */ +package edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal; + +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.HashMap; +import java.util.List; + +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.QueryTimingHandler; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryJoinColumnType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryJoinType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryOperatorType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryAggregateOperatorType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryConstraintType; + +public class TemporalQueryConstraintMapping { + + private HashMap>> constraints = new HashMap>>(); + private HashMap> returnColumns = new HashMap>(); + private ArrayList orderedSet = new ArrayList(); + + public TemporalQueryConstraintMapping(QueryDefinitionType queryDef){ + parseConstraints(queryDef); + } + + public HashMap> getConstraintsForQuery(String eventId){ + if (eventId==null) + return null; + else + return constraints.get(eventId); + } + + public EnumSet getReturnColumnsForQuery(String eventId){ + if (eventId==null) + return null; + else + return returnColumns.get(eventId); + } + + public List getOrderedQueryList(){ + return orderedSet; + } + + private void parseConstraints(QueryDefinitionType queryDef){ + if (queryDef.getSubqueryConstraint()!=null&&queryDef.getSubqueryConstraint().size()>0){ + + //first, preprocess constraints to figure out which queries have the most + HashMap constraintCounts = new HashMap(); + for (QueryConstraintType constraint : queryDef.getSubqueryConstraint()){ + + Integer firstCount = constraintCounts.get(constraint.getFirstQuery().getQueryId()); + if (firstCount==null) + firstCount = 1; + else + firstCount++; + constraintCounts.put(constraint.getFirstQuery().getQueryId(), firstCount); + + Integer secondCount = constraintCounts.get(constraint.getSecondQuery().getQueryId()); + if (secondCount==null) + secondCount = 1; + else + secondCount++; + constraintCounts.put(constraint.getSecondQuery().getQueryId(), secondCount); + } + + for (QueryConstraintType constraint : queryDef.getSubqueryConstraint()){ + + //rule one: process first and last prior to an any + //rule two: query with fewer constraints should be processed first + //rule three: first occurring query in constraint should go first + + String firstQuery = constraint.getFirstQuery().getQueryId(); + String secondQuery = constraint.getSecondQuery().getQueryId(); + if ((constraint.getFirstQuery().getAggregateOperator()==QueryAggregateOperatorType.ANY)&& + ((constraint.getSecondQuery().getAggregateOperator()==QueryAggregateOperatorType.FIRST)|| + (constraint.getSecondQuery().getAggregateOperator()==QueryAggregateOperatorType.LAST))){ + firstQuery = constraint.getSecondQuery().getQueryId(); + secondQuery = constraint.getFirstQuery().getQueryId(); + } + else if ((constraint.getSecondQuery().getAggregateOperator()==QueryAggregateOperatorType.ANY)&& + ((constraint.getFirstQuery().getAggregateOperator()==QueryAggregateOperatorType.FIRST)|| + (constraint.getFirstQuery().getAggregateOperator()==QueryAggregateOperatorType.LAST))){ + firstQuery = constraint.getFirstQuery().getQueryId(); + secondQuery = constraint.getSecondQuery().getQueryId(); + } + else { + Integer firstConstraints = -1; + Integer secondConstraints = -1; + if (constraintCounts.get(firstQuery)!=null) + firstConstraints = constraintCounts.get(firstQuery); + if (constraintCounts.get(secondQuery)!=null) + secondConstraints = constraintCounts.get(secondQuery); + + if (firstConstraints==null) + firstConstraints = -1; + if (secondConstraints==null) + secondConstraints = -1; + + if (firstConstraints=orderedSet.size()) + orderedSet.add(secondQuery); + else + orderedSet.add((firstIndex+1), secondQuery); + } + else if (secondIndex>firstIndex){ + orderedSet.remove(secondIndex); + orderedSet.add(firstIndex, secondQuery); + } + + //attach constraints to event that came last + + HashMap> constraintMapping = constraints.get(secondQuery); + if (constraintMapping==null) + constraintMapping = new HashMap>(); + List constraintList = constraintMapping.get(firstQuery); + if (constraintList==null) + constraintList = new ArrayList(); + constraintList.add(constraint); + constraintMapping.put(firstQuery, constraintList); + constraints.put(secondQuery, constraintMapping); + + parseReturnColumns(constraint.getFirstQuery(), queryDef.getQueryTiming()); + parseReturnColumns(constraint.getSecondQuery(), queryDef.getQueryTiming()); + } + } + } + + private void parseReturnColumns(QueryJoinType eventJoin, String queryTiming){ + String eventId = eventJoin.getQueryId(); + EnumSet columns = returnColumns.get(eventId); + + QueryJoinColumnType joinColumn = eventJoin.getJoinColumn(); + if (joinColumn!=null){ + TemporalSubQuery.TemporalQueryReturnColumns value = null; + if (joinColumn.equals(QueryJoinColumnType.ENCOUNTER)) + value = TemporalSubQuery.TemporalQueryReturnColumns.ENCOUNTER; + else if (joinColumn.equals(QueryJoinColumnType.PATIENT)) + value = TemporalSubQuery.TemporalQueryReturnColumns.PATIENT; + else if (joinColumn.equals(QueryJoinColumnType.INSTANCE)) + value = TemporalSubQuery.TemporalQueryReturnColumns.INSTANCE; + else if (joinColumn.equals(QueryJoinColumnType.STARTDATE)){ + if (eventJoin.getAggregateOperator().equals(QueryAggregateOperatorType.FIRST)) + value = TemporalSubQuery.TemporalQueryReturnColumns.FIRST_START_DATE; + else if (eventJoin.getAggregateOperator().equals(QueryAggregateOperatorType.LAST)) + value = TemporalSubQuery.TemporalQueryReturnColumns.LAST_START_DATE; + else + value = TemporalSubQuery.TemporalQueryReturnColumns.START_DATE; + } + else if (joinColumn.equals(QueryJoinColumnType.ENDDATE)) + if (eventJoin.getAggregateOperator().equals(QueryAggregateOperatorType.FIRST)) + value = TemporalSubQuery.TemporalQueryReturnColumns.FIRST_END_DATE; + else if (eventJoin.getAggregateOperator().equals(QueryAggregateOperatorType.LAST)) + value = TemporalSubQuery.TemporalQueryReturnColumns.LAST_END_DATE; + else + value = TemporalSubQuery.TemporalQueryReturnColumns.END_DATE; + else if (joinColumn.equals(QueryJoinColumnType.ENCOUNTER_STARTDATE)){ + if (eventJoin.getAggregateOperator().equals(QueryAggregateOperatorType.FIRST)) + value = TemporalSubQuery.TemporalQueryReturnColumns.FIRST_ENCOUNTER_START_DATE; + else if (eventJoin.getAggregateOperator().equals(QueryAggregateOperatorType.LAST)) + value = TemporalSubQuery.TemporalQueryReturnColumns.LAST_ENCOUNTER_START_DATE; + else + value = TemporalSubQuery.TemporalQueryReturnColumns.ENCOUNTER_START_DATE; + } + else if (joinColumn.equals(QueryJoinColumnType.ENCOUNTER_ENDDATE)) + if (eventJoin.getAggregateOperator().equals(QueryAggregateOperatorType.FIRST)) + value = TemporalSubQuery.TemporalQueryReturnColumns.FIRST_ENCOUNTER_END_DATE; + else if (eventJoin.getAggregateOperator().equals(QueryAggregateOperatorType.LAST)) + value = TemporalSubQuery.TemporalQueryReturnColumns.LAST_ENCOUNTER_END_DATE; + else + value = TemporalSubQuery.TemporalQueryReturnColumns.ENCOUNTER_START_DATE; + else + value = TemporalSubQuery.TemporalQueryReturnColumns.PATIENT; + + if (columns==null) + columns = EnumSet.of(value); + else + columns.add(value); + } + else + columns = EnumSet.of(TemporalSubQuery.TemporalQueryReturnColumns.PATIENT); + + + if (queryTiming!=null&& + (queryTiming.equalsIgnoreCase(QueryTimingHandler.SAME)|| + queryTiming.equalsIgnoreCase(QueryTimingHandler.SAMEVISIT))){ + columns.add(TemporalSubQuery.TemporalQueryReturnColumns.ENCOUNTER); + } + + returnColumns.put(eventId, columns); + + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalQueryHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalQueryHandler.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalQueryHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalQueryHandler.java index fbf0dbbc..67ce8b63 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalQueryHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalQueryHandler.java @@ -1,152 +1,152 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Christopher Herrick - */ -package edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal; - - -import java.util.List; -import java.util.Map; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.ProcessTimingReportUtil; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal.TemporalQueryOptions.QueryConstraintStrategy; - -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; - - -public class TemporalQueryHandler extends CRCDAO { - - protected final Log logesapi = LogFactory.getLog(getClass()); - - private DataSourceLookup dataSourceLookup = null; - private String queryXML = null; - private String noLockSqlServer = " "; - private String tempTableName = " "; - private String tempDxTableName = " "; - private StringBuffer ignoredItemMessageBuffer = new StringBuffer(); - private boolean encounterSetOutputFlag = false; - private int maxPanelNum = 0; - private ProcessTimingReportUtil processTimingUtil = null; - private String processTimingFlag = ProcessTimingReportUtil.NONE; - private Map projectParamMap = null; - private StringBuffer processTimingStr = new StringBuffer(); - private boolean allowLargeTextValueConstrainFlag = true; - private List userRoles = null; - private boolean queryWithoutTempTableFlag = false; - private boolean isTemporalQuery = false; - private boolean isProtectedQuery = false; - - public TemporalQueryHandler(DataSourceLookup dataSourceLookup, String queryXML, - boolean encounterSetOutputFlag) { - this.setDbSchemaName(dataSourceLookup.getFullSchema()); - this.dataSourceLookup = dataSourceLookup; - this.queryXML = queryXML; - this.encounterSetOutputFlag = encounterSetOutputFlag; - try { - this.processTimingUtil = new ProcessTimingReportUtil(dataSourceLookup); - } catch (I2B2DAOException e) { - log.error("Error creating ProcessTimingReportUtil [" + e.getMessage() + "]"); - } - - if (this.dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER)) { - noLockSqlServer = " WITH(NOLOCK) "; - tempTableName = "#global_temp_table"; - tempDxTableName = "#dx"; - } else if (this.dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE) || this.dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.POSTGRESQL)) { - tempTableName = "QUERY_GLOBAL_TEMP"; - tempDxTableName = "DX"; - } - } - - public int getMaxPanelNumber() { - return maxPanelNum; - } - - public void setProcessTimingFlag(String level) { - this.processTimingFlag = level; - } - - public void setProjectParamMap(Map projectParamMap) { - this.projectParamMap = projectParamMap; - } - - public String getProcessTimingMessage() { - return this.processTimingStr.toString(); - } - - public void setAllowLargeTextValueConstrainFlag(boolean allowLargeTextValueConstrainFlag) { - this.allowLargeTextValueConstrainFlag = allowLargeTextValueConstrainFlag; - } - - public void setUserRoles(List userRoles) { - this.userRoles = userRoles; - } - - public String buildSql() throws JAXBUtilException, I2B2Exception { - TemporalQuery tQuery = new TemporalQuery(this.dataSourceLookup, this.projectParamMap, this.queryXML, this.allowLargeTextValueConstrainFlag, this.userRoles); - if (this.queryWithoutTempTableFlag) - tQuery.getQueryOptions().setQueryConstraintLogic(QueryConstraintStrategy.DERIVED_TABLES); - String tQuerySql = tQuery.buildSql(); - this.ignoredItemMessageBuffer = tQuery.getIgnoredItemMessageBuffer(); - this.maxPanelNum = tQuery.getMaxPanelIndex(); - this.isTemporalQuery = (tQuery.getSubQueryCount()>1?true:false); - this.isProtectedQuery = tQuery.isProtectedQuery(); - logesapi.debug(tQuerySql); - - return tQuerySql; - - } - - public String getIgnoredItemMessage() { - if (this.ignoredItemMessageBuffer != null - && this.ignoredItemMessageBuffer.length() > 0) { - return "Missing Concept in Ontology Cell : \n" - + this.ignoredItemMessageBuffer.toString(); - } else { - return ""; - } - } - - /** - * @return the queryWithoutTempTableFlag - */ - public boolean getQueryWithoutTempTableFlag() { - return queryWithoutTempTableFlag; - } - - /** - * @param queryWithoutTempTableFlag the queryWithoutTempTableFlag to set - */ - public void setQueryWithoutTempTableFlag(boolean queryWithoutTempTableFlag) { - this.queryWithoutTempTableFlag = queryWithoutTempTableFlag; - } - - public boolean isTemporalQuery(){ - return this.isTemporalQuery; - } - - public boolean isProtectedQuery() { - return isProtectedQuery; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Christopher Herrick + */ +package edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal; + + +import java.util.List; +import java.util.Map; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.ProcessTimingReportUtil; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal.TemporalQueryOptions.QueryConstraintStrategy; + +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; + + +public class TemporalQueryHandler extends CRCDAO { + + protected final Log logesapi = LogFactory.getLog(getClass()); + + private DataSourceLookup dataSourceLookup = null; + private String queryXML = null; + private String noLockSqlServer = " "; + private String tempTableName = " "; + private String tempDxTableName = " "; + private StringBuffer ignoredItemMessageBuffer = new StringBuffer(); + private boolean encounterSetOutputFlag = false; + private int maxPanelNum = 0; + private ProcessTimingReportUtil processTimingUtil = null; + private String processTimingFlag = ProcessTimingReportUtil.NONE; + private Map projectParamMap = null; + private StringBuffer processTimingStr = new StringBuffer(); + private boolean allowLargeTextValueConstrainFlag = true; + private List userRoles = null; + private boolean queryWithoutTempTableFlag = false; + private boolean isTemporalQuery = false; + private boolean isProtectedQuery = false; + + public TemporalQueryHandler(DataSourceLookup dataSourceLookup, String queryXML, + boolean encounterSetOutputFlag) { + this.setDbSchemaName(dataSourceLookup.getFullSchema()); + this.dataSourceLookup = dataSourceLookup; + this.queryXML = queryXML; + this.encounterSetOutputFlag = encounterSetOutputFlag; + try { + this.processTimingUtil = new ProcessTimingReportUtil(dataSourceLookup); + } catch (I2B2DAOException e) { + log.error("Error creating ProcessTimingReportUtil [" + e.getMessage() + "]"); + } + + if (this.dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER)) { + noLockSqlServer = " WITH(NOLOCK) "; + tempTableName = "#global_temp_table"; + tempDxTableName = "#dx"; + } else if (this.dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.ORACLE) || this.dataSourceLookup.getServerType().equalsIgnoreCase( + DAOFactoryHelper.POSTGRESQL)) { + tempTableName = "QUERY_GLOBAL_TEMP"; + tempDxTableName = "DX"; + } + } + + public int getMaxPanelNumber() { + return maxPanelNum; + } + + public void setProcessTimingFlag(String level) { + this.processTimingFlag = level; + } + + public void setProjectParamMap(Map projectParamMap) { + this.projectParamMap = projectParamMap; + } + + public String getProcessTimingMessage() { + return this.processTimingStr.toString(); + } + + public void setAllowLargeTextValueConstrainFlag(boolean allowLargeTextValueConstrainFlag) { + this.allowLargeTextValueConstrainFlag = allowLargeTextValueConstrainFlag; + } + + public void setUserRoles(List userRoles) { + this.userRoles = userRoles; + } + + public String buildSql() throws JAXBUtilException, I2B2Exception { + TemporalQuery tQuery = new TemporalQuery(this.dataSourceLookup, this.projectParamMap, this.queryXML, this.allowLargeTextValueConstrainFlag, this.userRoles); + if (this.queryWithoutTempTableFlag) + tQuery.getQueryOptions().setQueryConstraintLogic(QueryConstraintStrategy.DERIVED_TABLES); + String tQuerySql = tQuery.buildSql(); + this.ignoredItemMessageBuffer = tQuery.getIgnoredItemMessageBuffer(); + this.maxPanelNum = tQuery.getMaxPanelIndex(); + this.isTemporalQuery = (tQuery.getSubQueryCount()>1?true:false); + this.isProtectedQuery = tQuery.isProtectedQuery(); + logesapi.debug(tQuerySql); + + return tQuerySql; + + } + + public String getIgnoredItemMessage() { + if (this.ignoredItemMessageBuffer != null + && this.ignoredItemMessageBuffer.length() > 0) { + return "Missing Concept in Ontology Cell : \n" + + this.ignoredItemMessageBuffer.toString(); + } else { + return ""; + } + } + + /** + * @return the queryWithoutTempTableFlag + */ + public boolean getQueryWithoutTempTableFlag() { + return queryWithoutTempTableFlag; + } + + /** + * @param queryWithoutTempTableFlag the queryWithoutTempTableFlag to set + */ + public void setQueryWithoutTempTableFlag(boolean queryWithoutTempTableFlag) { + this.queryWithoutTempTableFlag = queryWithoutTempTableFlag; + } + + public boolean isTemporalQuery(){ + return this.isTemporalQuery; + } + + public boolean isProtectedQuery() { + return isProtectedQuery; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalQueryOptions.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalQueryOptions.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalQueryOptions.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalQueryOptions.java index 5b3783d7..975ed558 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalQueryOptions.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalQueryOptions.java @@ -1,139 +1,139 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Christopher Herrick - */ -package edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal; - -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - -public class TemporalQueryOptions { - - - public enum QueryConstraintStrategy{ - TEMP_TABLES, - WITH_STATEMENT, - DERIVED_TABLES - } - - public enum TemporalConstraintStrategy{ - TEMP_TABLE_UPDATE, - WITH_CONSTRAINT - } - - - private boolean usePanelLevelOccurrence = false; - private QueryConstraintStrategy queryConstraintLogic = QueryConstraintStrategy.WITH_STATEMENT; - private TemporalConstraintStrategy temporalConstraintLogic = TemporalConstraintStrategy.TEMP_TABLE_UPDATE; - private boolean useItemGroupByStatement = true; - private boolean useSqlHints = true; - private boolean derivedFactTable = QueryProcessorUtil.getInstance().getDerivedFactTable(); - - /** - * @return the usePanelLevelOccurrence - */ - public boolean usePanelLevelOccurrence() { - return usePanelLevelOccurrence; - } - - public enum InvertedConstraintStrategy{ - NOT_EXISTS, - MINUS_CLAUSE - } - private InvertedConstraintStrategy invertedConstraintLogic = InvertedConstraintStrategy.NOT_EXISTS; - - /** - * @param usePanelLevelOccurrence the usePanelLevelOccurrence to set - */ - public void setUsePanelLevelOccurrence(boolean usePanelLevelOccurrence) { - this.usePanelLevelOccurrence = usePanelLevelOccurrence; - } - - /** - * @return the queryConstraintLogic - */ - public QueryConstraintStrategy getQueryConstraintLogic() { - return queryConstraintLogic; - } - - /** - * @param queryConstraintLogic the queryConstraintLogic to set - */ - public void setQueryConstraintLogic(QueryConstraintStrategy queryConstraintLogic) { - this.queryConstraintLogic = queryConstraintLogic; - } - - /** - * @return the temporalConstraintType - */ - public TemporalConstraintStrategy getTemporalConstraintStrategy() { - return temporalConstraintLogic; - } - - /** - * @param temporalConstraintType the temporalConstraintType to set - */ - public void setTemporalConstraintStrategy(TemporalConstraintStrategy temporalConstraintStrategy) { - this.temporalConstraintLogic = temporalConstraintStrategy; - } - - /** - * @return the useItemGroupByStatement - */ - public boolean useItemGroupByStatement() { - return useItemGroupByStatement; - } - - /** - * @param useItemGroupByStatement the useItemGroupByStatement to set - */ - public void setUseItemGroupByStatement(boolean useItemGroupByStatement) { - this.useItemGroupByStatement = useItemGroupByStatement; - } - - /** - * @return the invertedConstraintLogic - */ - public InvertedConstraintStrategy getInvertedConstraintLogic() { - return invertedConstraintLogic; - } - - /** - * @param invertedConstraintLogic the invertedConstraintLogic to set - */ - public void setInvertedConstraintLogic(InvertedConstraintStrategy invertedConstraintLogic) { - this.invertedConstraintLogic = invertedConstraintLogic; - } - - /** - * @return the useSqlHints - */ - public boolean useSqlHints() { - return useSqlHints; - } - - /** - * @param useSqlHints the useSqlHints to set - */ - public void setUseSqlHints(boolean useSqlHints) { - this.useSqlHints = useSqlHints; - } - - public boolean useDerivedFactTable() { - return derivedFactTable; - } - - public void setUseDerivedFactTable(boolean derivedFactTable) { - this.derivedFactTable = derivedFactTable; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Christopher Herrick + */ +package edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal; + +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + +public class TemporalQueryOptions { + + + public enum QueryConstraintStrategy{ + TEMP_TABLES, + WITH_STATEMENT, + DERIVED_TABLES + } + + public enum TemporalConstraintStrategy{ + TEMP_TABLE_UPDATE, + WITH_CONSTRAINT + } + + + private boolean usePanelLevelOccurrence = false; + private QueryConstraintStrategy queryConstraintLogic = QueryConstraintStrategy.WITH_STATEMENT; + private TemporalConstraintStrategy temporalConstraintLogic = TemporalConstraintStrategy.TEMP_TABLE_UPDATE; + private boolean useItemGroupByStatement = true; + private boolean useSqlHints = true; + private boolean derivedFactTable = QueryProcessorUtil.getInstance().getDerivedFactTable(); + + /** + * @return the usePanelLevelOccurrence + */ + public boolean usePanelLevelOccurrence() { + return usePanelLevelOccurrence; + } + + public enum InvertedConstraintStrategy{ + NOT_EXISTS, + MINUS_CLAUSE + } + private InvertedConstraintStrategy invertedConstraintLogic = InvertedConstraintStrategy.NOT_EXISTS; + + /** + * @param usePanelLevelOccurrence the usePanelLevelOccurrence to set + */ + public void setUsePanelLevelOccurrence(boolean usePanelLevelOccurrence) { + this.usePanelLevelOccurrence = usePanelLevelOccurrence; + } + + /** + * @return the queryConstraintLogic + */ + public QueryConstraintStrategy getQueryConstraintLogic() { + return queryConstraintLogic; + } + + /** + * @param queryConstraintLogic the queryConstraintLogic to set + */ + public void setQueryConstraintLogic(QueryConstraintStrategy queryConstraintLogic) { + this.queryConstraintLogic = queryConstraintLogic; + } + + /** + * @return the temporalConstraintType + */ + public TemporalConstraintStrategy getTemporalConstraintStrategy() { + return temporalConstraintLogic; + } + + /** + * @param temporalConstraintType the temporalConstraintType to set + */ + public void setTemporalConstraintStrategy(TemporalConstraintStrategy temporalConstraintStrategy) { + this.temporalConstraintLogic = temporalConstraintStrategy; + } + + /** + * @return the useItemGroupByStatement + */ + public boolean useItemGroupByStatement() { + return useItemGroupByStatement; + } + + /** + * @param useItemGroupByStatement the useItemGroupByStatement to set + */ + public void setUseItemGroupByStatement(boolean useItemGroupByStatement) { + this.useItemGroupByStatement = useItemGroupByStatement; + } + + /** + * @return the invertedConstraintLogic + */ + public InvertedConstraintStrategy getInvertedConstraintLogic() { + return invertedConstraintLogic; + } + + /** + * @param invertedConstraintLogic the invertedConstraintLogic to set + */ + public void setInvertedConstraintLogic(InvertedConstraintStrategy invertedConstraintLogic) { + this.invertedConstraintLogic = invertedConstraintLogic; + } + + /** + * @return the useSqlHints + */ + public boolean useSqlHints() { + return useSqlHints; + } + + /** + * @param useSqlHints the useSqlHints to set + */ + public void setUseSqlHints(boolean useSqlHints) { + this.useSqlHints = useSqlHints; + } + + public boolean useDerivedFactTable() { + return derivedFactTable; + } + + public void setUseDerivedFactTable(boolean derivedFactTable) { + this.derivedFactTable = derivedFactTable; + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalQuerySimpleSqlParser.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalQuerySimpleSqlParser.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalQuerySimpleSqlParser.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalQuerySimpleSqlParser.java index 9f853996..46e44bd7 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalQuerySimpleSqlParser.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalQuerySimpleSqlParser.java @@ -1,120 +1,120 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Christopher Herrick - */ -package edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -public class TemporalQuerySimpleSqlParser { - - protected final Log log = LogFactory.getLog(TemporalQuerySimpleSqlParser.class); - private String fullSql = null; - - private String selectClause = null; - private String fromClause = null; - private String whereClause = null; - private String groupByClause = null; - private String havingClause = null; - private String orderByClause = null; - - public TemporalQuerySimpleSqlParser(String simpleSqlStatement){ - fullSql = simpleSqlStatement; - selectClause = parseSelectClause(fullSql); - fromClause = parseFromClause(fullSql); - whereClause = parseWhereClause(fullSql); - groupByClause = parseGroupByClause(fullSql); - havingClause = parseHavingClause(fullSql); - orderByClause = parseOrderByClause(fullSql); - } - - private String parseFromClause(String sql){ - if (sql==null||sql.trim().length()==0) - return null; - - return runRegExExpression(sql, "\\bfrom\\b(.*?)(?:(\\bwhere\\b|\\bgroup by\\b|\\border by\\b|$))"); - } - - private String parseSelectClause(String sql){ - if (sql==null||sql.trim().length()==0) - return null; - - return runRegExExpression(sql, "\\bselect\\b(.*?)(?:(\\bfrom\\b|$))"); - } - - private String parseWhereClause(String sql){ - if (sql==null||sql.trim().length()==0) - return null; - - return runRegExExpression(sql, "\\bwhere\\b(.*?)(?:(\\bgroup by\\b|\\border by\\b|$))"); - } - - private String parseGroupByClause(String sql){ - if (sql==null||sql.trim().length()==0) - return null; - - return runRegExExpression(sql, "\\bgroup by\\b(.*?)(?:(\\bhaving\\b|\\border by\\b|$))"); - } - - private String parseHavingClause(String sql){ - if (sql==null||sql.trim().length()==0) - return null; - - return runRegExExpression(sql, "\\bhaving\\b(.*?)(?:(\\border by\\b|$))"); - } - - private String parseOrderByClause(String sql){ - if (sql==null||sql.trim().length()==0) - return null; - - return runRegExExpression(sql, "\\border by\\b(.*)"); - } - - private String runRegExExpression(String sqlString, String regEx){ - Pattern p = Pattern.compile(regEx, Pattern.DOTALL|Pattern.CASE_INSENSITIVE); - Matcher m = p.matcher(sqlString); - if (m.find() && m.groupCount()>0) - return m.group(1).trim(); - else - return null; - } - - public String getSelectClause() { - return selectClause; - } - - public String getFromClause() { - return fromClause; - } - - public String getWhereClause() { - return whereClause; - } - - public String getGroupByClause() { - return groupByClause; - } - - public String getHavingClause() { - return havingClause; - } - - public String getOrderByClause() { - return orderByClause; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Christopher Herrick + */ +package edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +public class TemporalQuerySimpleSqlParser { + + protected final Log log = LogFactory.getLog(TemporalQuerySimpleSqlParser.class); + private String fullSql = null; + + private String selectClause = null; + private String fromClause = null; + private String whereClause = null; + private String groupByClause = null; + private String havingClause = null; + private String orderByClause = null; + + public TemporalQuerySimpleSqlParser(String simpleSqlStatement){ + fullSql = simpleSqlStatement; + selectClause = parseSelectClause(fullSql); + fromClause = parseFromClause(fullSql); + whereClause = parseWhereClause(fullSql); + groupByClause = parseGroupByClause(fullSql); + havingClause = parseHavingClause(fullSql); + orderByClause = parseOrderByClause(fullSql); + } + + private String parseFromClause(String sql){ + if (sql==null||sql.trim().length()==0) + return null; + + return runRegExExpression(sql, "\\bfrom\\b(.*?)(?:(\\bwhere\\b|\\bgroup by\\b|\\border by\\b|$))"); + } + + private String parseSelectClause(String sql){ + if (sql==null||sql.trim().length()==0) + return null; + + return runRegExExpression(sql, "\\bselect\\b(.*?)(?:(\\bfrom\\b|$))"); + } + + private String parseWhereClause(String sql){ + if (sql==null||sql.trim().length()==0) + return null; + + return runRegExExpression(sql, "\\bwhere\\b(.*?)(?:(\\bgroup by\\b|\\border by\\b|$))"); + } + + private String parseGroupByClause(String sql){ + if (sql==null||sql.trim().length()==0) + return null; + + return runRegExExpression(sql, "\\bgroup by\\b(.*?)(?:(\\bhaving\\b|\\border by\\b|$))"); + } + + private String parseHavingClause(String sql){ + if (sql==null||sql.trim().length()==0) + return null; + + return runRegExExpression(sql, "\\bhaving\\b(.*?)(?:(\\border by\\b|$))"); + } + + private String parseOrderByClause(String sql){ + if (sql==null||sql.trim().length()==0) + return null; + + return runRegExExpression(sql, "\\border by\\b(.*)"); + } + + private String runRegExExpression(String sqlString, String regEx){ + Pattern p = Pattern.compile(regEx, Pattern.DOTALL|Pattern.CASE_INSENSITIVE); + Matcher m = p.matcher(sqlString); + if (m.find() && m.groupCount()>0) + return m.group(1).trim(); + else + return null; + } + + public String getSelectClause() { + return selectClause; + } + + public String getFromClause() { + return fromClause; + } + + public String getWhereClause() { + return whereClause; + } + + public String getGroupByClause() { + return groupByClause; + } + + public String getHavingClause() { + return havingClause; + } + + public String getOrderByClause() { + return orderByClause; + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalSubQuery.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalSubQuery.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalSubQuery.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalSubQuery.java index 09ad1681..482ab969 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalSubQuery.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/setfinder/querybuilder/temporal/TemporalSubQuery.java @@ -1,1332 +1,1332 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Christopher Herrick - */ -package edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal; - -import java.util.ArrayList; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.TreeSet; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.QueryTimingHandler; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal.TemporalQueryOptions.QueryConstraintStrategy; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal.TemporalQueryOptions.TemporalConstraintStrategy; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryJoinColumnType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryJoinType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryOperatorType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QuerySpanConstraintType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryAggregateOperatorType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.PanelType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryConstraintType; - -public class TemporalSubQuery implements Comparable{ - - protected final Log log = LogFactory.getLog(getClass()); - - public enum TemporalQuerySpanUnits{ - YEAR, - MONTH, - DAY, - HOUR, - SECOND, - MINUTE - }; - - public enum TemporalQueryReturnColumns { - PATIENT, - ENCOUNTER, - INSTANCE, - START_DATE, - END_DATE, - FIRST_START_DATE, - LAST_START_DATE, - FIRST_END_DATE, - LAST_END_DATE, - ENCOUNTER_START_DATE, - ENCOUNTER_END_DATE, - FIRST_ENCOUNTER_START_DATE, - LAST_ENCOUNTER_START_DATE, - FIRST_ENCOUNTER_END_DATE, - LAST_ENCOUNTER_END_DATE - }; - - private List panelList = null; - private TemporalQuery parent; - private int invertedPanelCount = 0; - private int startPanelIndex = 0; - private int endPanelIndex = -1; - private boolean isProtectedQuery = false; - - - private EnumSet rtnColumns = EnumSet.of(TemporalQueryReturnColumns.PATIENT); - private QueryDefinitionType subQuery = null; - private String subQueryId = null; - private HashMap> constraints = null; - private boolean aggregateApplied = false; - private List preProcessingSql = null; - private List postProcessingSql = null; - - - public TemporalSubQuery(TemporalQuery parent, List groupPanels) throws I2B2Exception{ - this.parent = parent; - this.subQuery = new QueryDefinitionType(); - this.subQuery.setQueryId(parent.generateUniqueId()); - this.subQuery.getPanel().addAll(groupPanels); - - this.preProcessingSql = new ArrayList(); - this.postProcessingSql = new ArrayList(); - parsePanels(groupPanels); - } - - public TemporalSubQuery(TemporalQuery parent, QueryDefinitionType event) throws I2B2Exception{ - this.parent = parent; - this.subQuery = event; - if (event.getQueryId()==null||event.getQueryId().trim().length()==0) - event.setQueryId(parent.generateUniqueId()); - - this.preProcessingSql = new ArrayList(); - this.postProcessingSql = new ArrayList(); - parsePanels(event.getPanel()); - } - - public TemporalSubQuery(TemporalQuery parent, QueryDefinitionType event, HashMap> constraintList) throws I2B2Exception{ - this.parent = parent; - this.subQuery = event; - if (event.getQueryId()==null||event.getQueryId().trim().length()==0) - event.setQueryId(parent.generateUniqueId()); - if (constraintList!=null) - this.constraints = constraintList; - - this.preProcessingSql = new ArrayList(); - this.postProcessingSql = new ArrayList(); - parsePanels(event.getPanel()); - } - - public TemporalSubQuery(TemporalQuery parent, QueryDefinitionType event, HashMap> constraintList, EnumSet returnColumns) throws I2B2Exception{ - this.parent = parent; - this.subQuery = event; - if (event.getQueryId()==null||event.getQueryId().trim().length()==0) - event.setQueryId(parent.generateUniqueId()); - if (constraintList!=null) - this.constraints = constraintList; - if (returnColumns!=null) - this.rtnColumns = returnColumns; - - this.preProcessingSql = new ArrayList(); - this.postProcessingSql = new ArrayList(); - parsePanels(event.getPanel()); - } - - private void parsePanels(List grpList) throws I2B2Exception{ - TreeSet panelSet = new TreeSet(); - for (PanelType panelType : grpList) { - TemporalPanel panelItem = new TemporalPanel(this, panelType); - if (panelItem.isPanelInverted()) - invertedPanelCount++; - panelSet.add(panelItem); - } - - panelList = new ArrayList(); - panelList.addAll(panelSet); - } - - public String buildSql() throws I2B2DAOException{ - StringBuffer subQuerySqlBuffer = new StringBuffer(); - int currentPanelIndex = 0; - for (TemporalPanel panel : panelList){ - String panelSql = panel.buildSql(currentPanelIndex); - subQuerySqlBuffer.append(panelSql); - - - if (!panel.isPanelInverted()){ - endPanelIndex = currentPanelIndex; - currentPanelIndex++; - } - - subQuerySqlBuffer.append(getSqlDelimiter()); - } - - if (parent.getSubQueryCount()>1){ - int level = 0; - if (this.isFirstSubQuery()) - level = 1; - subQuerySqlBuffer.append(buildMoveToMasterSql(level)); - subQuerySqlBuffer.append(getSqlDelimiter()); - - if (parent.getServerType().equals(DAOFactoryHelper.ORACLE)) - parent.addPostProcessingSql(getDeleteTempMasterSql(this.getSubQueryId(), 0)); - - subQuerySqlBuffer.append(getDeleteTempTableSql()); - subQuerySqlBuffer.append(getSqlDelimiter()); - } - - if (!this.isFirstSubQuery()){ - subQuerySqlBuffer.append(buildMasterTableTimingConstraintUpdate(1)); - subQuerySqlBuffer.append(getSqlDelimiter()); - } - - StringBuffer sqlBuffer = new StringBuffer(); - if (this.preProcessingSql!=null&&this.preProcessingSql.size()>0){ - for(String sql : this.preProcessingSql){ - sqlBuffer.append(sql); - sqlBuffer.append(getSqlDelimiter()); - } - } - sqlBuffer.append(subQuerySqlBuffer.toString()); - if (this.postProcessingSql!=null&&this.postProcessingSql.size()>0){ - for(String sql : this.postProcessingSql){ - sqlBuffer.append(sql); - sqlBuffer.append(getSqlDelimiter()); - } - } - - - return sqlBuffer.toString(); - } - - public boolean isFirstSubQuery(){ - return parent.isFirstSubQuery(this); - } - - public boolean isLastSubQuery(){ - return parent.isLastSubQuery(this); - } - - - public boolean isProtectedQuery() { - return isProtectedQuery; - } - - public void setProtectedQuery(boolean isProtectedQuery) { - this.isProtectedQuery = isProtectedQuery; - } - - protected TemporalQueryReturnColumns getStartDateReturnType(){ - //currently, we only support one start and end date type per query. if both instance and encounter start dates - //are specified in a query, we'll use the instance date - - if (rtnColumns.contains(TemporalQueryReturnColumns.START_DATE) - || (rtnColumns - .contains(TemporalQueryReturnColumns.FIRST_START_DATE) && rtnColumns - .contains(TemporalQueryReturnColumns.LAST_START_DATE)) - || (rtnColumns - .contains(TemporalQueryReturnColumns.END_DATE) && (rtnColumns - .contains(TemporalQueryReturnColumns.FIRST_START_DATE) || rtnColumns - .contains(TemporalQueryReturnColumns.LAST_START_DATE)))) { - return TemporalQueryReturnColumns.START_DATE; - } else if (rtnColumns - .contains(TemporalQueryReturnColumns.FIRST_START_DATE)) { - return TemporalQueryReturnColumns.FIRST_START_DATE; - } else if (rtnColumns - .contains(TemporalQueryReturnColumns.LAST_START_DATE)) { - return TemporalQueryReturnColumns.LAST_START_DATE; - } else if (rtnColumns - .contains(TemporalQueryReturnColumns.ENCOUNTER_START_DATE) - || (rtnColumns - .contains(TemporalQueryReturnColumns.FIRST_ENCOUNTER_START_DATE) && rtnColumns - .contains(TemporalQueryReturnColumns.LAST_ENCOUNTER_START_DATE)) - || (rtnColumns - .contains(TemporalQueryReturnColumns.ENCOUNTER_END_DATE) && (rtnColumns - .contains(TemporalQueryReturnColumns.FIRST_ENCOUNTER_START_DATE) || rtnColumns - .contains(TemporalQueryReturnColumns.LAST_ENCOUNTER_START_DATE)))) { - return TemporalQueryReturnColumns.ENCOUNTER_START_DATE; - } else if (rtnColumns - .contains(TemporalQueryReturnColumns.FIRST_ENCOUNTER_START_DATE)) { - return TemporalQueryReturnColumns.FIRST_ENCOUNTER_START_DATE; - } else if (rtnColumns - .contains(TemporalQueryReturnColumns.LAST_ENCOUNTER_START_DATE)) { - return TemporalQueryReturnColumns.LAST_ENCOUNTER_START_DATE; - } - return null; - } - - - - protected TemporalQueryReturnColumns getEndDateReturnType(){ - if (rtnColumns.contains(TemporalQueryReturnColumns.END_DATE) - || (rtnColumns.contains(TemporalQueryReturnColumns.FIRST_END_DATE) && rtnColumns - .contains(TemporalQueryReturnColumns.LAST_END_DATE)) - || (rtnColumns - .contains(TemporalQueryReturnColumns.START_DATE) && (rtnColumns - .contains(TemporalQueryReturnColumns.FIRST_END_DATE) || rtnColumns - .contains(TemporalQueryReturnColumns.LAST_END_DATE)))) { - return TemporalQueryReturnColumns.END_DATE; - } else if (rtnColumns - .contains(TemporalQueryReturnColumns.FIRST_END_DATE)) { - return TemporalQueryReturnColumns.FIRST_END_DATE; - } else if (rtnColumns - .contains(TemporalQueryReturnColumns.LAST_END_DATE)) { - return TemporalQueryReturnColumns.LAST_END_DATE; - } else if (rtnColumns - .contains(TemporalQueryReturnColumns.ENCOUNTER_END_DATE) - || (rtnColumns - .contains(TemporalQueryReturnColumns.FIRST_ENCOUNTER_END_DATE) && rtnColumns - .contains(TemporalQueryReturnColumns.LAST_ENCOUNTER_END_DATE)) - || (rtnColumns - .contains(TemporalQueryReturnColumns.ENCOUNTER_START_DATE) && (rtnColumns - .contains(TemporalQueryReturnColumns.FIRST_ENCOUNTER_END_DATE) || rtnColumns - .contains(TemporalQueryReturnColumns.LAST_ENCOUNTER_END_DATE)))) { - return TemporalQueryReturnColumns.ENCOUNTER_END_DATE; - } else if (rtnColumns - .contains(TemporalQueryReturnColumns.FIRST_ENCOUNTER_END_DATE)) { - return TemporalQueryReturnColumns.FIRST_ENCOUNTER_END_DATE; - } else if (rtnColumns - .contains(TemporalQueryReturnColumns.LAST_ENCOUNTER_END_DATE)) { - return TemporalQueryReturnColumns.LAST_ENCOUNTER_END_DATE; - } - return null; - } - - protected String buildMasterTableTimingConstraintUpdate(int level){ - String timingConstraintSql = buildTimingConstraintSql(level); - - StringBuilder updateSql = new StringBuilder(); - if (parent.getServerType().equals(DAOFactoryHelper.SQLSERVER)){ - if (useSqlServerTempTables()){ - updateSql.append("update #m" + getSubQueryId() + " "); - updateSql.append("set level_no = " + String.valueOf(level) + " "); - updateSql.append("from #m" + getSubQueryId() + " t "); - updateSql.append(timingConstraintSql + " "); - updateSql.append("and t.level_no = " + String.valueOf(level - 1) + " "); - } - else { - updateSql.append("update " + parent.getMasterTempTableName() + " "); - updateSql.append("set level_no = " + String.valueOf(level) + " "); - updateSql.append("from " + parent.getMasterTempTableName() + " t "); - updateSql.append(timingConstraintSql + " "); - updateSql.append("and t.level_no = " + String.valueOf(level - 1) + " "); - updateSql.append("and t.master_id = '" + this.getSubQueryId() + "'"); - } - } - else { - updateSql.append("update " + parent.getMasterTempTableName() + " t "); - updateSql.append("set level_no = " + String.valueOf(level) + " "); - updateSql.append(timingConstraintSql + " "); - updateSql.append("and t.level_no = " + String.valueOf(level - 1) + " "); - updateSql.append("and t.master_id = '" + this.getSubQueryId() + "'"); - } - - - return updateSql.toString(); - } - - protected String buildTimingConstraintUpdate(int panelCount){ - String timingConstraintSql = buildTimingConstraintSql(panelCount); - - StringBuilder updateSql = new StringBuilder(); - if (parent.getServerType().equals(DAOFactoryHelper.SQLSERVER)){ - updateSql.append("update " + parent.getTempTableName() + " "); - updateSql.append("set panel_count = " + String.valueOf(panelCount) + " "); - updateSql.append("from " + parent.getTempTableName() + " t "); - } - else { - updateSql.append("update " + parent.getTempTableName() + " t "); - updateSql.append("set panel_count = " + String.valueOf(panelCount) + " "); - } - - updateSql.append(timingConstraintSql + " "); - updateSql.append("and t.panel_count = " + String.valueOf(panelCount - 1)); - - return updateSql.toString(); - } - - private String addTimingConstraintSql(String panelSql){ - String timingConstraint = buildTimingConstraintSql(); - int lastIndex = panelSql.lastIndexOf(this.getSqlDelimiter()); - if (lastIndex==-1){ - panelSql += timingConstraint; - } - else if (parent.getQueryOptions().getQueryConstraintLogic()==QueryConstraintStrategy.TEMP_TABLES && - parent.getServerType().equals(DAOFactoryHelper.SQLSERVER)){ - panelSql = addToRegExExpression(panelSql, "insert into " + parent.getTempTableName() + "(.*?)(?:(" + getSqlDelimiter().replace("*", "\\*") + "|$))", timingConstraint); - } - else { - panelSql = panelSql.replace(getSqlDelimiter(), timingConstraint + getSqlDelimiter()) + timingConstraint; - } - return panelSql; - } - - private String addToRegExExpression(String sqlString, String regEx, String newSql){ - StringBuilder sql = new StringBuilder(); - Pattern p = Pattern.compile(regEx, Pattern.DOTALL|Pattern.CASE_INSENSITIVE); - Matcher m = p.matcher(sqlString); - int lastIndex = 0; - while (m.find()){ - int endIndex = m.end(); - String text = sqlString.substring(lastIndex, endIndex - getSqlDelimiter().length()); - sql.append(text); - sql.append(newSql); - sql.append(getSqlDelimiter()); - lastIndex = endIndex; - } - sql.append(sqlString.substring(lastIndex)); - return sql.toString(); - } - - protected String buildTimingConstraintSql(){ - return buildTimingConstraintSql(-1); - } - - protected String buildTimingConstraintSql(int panelCount){ - StringBuffer timingSqlBuf = new StringBuffer(""); - - boolean firstConstraint = true; - - boolean encounterConstraint = false; - if (parent.getQueryTiming()!=null&& - (parent.getQueryTiming().equalsIgnoreCase(QueryTimingHandler.SAME)|| - parent.getQueryTiming().equalsIgnoreCase(QueryTimingHandler.SAMEVISIT))) - encounterConstraint = true; - - String lastSubQueryId = parent.getLastProcessedSubQueryId(); - if (lastSubQueryId!=null&&lastSubQueryId.trim().length()>0){ - if (useSqlServerTempTables()){ - timingSqlBuf.append(" where exists (select 1 from " + - "#m" + lastSubQueryId + " m " + - "where m.patient_num = t.patient_num " + - (encounterConstraint?"and m.encounter_num = t.encounter_num ":"") + - "and m.level_no = 1 " + - //"group by m.patient_num" + - ") \n"); - } - else { - timingSqlBuf.append(" where exists (select 1 from " + parent.getMasterTempTableName() + " m " + - "where m.master_id = '" + lastSubQueryId + "' " + - "and m.patient_num = t.patient_num " + - (encounterConstraint?"and m.encounter_num = t.encounter_num ":"") + - "and m.level_no = 1 " + - //"group by m.patient_num " + - ") \n"); - } - firstConstraint = false; - } - - if (constraints!=null){ - for (List constraintLists: constraints.values()){ - for (QueryConstraintType constraint: constraintLists){ - - QueryJoinType masterTableQuery = constraint.getFirstQuery(); - QueryJoinType tempTableQuery = constraint.getSecondQuery(); - - //first, get the right column comparison - String firstColumn = getColumnNameFromType(constraint.getFirstQuery().getJoinColumn()); - String secondColumn = getColumnNameFromType(constraint.getSecondQuery().getJoinColumn()); - - String firstPrefix = "m"; - String secondPrefix = "t"; - boolean switchedPrefix = false; - - String otherQueryId = constraint.getFirstQuery().getQueryId(); - if (constraint.getFirstQuery().getQueryId().equals(getQueryId())){ - firstPrefix = secondPrefix; - secondPrefix = "m"; - otherQueryId = constraint.getSecondQuery().getQueryId(); - masterTableQuery = tempTableQuery; - tempTableQuery = constraint.getFirstQuery(); - switchedPrefix = true; - } - - String dateConstraintSql = buildDateSqlForMaster(masterTableQuery, encounterConstraint); - - if (dateConstraintSql!=null&&dateConstraintSql.trim().length()>0){ - - if (firstConstraint){ - timingSqlBuf.append(" where "); - firstConstraint = false; - } - else - timingSqlBuf.append(" and "); - - - timingSqlBuf.append(" exists (" + - "select 1 " + - "from (" + dateConstraintSql + ") m "); - - - String newPrefix = "t"; - String columnName = getColumnNameFromType(tempTableQuery.getJoinColumn()); - if (tempTableQuery.getAggregateOperator().equals(QueryAggregateOperatorType.FIRST)){ - timingSqlBuf.append(", (select m.patient_num " + - (encounterConstraint?", m.encounter_num ":"") + - ", min(m." + columnName + ") " + columnName + " "); - if (useSqlServerTempTables()){ - timingSqlBuf.append("from #m" + this.buildSubQueryId(tempTableQuery.getQueryId()) + " m "); - } - else { - timingSqlBuf.append("from " + parent.getMasterTempTableName() + " m " + - "where m.master_id = '" + this.buildSubQueryId(tempTableQuery.getQueryId()) + "' "); - } - timingSqlBuf.append("group by m.patient_num" + - (encounterConstraint?", m.encounter_num ":"") + - ") t2 " + - "where m.patient_num = t2.patient_num " + - (encounterConstraint?"and m.encounter_num = t2.encounter_num ":"") + - "and t.patient_num = t2.patient_num " + - (encounterConstraint?"and t.encounter_num = t2.encounter_num ":"") + - "and "); - newPrefix = "t2"; - } - else if (tempTableQuery.getAggregateOperator().equals(QueryAggregateOperatorType.LAST)){ - timingSqlBuf.append(", (select m.patient_num, max(m." + columnName + ") " + columnName + " "); - if (useSqlServerTempTables()){ - timingSqlBuf.append("from #m" + this.buildSubQueryId(tempTableQuery.getQueryId()) + " m "); - } - else { - timingSqlBuf.append("from " + parent.getMasterTempTableName() + " m " + - "where m.master_id = '" + this.buildSubQueryId(tempTableQuery.getQueryId()) + "' "); - } - timingSqlBuf.append("group by m.patient_num) t2 " + - "where m.patient_num = t2.patient_num " + - (encounterConstraint?"and m.encounter_num = t2.encounter_num ":"") + - "and t.patient_num = t2.patient_num " + - (encounterConstraint?"and t.encounter_num = t2.encounter_num ":"") + - "and "); - newPrefix = "t2"; - } - else { - timingSqlBuf.append("where "); - } - - if (firstPrefix.equals("t")) - firstPrefix = newPrefix; - else - secondPrefix = newPrefix; - - timingSqlBuf.append("m.patient_num = t.patient_num " + - (encounterConstraint?"and m.encounter_num = t.encounter_num ":"")); - timingSqlBuf.append("and " + firstPrefix + "." + firstColumn + " "); - - QueryOperatorType dateOperator = constraint.getOperator(); - if (dateOperator.equals(QueryOperatorType.EQUAL)) - timingSqlBuf.append("= "); - else if (dateOperator.equals(QueryOperatorType.GREATER)) - timingSqlBuf.append("> "); - else if (dateOperator.equals(QueryOperatorType.GREATEREQUAL)) - timingSqlBuf.append(">= "); - else if (dateOperator.equals(QueryOperatorType.LESS)) - timingSqlBuf.append("< "); - else if (dateOperator.equals(QueryOperatorType.LESSEQUAL)) - timingSqlBuf.append("<= "); - - timingSqlBuf.append(secondPrefix + "." + secondColumn + " "); - - if (constraint.getSpan()!=null&&constraint.getSpan().size()>0){ - for (QuerySpanConstraintType spanConstraint : constraint.getSpan()) - { - String spanFirstPrefix = firstPrefix; - String spanFirstColumn = firstColumn; - String spanSecondPrefix = secondPrefix; - String spanSecondColumn = secondColumn; - - - String spanOperator = "="; - QueryOperatorType spanOpType = spanConstraint.getOperator(); - if (spanConstraint.getOperator()!=null){ - if (spanOpType.equals(QueryOperatorType.EQUAL)) - spanOperator = "= "; - else if (spanOpType.equals(QueryOperatorType.GREATER)) - spanOperator = "> "; - else if (spanOpType.equals(QueryOperatorType.GREATEREQUAL)) - spanOperator = ">= "; - else if (spanOpType.equals(QueryOperatorType.LESS)) - spanOperator = "< "; - else if (spanOpType.equals(QueryOperatorType.LESSEQUAL)) - spanOperator = "<= "; - } - - String units = spanConstraint.getUnits(); - String sqlUnits = ""; - int span = spanConstraint.getSpanValue(); - - if (units!=null){ - - if (dateOperator.equals(QueryOperatorType.GREATER)||dateOperator.equals(QueryOperatorType.GREATEREQUAL)){ - String spanPrefix = spanFirstPrefix; - String spanColumn = spanFirstColumn; - spanFirstPrefix = spanSecondPrefix; - spanFirstColumn = spanSecondColumn; - spanSecondPrefix = spanPrefix; - spanSecondColumn = spanColumn; - } - - if (TemporalQuerySpanUnits.valueOf(units)==TemporalQuerySpanUnits.YEAR){ - if (parent.getServerType().equals(DAOFactoryHelper.ORACLE)) - sqlUnits = "ADD_MONTHS(" + spanFirstPrefix + "." + spanFirstColumn + ", (12 * " + span + "))"; - else if (parent.getServerType().equals(DAOFactoryHelper.SQLSERVER)) - sqlUnits = "DATEADD(YEAR, (" + span + "), " + spanFirstPrefix + "." + spanFirstColumn + ")"; - else if (parent.getServerType().equals(DAOFactoryHelper.POSTGRESQL)) - sqlUnits = " " + spanFirstPrefix + "." + spanFirstColumn + " + cast('" + span + " years' as interval) "; - - } - else if (TemporalQuerySpanUnits.valueOf(units)==TemporalQuerySpanUnits.MONTH){ - if (parent.getServerType().equals(DAOFactoryHelper.ORACLE)) - sqlUnits = "ADD_MONTHS(" + spanFirstPrefix + "." + spanFirstColumn + ", (" + span + "))"; - else if (parent.getServerType().equals(DAOFactoryHelper.SQLSERVER)) - sqlUnits = "DATEADD(MONTH, (" + span + "), " + spanFirstPrefix + "." + spanFirstColumn + ")"; - else if (parent.getServerType().equals(DAOFactoryHelper.POSTGRESQL)) - sqlUnits = " " + spanFirstPrefix + "." + spanFirstColumn + " + cast('" + span + " months' as interval) "; - } - else if (TemporalQuerySpanUnits.valueOf(units)==TemporalQuerySpanUnits.DAY){ - if (parent.getServerType().equals(DAOFactoryHelper.ORACLE)) - sqlUnits = "(" + spanFirstPrefix + "." + spanFirstColumn + " + (" + span + "))"; - else if (parent.getServerType().equals(DAOFactoryHelper.SQLSERVER)) - sqlUnits = "DATEADD(DAY, (" + span + "), " + spanFirstPrefix + "." + spanFirstColumn + ")"; - else if (parent.getServerType().equals(DAOFactoryHelper.POSTGRESQL)) - sqlUnits = " " + spanFirstPrefix + "." + spanFirstColumn + " + cast('" + span + " days' as interval) "; - } - else if (TemporalQuerySpanUnits.valueOf(units)==TemporalQuerySpanUnits.HOUR){ - if (parent.getServerType().equals(DAOFactoryHelper.ORACLE)) - sqlUnits = "(" + spanFirstPrefix + "." + spanFirstColumn + " + (1/24 * " + span + "))"; - else if (parent.getServerType().equals(DAOFactoryHelper.SQLSERVER)) - sqlUnits = "DATEADD(HOUR, (" + span + "), " + spanFirstPrefix + "." + spanFirstColumn + ")"; - else if (parent.getServerType().equals(DAOFactoryHelper.POSTGRESQL)) - sqlUnits = " " + spanFirstPrefix + "." + spanFirstColumn + " + cast('" + span + " hours' as interval) "; - } - else if (TemporalQuerySpanUnits.valueOf(units)==TemporalQuerySpanUnits.MINUTE){ - if (parent.getServerType().equals(DAOFactoryHelper.ORACLE)) - sqlUnits = "(" + spanFirstPrefix + "." + spanFirstColumn + " + (1/1440 * " + span + "))"; - else if (parent.getServerType().equals(DAOFactoryHelper.SQLSERVER)) - sqlUnits = "DATEADD(MINUTE, (" + span + "), " + spanFirstPrefix + "." + spanFirstColumn + ")"; - else if (parent.getServerType().equals(DAOFactoryHelper.POSTGRESQL)) - sqlUnits = " " + spanFirstPrefix + "." + spanFirstColumn + " + cast('" + span + " minutes' as interval) "; - } - else if (TemporalQuerySpanUnits.valueOf(units)==TemporalQuerySpanUnits.SECOND){ - if (parent.getServerType().equals(DAOFactoryHelper.ORACLE)) - sqlUnits = "(" + spanFirstPrefix + "." + spanFirstColumn + " + (1/86400 * " + span + "))"; - else if (parent.getServerType().equals(DAOFactoryHelper.SQLSERVER)) - sqlUnits = "DATEADD(SECOND, (" + span + "), " + spanFirstPrefix + "." + spanFirstColumn + ")"; - else if (parent.getServerType().equals(DAOFactoryHelper.POSTGRESQL)) - sqlUnits = " " + spanFirstPrefix + "." + spanFirstColumn + " + cast('" + span + " seconds' as interval) "; - } - } - - if (sqlUnits.trim().length()>0) - timingSqlBuf.append("and " + spanSecondPrefix + "." + spanSecondColumn + " " + spanOperator + " " + sqlUnits); - } - - } - } - - timingSqlBuf.append(")"); - } - } - } - return timingSqlBuf.toString(); - } - - private String getTempQueryConstraint(QueryJoinType tempJoin, int panelCount){ - boolean useTempTables = false; - if (parent.getServerType().equalsIgnoreCase( - DAOFactoryHelper.SQLSERVER)&& - parent.getQueryOptions().getQueryConstraintLogic()==QueryConstraintStrategy.TEMP_TABLES){ - useTempTables = true; - } - - StringBuilder tempClause = new StringBuilder(); - if (tempJoin!=null){ - String columnName = ""; - String columnAlias = ""; - String temporalTableAlias = "f"; - String temporalJoinTable = "observation_fact"; - if (tempJoin.getJoinColumn().equals(QueryJoinColumnType.STARTDATE)){ - columnName = "start_date"; - columnAlias = "temporal_start_date"; - temporalTableAlias = "f"; - temporalJoinTable = "observation_fact"; - } - else if (tempJoin.getJoinColumn().equals(QueryJoinColumnType.ENDDATE)){ - columnName = "end_date"; - columnAlias = "temporal_end_date"; - temporalTableAlias = "f"; - temporalJoinTable = "observation_fact"; - } - else if (tempJoin.getJoinColumn().equals(QueryJoinColumnType.ENCOUNTER_STARTDATE)){ - columnName = "start_date"; - columnAlias = "temporal_start_date"; - temporalTableAlias = "v"; - temporalJoinTable = "visit_dimension"; - } - else if (tempJoin.getJoinColumn().equals(QueryJoinColumnType.ENCOUNTER_ENDDATE)){ - columnName = "end_date"; - columnAlias = "temporal_end_date"; - temporalTableAlias = "v"; - temporalJoinTable = "visit_dimension"; - } - - if (columnName.trim().length()>0){ - if (tempJoin.getAggregateOperator().equals(QueryAggregateOperatorType.FIRST)){ - tempClause.append("select " + temporalTableAlias + ".patient_num, " + - "min(" + temporalTableAlias + "." + columnName + ") " + columnAlias + " " + - "from " + parent.getDatabaseSchema() + temporalJoinTable + " " + temporalTableAlias + " "); - } - else if (tempJoin.getAggregateOperator().equals(QueryAggregateOperatorType.LAST)){ - tempClause.append("select " + temporalTableAlias + ".patient_num, max(" + temporalTableAlias + "." + columnName + ") " + columnAlias + " " + - "from " + parent.getDatabaseSchema() + temporalJoinTable + " " + temporalTableAlias + " "); - } - else{ - tempClause.append("select " + temporalTableAlias + ".patient_num, " + temporalTableAlias + ".encounter_num, " + temporalTableAlias + "." + columnName + " " + columnAlias + " " + - "from " + parent.getDatabaseSchema() + temporalJoinTable + " " + temporalTableAlias + " "); - } - - String tableAlias = "cnst"; - - if (parent.getQueryOptions().getTemporalConstraintStrategy()==TemporalConstraintStrategy.TEMP_TABLE_UPDATE){ - tempClause.append(", " + getTempTableName() + " cnst "); - } - else if (useTempTables){ - tempClause.append(", #t cnst "); - } - else { - tempClause.append(", t cnst "); - } - - - tempClause.append("where " + tableAlias + ".patient_num = " + temporalTableAlias + ".patient_num "); - if (this.getQueryTiming().equalsIgnoreCase(QueryTimingHandler.ANY)){ - tempClause.append("and " + tableAlias + ".encounter_num = " + temporalTableAlias + ".encounter_num "); - } - if (parent.getQueryOptions().getTemporalConstraintStrategy()==TemporalConstraintStrategy.TEMP_TABLE_UPDATE){ - tempClause.append("and " + tableAlias + ".panel_count = " + String.valueOf(panelCount) + " "); - } - - if ((tempJoin.getAggregateOperator().equals(QueryAggregateOperatorType.FIRST))|| - (tempJoin.getAggregateOperator().equals(QueryAggregateOperatorType.LAST))) - tempClause.append("group by " + temporalTableAlias + ".patient_num "); - else - tempClause.append("group by " + temporalTableAlias + ".patient_num, " + temporalTableAlias + ".encounter_num, v." + columnName + " "); - } - } - return tempClause.toString(); - } - - private String buildDateSqlForMaster(QueryJoinType masterJoin, boolean includeEncounter){ - String columnName = getColumnNameFromType(masterJoin.getJoinColumn()); - - String encounterColumn = (includeEncounter?", m.encounter_num ":""); - - String selectStatement = "select m.patient_num " + encounterColumn + ", m." + columnName + " "; - String fromStatement = "from " + parent.getMasterTempTableName() + " m "; - String whereStatement = "where m.master_id = '" + this.buildSubQueryId(masterJoin.getQueryId()) + "' "; - String groupByStatement = "group by m.patient_num " + encounterColumn + " "; - - if (useSqlServerTempTables()){ - fromStatement = "from #m" + this.buildSubQueryId(masterJoin.getQueryId()) + " m "; - whereStatement = ""; - } - - if (!masterJoin.getJoinColumn().equals(QueryJoinColumnType.INSTANCE)){ - if (masterJoin.getAggregateOperator().equals(QueryAggregateOperatorType.FIRST)){ - selectStatement = "select m.patient_num " + encounterColumn + ", min(m." + columnName + ") " + columnName + " "; - } - else if (masterJoin.getAggregateOperator().equals(QueryAggregateOperatorType.LAST)){ - selectStatement = "select m.patient_num " + encounterColumn + ", max(m." + columnName + ") " + columnName + " "; - } - else { - selectStatement = "select m.patient_num " + encounterColumn + ", m." + columnName + " "; - if (whereStatement.trim().length()>0) - whereStatement += "and m.level_no = 1 "; - else - whereStatement = "where m.level_no = 1 "; - groupByStatement = ""; - } - } - else { - selectStatement = "select " + columnName + ", temporal_start_date, temporal_end_date "; - groupByStatement = ""; - } - - return selectStatement + " " + - fromStatement + " " + - whereStatement + " " + - groupByStatement; - } - - /*private String getConstrainedDateSqlFromMaster(QueryJoinType masterJoin){ - String columnName = getColumnNameFromType(masterJoin.getJoinColumn()); - - if (!masterJoin.getJoinColumn().equals(QueryJoinColumnType.INSTANCE)){ - if (masterJoin.getAggregateOperator().equals(QueryAggregateOperatorType.FIRST)) - return "select m.patient_num, min(m." + columnName + ") " + columnName + " " + - "from " + parent.getMasterTempTableName() + " m " + - "where m.master_id = '" + this.buildSubQueryId(masterJoin.getQueryId()) + "' " + - "group by m.patient_num"; - else if (masterJoin.getAggregateOperator().equals(QueryAggregateOperatorType.LAST)) - return "select m.patient_num, max(m." + columnName + ") " + columnName + " " + - "from " + parent.getMasterTempTableName() + " m " + - "where m.master_id = '" + this.buildSubQueryId(masterJoin.getQueryId()) + "' " + - "group by m.patient_num"; - else - return "select m.patient_num, m." + columnName + " " + - "from " + parent.getMasterTempTableName() + " m " + - "where m.master_id = '" + this.buildSubQueryId(masterJoin.getQueryId()) + "' " + - "and m.level_no = 1 "; - } - else - return "select " + columnName + ", temporal_start_date, temporal_end_date " + - "from " + parent.getMasterTempTableName() + " m " + - "where m.master_id = '" + this.buildSubQueryId(masterJoin.getQueryId()) + "' "; - }*/ - - protected String getColumnNameFromType(QueryJoinColumnType columnType){ - if (columnType!=null){ - if (columnType.equals(QueryJoinColumnType.ENCOUNTER)) - return "encounter_num"; - else if (columnType.equals(QueryJoinColumnType.STARTDATE)) - return "temporal_start_date"; - else if (columnType.equals(QueryJoinColumnType.ENDDATE)) - return "temporal_end_date"; - else if (columnType.equals(QueryJoinColumnType.ENCOUNTER_STARTDATE)) - return "temporal_start_date"; - else if (columnType.equals(QueryJoinColumnType.ENCOUNTER_ENDDATE)) - return "temporal_end_date"; - else if (columnType.equals(QueryJoinColumnType.INSTANCE)) - return "provider_id, start_date, concept_cd, instance_num, encounter_num, patient_num"; - } - return "patient_num"; - } - - protected String buildMoveToMasterSql(int level) { - String tempTableName = parent.getTempTableName(); - String masterTableName = parent.getMasterTempTableName(); - StringBuilder masterSql = new StringBuilder(); - - StringBuilder insertClause = new StringBuilder(); - if (!useSqlServerTempTables()){ - insertClause.append(" insert into " + masterTableName); - insertClause.append("(master_id, patient_num, level_no"); - if (rtnColumns.contains(TemporalQueryReturnColumns.ENCOUNTER)){ - insertClause.append(", encounter_num"); - } - if (rtnColumns.contains(TemporalQueryReturnColumns.INSTANCE)){ - if (!rtnColumns.contains(TemporalQueryReturnColumns.ENCOUNTER)){ - insertClause.append(", encounter_num"); - } - insertClause.append(", provider_id, start_date, concept_cd, instance_num"); - } - if (returnInstanceStartDate()||returnEncounterStartDate()){ - insertClause.append(", temporal_start_date"); - } - if (returnInstanceEndDate()||returnEncounterEndDate()){ - insertClause.append(", temporal_end_date"); - } - insertClause.append(") "); - } - else { - masterSql.append(parent.buildTempTableCheckDrop("#m" + getSubQueryId())); - masterSql.append(parent.getSqlDelimiter()); - } - - - String schema = getDatabaseSchema(); - if (schema==null) - schema = ""; - else if (!schema.endsWith(".")) - schema += "."; - - String primaryTableAlias = "t."; - StringBuilder fromClause = new StringBuilder("from " + tempTableName + " t "); - StringBuilder whereClause = new StringBuilder(" where t.panel_count = " + this.getEndPanelIndex() + " "); - if ((((rtnColumns.contains(TemporalQueryReturnColumns.INSTANCE)|| - returnInstanceStartDate()))&& - (!this.getQueryTiming().equalsIgnoreCase(QueryTimingHandler.SAMEINSTANCENUM)))|| - (returnInstanceEndDate())){ - primaryTableAlias = "f."; - fromClause.append(", " + schema + "observation_fact f "); - whereClause.append("and f.patient_num = t.patient_num "); - if (this.getQueryTiming().equalsIgnoreCase(QueryTimingHandler.SAME)|| - this.getQueryTiming().equalsIgnoreCase(QueryTimingHandler.SAMEVISIT)){ - whereClause.append("and f.encounter_num = t.encounter_num "); - } - else if (this.getQueryTiming().equalsIgnoreCase(QueryTimingHandler.SAMEINSTANCENUM)){ - whereClause.append("and f.encounter_num = t.encounter_num "); - whereClause.append("and f.provider_id = t.provider_id "); - whereClause.append("and f.start_date = t.start_date "); - whereClause.append("and f.instance_num = t.instance_num "); - whereClause.append("and f.concept_cd = t.concept_cd "); - } - - if (returnEncounterEndDate()||returnEncounterStartDate()){ - fromClause.append(", " + schema + "visit_dimension v "); - whereClause.append("and f.patient_num = v.patient_num "); - whereClause.append("and f.encounter_num = v.encounter_num "); - } - } - else if ((rtnColumns.contains(TemporalQueryReturnColumns.ENCOUNTER)&& - !this.getQueryTiming().equalsIgnoreCase(QueryTimingHandler.SAME)&& - !this.getQueryTiming().equalsIgnoreCase(QueryTimingHandler.SAMEVISIT)&& - !this.getQueryTiming().equalsIgnoreCase(QueryTimingHandler.SAMEINSTANCENUM))|| - returnEncounterStartDate()|| - returnEncounterEndDate()){ - primaryTableAlias = "v."; - fromClause.append(", " + schema + "visit_dimension v "); - whereClause.append("and v.patient_num = t.patient_num "); - if (!this.getQueryTiming().equalsIgnoreCase(QueryTimingHandler.ANY)){ - whereClause.append("and v.encounter_num = t.encounter_num "); - } - } - - boolean aggregate = false; - StringBuilder selectClause = new StringBuilder(); - if (useSqlServerTempTables()){ - selectClause.append("select t.patient_num, " + String.valueOf(level) + " level_no "); - } - else { - selectClause.append("select '" + getSubQueryId() + "', t.patient_num, " + String.valueOf(level) + " "); - } - StringBuilder groupByClause = new StringBuilder("group by t.patient_num "); - if (rtnColumns.contains(TemporalQueryReturnColumns.INSTANCE)){ - selectClause.append(", " + primaryTableAlias + "encounter_num, " + - primaryTableAlias + "provider_id, " + - primaryTableAlias + "start_date, " + - primaryTableAlias + "concept_cd, " + - primaryTableAlias + "instance_num"); - groupByClause.append(", " + primaryTableAlias + "encounter_num, " + - primaryTableAlias + "provider_id, " + - primaryTableAlias + "start_date, " + - primaryTableAlias + "concept_cd, " + - primaryTableAlias + "instance_num"); - } - else if (rtnColumns.contains(TemporalQueryReturnColumns.ENCOUNTER)){ - selectClause.append(", " + primaryTableAlias + "encounter_num"); - groupByClause.append(", " + primaryTableAlias + "encounter_num"); - } - - TemporalQueryReturnColumns startDateRtn = getStartDateReturnType(); - if (startDateRtn!=null){ - if (startDateRtn==TemporalQueryReturnColumns.FIRST_START_DATE){ - selectClause.append(", min(" + primaryTableAlias + "start_date) temporal_start_date "); - aggregate = true; - } - else if (startDateRtn==TemporalQueryReturnColumns.LAST_START_DATE){ - selectClause.append(", max(" + primaryTableAlias + "start_date) temporal_start_date "); - aggregate = true; - } - else if (startDateRtn==TemporalQueryReturnColumns.START_DATE){ - selectClause.append(", " + primaryTableAlias + "start_date temporal_start_date "); - groupByClause.append(", " + primaryTableAlias + "start_date"); - } - else if (startDateRtn==TemporalQueryReturnColumns.FIRST_ENCOUNTER_START_DATE){ - selectClause.append(", min(" + primaryTableAlias + "start_date) temporal_start_date "); - aggregate = true; - } - else if (startDateRtn==TemporalQueryReturnColumns.LAST_ENCOUNTER_START_DATE){ - selectClause.append(", max(" + primaryTableAlias + "start_date) temporal_start_date "); - aggregate = true; - } - else if (startDateRtn==TemporalQueryReturnColumns.ENCOUNTER_START_DATE){ - selectClause.append(", " + primaryTableAlias + "start_date temporal_start_date "); - groupByClause.append(", " + primaryTableAlias + "start_date"); - } - } - - TemporalQueryReturnColumns endDateRtn = getEndDateReturnType(); - if (endDateRtn!=null){ - if (endDateRtn==TemporalQueryReturnColumns.FIRST_END_DATE){ - selectClause.append(", min(" + primaryTableAlias + "end_date) temporal_end_date "); - aggregate = true; - } - else if (endDateRtn==TemporalQueryReturnColumns.LAST_END_DATE){ - selectClause.append(", max(" + primaryTableAlias + "end_date) temporal_end_date "); - aggregate = true; - } - else if (endDateRtn==TemporalQueryReturnColumns.END_DATE){ - selectClause.append(", " + primaryTableAlias + "end_date temporal_end_date "); - groupByClause.append(", " + primaryTableAlias + "end_date"); - } - else if (endDateRtn==TemporalQueryReturnColumns.FIRST_ENCOUNTER_END_DATE){ - selectClause.append(", min(" + primaryTableAlias + "end_date) temporal_end_date "); - aggregate = true; - } - else if (endDateRtn==TemporalQueryReturnColumns.LAST_ENCOUNTER_END_DATE){ - selectClause.append(", max(" + primaryTableAlias + "end_date) temporal_end_date "); - aggregate = true; - } - else if (endDateRtn==TemporalQueryReturnColumns.ENCOUNTER_END_DATE){ - selectClause.append(", " + primaryTableAlias + "end_date temporal_end_date "); - groupByClause.append(", " + primaryTableAlias + "end_date"); - } - } - - String intoClause = ""; - if (useSqlServerTempTables()){ - intoClause = " into #m" + getSubQueryId() + " "; - } - - String indexClause = ""; - if (useSqlServerTempTables()){ - indexClause = "CREATE NONCLUSTERED INDEX m" + getSubQueryId() + "_idx on #m" + getSubQueryId() + " (patient_num, " + - (startDateRtn!=null ? "temporal_start_date, " : "") + - (endDateRtn!=null ? "temporal_end_date, " : "") + - "level_no)"; - } - - masterSql.append(insertClause.toString()); - masterSql.append(selectClause.toString()); - masterSql.append(intoClause); - masterSql.append(fromClause.toString()); - masterSql.append(whereClause.toString()); - if (aggregate) - masterSql.append(groupByClause.toString()); - - if (indexClause.trim().length()>0){ - masterSql.append(getSqlDelimiter()); - masterSql.append(indexClause); - } - - return masterSql.toString(); - } - - private boolean useSqlServerTempTables(){ - return parent.useSqlServerTempTables(); - } - - protected String getDeleteTempTableSql() { - String tempTableName = parent.getTempTableName(); - - if (parent.getServerType().equals(DAOFactoryHelper.SQLSERVER)) - return "truncate table "+ tempTableName; - else - return "delete "+ - (parent.getServerType().equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)? " from " : "") + tempTableName; - } - - protected String getDeleteDxTempTableSql() { - String tempTableName = parent.getDxTempTableName(); - - if (parent.getServerType().equals(DAOFactoryHelper.SQLSERVER)) - return "truncate table "+ tempTableName; - else - return "delete "+ - (parent.getServerType().equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)? " from " : "") + tempTableName; - } - - protected String getDeleteTempMasterSql(String masterId, int level) { - String masterTableName = parent.getMasterTempTableName(); - - if (useSqlServerTempTables()){ - return "if (object_id(#m" + masterId + ") is not null) drop table #m" + masterId + "\n" + - " else delete " + masterTableName + " " + - "where master_id = '" + masterId + "' " + - "and level_no >= " + String.valueOf(level); - } - else - return "delete " + - (parent.getServerType().equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)? " from " : "") + - masterTableName + " " + - "where master_id = '" + masterId + "' " + - "and level_no >= " + String.valueOf(level); - } - - public List getPanelList() { - return panelList; - } - - public int getPanelCount(){ - return this.panelList.size(); - } - - public boolean allAreInverted(){ - return this.invertedPanelCount == this.panelList.size(); - } - - public int getInvertedPanelCount(){ - return this.invertedPanelCount; - } - - public int getNonInvertedPanelCount(){ - return this.panelList.size() - this.invertedPanelCount; - } - - protected SecurityType getSecurityType() { - return parent.getSecurityType(); - } - - protected SecurityType getRequestorSecurityType() { - return parent.getRequestorSecurityType(); - } - - protected String getProjectId() { - return parent.getProjectId(); - } - - protected DataSourceLookup getDataSourceLookup(){ - return parent.getDataSourceLookup(); - } - - protected String getDatabaseSchema(){ - return parent.getDatabaseSchema(); - } - - protected String getParentQueryTiming(){ - return parent.getQueryTiming(); - } - - protected String getQueryTiming(){ - String timing = subQuery.getQueryTiming(); - if (timing==null||timing.trim().length()==0) - timing = parent.getQueryTiming(); - if (timing==null||timing.trim().length()==0) - timing = QueryTimingHandler.ANY; - return timing; - } - - protected String getServerType(){ - return parent.getServerType(); - } - - protected Map getProjectParameterMap(){ - return parent.getProjectParameterMap(); - } - - protected QueryTimingHandler getTimingHandler(){ - return parent.getTimingHandler(); - } - - protected int getPanelIndex(TemporalPanel panel){ - if (panel==null||panelList==null) - return -1; - else - return this.panelList.indexOf(panel); - } - - protected String getTempTableName(){ - return parent.getTempTableName(); - } - - protected boolean allowLargeTextValueConstrainFlag(){ - return parent.allowLargeTextValueConstrainFlag(); - } - - protected List getUserRoles() { - return parent.getUserRoles(); - } - - protected boolean hasInvertedPanel(){ - return invertedPanelCount>0; - } - - private String buildSubQueryId(String eventId){ - if (eventId==null) - return null; - else{ - int index = parent.getSubQueryIndex(eventId); - return parent.getQueryId() + "_S" + String.valueOf(index); - } - } - - protected String getSubQueryId(){ - if (this.subQueryId==null) - subQueryId = buildSubQueryId(getQueryId()); - return subQueryId; - } - - protected String getQueryId(){ - if (subQuery==null) - return null; - else - return subQuery.getQueryId(); - } - - protected String buildTempTableCheckDrop(String tempTableName) { - return parent.buildTempTableCheckDrop(tempTableName); - } - - protected boolean returnEncounterNum(){ - if (this.getQueryTiming().equalsIgnoreCase(QueryTimingHandler.SAMEVISIT)|| - this.getQueryTiming().equalsIgnoreCase(QueryTimingHandler.SAME)) - return true; - else - return false; - } - - protected boolean returnInstanceNum(){ - if (this.getQueryTiming().equalsIgnoreCase(QueryTimingHandler.SAMEINSTANCENUM)) - return true; - else - return false; - } - - protected boolean returnEncounterStartDate(){ - if (rtnColumns.contains(TemporalQueryReturnColumns.ENCOUNTER_START_DATE) || - rtnColumns.contains(TemporalQueryReturnColumns.FIRST_ENCOUNTER_START_DATE) || - rtnColumns.contains(TemporalQueryReturnColumns.LAST_ENCOUNTER_START_DATE)) - return true; - else - return false; - } - - protected boolean returnEncounterEndDate(){ - if (rtnColumns.contains(TemporalQueryReturnColumns.ENCOUNTER_END_DATE) || - rtnColumns.contains(TemporalQueryReturnColumns.FIRST_ENCOUNTER_END_DATE) || - rtnColumns.contains(TemporalQueryReturnColumns.LAST_ENCOUNTER_END_DATE)) - return true; - else - return false; - } - - protected boolean returnInstanceStartDate(){ - if (rtnColumns.contains(TemporalQueryReturnColumns.START_DATE) || - rtnColumns.contains(TemporalQueryReturnColumns.FIRST_START_DATE) || - rtnColumns.contains(TemporalQueryReturnColumns.LAST_START_DATE)) - return true; - else - return false; - } - - protected boolean returnInstanceEndDate(){ - if (rtnColumns.contains(TemporalQueryReturnColumns.END_DATE) || - rtnColumns.contains(TemporalQueryReturnColumns.FIRST_END_DATE) || - rtnColumns.contains(TemporalQueryReturnColumns.LAST_END_DATE)) - return true; - else - return false; - } - - protected int getProcessingLevel(){ - return parent.getProcessingLevel(); - } - - public String getSqlDelimiter() { - return parent.getSqlDelimiter(); - } - - protected int getEndPanelIndex() { - if (endPanelIndex==-1){ - int nonInvertedPanels = getPanelCount() - getInvertedPanelCount(); - if (!this.isFirstSubQuery()&&(parent.getQueryOptions().getTemporalConstraintStrategy()==TemporalConstraintStrategy.TEMP_TABLE_UPDATE)) - nonInvertedPanels++; - endPanelIndex = this.startPanelIndex + (nonInvertedPanels>0?nonInvertedPanels-1:0); - } - return endPanelIndex; - } - - - private List getConstraintsForSubQuery(TemporalSubQuery subQuery){ - if (subQuery!=null){ - String eventId = subQuery.getQueryId(); - if (this.constraints!=null){ - return constraints.get(eventId); - } - } - return null; - } - - protected TemporalQueryOptions getQueryOptions() { - return parent.getQueryOptions(); - } - - public void addIgnoredMessage(String errorMessage) { - parent.addIgnoredMessage(errorMessage); - } - - protected void addPreProcessingSql(String sql){ - if (sql!=null&&sql.trim().length()>0) - this.preProcessingSql.add(sql); - } - - protected void addPostProcessingSql(String sql){ - if (sql!=null&&sql.trim().length()>0) - this.postProcessingSql.add(sql); - } - - protected QueryDefinitionType searchForQueryInRequestDefinition(String subQueryId){ - return parent.searchForSubQuery(subQueryId); - } - - - public boolean occursTogether(TemporalSubQuery subQuery){ - String eventId = subQuery.getQueryId(); - List constraintList = getConstraintsForSubQuery(subQuery); - if (constraintList!=null){ - for(QueryConstraintType constraint : constraintList){ - if (((constraint.getFirstQuery().getQueryId()!=null&constraint.getFirstQuery().getQueryId().equalsIgnoreCase(eventId))|| - (constraint.getSecondQuery().getQueryId()!=null&constraint.getSecondQuery().getQueryId().equalsIgnoreCase(eventId)))&& - (constraint.getOperator().equals(QueryOperatorType.EQUAL)||constraint.getOperator().equals(QueryOperatorType.GREATEREQUAL)||constraint.getOperator().equals(QueryOperatorType.LESSEQUAL))){ - return true; - } - } - } - return false; - } - - public boolean occursAfter(TemporalSubQuery subQuery){ - String eventId = subQuery.getQueryId(); - List constraintList = getConstraintsForSubQuery(subQuery); - if (constraintList!=null){ - for(QueryConstraintType constraint : constraintList){ - if ((constraint.getSecondQuery().getQueryId()!=null&&constraint.getSecondQuery().getQueryId().equalsIgnoreCase(eventId))&& - (constraint.getOperator().equals(QueryOperatorType.GREATER)||constraint.getOperator().equals(QueryOperatorType.GREATEREQUAL))){ - return true; - } - else if ((constraint.getFirstQuery().getQueryId()!=null&&constraint.getFirstQuery().getQueryId().equalsIgnoreCase(eventId))&& - (constraint.getOperator().equals(QueryOperatorType.LESS)||constraint.getOperator().equals(QueryOperatorType.LESSEQUAL))){ - return true; - } - } - - } - return false; - } - - public boolean occursBefore(TemporalSubQuery subQuery){ - String eventId = subQuery.getQueryId(); - List constraintList = getConstraintsForSubQuery(subQuery); - if (constraintList!=null){ - for(QueryConstraintType constraint : constraintList){ - if ((constraint.getSecondQuery().getQueryId()!=null&&constraint.getSecondQuery().getQueryId().equalsIgnoreCase(eventId))&& - (constraint.getOperator().equals(QueryOperatorType.LESS)||constraint.getOperator().equals(QueryOperatorType.LESSEQUAL))){ - return true; - } - else if ((constraint.getFirstQuery().getQueryId()!=null&&constraint.getFirstQuery().getQueryId().equalsIgnoreCase(eventId))&& - (constraint.getOperator().equals(QueryOperatorType.GREATER)||constraint.getOperator().equals(QueryOperatorType.GREATEREQUAL))){ - return true; - } - } - } - return false; - } - - @Override - public int compareTo(Object element) { - if (element.getClass().equals((TemporalSubQuery.class))) { - TemporalSubQuery tp2 = (TemporalSubQuery) element; - boolean before = occursBefore(tp2); - boolean after = occursAfter(tp2); - if (before&&!after) - return -1; - else if (after&&!before) - return 1; - else { - return this.panelList.get(0).compareTo(tp2.panelList.get(0)); - } - } else { - return this.toString().compareTo(element.toString()); - } - } - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Christopher Herrick + */ +package edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal; + +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.TreeSet; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.QueryTimingHandler; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal.TemporalQueryOptions.QueryConstraintStrategy; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal.TemporalQueryOptions.TemporalConstraintStrategy; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryJoinColumnType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryJoinType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryOperatorType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QuerySpanConstraintType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryAggregateOperatorType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.PanelType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryConstraintType; + +public class TemporalSubQuery implements Comparable{ + + protected final Log log = LogFactory.getLog(getClass()); + + public enum TemporalQuerySpanUnits{ + YEAR, + MONTH, + DAY, + HOUR, + SECOND, + MINUTE + }; + + public enum TemporalQueryReturnColumns { + PATIENT, + ENCOUNTER, + INSTANCE, + START_DATE, + END_DATE, + FIRST_START_DATE, + LAST_START_DATE, + FIRST_END_DATE, + LAST_END_DATE, + ENCOUNTER_START_DATE, + ENCOUNTER_END_DATE, + FIRST_ENCOUNTER_START_DATE, + LAST_ENCOUNTER_START_DATE, + FIRST_ENCOUNTER_END_DATE, + LAST_ENCOUNTER_END_DATE + }; + + private List panelList = null; + private TemporalQuery parent; + private int invertedPanelCount = 0; + private int startPanelIndex = 0; + private int endPanelIndex = -1; + private boolean isProtectedQuery = false; + + + private EnumSet rtnColumns = EnumSet.of(TemporalQueryReturnColumns.PATIENT); + private QueryDefinitionType subQuery = null; + private String subQueryId = null; + private HashMap> constraints = null; + private boolean aggregateApplied = false; + private List preProcessingSql = null; + private List postProcessingSql = null; + + + public TemporalSubQuery(TemporalQuery parent, List groupPanels) throws I2B2Exception{ + this.parent = parent; + this.subQuery = new QueryDefinitionType(); + this.subQuery.setQueryId(parent.generateUniqueId()); + this.subQuery.getPanel().addAll(groupPanels); + + this.preProcessingSql = new ArrayList(); + this.postProcessingSql = new ArrayList(); + parsePanels(groupPanels); + } + + public TemporalSubQuery(TemporalQuery parent, QueryDefinitionType event) throws I2B2Exception{ + this.parent = parent; + this.subQuery = event; + if (event.getQueryId()==null||event.getQueryId().trim().length()==0) + event.setQueryId(parent.generateUniqueId()); + + this.preProcessingSql = new ArrayList(); + this.postProcessingSql = new ArrayList(); + parsePanels(event.getPanel()); + } + + public TemporalSubQuery(TemporalQuery parent, QueryDefinitionType event, HashMap> constraintList) throws I2B2Exception{ + this.parent = parent; + this.subQuery = event; + if (event.getQueryId()==null||event.getQueryId().trim().length()==0) + event.setQueryId(parent.generateUniqueId()); + if (constraintList!=null) + this.constraints = constraintList; + + this.preProcessingSql = new ArrayList(); + this.postProcessingSql = new ArrayList(); + parsePanels(event.getPanel()); + } + + public TemporalSubQuery(TemporalQuery parent, QueryDefinitionType event, HashMap> constraintList, EnumSet returnColumns) throws I2B2Exception{ + this.parent = parent; + this.subQuery = event; + if (event.getQueryId()==null||event.getQueryId().trim().length()==0) + event.setQueryId(parent.generateUniqueId()); + if (constraintList!=null) + this.constraints = constraintList; + if (returnColumns!=null) + this.rtnColumns = returnColumns; + + this.preProcessingSql = new ArrayList(); + this.postProcessingSql = new ArrayList(); + parsePanels(event.getPanel()); + } + + private void parsePanels(List grpList) throws I2B2Exception{ + TreeSet panelSet = new TreeSet(); + for (PanelType panelType : grpList) { + TemporalPanel panelItem = new TemporalPanel(this, panelType); + if (panelItem.isPanelInverted()) + invertedPanelCount++; + panelSet.add(panelItem); + } + + panelList = new ArrayList(); + panelList.addAll(panelSet); + } + + public String buildSql() throws I2B2DAOException{ + StringBuffer subQuerySqlBuffer = new StringBuffer(); + int currentPanelIndex = 0; + for (TemporalPanel panel : panelList){ + String panelSql = panel.buildSql(currentPanelIndex); + subQuerySqlBuffer.append(panelSql); + + + if (!panel.isPanelInverted()){ + endPanelIndex = currentPanelIndex; + currentPanelIndex++; + } + + subQuerySqlBuffer.append(getSqlDelimiter()); + } + + if (parent.getSubQueryCount()>1){ + int level = 0; + if (this.isFirstSubQuery()) + level = 1; + subQuerySqlBuffer.append(buildMoveToMasterSql(level)); + subQuerySqlBuffer.append(getSqlDelimiter()); + + if (parent.getServerType().equals(DAOFactoryHelper.ORACLE)) + parent.addPostProcessingSql(getDeleteTempMasterSql(this.getSubQueryId(), 0)); + + subQuerySqlBuffer.append(getDeleteTempTableSql()); + subQuerySqlBuffer.append(getSqlDelimiter()); + } + + if (!this.isFirstSubQuery()){ + subQuerySqlBuffer.append(buildMasterTableTimingConstraintUpdate(1)); + subQuerySqlBuffer.append(getSqlDelimiter()); + } + + StringBuffer sqlBuffer = new StringBuffer(); + if (this.preProcessingSql!=null&&this.preProcessingSql.size()>0){ + for(String sql : this.preProcessingSql){ + sqlBuffer.append(sql); + sqlBuffer.append(getSqlDelimiter()); + } + } + sqlBuffer.append(subQuerySqlBuffer.toString()); + if (this.postProcessingSql!=null&&this.postProcessingSql.size()>0){ + for(String sql : this.postProcessingSql){ + sqlBuffer.append(sql); + sqlBuffer.append(getSqlDelimiter()); + } + } + + + return sqlBuffer.toString(); + } + + public boolean isFirstSubQuery(){ + return parent.isFirstSubQuery(this); + } + + public boolean isLastSubQuery(){ + return parent.isLastSubQuery(this); + } + + + public boolean isProtectedQuery() { + return isProtectedQuery; + } + + public void setProtectedQuery(boolean isProtectedQuery) { + this.isProtectedQuery = isProtectedQuery; + } + + protected TemporalQueryReturnColumns getStartDateReturnType(){ + //currently, we only support one start and end date type per query. if both instance and encounter start dates + //are specified in a query, we'll use the instance date + + if (rtnColumns.contains(TemporalQueryReturnColumns.START_DATE) + || (rtnColumns + .contains(TemporalQueryReturnColumns.FIRST_START_DATE) && rtnColumns + .contains(TemporalQueryReturnColumns.LAST_START_DATE)) + || (rtnColumns + .contains(TemporalQueryReturnColumns.END_DATE) && (rtnColumns + .contains(TemporalQueryReturnColumns.FIRST_START_DATE) || rtnColumns + .contains(TemporalQueryReturnColumns.LAST_START_DATE)))) { + return TemporalQueryReturnColumns.START_DATE; + } else if (rtnColumns + .contains(TemporalQueryReturnColumns.FIRST_START_DATE)) { + return TemporalQueryReturnColumns.FIRST_START_DATE; + } else if (rtnColumns + .contains(TemporalQueryReturnColumns.LAST_START_DATE)) { + return TemporalQueryReturnColumns.LAST_START_DATE; + } else if (rtnColumns + .contains(TemporalQueryReturnColumns.ENCOUNTER_START_DATE) + || (rtnColumns + .contains(TemporalQueryReturnColumns.FIRST_ENCOUNTER_START_DATE) && rtnColumns + .contains(TemporalQueryReturnColumns.LAST_ENCOUNTER_START_DATE)) + || (rtnColumns + .contains(TemporalQueryReturnColumns.ENCOUNTER_END_DATE) && (rtnColumns + .contains(TemporalQueryReturnColumns.FIRST_ENCOUNTER_START_DATE) || rtnColumns + .contains(TemporalQueryReturnColumns.LAST_ENCOUNTER_START_DATE)))) { + return TemporalQueryReturnColumns.ENCOUNTER_START_DATE; + } else if (rtnColumns + .contains(TemporalQueryReturnColumns.FIRST_ENCOUNTER_START_DATE)) { + return TemporalQueryReturnColumns.FIRST_ENCOUNTER_START_DATE; + } else if (rtnColumns + .contains(TemporalQueryReturnColumns.LAST_ENCOUNTER_START_DATE)) { + return TemporalQueryReturnColumns.LAST_ENCOUNTER_START_DATE; + } + return null; + } + + + + protected TemporalQueryReturnColumns getEndDateReturnType(){ + if (rtnColumns.contains(TemporalQueryReturnColumns.END_DATE) + || (rtnColumns.contains(TemporalQueryReturnColumns.FIRST_END_DATE) && rtnColumns + .contains(TemporalQueryReturnColumns.LAST_END_DATE)) + || (rtnColumns + .contains(TemporalQueryReturnColumns.START_DATE) && (rtnColumns + .contains(TemporalQueryReturnColumns.FIRST_END_DATE) || rtnColumns + .contains(TemporalQueryReturnColumns.LAST_END_DATE)))) { + return TemporalQueryReturnColumns.END_DATE; + } else if (rtnColumns + .contains(TemporalQueryReturnColumns.FIRST_END_DATE)) { + return TemporalQueryReturnColumns.FIRST_END_DATE; + } else if (rtnColumns + .contains(TemporalQueryReturnColumns.LAST_END_DATE)) { + return TemporalQueryReturnColumns.LAST_END_DATE; + } else if (rtnColumns + .contains(TemporalQueryReturnColumns.ENCOUNTER_END_DATE) + || (rtnColumns + .contains(TemporalQueryReturnColumns.FIRST_ENCOUNTER_END_DATE) && rtnColumns + .contains(TemporalQueryReturnColumns.LAST_ENCOUNTER_END_DATE)) + || (rtnColumns + .contains(TemporalQueryReturnColumns.ENCOUNTER_START_DATE) && (rtnColumns + .contains(TemporalQueryReturnColumns.FIRST_ENCOUNTER_END_DATE) || rtnColumns + .contains(TemporalQueryReturnColumns.LAST_ENCOUNTER_END_DATE)))) { + return TemporalQueryReturnColumns.ENCOUNTER_END_DATE; + } else if (rtnColumns + .contains(TemporalQueryReturnColumns.FIRST_ENCOUNTER_END_DATE)) { + return TemporalQueryReturnColumns.FIRST_ENCOUNTER_END_DATE; + } else if (rtnColumns + .contains(TemporalQueryReturnColumns.LAST_ENCOUNTER_END_DATE)) { + return TemporalQueryReturnColumns.LAST_ENCOUNTER_END_DATE; + } + return null; + } + + protected String buildMasterTableTimingConstraintUpdate(int level){ + String timingConstraintSql = buildTimingConstraintSql(level); + + StringBuilder updateSql = new StringBuilder(); + if (parent.getServerType().equals(DAOFactoryHelper.SQLSERVER)){ + if (useSqlServerTempTables()){ + updateSql.append("update #m" + getSubQueryId() + " "); + updateSql.append("set level_no = " + String.valueOf(level) + " "); + updateSql.append("from #m" + getSubQueryId() + " t "); + updateSql.append(timingConstraintSql + " "); + updateSql.append("and t.level_no = " + String.valueOf(level - 1) + " "); + } + else { + updateSql.append("update " + parent.getMasterTempTableName() + " "); + updateSql.append("set level_no = " + String.valueOf(level) + " "); + updateSql.append("from " + parent.getMasterTempTableName() + " t "); + updateSql.append(timingConstraintSql + " "); + updateSql.append("and t.level_no = " + String.valueOf(level - 1) + " "); + updateSql.append("and t.master_id = '" + this.getSubQueryId() + "'"); + } + } + else { + updateSql.append("update " + parent.getMasterTempTableName() + " t "); + updateSql.append("set level_no = " + String.valueOf(level) + " "); + updateSql.append(timingConstraintSql + " "); + updateSql.append("and t.level_no = " + String.valueOf(level - 1) + " "); + updateSql.append("and t.master_id = '" + this.getSubQueryId() + "'"); + } + + + return updateSql.toString(); + } + + protected String buildTimingConstraintUpdate(int panelCount){ + String timingConstraintSql = buildTimingConstraintSql(panelCount); + + StringBuilder updateSql = new StringBuilder(); + if (parent.getServerType().equals(DAOFactoryHelper.SQLSERVER)){ + updateSql.append("update " + parent.getTempTableName() + " "); + updateSql.append("set panel_count = " + String.valueOf(panelCount) + " "); + updateSql.append("from " + parent.getTempTableName() + " t "); + } + else { + updateSql.append("update " + parent.getTempTableName() + " t "); + updateSql.append("set panel_count = " + String.valueOf(panelCount) + " "); + } + + updateSql.append(timingConstraintSql + " "); + updateSql.append("and t.panel_count = " + String.valueOf(panelCount - 1)); + + return updateSql.toString(); + } + + private String addTimingConstraintSql(String panelSql){ + String timingConstraint = buildTimingConstraintSql(); + int lastIndex = panelSql.lastIndexOf(this.getSqlDelimiter()); + if (lastIndex==-1){ + panelSql += timingConstraint; + } + else if (parent.getQueryOptions().getQueryConstraintLogic()==QueryConstraintStrategy.TEMP_TABLES && + parent.getServerType().equals(DAOFactoryHelper.SQLSERVER)){ + panelSql = addToRegExExpression(panelSql, "insert into " + parent.getTempTableName() + "(.*?)(?:(" + getSqlDelimiter().replace("*", "\\*") + "|$))", timingConstraint); + } + else { + panelSql = panelSql.replace(getSqlDelimiter(), timingConstraint + getSqlDelimiter()) + timingConstraint; + } + return panelSql; + } + + private String addToRegExExpression(String sqlString, String regEx, String newSql){ + StringBuilder sql = new StringBuilder(); + Pattern p = Pattern.compile(regEx, Pattern.DOTALL|Pattern.CASE_INSENSITIVE); + Matcher m = p.matcher(sqlString); + int lastIndex = 0; + while (m.find()){ + int endIndex = m.end(); + String text = sqlString.substring(lastIndex, endIndex - getSqlDelimiter().length()); + sql.append(text); + sql.append(newSql); + sql.append(getSqlDelimiter()); + lastIndex = endIndex; + } + sql.append(sqlString.substring(lastIndex)); + return sql.toString(); + } + + protected String buildTimingConstraintSql(){ + return buildTimingConstraintSql(-1); + } + + protected String buildTimingConstraintSql(int panelCount){ + StringBuffer timingSqlBuf = new StringBuffer(""); + + boolean firstConstraint = true; + + boolean encounterConstraint = false; + if (parent.getQueryTiming()!=null&& + (parent.getQueryTiming().equalsIgnoreCase(QueryTimingHandler.SAME)|| + parent.getQueryTiming().equalsIgnoreCase(QueryTimingHandler.SAMEVISIT))) + encounterConstraint = true; + + String lastSubQueryId = parent.getLastProcessedSubQueryId(); + if (lastSubQueryId!=null&&lastSubQueryId.trim().length()>0){ + if (useSqlServerTempTables()){ + timingSqlBuf.append(" where exists (select 1 from " + + "#m" + lastSubQueryId + " m " + + "where m.patient_num = t.patient_num " + + (encounterConstraint?"and m.encounter_num = t.encounter_num ":"") + + "and m.level_no = 1 " + + //"group by m.patient_num" + + ") \n"); + } + else { + timingSqlBuf.append(" where exists (select 1 from " + parent.getMasterTempTableName() + " m " + + "where m.master_id = '" + lastSubQueryId + "' " + + "and m.patient_num = t.patient_num " + + (encounterConstraint?"and m.encounter_num = t.encounter_num ":"") + + "and m.level_no = 1 " + + //"group by m.patient_num " + + ") \n"); + } + firstConstraint = false; + } + + if (constraints!=null){ + for (List constraintLists: constraints.values()){ + for (QueryConstraintType constraint: constraintLists){ + + QueryJoinType masterTableQuery = constraint.getFirstQuery(); + QueryJoinType tempTableQuery = constraint.getSecondQuery(); + + //first, get the right column comparison + String firstColumn = getColumnNameFromType(constraint.getFirstQuery().getJoinColumn()); + String secondColumn = getColumnNameFromType(constraint.getSecondQuery().getJoinColumn()); + + String firstPrefix = "m"; + String secondPrefix = "t"; + boolean switchedPrefix = false; + + String otherQueryId = constraint.getFirstQuery().getQueryId(); + if (constraint.getFirstQuery().getQueryId().equals(getQueryId())){ + firstPrefix = secondPrefix; + secondPrefix = "m"; + otherQueryId = constraint.getSecondQuery().getQueryId(); + masterTableQuery = tempTableQuery; + tempTableQuery = constraint.getFirstQuery(); + switchedPrefix = true; + } + + String dateConstraintSql = buildDateSqlForMaster(masterTableQuery, encounterConstraint); + + if (dateConstraintSql!=null&&dateConstraintSql.trim().length()>0){ + + if (firstConstraint){ + timingSqlBuf.append(" where "); + firstConstraint = false; + } + else + timingSqlBuf.append(" and "); + + + timingSqlBuf.append(" exists (" + + "select 1 " + + "from (" + dateConstraintSql + ") m "); + + + String newPrefix = "t"; + String columnName = getColumnNameFromType(tempTableQuery.getJoinColumn()); + if (tempTableQuery.getAggregateOperator().equals(QueryAggregateOperatorType.FIRST)){ + timingSqlBuf.append(", (select m.patient_num " + + (encounterConstraint?", m.encounter_num ":"") + + ", min(m." + columnName + ") " + columnName + " "); + if (useSqlServerTempTables()){ + timingSqlBuf.append("from #m" + this.buildSubQueryId(tempTableQuery.getQueryId()) + " m "); + } + else { + timingSqlBuf.append("from " + parent.getMasterTempTableName() + " m " + + "where m.master_id = '" + this.buildSubQueryId(tempTableQuery.getQueryId()) + "' "); + } + timingSqlBuf.append("group by m.patient_num" + + (encounterConstraint?", m.encounter_num ":"") + + ") t2 " + + "where m.patient_num = t2.patient_num " + + (encounterConstraint?"and m.encounter_num = t2.encounter_num ":"") + + "and t.patient_num = t2.patient_num " + + (encounterConstraint?"and t.encounter_num = t2.encounter_num ":"") + + "and "); + newPrefix = "t2"; + } + else if (tempTableQuery.getAggregateOperator().equals(QueryAggregateOperatorType.LAST)){ + timingSqlBuf.append(", (select m.patient_num, max(m." + columnName + ") " + columnName + " "); + if (useSqlServerTempTables()){ + timingSqlBuf.append("from #m" + this.buildSubQueryId(tempTableQuery.getQueryId()) + " m "); + } + else { + timingSqlBuf.append("from " + parent.getMasterTempTableName() + " m " + + "where m.master_id = '" + this.buildSubQueryId(tempTableQuery.getQueryId()) + "' "); + } + timingSqlBuf.append("group by m.patient_num) t2 " + + "where m.patient_num = t2.patient_num " + + (encounterConstraint?"and m.encounter_num = t2.encounter_num ":"") + + "and t.patient_num = t2.patient_num " + + (encounterConstraint?"and t.encounter_num = t2.encounter_num ":"") + + "and "); + newPrefix = "t2"; + } + else { + timingSqlBuf.append("where "); + } + + if (firstPrefix.equals("t")) + firstPrefix = newPrefix; + else + secondPrefix = newPrefix; + + timingSqlBuf.append("m.patient_num = t.patient_num " + + (encounterConstraint?"and m.encounter_num = t.encounter_num ":"")); + timingSqlBuf.append("and " + firstPrefix + "." + firstColumn + " "); + + QueryOperatorType dateOperator = constraint.getOperator(); + if (dateOperator.equals(QueryOperatorType.EQUAL)) + timingSqlBuf.append("= "); + else if (dateOperator.equals(QueryOperatorType.GREATER)) + timingSqlBuf.append("> "); + else if (dateOperator.equals(QueryOperatorType.GREATEREQUAL)) + timingSqlBuf.append(">= "); + else if (dateOperator.equals(QueryOperatorType.LESS)) + timingSqlBuf.append("< "); + else if (dateOperator.equals(QueryOperatorType.LESSEQUAL)) + timingSqlBuf.append("<= "); + + timingSqlBuf.append(secondPrefix + "." + secondColumn + " "); + + if (constraint.getSpan()!=null&&constraint.getSpan().size()>0){ + for (QuerySpanConstraintType spanConstraint : constraint.getSpan()) + { + String spanFirstPrefix = firstPrefix; + String spanFirstColumn = firstColumn; + String spanSecondPrefix = secondPrefix; + String spanSecondColumn = secondColumn; + + + String spanOperator = "="; + QueryOperatorType spanOpType = spanConstraint.getOperator(); + if (spanConstraint.getOperator()!=null){ + if (spanOpType.equals(QueryOperatorType.EQUAL)) + spanOperator = "= "; + else if (spanOpType.equals(QueryOperatorType.GREATER)) + spanOperator = "> "; + else if (spanOpType.equals(QueryOperatorType.GREATEREQUAL)) + spanOperator = ">= "; + else if (spanOpType.equals(QueryOperatorType.LESS)) + spanOperator = "< "; + else if (spanOpType.equals(QueryOperatorType.LESSEQUAL)) + spanOperator = "<= "; + } + + String units = spanConstraint.getUnits(); + String sqlUnits = ""; + int span = spanConstraint.getSpanValue(); + + if (units!=null){ + + if (dateOperator.equals(QueryOperatorType.GREATER)||dateOperator.equals(QueryOperatorType.GREATEREQUAL)){ + String spanPrefix = spanFirstPrefix; + String spanColumn = spanFirstColumn; + spanFirstPrefix = spanSecondPrefix; + spanFirstColumn = spanSecondColumn; + spanSecondPrefix = spanPrefix; + spanSecondColumn = spanColumn; + } + + if (TemporalQuerySpanUnits.valueOf(units)==TemporalQuerySpanUnits.YEAR){ + if (parent.getServerType().equals(DAOFactoryHelper.ORACLE)) + sqlUnits = "ADD_MONTHS(" + spanFirstPrefix + "." + spanFirstColumn + ", (12 * " + span + "))"; + else if (parent.getServerType().equals(DAOFactoryHelper.SQLSERVER)) + sqlUnits = "DATEADD(YEAR, (" + span + "), " + spanFirstPrefix + "." + spanFirstColumn + ")"; + else if (parent.getServerType().equals(DAOFactoryHelper.POSTGRESQL)) + sqlUnits = " " + spanFirstPrefix + "." + spanFirstColumn + " + cast('" + span + " years' as interval) "; + + } + else if (TemporalQuerySpanUnits.valueOf(units)==TemporalQuerySpanUnits.MONTH){ + if (parent.getServerType().equals(DAOFactoryHelper.ORACLE)) + sqlUnits = "ADD_MONTHS(" + spanFirstPrefix + "." + spanFirstColumn + ", (" + span + "))"; + else if (parent.getServerType().equals(DAOFactoryHelper.SQLSERVER)) + sqlUnits = "DATEADD(MONTH, (" + span + "), " + spanFirstPrefix + "." + spanFirstColumn + ")"; + else if (parent.getServerType().equals(DAOFactoryHelper.POSTGRESQL)) + sqlUnits = " " + spanFirstPrefix + "." + spanFirstColumn + " + cast('" + span + " months' as interval) "; + } + else if (TemporalQuerySpanUnits.valueOf(units)==TemporalQuerySpanUnits.DAY){ + if (parent.getServerType().equals(DAOFactoryHelper.ORACLE)) + sqlUnits = "(" + spanFirstPrefix + "." + spanFirstColumn + " + (" + span + "))"; + else if (parent.getServerType().equals(DAOFactoryHelper.SQLSERVER)) + sqlUnits = "DATEADD(DAY, (" + span + "), " + spanFirstPrefix + "." + spanFirstColumn + ")"; + else if (parent.getServerType().equals(DAOFactoryHelper.POSTGRESQL)) + sqlUnits = " " + spanFirstPrefix + "." + spanFirstColumn + " + cast('" + span + " days' as interval) "; + } + else if (TemporalQuerySpanUnits.valueOf(units)==TemporalQuerySpanUnits.HOUR){ + if (parent.getServerType().equals(DAOFactoryHelper.ORACLE)) + sqlUnits = "(" + spanFirstPrefix + "." + spanFirstColumn + " + (1/24 * " + span + "))"; + else if (parent.getServerType().equals(DAOFactoryHelper.SQLSERVER)) + sqlUnits = "DATEADD(HOUR, (" + span + "), " + spanFirstPrefix + "." + spanFirstColumn + ")"; + else if (parent.getServerType().equals(DAOFactoryHelper.POSTGRESQL)) + sqlUnits = " " + spanFirstPrefix + "." + spanFirstColumn + " + cast('" + span + " hours' as interval) "; + } + else if (TemporalQuerySpanUnits.valueOf(units)==TemporalQuerySpanUnits.MINUTE){ + if (parent.getServerType().equals(DAOFactoryHelper.ORACLE)) + sqlUnits = "(" + spanFirstPrefix + "." + spanFirstColumn + " + (1/1440 * " + span + "))"; + else if (parent.getServerType().equals(DAOFactoryHelper.SQLSERVER)) + sqlUnits = "DATEADD(MINUTE, (" + span + "), " + spanFirstPrefix + "." + spanFirstColumn + ")"; + else if (parent.getServerType().equals(DAOFactoryHelper.POSTGRESQL)) + sqlUnits = " " + spanFirstPrefix + "." + spanFirstColumn + " + cast('" + span + " minutes' as interval) "; + } + else if (TemporalQuerySpanUnits.valueOf(units)==TemporalQuerySpanUnits.SECOND){ + if (parent.getServerType().equals(DAOFactoryHelper.ORACLE)) + sqlUnits = "(" + spanFirstPrefix + "." + spanFirstColumn + " + (1/86400 * " + span + "))"; + else if (parent.getServerType().equals(DAOFactoryHelper.SQLSERVER)) + sqlUnits = "DATEADD(SECOND, (" + span + "), " + spanFirstPrefix + "." + spanFirstColumn + ")"; + else if (parent.getServerType().equals(DAOFactoryHelper.POSTGRESQL)) + sqlUnits = " " + spanFirstPrefix + "." + spanFirstColumn + " + cast('" + span + " seconds' as interval) "; + } + } + + if (sqlUnits.trim().length()>0) + timingSqlBuf.append("and " + spanSecondPrefix + "." + spanSecondColumn + " " + spanOperator + " " + sqlUnits); + } + + } + } + + timingSqlBuf.append(")"); + } + } + } + return timingSqlBuf.toString(); + } + + private String getTempQueryConstraint(QueryJoinType tempJoin, int panelCount){ + boolean useTempTables = false; + if (parent.getServerType().equalsIgnoreCase( + DAOFactoryHelper.SQLSERVER)&& + parent.getQueryOptions().getQueryConstraintLogic()==QueryConstraintStrategy.TEMP_TABLES){ + useTempTables = true; + } + + StringBuilder tempClause = new StringBuilder(); + if (tempJoin!=null){ + String columnName = ""; + String columnAlias = ""; + String temporalTableAlias = "f"; + String temporalJoinTable = "observation_fact"; + if (tempJoin.getJoinColumn().equals(QueryJoinColumnType.STARTDATE)){ + columnName = "start_date"; + columnAlias = "temporal_start_date"; + temporalTableAlias = "f"; + temporalJoinTable = "observation_fact"; + } + else if (tempJoin.getJoinColumn().equals(QueryJoinColumnType.ENDDATE)){ + columnName = "end_date"; + columnAlias = "temporal_end_date"; + temporalTableAlias = "f"; + temporalJoinTable = "observation_fact"; + } + else if (tempJoin.getJoinColumn().equals(QueryJoinColumnType.ENCOUNTER_STARTDATE)){ + columnName = "start_date"; + columnAlias = "temporal_start_date"; + temporalTableAlias = "v"; + temporalJoinTable = "visit_dimension"; + } + else if (tempJoin.getJoinColumn().equals(QueryJoinColumnType.ENCOUNTER_ENDDATE)){ + columnName = "end_date"; + columnAlias = "temporal_end_date"; + temporalTableAlias = "v"; + temporalJoinTable = "visit_dimension"; + } + + if (columnName.trim().length()>0){ + if (tempJoin.getAggregateOperator().equals(QueryAggregateOperatorType.FIRST)){ + tempClause.append("select " + temporalTableAlias + ".patient_num, " + + "min(" + temporalTableAlias + "." + columnName + ") " + columnAlias + " " + + "from " + parent.getDatabaseSchema() + temporalJoinTable + " " + temporalTableAlias + " "); + } + else if (tempJoin.getAggregateOperator().equals(QueryAggregateOperatorType.LAST)){ + tempClause.append("select " + temporalTableAlias + ".patient_num, max(" + temporalTableAlias + "." + columnName + ") " + columnAlias + " " + + "from " + parent.getDatabaseSchema() + temporalJoinTable + " " + temporalTableAlias + " "); + } + else{ + tempClause.append("select " + temporalTableAlias + ".patient_num, " + temporalTableAlias + ".encounter_num, " + temporalTableAlias + "." + columnName + " " + columnAlias + " " + + "from " + parent.getDatabaseSchema() + temporalJoinTable + " " + temporalTableAlias + " "); + } + + String tableAlias = "cnst"; + + if (parent.getQueryOptions().getTemporalConstraintStrategy()==TemporalConstraintStrategy.TEMP_TABLE_UPDATE){ + tempClause.append(", " + getTempTableName() + " cnst "); + } + else if (useTempTables){ + tempClause.append(", #t cnst "); + } + else { + tempClause.append(", t cnst "); + } + + + tempClause.append("where " + tableAlias + ".patient_num = " + temporalTableAlias + ".patient_num "); + if (this.getQueryTiming().equalsIgnoreCase(QueryTimingHandler.ANY)){ + tempClause.append("and " + tableAlias + ".encounter_num = " + temporalTableAlias + ".encounter_num "); + } + if (parent.getQueryOptions().getTemporalConstraintStrategy()==TemporalConstraintStrategy.TEMP_TABLE_UPDATE){ + tempClause.append("and " + tableAlias + ".panel_count = " + String.valueOf(panelCount) + " "); + } + + if ((tempJoin.getAggregateOperator().equals(QueryAggregateOperatorType.FIRST))|| + (tempJoin.getAggregateOperator().equals(QueryAggregateOperatorType.LAST))) + tempClause.append("group by " + temporalTableAlias + ".patient_num "); + else + tempClause.append("group by " + temporalTableAlias + ".patient_num, " + temporalTableAlias + ".encounter_num, v." + columnName + " "); + } + } + return tempClause.toString(); + } + + private String buildDateSqlForMaster(QueryJoinType masterJoin, boolean includeEncounter){ + String columnName = getColumnNameFromType(masterJoin.getJoinColumn()); + + String encounterColumn = (includeEncounter?", m.encounter_num ":""); + + String selectStatement = "select m.patient_num " + encounterColumn + ", m." + columnName + " "; + String fromStatement = "from " + parent.getMasterTempTableName() + " m "; + String whereStatement = "where m.master_id = '" + this.buildSubQueryId(masterJoin.getQueryId()) + "' "; + String groupByStatement = "group by m.patient_num " + encounterColumn + " "; + + if (useSqlServerTempTables()){ + fromStatement = "from #m" + this.buildSubQueryId(masterJoin.getQueryId()) + " m "; + whereStatement = ""; + } + + if (!masterJoin.getJoinColumn().equals(QueryJoinColumnType.INSTANCE)){ + if (masterJoin.getAggregateOperator().equals(QueryAggregateOperatorType.FIRST)){ + selectStatement = "select m.patient_num " + encounterColumn + ", min(m." + columnName + ") " + columnName + " "; + } + else if (masterJoin.getAggregateOperator().equals(QueryAggregateOperatorType.LAST)){ + selectStatement = "select m.patient_num " + encounterColumn + ", max(m." + columnName + ") " + columnName + " "; + } + else { + selectStatement = "select m.patient_num " + encounterColumn + ", m." + columnName + " "; + if (whereStatement.trim().length()>0) + whereStatement += "and m.level_no = 1 "; + else + whereStatement = "where m.level_no = 1 "; + groupByStatement = ""; + } + } + else { + selectStatement = "select " + columnName + ", temporal_start_date, temporal_end_date "; + groupByStatement = ""; + } + + return selectStatement + " " + + fromStatement + " " + + whereStatement + " " + + groupByStatement; + } + + /*private String getConstrainedDateSqlFromMaster(QueryJoinType masterJoin){ + String columnName = getColumnNameFromType(masterJoin.getJoinColumn()); + + if (!masterJoin.getJoinColumn().equals(QueryJoinColumnType.INSTANCE)){ + if (masterJoin.getAggregateOperator().equals(QueryAggregateOperatorType.FIRST)) + return "select m.patient_num, min(m." + columnName + ") " + columnName + " " + + "from " + parent.getMasterTempTableName() + " m " + + "where m.master_id = '" + this.buildSubQueryId(masterJoin.getQueryId()) + "' " + + "group by m.patient_num"; + else if (masterJoin.getAggregateOperator().equals(QueryAggregateOperatorType.LAST)) + return "select m.patient_num, max(m." + columnName + ") " + columnName + " " + + "from " + parent.getMasterTempTableName() + " m " + + "where m.master_id = '" + this.buildSubQueryId(masterJoin.getQueryId()) + "' " + + "group by m.patient_num"; + else + return "select m.patient_num, m." + columnName + " " + + "from " + parent.getMasterTempTableName() + " m " + + "where m.master_id = '" + this.buildSubQueryId(masterJoin.getQueryId()) + "' " + + "and m.level_no = 1 "; + } + else + return "select " + columnName + ", temporal_start_date, temporal_end_date " + + "from " + parent.getMasterTempTableName() + " m " + + "where m.master_id = '" + this.buildSubQueryId(masterJoin.getQueryId()) + "' "; + }*/ + + protected String getColumnNameFromType(QueryJoinColumnType columnType){ + if (columnType!=null){ + if (columnType.equals(QueryJoinColumnType.ENCOUNTER)) + return "encounter_num"; + else if (columnType.equals(QueryJoinColumnType.STARTDATE)) + return "temporal_start_date"; + else if (columnType.equals(QueryJoinColumnType.ENDDATE)) + return "temporal_end_date"; + else if (columnType.equals(QueryJoinColumnType.ENCOUNTER_STARTDATE)) + return "temporal_start_date"; + else if (columnType.equals(QueryJoinColumnType.ENCOUNTER_ENDDATE)) + return "temporal_end_date"; + else if (columnType.equals(QueryJoinColumnType.INSTANCE)) + return "provider_id, start_date, concept_cd, instance_num, encounter_num, patient_num"; + } + return "patient_num"; + } + + protected String buildMoveToMasterSql(int level) { + String tempTableName = parent.getTempTableName(); + String masterTableName = parent.getMasterTempTableName(); + StringBuilder masterSql = new StringBuilder(); + + StringBuilder insertClause = new StringBuilder(); + if (!useSqlServerTempTables()){ + insertClause.append(" insert into " + masterTableName); + insertClause.append("(master_id, patient_num, level_no"); + if (rtnColumns.contains(TemporalQueryReturnColumns.ENCOUNTER)){ + insertClause.append(", encounter_num"); + } + if (rtnColumns.contains(TemporalQueryReturnColumns.INSTANCE)){ + if (!rtnColumns.contains(TemporalQueryReturnColumns.ENCOUNTER)){ + insertClause.append(", encounter_num"); + } + insertClause.append(", provider_id, start_date, concept_cd, instance_num"); + } + if (returnInstanceStartDate()||returnEncounterStartDate()){ + insertClause.append(", temporal_start_date"); + } + if (returnInstanceEndDate()||returnEncounterEndDate()){ + insertClause.append(", temporal_end_date"); + } + insertClause.append(") "); + } + else { + masterSql.append(parent.buildTempTableCheckDrop("#m" + getSubQueryId())); + masterSql.append(parent.getSqlDelimiter()); + } + + + String schema = getDatabaseSchema(); + if (schema==null) + schema = ""; + else if (!schema.endsWith(".")) + schema += "."; + + String primaryTableAlias = "t."; + StringBuilder fromClause = new StringBuilder("from " + tempTableName + " t "); + StringBuilder whereClause = new StringBuilder(" where t.panel_count = " + this.getEndPanelIndex() + " "); + if ((((rtnColumns.contains(TemporalQueryReturnColumns.INSTANCE)|| + returnInstanceStartDate()))&& + (!this.getQueryTiming().equalsIgnoreCase(QueryTimingHandler.SAMEINSTANCENUM)))|| + (returnInstanceEndDate())){ + primaryTableAlias = "f."; + fromClause.append(", " + schema + "observation_fact f "); + whereClause.append("and f.patient_num = t.patient_num "); + if (this.getQueryTiming().equalsIgnoreCase(QueryTimingHandler.SAME)|| + this.getQueryTiming().equalsIgnoreCase(QueryTimingHandler.SAMEVISIT)){ + whereClause.append("and f.encounter_num = t.encounter_num "); + } + else if (this.getQueryTiming().equalsIgnoreCase(QueryTimingHandler.SAMEINSTANCENUM)){ + whereClause.append("and f.encounter_num = t.encounter_num "); + whereClause.append("and f.provider_id = t.provider_id "); + whereClause.append("and f.start_date = t.start_date "); + whereClause.append("and f.instance_num = t.instance_num "); + whereClause.append("and f.concept_cd = t.concept_cd "); + } + + if (returnEncounterEndDate()||returnEncounterStartDate()){ + fromClause.append(", " + schema + "visit_dimension v "); + whereClause.append("and f.patient_num = v.patient_num "); + whereClause.append("and f.encounter_num = v.encounter_num "); + } + } + else if ((rtnColumns.contains(TemporalQueryReturnColumns.ENCOUNTER)&& + !this.getQueryTiming().equalsIgnoreCase(QueryTimingHandler.SAME)&& + !this.getQueryTiming().equalsIgnoreCase(QueryTimingHandler.SAMEVISIT)&& + !this.getQueryTiming().equalsIgnoreCase(QueryTimingHandler.SAMEINSTANCENUM))|| + returnEncounterStartDate()|| + returnEncounterEndDate()){ + primaryTableAlias = "v."; + fromClause.append(", " + schema + "visit_dimension v "); + whereClause.append("and v.patient_num = t.patient_num "); + if (!this.getQueryTiming().equalsIgnoreCase(QueryTimingHandler.ANY)){ + whereClause.append("and v.encounter_num = t.encounter_num "); + } + } + + boolean aggregate = false; + StringBuilder selectClause = new StringBuilder(); + if (useSqlServerTempTables()){ + selectClause.append("select t.patient_num, " + String.valueOf(level) + " level_no "); + } + else { + selectClause.append("select '" + getSubQueryId() + "', t.patient_num, " + String.valueOf(level) + " "); + } + StringBuilder groupByClause = new StringBuilder("group by t.patient_num "); + if (rtnColumns.contains(TemporalQueryReturnColumns.INSTANCE)){ + selectClause.append(", " + primaryTableAlias + "encounter_num, " + + primaryTableAlias + "provider_id, " + + primaryTableAlias + "start_date, " + + primaryTableAlias + "concept_cd, " + + primaryTableAlias + "instance_num"); + groupByClause.append(", " + primaryTableAlias + "encounter_num, " + + primaryTableAlias + "provider_id, " + + primaryTableAlias + "start_date, " + + primaryTableAlias + "concept_cd, " + + primaryTableAlias + "instance_num"); + } + else if (rtnColumns.contains(TemporalQueryReturnColumns.ENCOUNTER)){ + selectClause.append(", " + primaryTableAlias + "encounter_num"); + groupByClause.append(", " + primaryTableAlias + "encounter_num"); + } + + TemporalQueryReturnColumns startDateRtn = getStartDateReturnType(); + if (startDateRtn!=null){ + if (startDateRtn==TemporalQueryReturnColumns.FIRST_START_DATE){ + selectClause.append(", min(" + primaryTableAlias + "start_date) temporal_start_date "); + aggregate = true; + } + else if (startDateRtn==TemporalQueryReturnColumns.LAST_START_DATE){ + selectClause.append(", max(" + primaryTableAlias + "start_date) temporal_start_date "); + aggregate = true; + } + else if (startDateRtn==TemporalQueryReturnColumns.START_DATE){ + selectClause.append(", " + primaryTableAlias + "start_date temporal_start_date "); + groupByClause.append(", " + primaryTableAlias + "start_date"); + } + else if (startDateRtn==TemporalQueryReturnColumns.FIRST_ENCOUNTER_START_DATE){ + selectClause.append(", min(" + primaryTableAlias + "start_date) temporal_start_date "); + aggregate = true; + } + else if (startDateRtn==TemporalQueryReturnColumns.LAST_ENCOUNTER_START_DATE){ + selectClause.append(", max(" + primaryTableAlias + "start_date) temporal_start_date "); + aggregate = true; + } + else if (startDateRtn==TemporalQueryReturnColumns.ENCOUNTER_START_DATE){ + selectClause.append(", " + primaryTableAlias + "start_date temporal_start_date "); + groupByClause.append(", " + primaryTableAlias + "start_date"); + } + } + + TemporalQueryReturnColumns endDateRtn = getEndDateReturnType(); + if (endDateRtn!=null){ + if (endDateRtn==TemporalQueryReturnColumns.FIRST_END_DATE){ + selectClause.append(", min(" + primaryTableAlias + "end_date) temporal_end_date "); + aggregate = true; + } + else if (endDateRtn==TemporalQueryReturnColumns.LAST_END_DATE){ + selectClause.append(", max(" + primaryTableAlias + "end_date) temporal_end_date "); + aggregate = true; + } + else if (endDateRtn==TemporalQueryReturnColumns.END_DATE){ + selectClause.append(", " + primaryTableAlias + "end_date temporal_end_date "); + groupByClause.append(", " + primaryTableAlias + "end_date"); + } + else if (endDateRtn==TemporalQueryReturnColumns.FIRST_ENCOUNTER_END_DATE){ + selectClause.append(", min(" + primaryTableAlias + "end_date) temporal_end_date "); + aggregate = true; + } + else if (endDateRtn==TemporalQueryReturnColumns.LAST_ENCOUNTER_END_DATE){ + selectClause.append(", max(" + primaryTableAlias + "end_date) temporal_end_date "); + aggregate = true; + } + else if (endDateRtn==TemporalQueryReturnColumns.ENCOUNTER_END_DATE){ + selectClause.append(", " + primaryTableAlias + "end_date temporal_end_date "); + groupByClause.append(", " + primaryTableAlias + "end_date"); + } + } + + String intoClause = ""; + if (useSqlServerTempTables()){ + intoClause = " into #m" + getSubQueryId() + " "; + } + + String indexClause = ""; + if (useSqlServerTempTables()){ + indexClause = "CREATE NONCLUSTERED INDEX m" + getSubQueryId() + "_idx on #m" + getSubQueryId() + " (patient_num, " + + (startDateRtn!=null ? "temporal_start_date, " : "") + + (endDateRtn!=null ? "temporal_end_date, " : "") + + "level_no)"; + } + + masterSql.append(insertClause.toString()); + masterSql.append(selectClause.toString()); + masterSql.append(intoClause); + masterSql.append(fromClause.toString()); + masterSql.append(whereClause.toString()); + if (aggregate) + masterSql.append(groupByClause.toString()); + + if (indexClause.trim().length()>0){ + masterSql.append(getSqlDelimiter()); + masterSql.append(indexClause); + } + + return masterSql.toString(); + } + + private boolean useSqlServerTempTables(){ + return parent.useSqlServerTempTables(); + } + + protected String getDeleteTempTableSql() { + String tempTableName = parent.getTempTableName(); + + if (parent.getServerType().equals(DAOFactoryHelper.SQLSERVER)) + return "truncate table "+ tempTableName; + else + return "delete "+ + (parent.getServerType().equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)? " from " : "") + tempTableName; + } + + protected String getDeleteDxTempTableSql() { + String tempTableName = parent.getDxTempTableName(); + + if (parent.getServerType().equals(DAOFactoryHelper.SQLSERVER)) + return "truncate table "+ tempTableName; + else + return "delete "+ + (parent.getServerType().equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)? " from " : "") + tempTableName; + } + + protected String getDeleteTempMasterSql(String masterId, int level) { + String masterTableName = parent.getMasterTempTableName(); + + if (useSqlServerTempTables()){ + return "if (object_id(#m" + masterId + ") is not null) drop table #m" + masterId + "\n" + + " else delete " + masterTableName + " " + + "where master_id = '" + masterId + "' " + + "and level_no >= " + String.valueOf(level); + } + else + return "delete " + + (parent.getServerType().equalsIgnoreCase(DAOFactoryHelper.POSTGRESQL)? " from " : "") + + masterTableName + " " + + "where master_id = '" + masterId + "' " + + "and level_no >= " + String.valueOf(level); + } + + public List getPanelList() { + return panelList; + } + + public int getPanelCount(){ + return this.panelList.size(); + } + + public boolean allAreInverted(){ + return this.invertedPanelCount == this.panelList.size(); + } + + public int getInvertedPanelCount(){ + return this.invertedPanelCount; + } + + public int getNonInvertedPanelCount(){ + return this.panelList.size() - this.invertedPanelCount; + } + + protected SecurityType getSecurityType() { + return parent.getSecurityType(); + } + + protected SecurityType getRequestorSecurityType() { + return parent.getRequestorSecurityType(); + } + + protected String getProjectId() { + return parent.getProjectId(); + } + + protected DataSourceLookup getDataSourceLookup(){ + return parent.getDataSourceLookup(); + } + + protected String getDatabaseSchema(){ + return parent.getDatabaseSchema(); + } + + protected String getParentQueryTiming(){ + return parent.getQueryTiming(); + } + + protected String getQueryTiming(){ + String timing = subQuery.getQueryTiming(); + if (timing==null||timing.trim().length()==0) + timing = parent.getQueryTiming(); + if (timing==null||timing.trim().length()==0) + timing = QueryTimingHandler.ANY; + return timing; + } + + protected String getServerType(){ + return parent.getServerType(); + } + + protected Map getProjectParameterMap(){ + return parent.getProjectParameterMap(); + } + + protected QueryTimingHandler getTimingHandler(){ + return parent.getTimingHandler(); + } + + protected int getPanelIndex(TemporalPanel panel){ + if (panel==null||panelList==null) + return -1; + else + return this.panelList.indexOf(panel); + } + + protected String getTempTableName(){ + return parent.getTempTableName(); + } + + protected boolean allowLargeTextValueConstrainFlag(){ + return parent.allowLargeTextValueConstrainFlag(); + } + + protected List getUserRoles() { + return parent.getUserRoles(); + } + + protected boolean hasInvertedPanel(){ + return invertedPanelCount>0; + } + + private String buildSubQueryId(String eventId){ + if (eventId==null) + return null; + else{ + int index = parent.getSubQueryIndex(eventId); + return parent.getQueryId() + "_S" + String.valueOf(index); + } + } + + protected String getSubQueryId(){ + if (this.subQueryId==null) + subQueryId = buildSubQueryId(getQueryId()); + return subQueryId; + } + + protected String getQueryId(){ + if (subQuery==null) + return null; + else + return subQuery.getQueryId(); + } + + protected String buildTempTableCheckDrop(String tempTableName) { + return parent.buildTempTableCheckDrop(tempTableName); + } + + protected boolean returnEncounterNum(){ + if (this.getQueryTiming().equalsIgnoreCase(QueryTimingHandler.SAMEVISIT)|| + this.getQueryTiming().equalsIgnoreCase(QueryTimingHandler.SAME)) + return true; + else + return false; + } + + protected boolean returnInstanceNum(){ + if (this.getQueryTiming().equalsIgnoreCase(QueryTimingHandler.SAMEINSTANCENUM)) + return true; + else + return false; + } + + protected boolean returnEncounterStartDate(){ + if (rtnColumns.contains(TemporalQueryReturnColumns.ENCOUNTER_START_DATE) || + rtnColumns.contains(TemporalQueryReturnColumns.FIRST_ENCOUNTER_START_DATE) || + rtnColumns.contains(TemporalQueryReturnColumns.LAST_ENCOUNTER_START_DATE)) + return true; + else + return false; + } + + protected boolean returnEncounterEndDate(){ + if (rtnColumns.contains(TemporalQueryReturnColumns.ENCOUNTER_END_DATE) || + rtnColumns.contains(TemporalQueryReturnColumns.FIRST_ENCOUNTER_END_DATE) || + rtnColumns.contains(TemporalQueryReturnColumns.LAST_ENCOUNTER_END_DATE)) + return true; + else + return false; + } + + protected boolean returnInstanceStartDate(){ + if (rtnColumns.contains(TemporalQueryReturnColumns.START_DATE) || + rtnColumns.contains(TemporalQueryReturnColumns.FIRST_START_DATE) || + rtnColumns.contains(TemporalQueryReturnColumns.LAST_START_DATE)) + return true; + else + return false; + } + + protected boolean returnInstanceEndDate(){ + if (rtnColumns.contains(TemporalQueryReturnColumns.END_DATE) || + rtnColumns.contains(TemporalQueryReturnColumns.FIRST_END_DATE) || + rtnColumns.contains(TemporalQueryReturnColumns.LAST_END_DATE)) + return true; + else + return false; + } + + protected int getProcessingLevel(){ + return parent.getProcessingLevel(); + } + + public String getSqlDelimiter() { + return parent.getSqlDelimiter(); + } + + protected int getEndPanelIndex() { + if (endPanelIndex==-1){ + int nonInvertedPanels = getPanelCount() - getInvertedPanelCount(); + if (!this.isFirstSubQuery()&&(parent.getQueryOptions().getTemporalConstraintStrategy()==TemporalConstraintStrategy.TEMP_TABLE_UPDATE)) + nonInvertedPanels++; + endPanelIndex = this.startPanelIndex + (nonInvertedPanels>0?nonInvertedPanels-1:0); + } + return endPanelIndex; + } + + + private List getConstraintsForSubQuery(TemporalSubQuery subQuery){ + if (subQuery!=null){ + String eventId = subQuery.getQueryId(); + if (this.constraints!=null){ + return constraints.get(eventId); + } + } + return null; + } + + protected TemporalQueryOptions getQueryOptions() { + return parent.getQueryOptions(); + } + + public void addIgnoredMessage(String errorMessage) { + parent.addIgnoredMessage(errorMessage); + } + + protected void addPreProcessingSql(String sql){ + if (sql!=null&&sql.trim().length()>0) + this.preProcessingSql.add(sql); + } + + protected void addPostProcessingSql(String sql){ + if (sql!=null&&sql.trim().length()>0) + this.postProcessingSql.add(sql); + } + + protected QueryDefinitionType searchForQueryInRequestDefinition(String subQueryId){ + return parent.searchForSubQuery(subQueryId); + } + + + public boolean occursTogether(TemporalSubQuery subQuery){ + String eventId = subQuery.getQueryId(); + List constraintList = getConstraintsForSubQuery(subQuery); + if (constraintList!=null){ + for(QueryConstraintType constraint : constraintList){ + if (((constraint.getFirstQuery().getQueryId()!=null&constraint.getFirstQuery().getQueryId().equalsIgnoreCase(eventId))|| + (constraint.getSecondQuery().getQueryId()!=null&constraint.getSecondQuery().getQueryId().equalsIgnoreCase(eventId)))&& + (constraint.getOperator().equals(QueryOperatorType.EQUAL)||constraint.getOperator().equals(QueryOperatorType.GREATEREQUAL)||constraint.getOperator().equals(QueryOperatorType.LESSEQUAL))){ + return true; + } + } + } + return false; + } + + public boolean occursAfter(TemporalSubQuery subQuery){ + String eventId = subQuery.getQueryId(); + List constraintList = getConstraintsForSubQuery(subQuery); + if (constraintList!=null){ + for(QueryConstraintType constraint : constraintList){ + if ((constraint.getSecondQuery().getQueryId()!=null&&constraint.getSecondQuery().getQueryId().equalsIgnoreCase(eventId))&& + (constraint.getOperator().equals(QueryOperatorType.GREATER)||constraint.getOperator().equals(QueryOperatorType.GREATEREQUAL))){ + return true; + } + else if ((constraint.getFirstQuery().getQueryId()!=null&&constraint.getFirstQuery().getQueryId().equalsIgnoreCase(eventId))&& + (constraint.getOperator().equals(QueryOperatorType.LESS)||constraint.getOperator().equals(QueryOperatorType.LESSEQUAL))){ + return true; + } + } + + } + return false; + } + + public boolean occursBefore(TemporalSubQuery subQuery){ + String eventId = subQuery.getQueryId(); + List constraintList = getConstraintsForSubQuery(subQuery); + if (constraintList!=null){ + for(QueryConstraintType constraint : constraintList){ + if ((constraint.getSecondQuery().getQueryId()!=null&&constraint.getSecondQuery().getQueryId().equalsIgnoreCase(eventId))&& + (constraint.getOperator().equals(QueryOperatorType.LESS)||constraint.getOperator().equals(QueryOperatorType.LESSEQUAL))){ + return true; + } + else if ((constraint.getFirstQuery().getQueryId()!=null&&constraint.getFirstQuery().getQueryId().equalsIgnoreCase(eventId))&& + (constraint.getOperator().equals(QueryOperatorType.GREATER)||constraint.getOperator().equals(QueryOperatorType.GREATEREQUAL))){ + return true; + } + } + } + return false; + } + + @Override + public int compareTo(Object element) { + if (element.getClass().equals((TemporalSubQuery.class))) { + TemporalSubQuery tp2 = (TemporalSubQuery) element; + boolean before = occursBefore(tp2); + boolean after = occursAfter(tp2); + if (before&&!after) + return -1; + else if (after&&!before) + return 1; + else { + return this.panelList.get(0).compareTo(tp2.panelList.get(0)); + } + } else { + return this.toString().compareTo(element.toString()); + } + } + + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/temptable/TempTableDao.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/temptable/TempTableDao.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/temptable/TempTableDao.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/temptable/TempTableDao.java index 2c6a9375..85b30a3a --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/temptable/TempTableDao.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/temptable/TempTableDao.java @@ -1,42 +1,42 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.temptable; - -import java.sql.Connection; -import java.sql.SQLException; -import java.sql.Statement; - -public class TempTableDao { - - public void deleteTempTable(Connection conn, String tempTableName) - throws SQLException { - - Statement deleteStmt = null; - try { - deleteStmt = conn.createStatement(); - //conn.createStatement().executeUpdate("drop table " + tempTableName); - deleteStmt.executeUpdate("drop table " + tempTableName); - - } catch (SQLException sqle) { - throw sqle; - } finally { - try { - deleteStmt.close(); - } catch (SQLException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - } - - public void createTable() { - - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.temptable; + +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.Statement; + +public class TempTableDao { + + public void deleteTempTable(Connection conn, String tempTableName) + throws SQLException { + + Statement deleteStmt = null; + try { + deleteStmt = conn.createStatement(); + //conn.createStatement().executeUpdate("drop table " + tempTableName); + deleteStmt.executeUpdate("drop table " + tempTableName); + + } catch (SQLException sqle) { + throw sqle; + } finally { + try { + deleteStmt.close(); + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + } + + public void createTable() { + + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/xml/CommentsDeterminingExclusion.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/xml/CommentsDeterminingExclusion.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/xml/CommentsDeterminingExclusion.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/xml/CommentsDeterminingExclusion.java index 62d6a471..c846b5cf --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/xml/CommentsDeterminingExclusion.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/xml/CommentsDeterminingExclusion.java @@ -1,33 +1,33 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ - -package edu.harvard.i2b2.crc.dao.xml; - - -public class CommentsDeterminingExclusion -{ -private String Com = ""; - -public String getCom () -{ -return Com; -} - -public void setCom (String Com) -{ -this.Com = Com; -} - -@Override -public String toString() -{ -return "ClassPojo [Com = "+Com+"]"; -} -} - +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ + +package edu.harvard.i2b2.crc.dao.xml; + + +public class CommentsDeterminingExclusion +{ +private String Com = ""; + +public String getCom () +{ +return Com; +} + +public void setCom (String Com) +{ +this.Com = Com; +} + +@Override +public String toString() +{ +return "ClassPojo [Com = "+Com+"]"; +} +} + diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/xml/ExportXml.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/xml/ExportXml.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/xml/ExportXml.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/xml/ExportXml.java index cd51dbac..6258951a --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/xml/ExportXml.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/xml/ExportXml.java @@ -1,32 +1,32 @@ -package edu.harvard.i2b2.crc.dao.xml; -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ - - - -public class ExportXml -{ - private ValueExport ValueExport; - - public ValueExport getValueExport () - { - return ValueExport; - } - - public void setValueExport (ValueExport ValueExport) - { - this.ValueExport = ValueExport; - } - - @Override - public String toString() - { - return "ClassPojo [ValueExport = "+ValueExport+"]"; - } +package edu.harvard.i2b2.crc.dao.xml; +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ + + + +public class ExportXml +{ + private ValueExport ValueExport; + + public ValueExport getValueExport () + { + return ValueExport; + } + + public void setValueExport (ValueExport ValueExport) + { + this.ValueExport = ValueExport; + } + + @Override + public String toString() + { + return "ClassPojo [ValueExport = "+ValueExport+"]"; + } } \ No newline at end of file diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/xml/File.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/xml/File.java similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/xml/File.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/xml/File.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/xml/Item_orig.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/xml/Item_orig.java old mode 100755 new mode 100644 similarity index 95% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/xml/Item_orig.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/xml/Item_orig.java index 8c5a1d8b..f858b145 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/xml/Item_orig.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/xml/Item_orig.java @@ -1,88 +1,88 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ - -package edu.harvard.i2b2.crc.dao.xml; - -import jakarta.xml.bind.annotation.XmlAccessType; -import jakarta.xml.bind.annotation.XmlAccessorType; -import jakarta.xml.bind.annotation.XmlAttribute; -import jakarta.xml.bind.annotation.XmlType; -import jakarta.xml.bind.annotation.XmlValue; - -@XmlAccessorType(XmlAccessType.FIELD) -/*@XmlType(name = "Val", propOrder = { - "value" -}) -*/ -public class Item_orig -{ - - @XmlValue - private String filename = ""; - - @XmlValue - private String query = ""; - - @XmlValue - private String resultOutput = ""; - - @XmlValue - private String separatorCharacter = ""; - - - public String getFilename() { - return filename; - } - - - public void setFilename(String filename) { - this.filename = filename; - } - - - public String getQuery() { - return query; - } - - - public void setQuery(String query) { - this.query = query; - } - - - public String getResultOutput() { - return resultOutput; - } - - - public void setResultOutput(String resultOutput) { - this.resultOutput = resultOutput; - } - - - public String getSeparatorCharacter() { - return separatorCharacter; - } - - - public void setSeparatorCharacter(String separatorCharacter) { - this.separatorCharacter = separatorCharacter; - } - - - @Override - public String toString() - { - return "ClassPojo [query = "+query+", content = "+filename+"]"; - } - - -} - +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ + +package edu.harvard.i2b2.crc.dao.xml; + +import jakarta.xml.bind.annotation.XmlAccessType; +import jakarta.xml.bind.annotation.XmlAccessorType; +import jakarta.xml.bind.annotation.XmlAttribute; +import jakarta.xml.bind.annotation.XmlType; +import jakarta.xml.bind.annotation.XmlValue; + +@XmlAccessorType(XmlAccessType.FIELD) +/*@XmlType(name = "Val", propOrder = { + "value" +}) +*/ +public class Item_orig +{ + + @XmlValue + private String filename = ""; + + @XmlValue + private String query = ""; + + @XmlValue + private String resultOutput = ""; + + @XmlValue + private String separatorCharacter = ""; + + + public String getFilename() { + return filename; + } + + + public void setFilename(String filename) { + this.filename = filename; + } + + + public String getQuery() { + return query; + } + + + public void setQuery(String query) { + this.query = query; + } + + + public String getResultOutput() { + return resultOutput; + } + + + public void setResultOutput(String resultOutput) { + this.resultOutput = resultOutput; + } + + + public String getSeparatorCharacter() { + return separatorCharacter; + } + + + public void setSeparatorCharacter(String separatorCharacter) { + this.separatorCharacter = separatorCharacter; + } + + + @Override + public String toString() + { + return "ClassPojo [query = "+query+", content = "+filename+"]"; + } + + +} + \ No newline at end of file diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/xml/Items.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/xml/Items.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/xml/Items.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/xml/Items.java index 50cc59bc..a9d2353d --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/xml/Items.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/xml/Items.java @@ -1,34 +1,34 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ - -package edu.harvard.i2b2.crc.dao.xml; - -import jakarta.xml.bind.annotation.XmlElement; - -public class Items -{ - @XmlElement(name = "Item") - private Item_orig[] Item; - - public Item_orig[] getItem () - { - return Item; - } - - public void setItem (Item_orig[] Item) - { - this.Item = Item; - } - - @Override - public String toString() - { - return "ClassPojo [Item = "+Item+"]"; - } +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ + +package edu.harvard.i2b2.crc.dao.xml; + +import jakarta.xml.bind.annotation.XmlElement; + +public class Items +{ + @XmlElement(name = "Item") + private Item_orig[] Item; + + public Item_orig[] getItem () + { + return Item; + } + + public void setItem (Item_orig[] Item) + { + this.Item = Item; + } + + @Override + public String toString() + { + return "ClassPojo [Item = "+Item+"]"; + } } \ No newline at end of file diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/xml/ValueExport.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/xml/ValueExport.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/xml/ValueExport.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/xml/ValueExport.java index e2aa3bc8..323e9024 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/xml/ValueExport.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/xml/ValueExport.java @@ -1,146 +1,146 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ - -package edu.harvard.i2b2.crc.dao.xml; - -import jakarta.xml.bind.annotation.XmlAccessType; -import jakarta.xml.bind.annotation.XmlAccessorType; -import jakarta.xml.bind.annotation.XmlElement; -import jakarta.xml.bind.annotation.XmlRootElement; -import jakarta.xml.bind.annotation.XmlType; - -import edu.harvard.i2b2.crc.dao.redcap.xml.EnumValues; - -/* - * - - 3.02 - 08/09/2024 12:00:00 - /tmp/finalfile.zip - AES - test123 - - /tmp/tst.csv - select * from obser aiont)fact a, {{{DX}}} b where a.patient_num = b.patient_num - DEMOGRAPHIOCS_CSV - \t - - - /tmp/second.csv - select * from cat - OTHER_DATA_CSV - \t - - - */ - - -@XmlRootElement (name = "ValueExporter") -@XmlAccessorType(XmlAccessType.FIELD) -public class ValueExport -{ - public String getZipFilename() { - return zipFilename; - } - - public void setZipFilename(String zipFilename) { - this.zipFilename = zipFilename; - } - - public String getZipEncryptMethod() { - return zipEncryptMethod; - } - - public void setZipEncryptMethod(String zipEncryptMethod) { - this.zipEncryptMethod = zipEncryptMethod; - } - - public String getZipPassword() { - return zipPassword; - } - - public void setZipPassword(String zipPassword) { - this.zipPassword = zipPassword; - } - - public Items getItems() { - return Items; - } - - public void setItems(Items items) { - Items = items; - } - - - private CommentsDeterminingExclusion CommentsDeterminingExclusion; - - @XmlElement(name = "zipFilename") - private String zipFilename; - - @XmlElement(name = "zipEncryptMethod") - private String zipEncryptMethod; - - @XmlElement(name = "zipPassword") - private String zipPassword; - - @XmlElement(name = "CreationDateTime") - private String CreationDateTime; - - @XmlElement(name = "Version") - private String version; - - // @XmlElement(name = "Analysis") - // private Analysis Analysis; - - - public CommentsDeterminingExclusion getCommentsDeterminingExclusion () - { - return CommentsDeterminingExclusion; - } - - public void setCommentsDeterminingExclusion (CommentsDeterminingExclusion CommentsDeterminingExclusion) - { - this.CommentsDeterminingExclusion = CommentsDeterminingExclusion; - } - - - public String getCreationDateTime () - { - return CreationDateTime; - } - - public void setCreationDateTime (String CreationDateTime) - { - this.CreationDateTime = CreationDateTime; - } - - public String getVersion () - { - return version; - } - - public void setVersion (String Version) - { - this.version = Version; - } - - - @XmlElement(name = "Items") - private Items Items; - - - @Override - public String toString() - { - return ""; - //ClassPojo [CommentsDeterminingExclusion = "+CommentsDeterminingExclusion+", TestName = "+TestName+", LowofHighValue = "+LowofHighValue+", Oktousevalues = "+Oktousevalues+", UnitValues = "+UnitValues+", HighofToxicValue = "+HighofToxicValue+", HighofHighValue = "+HighofHighValue+", EnumValues = "+EnumValues+", LowofToxicValue = "+LowofToxicValue+", TestID = "+TestID+", MaxStringLength = "+MaxStringLength+", HighofLowValue = "+HighofLowValue+", CreationDateTime = "+CreationDateTime+", Version = "+version+", Analysis = "+Analysis+", LowofLowValue = "+LowofLowValue+", Loinc = "+Loinc+", DataType = "+DataType+", CodeType = "+CodeType+", Flagstouse = "+Flagstouse+"]"; - } -} - +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ + +package edu.harvard.i2b2.crc.dao.xml; + +import jakarta.xml.bind.annotation.XmlAccessType; +import jakarta.xml.bind.annotation.XmlAccessorType; +import jakarta.xml.bind.annotation.XmlElement; +import jakarta.xml.bind.annotation.XmlRootElement; +import jakarta.xml.bind.annotation.XmlType; + +import edu.harvard.i2b2.crc.dao.redcap.xml.EnumValues; + +/* + * + + 3.02 + 08/09/2024 12:00:00 + /tmp/finalfile.zip + AES + test123 + + /tmp/tst.csv + select * from obser aiont)fact a, {{{DX}}} b where a.patient_num = b.patient_num + DEMOGRAPHIOCS_CSV + \t + + + /tmp/second.csv + select * from cat + OTHER_DATA_CSV + \t + + + */ + + +@XmlRootElement (name = "ValueExporter") +@XmlAccessorType(XmlAccessType.FIELD) +public class ValueExport +{ + public String getZipFilename() { + return zipFilename; + } + + public void setZipFilename(String zipFilename) { + this.zipFilename = zipFilename; + } + + public String getZipEncryptMethod() { + return zipEncryptMethod; + } + + public void setZipEncryptMethod(String zipEncryptMethod) { + this.zipEncryptMethod = zipEncryptMethod; + } + + public String getZipPassword() { + return zipPassword; + } + + public void setZipPassword(String zipPassword) { + this.zipPassword = zipPassword; + } + + public Items getItems() { + return Items; + } + + public void setItems(Items items) { + Items = items; + } + + + private CommentsDeterminingExclusion CommentsDeterminingExclusion; + + @XmlElement(name = "zipFilename") + private String zipFilename; + + @XmlElement(name = "zipEncryptMethod") + private String zipEncryptMethod; + + @XmlElement(name = "zipPassword") + private String zipPassword; + + @XmlElement(name = "CreationDateTime") + private String CreationDateTime; + + @XmlElement(name = "Version") + private String version; + + // @XmlElement(name = "Analysis") + // private Analysis Analysis; + + + public CommentsDeterminingExclusion getCommentsDeterminingExclusion () + { + return CommentsDeterminingExclusion; + } + + public void setCommentsDeterminingExclusion (CommentsDeterminingExclusion CommentsDeterminingExclusion) + { + this.CommentsDeterminingExclusion = CommentsDeterminingExclusion; + } + + + public String getCreationDateTime () + { + return CreationDateTime; + } + + public void setCreationDateTime (String CreationDateTime) + { + this.CreationDateTime = CreationDateTime; + } + + public String getVersion () + { + return version; + } + + public void setVersion (String Version) + { + this.version = Version; + } + + + @XmlElement(name = "Items") + private Items Items; + + + @Override + public String toString() + { + return ""; + //ClassPojo [CommentsDeterminingExclusion = "+CommentsDeterminingExclusion+", TestName = "+TestName+", LowofHighValue = "+LowofHighValue+", Oktousevalues = "+Oktousevalues+", UnitValues = "+UnitValues+", HighofToxicValue = "+HighofToxicValue+", HighofHighValue = "+HighofHighValue+", EnumValues = "+EnumValues+", LowofToxicValue = "+LowofToxicValue+", TestID = "+TestID+", MaxStringLength = "+MaxStringLength+", HighofLowValue = "+HighofLowValue+", CreationDateTime = "+CreationDateTime+", Version = "+version+", Analysis = "+Analysis+", LowofLowValue = "+LowofLowValue+", Loinc = "+Loinc+", DataType = "+DataType+", CodeType = "+CodeType+", Flagstouse = "+Flagstouse+"]"; + } +} + \ No newline at end of file diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/xml/ValueExporter.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/xml/ValueExporter.java similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/dao/xml/ValueExporter.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/dao/xml/ValueExporter.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/CRCJAXBUtil.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/CRCJAXBUtil.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/CRCJAXBUtil.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/CRCJAXBUtil.java index 0a524dae..22a967a4 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/CRCJAXBUtil.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/CRCJAXBUtil.java @@ -1,63 +1,63 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.datavo; - -import java.util.List; - -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - -/** - * Factory class to create jaxb context Since jaxb context is tread safe, only - * one instance is created for this cell. The package used for jaxb context is - * read from spring config file $Id: CRCJAXBUtil.java,v 1.6 2007/09/11 20:05:40 - * rk903 Exp $ - * - * @author rkuttan - */ -public class CRCJAXBUtil { - private static JAXBUtil jaxbUtil = null; - private static JAXBUtil queryDefjaxbUtil = null; - private static JAXBUtil analysisDefjaxbUtil = null; - - //private CRCJAXBUtil() { - //} - - //@SuppressWarnings("unchecked") - public static JAXBUtil getJAXBUtil() { - if (jaxbUtil == null) { - jaxbUtil = new edu.harvard.i2b2.common.util.jaxb.JAXBUtil(edu.harvard.i2b2.crc.util.JAXBConstant.DEFAULT_PACKAGE_NAME); - } - return jaxbUtil; - } - - //@SuppressWarnings("unchecked") - public static JAXBUtil getQueryDefJAXBUtil() { - if (queryDefjaxbUtil == null) { - queryDefjaxbUtil = new JAXBUtil( - edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionType.class); - } - return queryDefjaxbUtil; - } - - //@SuppressWarnings("unchecked") - public static JAXBUtil getAnalysisDefJAXBUtil() { - if (analysisDefjaxbUtil == null) { - analysisDefjaxbUtil = new JAXBUtil( - edu.harvard.i2b2.crc.datavo.setfinder.query.AnalysisDefinitionRequestType.class); - } - return analysisDefjaxbUtil; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.datavo; + +import java.util.List; + +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + +/** + * Factory class to create jaxb context Since jaxb context is tread safe, only + * one instance is created for this cell. The package used for jaxb context is + * read from spring config file $Id: CRCJAXBUtil.java,v 1.6 2007/09/11 20:05:40 + * rk903 Exp $ + * + * @author rkuttan + */ +public class CRCJAXBUtil { + private static JAXBUtil jaxbUtil = null; + private static JAXBUtil queryDefjaxbUtil = null; + private static JAXBUtil analysisDefjaxbUtil = null; + + //private CRCJAXBUtil() { + //} + + //@SuppressWarnings("unchecked") + public static JAXBUtil getJAXBUtil() { + if (jaxbUtil == null) { + jaxbUtil = new edu.harvard.i2b2.common.util.jaxb.JAXBUtil(edu.harvard.i2b2.crc.util.JAXBConstant.DEFAULT_PACKAGE_NAME); + } + return jaxbUtil; + } + + //@SuppressWarnings("unchecked") + public static JAXBUtil getQueryDefJAXBUtil() { + if (queryDefjaxbUtil == null) { + queryDefjaxbUtil = new JAXBUtil( + edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionType.class); + } + return queryDefjaxbUtil; + } + + //@SuppressWarnings("unchecked") + public static JAXBUtil getAnalysisDefJAXBUtil() { + if (analysisDefjaxbUtil == null) { + analysisDefjaxbUtil = new JAXBUtil( + edu.harvard.i2b2.crc.datavo.setfinder.query.AnalysisDefinitionRequestType.class); + } + return analysisDefjaxbUtil; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/I2B2MessageResponseFactory.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/I2B2MessageResponseFactory.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/I2B2MessageResponseFactory.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/I2B2MessageResponseFactory.java index 0cd5fb42..4a4f0ed4 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/I2B2MessageResponseFactory.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/I2B2MessageResponseFactory.java @@ -1,177 +1,177 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.datavo; - -import java.io.StringWriter; -import java.math.BigDecimal; - -import jakarta.xml.bind.JAXBElement; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.datavo.i2b2message.ApplicationType; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2message.FacilityType; -import edu.harvard.i2b2.crc.datavo.i2b2message.InfoType; -import edu.harvard.i2b2.crc.datavo.i2b2message.MessageControlIdType; -import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.PollingUrlType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResultStatusType; -import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - -public class I2B2MessageResponseFactory { - - /** log * */ - protected final static Log log = LogFactory - .getLog(I2B2MessageResponseFactory.class); - - /** - * Function to build response message type using given bodytype and request - * xml - * - * @param requestXml - * @param bodyType - * @return i2b2 response message xml - * @throws JAXBUtilException - */ - public static String buildResponseMessage(String requestXml, - StatusType statusType, BodyType bodyType, boolean splCharFilterFlag) - throws JAXBUtilException { - JAXBUtil util = CRCJAXBUtil.getJAXBUtil(); - - - MessageHeaderType messageHeader = QueryProcessorUtil.getInstance().getMessageHeader(); - ApplicationType appType = messageHeader.getSendingApplication(); - if (requestXml != null) { - RequestMessageType requestMsgType = getI2B2RequestMessageType(requestXml); - MessageHeaderType clientMessageHeader = requestMsgType.getMessageHeader(); - // reverse sending and receiving app - if (clientMessageHeader != null) { - ApplicationType sendingApp = clientMessageHeader - .getSendingApplication(); - messageHeader.setSendingApplication(appType); - messageHeader.setReceivingApplication(sendingApp); - messageHeader.setProjectId(clientMessageHeader.getProjectId()); - } - } else { - messageHeader = new MessageHeaderType(); - messageHeader.setSendingApplication(appType); - } - - messageHeader.setI2B2VersionCompatible(new BigDecimal("1.1")); - messageHeader.setHl7VersionCompatible(new BigDecimal("2.4")); - - MessageControlIdType messageControlIdType = new MessageControlIdType(); - messageControlIdType.setInstanceNum(1); - messageHeader.setMessageControlId(messageControlIdType); - - FacilityType facility = new FacilityType(); - facility.setFacilityName("i2b2 Hive"); - messageHeader.setSendingFacility(facility); - messageHeader.setReceivingFacility(facility); - - // :TODO statusType.setValue(sessionId); - PollingUrlType pollingType = new PollingUrlType(); - pollingType.setIntervalMs(100); - - // :TODO value come from property file - // pollingType.setValue("http://localhost:8080/QueryProcessor/getResult"); - ResultStatusType resultStatusType = new ResultStatusType(); - resultStatusType.setStatus(statusType); - resultStatusType.setPollingUrl(pollingType); - - InfoType infoType = new InfoType(); - // :TODO value come from property file - // infoType.setUrl("http://localhost:8080/QueryProcessor/getStatus"); - infoType.setValue("Log information"); - - ResponseHeaderType responseHeader = new ResponseHeaderType(); - responseHeader.setResultStatus(resultStatusType); - responseHeader.setInfo(infoType); - - ResponseMessageType responseMessageType = new ResponseMessageType(); - responseMessageType.setMessageHeader(messageHeader); - responseMessageType.setResponseHeader(responseHeader); - responseMessageType.setMessageBody(bodyType); - - edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory(); - StringWriter strWriter = new StringWriter(); - util.marshallerWithCDATA(of.createResponse(responseMessageType), strWriter, - new String[]{"observation_blob","patient_blob","observer_blob","concept_blob","event_blob","message"}); - return strWriter.toString(); - } - - /** - * Function to build response message type using given bodytype and request - * xml - * - * @param requestXml - * @param bodyType - * @return i2b2 response message xml - * @throws JAXBUtilException - */ - public static String buildResponseMessage(String requestXml, - StatusType statusType, BodyType bodyType) throws JAXBUtilException { - return buildResponseMessage(requestXml, statusType, bodyType, false); - } - - /** - * Function to unmarshall i2b2 request message type - * - * @param requestXml - * @return RequestMessageType - * @throws JAXBUtilException - */ - private static RequestMessageType getI2B2RequestMessageType( - String requestXml) throws JAXBUtilException { - JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); - JAXBElement jaxbElement = jaxbUtil.unMashallFromString(requestXml); - RequestMessageType requestMessageType = (RequestMessageType) jaxbElement - .getValue(); - - return requestMessageType; - } - - /** - * Function marshall i2b2 response message type - * - * @param responseMessageType - * @return - */ - public static String getResponseString( - ResponseMessageType responseMessageType) { - StringWriter strWriter = new StringWriter(); - - try { - edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory(); - JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); - jaxbUtil.marshaller(of.createResponse(responseMessageType), - strWriter); - } catch (JAXBUtilException e) { - log.error("Error while generating response message" - + e.getMessage()); - } - - return strWriter.toString(); - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.datavo; + +import java.io.StringWriter; +import java.math.BigDecimal; + +import jakarta.xml.bind.JAXBElement; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.datavo.i2b2message.ApplicationType; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2message.FacilityType; +import edu.harvard.i2b2.crc.datavo.i2b2message.InfoType; +import edu.harvard.i2b2.crc.datavo.i2b2message.MessageControlIdType; +import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.PollingUrlType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResultStatusType; +import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + +public class I2B2MessageResponseFactory { + + /** log * */ + protected final static Log log = LogFactory + .getLog(I2B2MessageResponseFactory.class); + + /** + * Function to build response message type using given bodytype and request + * xml + * + * @param requestXml + * @param bodyType + * @return i2b2 response message xml + * @throws JAXBUtilException + */ + public static String buildResponseMessage(String requestXml, + StatusType statusType, BodyType bodyType, boolean splCharFilterFlag) + throws JAXBUtilException { + JAXBUtil util = CRCJAXBUtil.getJAXBUtil(); + + + MessageHeaderType messageHeader = QueryProcessorUtil.getInstance().getMessageHeader(); + ApplicationType appType = messageHeader.getSendingApplication(); + if (requestXml != null) { + RequestMessageType requestMsgType = getI2B2RequestMessageType(requestXml); + MessageHeaderType clientMessageHeader = requestMsgType.getMessageHeader(); + // reverse sending and receiving app + if (clientMessageHeader != null) { + ApplicationType sendingApp = clientMessageHeader + .getSendingApplication(); + messageHeader.setSendingApplication(appType); + messageHeader.setReceivingApplication(sendingApp); + messageHeader.setProjectId(clientMessageHeader.getProjectId()); + } + } else { + messageHeader = new MessageHeaderType(); + messageHeader.setSendingApplication(appType); + } + + messageHeader.setI2B2VersionCompatible(new BigDecimal("1.1")); + messageHeader.setHl7VersionCompatible(new BigDecimal("2.4")); + + MessageControlIdType messageControlIdType = new MessageControlIdType(); + messageControlIdType.setInstanceNum(1); + messageHeader.setMessageControlId(messageControlIdType); + + FacilityType facility = new FacilityType(); + facility.setFacilityName("i2b2 Hive"); + messageHeader.setSendingFacility(facility); + messageHeader.setReceivingFacility(facility); + + // :TODO statusType.setValue(sessionId); + PollingUrlType pollingType = new PollingUrlType(); + pollingType.setIntervalMs(100); + + // :TODO value come from property file + // pollingType.setValue("http://localhost:8080/QueryProcessor/getResult"); + ResultStatusType resultStatusType = new ResultStatusType(); + resultStatusType.setStatus(statusType); + resultStatusType.setPollingUrl(pollingType); + + InfoType infoType = new InfoType(); + // :TODO value come from property file + // infoType.setUrl("http://localhost:8080/QueryProcessor/getStatus"); + infoType.setValue("Log information"); + + ResponseHeaderType responseHeader = new ResponseHeaderType(); + responseHeader.setResultStatus(resultStatusType); + responseHeader.setInfo(infoType); + + ResponseMessageType responseMessageType = new ResponseMessageType(); + responseMessageType.setMessageHeader(messageHeader); + responseMessageType.setResponseHeader(responseHeader); + responseMessageType.setMessageBody(bodyType); + + edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory(); + StringWriter strWriter = new StringWriter(); + util.marshallerWithCDATA(of.createResponse(responseMessageType), strWriter, + new String[]{"observation_blob","patient_blob","observer_blob","concept_blob","event_blob","message"}); + return strWriter.toString(); + } + + /** + * Function to build response message type using given bodytype and request + * xml + * + * @param requestXml + * @param bodyType + * @return i2b2 response message xml + * @throws JAXBUtilException + */ + public static String buildResponseMessage(String requestXml, + StatusType statusType, BodyType bodyType) throws JAXBUtilException { + return buildResponseMessage(requestXml, statusType, bodyType, false); + } + + /** + * Function to unmarshall i2b2 request message type + * + * @param requestXml + * @return RequestMessageType + * @throws JAXBUtilException + */ + private static RequestMessageType getI2B2RequestMessageType( + String requestXml) throws JAXBUtilException { + JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); + JAXBElement jaxbElement = jaxbUtil.unMashallFromString(requestXml); + RequestMessageType requestMessageType = (RequestMessageType) jaxbElement + .getValue(); + + return requestMessageType; + } + + /** + * Function marshall i2b2 response message type + * + * @param responseMessageType + * @return + */ + public static String getResponseString( + ResponseMessageType responseMessageType) { + StringWriter strWriter = new StringWriter(); + + try { + edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory(); + JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); + jaxbUtil.marshaller(of.createResponse(responseMessageType), + strWriter); + } catch (JAXBUtilException e) { + log.error("Error while generating response message" + + e.getMessage()); + } + + return strWriter.toString(); + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/PSMFactory.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/PSMFactory.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/PSMFactory.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/PSMFactory.java index 24512521..d4c38be0 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/PSMFactory.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/PSMFactory.java @@ -1,183 +1,183 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.datavo; - -import edu.harvard.i2b2.common.util.jaxb.DTOFactory; -import edu.harvard.i2b2.crc.datavo.db.QtQueryInstance; -import edu.harvard.i2b2.crc.datavo.db.QtQueryMaster; -import edu.harvard.i2b2.crc.datavo.db.QtQueryResultInstance; -import edu.harvard.i2b2.crc.datavo.db.QtQueryResultType; -import edu.harvard.i2b2.crc.datavo.db.QtQueryStatusType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryInstanceType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryMasterType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryResultInstanceType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryResultTypeType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryStatusTypeType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.RequestXmlType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.XmlValueType; - -/** - * Class to convert database domain objects to response message objects - * - * @author rkuttan - */ -public class PSMFactory { - private static DTOFactory dtoFactory = new DTOFactory(); - - /** - * Returns QueryMasterType for the given QtQueryMaster - * - * @param queryMaster - * @return QueryMasterType - */ - public static QueryMasterType buildQueryMasterType(QtQueryMaster queryMaster) { - QueryMasterType queryMasterType = new QueryMasterType(); - - queryMasterType.setUserId(queryMaster.getUserId()); - queryMasterType.setQueryMasterId(queryMaster.getQueryMasterId()); - - RequestXmlType requestXmlType = new RequestXmlType(); - requestXmlType.getContent().add(queryMaster.getRequestXml()); - queryMasterType.setRequestXml(requestXmlType); - queryMasterType.setName(queryMaster.getName()); - queryMasterType.setGroupId(queryMaster.getGroupId()); - - DTOFactory dtoFactory = new DTOFactory(); - - if (queryMaster.getCreateDate() != null) { - queryMasterType.setCreateDate(dtoFactory - .getXMLGregorianCalendar(queryMaster.getCreateDate() - .getTime())); - } - - if (queryMaster.getDeleteDate() != null) { - queryMasterType.setDeleteDate(dtoFactory - .getXMLGregorianCalendar(queryMaster.getDeleteDate() - .getTime())); - } - - return queryMasterType; - } - - /** - * Returns QueryInstanceType for the given QtQueryInstance - * - * @param queryInstance - * @return QueryInstanceType - */ - public static QueryInstanceType buildQueryInstanceType( - QtQueryInstance queryInstance) { - QueryInstanceType queryInstanceType = new QueryInstanceType(); - queryInstanceType.setUserId(queryInstance.getUserId()); - queryInstanceType.setQueryMasterId(queryInstance.getQtQueryMaster() - .getQueryMasterId()); - queryInstanceType.setGroupId(queryInstance.getGroupId()); - queryInstanceType - .setQueryInstanceId(queryInstance.getQueryInstanceId()); - queryInstanceType.setBatchMode(queryInstance.getBatchMode()); - if (queryInstance.getStartDate() != null) { - queryInstanceType.setStartDate(dtoFactory - .getXMLGregorianCalendar(queryInstance.getStartDate() - .getTime())); - } - - if (queryInstance.getEndDate() != null) { - queryInstanceType.setEndDate(dtoFactory - .getXMLGregorianCalendar(queryInstance.getEndDate() - .getTime())); - } - - QueryStatusTypeType queryStatusType = new QueryStatusTypeType(); - queryStatusType.setDescription(queryInstance.getQtQueryStatusType() - .getDescription()); - queryStatusType.setName(queryInstance.getQtQueryStatusType().getName()); - queryStatusType.setStatusTypeId(String.valueOf(queryInstance - .getQtQueryStatusType().getStatusTypeId())); - queryInstanceType.setQueryStatusType(queryStatusType); - if (queryInstance.getMessage() != null) { - XmlValueType xmlValueType = new XmlValueType(); - xmlValueType.getContent().add(queryInstance.getMessage()); - queryInstanceType.setMessage(xmlValueType); - - } - - return queryInstanceType; - } - - /** - * Returns QueryInstanceType for the given QtQueryInstance - * - * @param queryInstance - * @return QueryInstanceType - */ - public static QueryResultInstanceType buildQueryResultInstanceType( - QtQueryResultInstance queryResultInstance) { - QueryResultInstanceType resultInstanceType = new QueryResultInstanceType(); - resultInstanceType.setResultInstanceId(queryResultInstance - .getResultInstanceId()); - resultInstanceType.setQueryInstanceId(queryResultInstance - .getQtQueryInstance().getQueryInstanceId()); - resultInstanceType.setDescription(queryResultInstance.getDescription()); - resultInstanceType - .setQueryResultType(buildQueryResultType(queryResultInstance - .getQtQueryResultType())); - resultInstanceType - .setQueryStatusType(buildQueryStatusType(queryResultInstance - .getQtQueryStatusType())); - resultInstanceType.setStartDate(dtoFactory - .getXMLGregorianCalendar(queryResultInstance.getStartDate() - .getTime())); - if (queryResultInstance.getEndDate() != null) { - resultInstanceType.setEndDate(dtoFactory - .getXMLGregorianCalendar(queryResultInstance.getEndDate() - .getTime())); - } - if (queryResultInstance.getSetSize() != null) { - resultInstanceType.setSetSize(queryResultInstance.getSetSize()); - } - resultInstanceType.setObfuscateMethod(queryResultInstance - .getObfuscateMethod()); - if (queryResultInstance.getMessage() != null) { - XmlValueType xmlValueType = new XmlValueType(); - xmlValueType.getContent().add(queryResultInstance.getMessage()); - resultInstanceType.setMessage(xmlValueType); - } - return resultInstanceType; - } - - public static QueryResultTypeType buildQueryResultType( - QtQueryResultType queryResult) { - QueryResultTypeType queryResultType = new QueryResultTypeType(); - queryResultType.setResultTypeId(String.valueOf(queryResult - .getResultTypeId())); - queryResultType.setName(queryResult.getName()); - queryResultType.setDescription(queryResult.getDescription()); - queryResultType.setDisplayType(queryResult.getDisplayType()); - queryResultType.setVisualAttributeType(queryResult - .getVisualAttributeType()); - queryResultType.setUserRoleCd(queryResult.getUserRoleCd()); - return queryResultType; - } - - public static QueryStatusTypeType buildQueryStatusType( - QtQueryStatusType queryStatus) { - QueryStatusTypeType queryStatusType = new QueryStatusTypeType(); - queryStatusType.setDescription(queryStatus.getDescription()); - queryStatusType.setName(queryStatus.getName()); - queryStatusType.setStatusTypeId(String.valueOf(queryStatus - .getStatusTypeId())); - return queryStatusType; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.datavo; + +import edu.harvard.i2b2.common.util.jaxb.DTOFactory; +import edu.harvard.i2b2.crc.datavo.db.QtQueryInstance; +import edu.harvard.i2b2.crc.datavo.db.QtQueryMaster; +import edu.harvard.i2b2.crc.datavo.db.QtQueryResultInstance; +import edu.harvard.i2b2.crc.datavo.db.QtQueryResultType; +import edu.harvard.i2b2.crc.datavo.db.QtQueryStatusType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryInstanceType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryMasterType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryResultInstanceType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryResultTypeType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryStatusTypeType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.RequestXmlType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.XmlValueType; + +/** + * Class to convert database domain objects to response message objects + * + * @author rkuttan + */ +public class PSMFactory { + private static DTOFactory dtoFactory = new DTOFactory(); + + /** + * Returns QueryMasterType for the given QtQueryMaster + * + * @param queryMaster + * @return QueryMasterType + */ + public static QueryMasterType buildQueryMasterType(QtQueryMaster queryMaster) { + QueryMasterType queryMasterType = new QueryMasterType(); + + queryMasterType.setUserId(queryMaster.getUserId()); + queryMasterType.setQueryMasterId(queryMaster.getQueryMasterId()); + + RequestXmlType requestXmlType = new RequestXmlType(); + requestXmlType.getContent().add(queryMaster.getRequestXml()); + queryMasterType.setRequestXml(requestXmlType); + queryMasterType.setName(queryMaster.getName()); + queryMasterType.setGroupId(queryMaster.getGroupId()); + + DTOFactory dtoFactory = new DTOFactory(); + + if (queryMaster.getCreateDate() != null) { + queryMasterType.setCreateDate(dtoFactory + .getXMLGregorianCalendar(queryMaster.getCreateDate() + .getTime())); + } + + if (queryMaster.getDeleteDate() != null) { + queryMasterType.setDeleteDate(dtoFactory + .getXMLGregorianCalendar(queryMaster.getDeleteDate() + .getTime())); + } + + return queryMasterType; + } + + /** + * Returns QueryInstanceType for the given QtQueryInstance + * + * @param queryInstance + * @return QueryInstanceType + */ + public static QueryInstanceType buildQueryInstanceType( + QtQueryInstance queryInstance) { + QueryInstanceType queryInstanceType = new QueryInstanceType(); + queryInstanceType.setUserId(queryInstance.getUserId()); + queryInstanceType.setQueryMasterId(queryInstance.getQtQueryMaster() + .getQueryMasterId()); + queryInstanceType.setGroupId(queryInstance.getGroupId()); + queryInstanceType + .setQueryInstanceId(queryInstance.getQueryInstanceId()); + queryInstanceType.setBatchMode(queryInstance.getBatchMode()); + if (queryInstance.getStartDate() != null) { + queryInstanceType.setStartDate(dtoFactory + .getXMLGregorianCalendar(queryInstance.getStartDate() + .getTime())); + } + + if (queryInstance.getEndDate() != null) { + queryInstanceType.setEndDate(dtoFactory + .getXMLGregorianCalendar(queryInstance.getEndDate() + .getTime())); + } + + QueryStatusTypeType queryStatusType = new QueryStatusTypeType(); + queryStatusType.setDescription(queryInstance.getQtQueryStatusType() + .getDescription()); + queryStatusType.setName(queryInstance.getQtQueryStatusType().getName()); + queryStatusType.setStatusTypeId(String.valueOf(queryInstance + .getQtQueryStatusType().getStatusTypeId())); + queryInstanceType.setQueryStatusType(queryStatusType); + if (queryInstance.getMessage() != null) { + XmlValueType xmlValueType = new XmlValueType(); + xmlValueType.getContent().add(queryInstance.getMessage()); + queryInstanceType.setMessage(xmlValueType); + + } + + return queryInstanceType; + } + + /** + * Returns QueryInstanceType for the given QtQueryInstance + * + * @param queryInstance + * @return QueryInstanceType + */ + public static QueryResultInstanceType buildQueryResultInstanceType( + QtQueryResultInstance queryResultInstance) { + QueryResultInstanceType resultInstanceType = new QueryResultInstanceType(); + resultInstanceType.setResultInstanceId(queryResultInstance + .getResultInstanceId()); + resultInstanceType.setQueryInstanceId(queryResultInstance + .getQtQueryInstance().getQueryInstanceId()); + resultInstanceType.setDescription(queryResultInstance.getDescription()); + resultInstanceType + .setQueryResultType(buildQueryResultType(queryResultInstance + .getQtQueryResultType())); + resultInstanceType + .setQueryStatusType(buildQueryStatusType(queryResultInstance + .getQtQueryStatusType())); + resultInstanceType.setStartDate(dtoFactory + .getXMLGregorianCalendar(queryResultInstance.getStartDate() + .getTime())); + if (queryResultInstance.getEndDate() != null) { + resultInstanceType.setEndDate(dtoFactory + .getXMLGregorianCalendar(queryResultInstance.getEndDate() + .getTime())); + } + if (queryResultInstance.getSetSize() != null) { + resultInstanceType.setSetSize(queryResultInstance.getSetSize()); + } + resultInstanceType.setObfuscateMethod(queryResultInstance + .getObfuscateMethod()); + if (queryResultInstance.getMessage() != null) { + XmlValueType xmlValueType = new XmlValueType(); + xmlValueType.getContent().add(queryResultInstance.getMessage()); + resultInstanceType.setMessage(xmlValueType); + } + return resultInstanceType; + } + + public static QueryResultTypeType buildQueryResultType( + QtQueryResultType queryResult) { + QueryResultTypeType queryResultType = new QueryResultTypeType(); + queryResultType.setResultTypeId(String.valueOf(queryResult + .getResultTypeId())); + queryResultType.setName(queryResult.getName()); + queryResultType.setDescription(queryResult.getDescription()); + queryResultType.setDisplayType(queryResult.getDisplayType()); + queryResultType.setVisualAttributeType(queryResult + .getVisualAttributeType()); + queryResultType.setUserRoleCd(queryResult.getUserRoleCd()); + return queryResultType; + } + + public static QueryStatusTypeType buildQueryStatusType( + QtQueryStatusType queryStatus) { + QueryStatusTypeType queryStatusType = new QueryStatusTypeType(); + queryStatusType.setDescription(queryStatus.getDescription()); + queryStatusType.setName(queryStatus.getName()); + queryStatusType.setStatusTypeId(String.valueOf(queryStatus + .getStatusTypeId())); + return queryStatusType; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/AnalysisJob.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/AnalysisJob.java old mode 100755 new mode 100644 similarity index 95% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/AnalysisJob.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/AnalysisJob.java index ddb4e4b1..e5d801a8 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/AnalysisJob.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/AnalysisJob.java @@ -1,96 +1,96 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.datavo.db; - -import java.util.Date; - -public class AnalysisJob { - String jobId; - String queueName; - int statusTypeId; - String domainId; - String projectId; - String userId; - String requestXml; - Date createDate; - - Date updateDate; - - public String getJobId() { - return jobId; - } - - public void setJobId(String jobId) { - this.jobId = jobId; - } - - public String getQueueName() { - return queueName; - } - - public void setQueueName(String queueName) { - this.queueName = queueName; - } - - public String getDomainId() { - return domainId; - } - - public int getStatusTypeId() { - return statusTypeId; - } - - public void setStatusTypeId(int statusTypeId) { - this.statusTypeId = statusTypeId; - } - - public void setDomainId(String domainId) { - this.domainId = domainId; - } - - public String getProjectId() { - return projectId; - } - - public void setProjectId(String projectId) { - this.projectId = projectId; - } - - public String getUserId() { - return userId; - } - - public void setUserId(String userId) { - this.userId = userId; - } - - public String getRequestXml() { - return requestXml; - } - - public void setRequestXml(String requestXml) { - this.requestXml = requestXml; - } - - public Date getCreateDate() { - return createDate; - } - - public void setCreateDate(Date createDate) { - this.createDate = createDate; - } - - public Date getUpdateDate() { - return updateDate; - } - - public void setUpdateDate(Date updateDate) { - this.updateDate = updateDate; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.datavo.db; + +import java.util.Date; + +public class AnalysisJob { + String jobId; + String queueName; + int statusTypeId; + String domainId; + String projectId; + String userId; + String requestXml; + Date createDate; + + Date updateDate; + + public String getJobId() { + return jobId; + } + + public void setJobId(String jobId) { + this.jobId = jobId; + } + + public String getQueueName() { + return queueName; + } + + public void setQueueName(String queueName) { + this.queueName = queueName; + } + + public String getDomainId() { + return domainId; + } + + public int getStatusTypeId() { + return statusTypeId; + } + + public void setStatusTypeId(int statusTypeId) { + this.statusTypeId = statusTypeId; + } + + public void setDomainId(String domainId) { + this.domainId = domainId; + } + + public String getProjectId() { + return projectId; + } + + public void setProjectId(String projectId) { + this.projectId = projectId; + } + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public String getRequestXml() { + return requestXml; + } + + public void setRequestXml(String requestXml) { + this.requestXml = requestXml; + } + + public Date getCreateDate() { + return createDate; + } + + public void setCreateDate(Date createDate) { + this.createDate = createDate; + } + + public Date getUpdateDate() { + return updateDate; + } + + public void setUpdateDate(Date updateDate) { + this.updateDate = updateDate; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/DataSourceLookup.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/DataSourceLookup.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/DataSourceLookup.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/DataSourceLookup.java index bb4df4cd..cbf3b6ba --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/DataSourceLookup.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/DataSourceLookup.java @@ -1,102 +1,102 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.datavo.db; - -import java.util.Date; - -public class DataSourceLookup { - private String domainId; - private String projectPath; - private String ownerId; - private String fullSchema; - private String dataSource; - private String serverType; - private String niceName; - private String toolTip; - private String comment; - private Date entryDate; - private Date changeDate; - private String statusCd; - - - public String getDomainId() { - return domainId; - } - public void setDomainId(String domainId) { - this.domainId = domainId; - } - public String getProjectPath() { - return projectPath; - } - public void setProjectPath(String projectPath) { - this.projectPath = projectPath; - } - public String getOwnerId() { - return ownerId; - } - public void setOwnerId(String ownerId) { - this.ownerId = ownerId; - } - public String getDataSource() { - return dataSource; - } - public void setDataSource(String dataSource) { - this.dataSource = dataSource; - } - public String getFullSchema() { - return fullSchema; - } - public void setFullSchema(String fullSchema) { - this.fullSchema = fullSchema; - } - public String getServerType() { - return serverType; - } - public void setServerType(String serverType) { - this.serverType = serverType; - } - public String getNiceName() { - return niceName; - } - public void setNiceName(String niceName) { - this.niceName = niceName; - } - public String getToolTip() { - return toolTip; - } - public void setToolTip(String toolTip) { - this.toolTip = toolTip; - } - public String getComment() { - return comment; - } - public void setComment(String comment) { - this.comment = comment; - } - public Date getEntryDate() { - return entryDate; - } - public void setEntryDate(Date entryDate) { - this.entryDate = entryDate; - } - public Date getChangeDate() { - return changeDate; - } - public void setChangeDate(Date changeDate) { - this.changeDate = changeDate; - } - public String getStatusCd() { - return statusCd; - } - public void setStatusCd(String statusCd) { - this.statusCd = statusCd; - } - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.datavo.db; + +import java.util.Date; + +public class DataSourceLookup { + private String domainId; + private String projectPath; + private String ownerId; + private String fullSchema; + private String dataSource; + private String serverType; + private String niceName; + private String toolTip; + private String comment; + private Date entryDate; + private Date changeDate; + private String statusCd; + + + public String getDomainId() { + return domainId; + } + public void setDomainId(String domainId) { + this.domainId = domainId; + } + public String getProjectPath() { + return projectPath; + } + public void setProjectPath(String projectPath) { + this.projectPath = projectPath; + } + public String getOwnerId() { + return ownerId; + } + public void setOwnerId(String ownerId) { + this.ownerId = ownerId; + } + public String getDataSource() { + return dataSource; + } + public void setDataSource(String dataSource) { + this.dataSource = dataSource; + } + public String getFullSchema() { + return fullSchema; + } + public void setFullSchema(String fullSchema) { + this.fullSchema = fullSchema; + } + public String getServerType() { + return serverType; + } + public void setServerType(String serverType) { + this.serverType = serverType; + } + public String getNiceName() { + return niceName; + } + public void setNiceName(String niceName) { + this.niceName = niceName; + } + public String getToolTip() { + return toolTip; + } + public void setToolTip(String toolTip) { + this.toolTip = toolTip; + } + public String getComment() { + return comment; + } + public void setComment(String comment) { + this.comment = comment; + } + public Date getEntryDate() { + return entryDate; + } + public void setEntryDate(Date entryDate) { + this.entryDate = entryDate; + } + public Date getChangeDate() { + return changeDate; + } + public void setChangeDate(Date changeDate) { + this.changeDate = changeDate; + } + public String getStatusCd() { + return statusCd; + } + public void setStatusCd(String statusCd) { + this.statusCd = statusCd; + } + + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/IntegerStringUserType.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/IntegerStringUserType.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/IntegerStringUserType.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/IntegerStringUserType.java index e91086ec..79866f7f --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/IntegerStringUserType.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/IntegerStringUserType.java @@ -1,104 +1,104 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ - -package edu.harvard.i2b2.crc.datavo.db; - - -import java.sql.Types; - -/** - * This class allows strings to be stored in an escaped form, so that -they will never be - * automatically converted to NULL values by the database, should they -be empty. - * Note that this class will not allow you to use NULL value strings -when they are not allowed by - * Hibernate (such as in Maps). - * - * Version for Hibernate 3 that does not add quotes to non-empty strings -but escapes by a keyword. - * This seems more economic in cases where empty strings are rare. - * - * @author rkuttan - */ -public class IntegerStringUserType { //implements UserType { - private static final int[] SQL_TYPES = { Types.INTEGER }; - - public int[] sqlTypes() { - return SQL_TYPES; - } - - public Class returnedClass() { - return String.class; - } -/* - public boolean equals(Object x, Object y) throws HibernateException { - if (x == y) { - return true; - } else if ((x == null) || (y == null)) { - return false; - } else { - return x.equals(y); - } - } - - public Object nullSafeGet(ResultSet resultSet, String[] names, Object owner) - throws HibernateException, SQLException { - String result = null; - int idInt = resultSet.getInt(names[0]); - - if (!resultSet.wasNull()) { - result = (idInt == 0) ? null : String.valueOf(idInt); - } - - return result; - } - - public void nullSafeSet(PreparedStatement statement, Object value, int index) - throws HibernateException, SQLException { - if (value == null) { - statement.setInt(index, 0); - } else { - Integer dateAsInteger = Integer.parseInt((String) value); - statement.setInt(index, dateAsInteger); - } - } - - public Object deepCopy(Object value) throws HibernateException { - return value; - } - - public boolean isMutable() { - return false; - } - - public Object assemble(Serializable arg0, Object arg1) throws HibernateException { - return deepCopy(arg0); - } - - public Serializable disassemble(Object arg0) throws HibernateException { - return (Serializable)deepCopy(arg0); - } - - public int hashCode(Object arg0) throws HibernateException { - - return arg0.hashCode(); - } - - public Object replace(Object arg0, Object arg1, Object arg2) throws HibernateException { - return deepCopy(arg0); - } - */ -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ + +package edu.harvard.i2b2.crc.datavo.db; + + +import java.sql.Types; + +/** + * This class allows strings to be stored in an escaped form, so that +they will never be + * automatically converted to NULL values by the database, should they +be empty. + * Note that this class will not allow you to use NULL value strings +when they are not allowed by + * Hibernate (such as in Maps). + * + * Version for Hibernate 3 that does not add quotes to non-empty strings +but escapes by a keyword. + * This seems more economic in cases where empty strings are rare. + * + * @author rkuttan + */ +public class IntegerStringUserType { //implements UserType { + private static final int[] SQL_TYPES = { Types.INTEGER }; + + public int[] sqlTypes() { + return SQL_TYPES; + } + + public Class returnedClass() { + return String.class; + } +/* + public boolean equals(Object x, Object y) throws HibernateException { + if (x == y) { + return true; + } else if ((x == null) || (y == null)) { + return false; + } else { + return x.equals(y); + } + } + + public Object nullSafeGet(ResultSet resultSet, String[] names, Object owner) + throws HibernateException, SQLException { + String result = null; + int idInt = resultSet.getInt(names[0]); + + if (!resultSet.wasNull()) { + result = (idInt == 0) ? null : String.valueOf(idInt); + } + + return result; + } + + public void nullSafeSet(PreparedStatement statement, Object value, int index) + throws HibernateException, SQLException { + if (value == null) { + statement.setInt(index, 0); + } else { + Integer dateAsInteger = Integer.parseInt((String) value); + statement.setInt(index, dateAsInteger); + } + } + + public Object deepCopy(Object value) throws HibernateException { + return value; + } + + public boolean isMutable() { + return false; + } + + public Object assemble(Serializable arg0, Object arg1) throws HibernateException { + return deepCopy(arg0); + } + + public Serializable disassemble(Object arg0) throws HibernateException { + return (Serializable)deepCopy(arg0); + } + + public int hashCode(Object arg0) throws HibernateException { + + return arg0.hashCode(); + } + + public Object replace(Object arg0, Object arg1, Object arg2) throws HibernateException { + return deepCopy(arg0); + } + */ +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/QtAnalysisPlugin.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/QtAnalysisPlugin.java old mode 100755 new mode 100644 similarity index 95% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/QtAnalysisPlugin.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/QtAnalysisPlugin.java index 4927e2f8..1d818e26 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/QtAnalysisPlugin.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/QtAnalysisPlugin.java @@ -1,151 +1,151 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.datavo.db; - -import java.util.Date; - -public class QtAnalysisPlugin { - - String pluginId; - String pluginName; - String description; - String version; - String commandOptionCd; - String parameterInfo; - String parameterInfoXsd; - String commandLine; - String workingFolder; - String pluginIcon; - String statusId; - String userId; - String groupId; - Date createDate; - Date updateDate; - - public String getPluginId() { - return pluginId; - } - - public void setPluginId(String pluginId) { - this.pluginId = pluginId; - } - - public String getPluginName() { - return pluginName; - } - - public void setPluginName(String pluginName) { - this.pluginName = pluginName; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getVersion() { - return version; - } - - public void setVersion(String version) { - this.version = version; - } - - public String getParameterInfo() { - return parameterInfo; - } - - public void setParameterInfo(String parameterInfo) { - this.parameterInfo = parameterInfo; - } - - public String getParameterInfoXsd() { - return parameterInfoXsd; - } - - public void setParameterInfoXsd(String parameterInfoXsd) { - this.parameterInfoXsd = parameterInfoXsd; - } - - public String getCommandLine() { - return commandLine; - } - - public void setCommandLine(String commandLine) { - this.commandLine = commandLine; - } - - public String getWorkingFolder() { - return workingFolder; - } - - public void setWorkingFolder(String workingFolder) { - this.workingFolder = workingFolder; - } - - public String getPluginIcon() { - return pluginIcon; - } - - public void setPluginIcon(String pluginIcon) { - this.pluginIcon = pluginIcon; - } - - public String getStatusId() { - return statusId; - } - - public void setStatusId(String statusId) { - this.statusId = statusId; - } - - public String getUserId() { - return userId; - } - - public void setUserId(String userId) { - this.userId = userId; - } - - public String getGroupId() { - return groupId; - } - - public void setGroupId(String groupId) { - this.groupId = groupId; - } - - public Date getCreateDate() { - return createDate; - } - - public void setCreateDate(Date createDate) { - this.createDate = createDate; - } - - public Date getUpdateDate() { - return updateDate; - } - - public void setUpdateDate(Date updateDate) { - this.updateDate = updateDate; - } - - public String getCommandOptionCd() { - return commandOptionCd; - } - - public void setCommandOptionCd(String commandOptionCd) { - this.commandOptionCd = commandOptionCd; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.datavo.db; + +import java.util.Date; + +public class QtAnalysisPlugin { + + String pluginId; + String pluginName; + String description; + String version; + String commandOptionCd; + String parameterInfo; + String parameterInfoXsd; + String commandLine; + String workingFolder; + String pluginIcon; + String statusId; + String userId; + String groupId; + Date createDate; + Date updateDate; + + public String getPluginId() { + return pluginId; + } + + public void setPluginId(String pluginId) { + this.pluginId = pluginId; + } + + public String getPluginName() { + return pluginName; + } + + public void setPluginName(String pluginName) { + this.pluginName = pluginName; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getParameterInfo() { + return parameterInfo; + } + + public void setParameterInfo(String parameterInfo) { + this.parameterInfo = parameterInfo; + } + + public String getParameterInfoXsd() { + return parameterInfoXsd; + } + + public void setParameterInfoXsd(String parameterInfoXsd) { + this.parameterInfoXsd = parameterInfoXsd; + } + + public String getCommandLine() { + return commandLine; + } + + public void setCommandLine(String commandLine) { + this.commandLine = commandLine; + } + + public String getWorkingFolder() { + return workingFolder; + } + + public void setWorkingFolder(String workingFolder) { + this.workingFolder = workingFolder; + } + + public String getPluginIcon() { + return pluginIcon; + } + + public void setPluginIcon(String pluginIcon) { + this.pluginIcon = pluginIcon; + } + + public String getStatusId() { + return statusId; + } + + public void setStatusId(String statusId) { + this.statusId = statusId; + } + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public String getGroupId() { + return groupId; + } + + public void setGroupId(String groupId) { + this.groupId = groupId; + } + + public Date getCreateDate() { + return createDate; + } + + public void setCreateDate(Date createDate) { + this.createDate = createDate; + } + + public Date getUpdateDate() { + return updateDate; + } + + public void setUpdateDate(Date updateDate) { + this.updateDate = updateDate; + } + + public String getCommandOptionCd() { + return commandOptionCd; + } + + public void setCommandOptionCd(String commandOptionCd) { + this.commandOptionCd = commandOptionCd; + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/QtPatientEncCollection.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/QtPatientEncCollection.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/QtPatientEncCollection.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/QtPatientEncCollection.java index 9b97761d..eb6e0147 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/QtPatientEncCollection.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/QtPatientEncCollection.java @@ -1,89 +1,89 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.datavo.db; -// Generated Oct 10, 2006 5:52:18 PM by Hibernate Tools 3.1.0.beta5 - - - -/** - * QtPatientEncCollection generated by hbm2java - */ -public class QtPatientEncCollection implements java.io.Serializable { - - // Fields - - private long patientEncCollId; - private QtQueryResultInstance qtQueryResultInstance; - private Long setIndex; - private Long patientId; - private Long encounterId; - - // Constructors - - /** default constructor */ - public QtPatientEncCollection() { - } - - /** minimal constructor */ - public QtPatientEncCollection(long patientEncCollId) { - this.patientEncCollId = patientEncCollId; - } - /** full constructor */ - public QtPatientEncCollection(long patientEncCollId, QtQueryResultInstance qtQueryResultInstance, Long setIndex, Long patientId, Long encounterId) { - this.patientEncCollId = patientEncCollId; - this.qtQueryResultInstance = qtQueryResultInstance; - this.setIndex = setIndex; - this.patientId = patientId; - this.encounterId = encounterId; - } - - - // Property accessors - public long getPatientEncCollId() { - return this.patientEncCollId; - } - - public void setPatientEncCollId(long patientEncCollId) { - this.patientEncCollId = patientEncCollId; - } - public QtQueryResultInstance getQtQueryResultInstance() { - return this.qtQueryResultInstance; - } - - public void setQtQueryResultInstance(QtQueryResultInstance qtQueryResultInstance) { - this.qtQueryResultInstance = qtQueryResultInstance; - } - public Long getSetIndex() { - return this.setIndex; - } - - public void setSetIndex(Long setIndex) { - this.setIndex = setIndex; - } - public Long getPatientId() { - return this.patientId; - } - - public void setPatientId(Long patientId) { - this.patientId = patientId; - } - public Long getEncounterId() { - return this.encounterId; - } - - public void setEncounterId(Long encounterId) { - this.encounterId = encounterId; - } - - - - -} - - +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.datavo.db; +// Generated Oct 10, 2006 5:52:18 PM by Hibernate Tools 3.1.0.beta5 + + + +/** + * QtPatientEncCollection generated by hbm2java + */ +public class QtPatientEncCollection implements java.io.Serializable { + + // Fields + + private long patientEncCollId; + private QtQueryResultInstance qtQueryResultInstance; + private Long setIndex; + private Long patientId; + private Long encounterId; + + // Constructors + + /** default constructor */ + public QtPatientEncCollection() { + } + + /** minimal constructor */ + public QtPatientEncCollection(long patientEncCollId) { + this.patientEncCollId = patientEncCollId; + } + /** full constructor */ + public QtPatientEncCollection(long patientEncCollId, QtQueryResultInstance qtQueryResultInstance, Long setIndex, Long patientId, Long encounterId) { + this.patientEncCollId = patientEncCollId; + this.qtQueryResultInstance = qtQueryResultInstance; + this.setIndex = setIndex; + this.patientId = patientId; + this.encounterId = encounterId; + } + + + // Property accessors + public long getPatientEncCollId() { + return this.patientEncCollId; + } + + public void setPatientEncCollId(long patientEncCollId) { + this.patientEncCollId = patientEncCollId; + } + public QtQueryResultInstance getQtQueryResultInstance() { + return this.qtQueryResultInstance; + } + + public void setQtQueryResultInstance(QtQueryResultInstance qtQueryResultInstance) { + this.qtQueryResultInstance = qtQueryResultInstance; + } + public Long getSetIndex() { + return this.setIndex; + } + + public void setSetIndex(Long setIndex) { + this.setIndex = setIndex; + } + public Long getPatientId() { + return this.patientId; + } + + public void setPatientId(Long patientId) { + this.patientId = patientId; + } + public Long getEncounterId() { + return this.encounterId; + } + + public void setEncounterId(Long encounterId) { + this.encounterId = encounterId; + } + + + + +} + + diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/QtPatientEncSetResult.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/QtPatientEncSetResult.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/QtPatientEncSetResult.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/QtPatientEncSetResult.java index 86a38a00..66ebf7bb --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/QtPatientEncSetResult.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/QtPatientEncSetResult.java @@ -1,82 +1,82 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.datavo.db; -// Generated Sep 25, 2006 1:09:02 PM by Hibernate Tools 3.1.0.beta5 - - -import java.util.HashSet; -import java.util.Set; - -/** - * QtPatientEncSetResult generated by hbm2java - */ -public class QtPatientEncSetResult implements java.io.Serializable { - - // Fields - - private Integer patientEncSetResultId; - private QtQueryResultInstance qtQueryResultInstance; - private Integer setSize; - private Set qtPatientEncCollections = new HashSet(0); - - // Constructors - - /** default constructor */ - public QtPatientEncSetResult() { - } - - /** minimal constructor */ - public QtPatientEncSetResult(Integer patientEncSetResultId) { - this.patientEncSetResultId = patientEncSetResultId; - } - /** full constructor */ - public QtPatientEncSetResult(Integer patientEncSetResultId, QtQueryResultInstance qtQueryResultInstance, Integer setSize, Set qtPatientEncCollections) { - this.patientEncSetResultId = patientEncSetResultId; - this.qtQueryResultInstance = qtQueryResultInstance; - this.setSize = setSize; - this.qtPatientEncCollections = qtPatientEncCollections; - } - - - // Property accessors - public Integer getPatientEncSetResultId() { - return this.patientEncSetResultId; - } - - public void setPatientEncSetResultId(Integer patientEncSetResultId) { - this.patientEncSetResultId = patientEncSetResultId; - } - public QtQueryResultInstance getQtQueryResultInstance() { - return this.qtQueryResultInstance; - } - - public void setQtQueryResultInstance(QtQueryResultInstance qtQueryResultInstance) { - this.qtQueryResultInstance = qtQueryResultInstance; - } - public Integer getSetSize() { - return this.setSize; - } - - public void setSetSize(Integer setSize) { - this.setSize = setSize; - } - public Set getQtPatientEncCollections() { - return this.qtPatientEncCollections; - } - - public void setQtPatientEncCollections(Set qtPatientEncCollections) { - this.qtPatientEncCollections = qtPatientEncCollections; - } - - - - -} - - +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.datavo.db; +// Generated Sep 25, 2006 1:09:02 PM by Hibernate Tools 3.1.0.beta5 + + +import java.util.HashSet; +import java.util.Set; + +/** + * QtPatientEncSetResult generated by hbm2java + */ +public class QtPatientEncSetResult implements java.io.Serializable { + + // Fields + + private Integer patientEncSetResultId; + private QtQueryResultInstance qtQueryResultInstance; + private Integer setSize; + private Set qtPatientEncCollections = new HashSet(0); + + // Constructors + + /** default constructor */ + public QtPatientEncSetResult() { + } + + /** minimal constructor */ + public QtPatientEncSetResult(Integer patientEncSetResultId) { + this.patientEncSetResultId = patientEncSetResultId; + } + /** full constructor */ + public QtPatientEncSetResult(Integer patientEncSetResultId, QtQueryResultInstance qtQueryResultInstance, Integer setSize, Set qtPatientEncCollections) { + this.patientEncSetResultId = patientEncSetResultId; + this.qtQueryResultInstance = qtQueryResultInstance; + this.setSize = setSize; + this.qtPatientEncCollections = qtPatientEncCollections; + } + + + // Property accessors + public Integer getPatientEncSetResultId() { + return this.patientEncSetResultId; + } + + public void setPatientEncSetResultId(Integer patientEncSetResultId) { + this.patientEncSetResultId = patientEncSetResultId; + } + public QtQueryResultInstance getQtQueryResultInstance() { + return this.qtQueryResultInstance; + } + + public void setQtQueryResultInstance(QtQueryResultInstance qtQueryResultInstance) { + this.qtQueryResultInstance = qtQueryResultInstance; + } + public Integer getSetSize() { + return this.setSize; + } + + public void setSetSize(Integer setSize) { + this.setSize = setSize; + } + public Set getQtPatientEncCollections() { + return this.qtPatientEncCollections; + } + + public void setQtPatientEncCollections(Set qtPatientEncCollections) { + this.qtPatientEncCollections = qtPatientEncCollections; + } + + + + +} + + diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/QtPatientSetCollection.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/QtPatientSetCollection.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/QtPatientSetCollection.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/QtPatientSetCollection.java index a3481f96..b6eb0a5d --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/QtPatientSetCollection.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/QtPatientSetCollection.java @@ -1,80 +1,80 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.datavo.db; -// Generated Oct 10, 2006 5:52:18 PM by Hibernate Tools 3.1.0.beta5 - - - -/** - * QtPatientSetCollection generated by hbm2java - */ -public class QtPatientSetCollection implements java.io.Serializable { - - // Fields - - private long patientSetCollId; - private QtQueryResultInstance qtQueryResultInstance; - private Integer setIndex; - private Long patientId; - - // Constructors - - /** default constructor */ - public QtPatientSetCollection() { - } - - /** minimal constructor */ - public QtPatientSetCollection(long patientSetCollId) { - this.patientSetCollId = patientSetCollId; - } - /** full constructor */ - public QtPatientSetCollection(long patientSetCollId, QtQueryResultInstance qtQueryResultInstance, Integer setIndex, Long patientId) { - this.patientSetCollId = patientSetCollId; - this.qtQueryResultInstance = qtQueryResultInstance; - this.setIndex = setIndex; - this.patientId = patientId; - } - - - // Property accessors - public long getPatientSetCollId() { - return this.patientSetCollId; - } - - public void setPatientSetCollId(long patientSetCollId) { - this.patientSetCollId = patientSetCollId; - } - public QtQueryResultInstance getQtQueryResultInstance() { - return this.qtQueryResultInstance; - } - - public void setQtQueryResultInstance(QtQueryResultInstance qtQueryResultInstance) { - this.qtQueryResultInstance = qtQueryResultInstance; - } - public Integer getSetIndex() { - return this.setIndex; - } - - public void setSetIndex(Integer setIndex) { - this.setIndex = setIndex; - } - public Long getPatientId() { - return this.patientId; - } - - public void setPatientId(Long patientId) { - this.patientId = patientId; - } - - - - -} - - +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.datavo.db; +// Generated Oct 10, 2006 5:52:18 PM by Hibernate Tools 3.1.0.beta5 + + + +/** + * QtPatientSetCollection generated by hbm2java + */ +public class QtPatientSetCollection implements java.io.Serializable { + + // Fields + + private long patientSetCollId; + private QtQueryResultInstance qtQueryResultInstance; + private Integer setIndex; + private Long patientId; + + // Constructors + + /** default constructor */ + public QtPatientSetCollection() { + } + + /** minimal constructor */ + public QtPatientSetCollection(long patientSetCollId) { + this.patientSetCollId = patientSetCollId; + } + /** full constructor */ + public QtPatientSetCollection(long patientSetCollId, QtQueryResultInstance qtQueryResultInstance, Integer setIndex, Long patientId) { + this.patientSetCollId = patientSetCollId; + this.qtQueryResultInstance = qtQueryResultInstance; + this.setIndex = setIndex; + this.patientId = patientId; + } + + + // Property accessors + public long getPatientSetCollId() { + return this.patientSetCollId; + } + + public void setPatientSetCollId(long patientSetCollId) { + this.patientSetCollId = patientSetCollId; + } + public QtQueryResultInstance getQtQueryResultInstance() { + return this.qtQueryResultInstance; + } + + public void setQtQueryResultInstance(QtQueryResultInstance qtQueryResultInstance) { + this.qtQueryResultInstance = qtQueryResultInstance; + } + public Integer getSetIndex() { + return this.setIndex; + } + + public void setSetIndex(Integer setIndex) { + this.setIndex = setIndex; + } + public Long getPatientId() { + return this.patientId; + } + + public void setPatientId(Long patientId) { + this.patientId = patientId; + } + + + + +} + + diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/QtPatientSetResult.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/QtPatientSetResult.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/QtPatientSetResult.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/QtPatientSetResult.java index 0878b46c..7c72181e --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/QtPatientSetResult.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/QtPatientSetResult.java @@ -1,82 +1,82 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.datavo.db; -// Generated Sep 25, 2006 1:09:02 PM by Hibernate Tools 3.1.0.beta5 - - -import java.util.HashSet; -import java.util.Set; - -/** - * QtPatientSetResult generated by hbm2java - */ -public class QtPatientSetResult implements java.io.Serializable { - - // Fields - - private String patientSetResultId; - private QtQueryResultInstance qtQueryResultInstance; - private Integer setSize; - private Set qtPatientSetCollections = new HashSet(0); - - // Constructors - - /** default constructor */ - public QtPatientSetResult() { - } - - /** minimal constructor */ - public QtPatientSetResult(String patientSetResultId) { - this.patientSetResultId = patientSetResultId; - } - /** full constructor */ - public QtPatientSetResult(String patientSetResultId, QtQueryResultInstance qtQueryResultInstance, Integer setSize, Set qtPatientSetCollections) { - this.patientSetResultId = patientSetResultId; - this.qtQueryResultInstance = qtQueryResultInstance; - this.setSize = setSize; - this.qtPatientSetCollections = qtPatientSetCollections; - } - - - // Property accessors - public String getPatientSetResultId() { - return this.patientSetResultId; - } - - public void setPatientSetResultId(String patientSetResultId) { - this.patientSetResultId = patientSetResultId; - } - public QtQueryResultInstance getQtQueryResultInstance() { - return this.qtQueryResultInstance; - } - - public void setQtQueryResultInstance(QtQueryResultInstance qtQueryResultInstance) { - this.qtQueryResultInstance = qtQueryResultInstance; - } - public Integer getSetSize() { - return this.setSize; - } - - public void setSetSize(Integer setSize) { - this.setSize = setSize; - } - public Set getQtPatientSetCollections() { - return this.qtPatientSetCollections; - } - - public void setQtPatientSetCollections(Set qtPatientSetCollections) { - this.qtPatientSetCollections = qtPatientSetCollections; - } - - - - -} - - +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.datavo.db; +// Generated Sep 25, 2006 1:09:02 PM by Hibernate Tools 3.1.0.beta5 + + +import java.util.HashSet; +import java.util.Set; + +/** + * QtPatientSetResult generated by hbm2java + */ +public class QtPatientSetResult implements java.io.Serializable { + + // Fields + + private String patientSetResultId; + private QtQueryResultInstance qtQueryResultInstance; + private Integer setSize; + private Set qtPatientSetCollections = new HashSet(0); + + // Constructors + + /** default constructor */ + public QtPatientSetResult() { + } + + /** minimal constructor */ + public QtPatientSetResult(String patientSetResultId) { + this.patientSetResultId = patientSetResultId; + } + /** full constructor */ + public QtPatientSetResult(String patientSetResultId, QtQueryResultInstance qtQueryResultInstance, Integer setSize, Set qtPatientSetCollections) { + this.patientSetResultId = patientSetResultId; + this.qtQueryResultInstance = qtQueryResultInstance; + this.setSize = setSize; + this.qtPatientSetCollections = qtPatientSetCollections; + } + + + // Property accessors + public String getPatientSetResultId() { + return this.patientSetResultId; + } + + public void setPatientSetResultId(String patientSetResultId) { + this.patientSetResultId = patientSetResultId; + } + public QtQueryResultInstance getQtQueryResultInstance() { + return this.qtQueryResultInstance; + } + + public void setQtQueryResultInstance(QtQueryResultInstance qtQueryResultInstance) { + this.qtQueryResultInstance = qtQueryResultInstance; + } + public Integer getSetSize() { + return this.setSize; + } + + public void setSetSize(Integer setSize) { + this.setSize = setSize; + } + public Set getQtPatientSetCollections() { + return this.qtPatientSetCollections; + } + + public void setQtPatientSetCollections(Set qtPatientSetCollections) { + this.qtPatientSetCollections = qtPatientSetCollections; + } + + + + +} + + diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/QtPriviledge.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/QtPriviledge.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/QtPriviledge.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/QtPriviledge.java index 225645bc..56b85770 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/QtPriviledge.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/QtPriviledge.java @@ -1,50 +1,50 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.datavo.db; - -public class QtPriviledge { - - String protectionLabelCd; - String dataProtCd; - String hivemgmtCd; - String pluginId; - - public String getProtectionLabelCd() { - return protectionLabelCd; - } - - public void setProtectionLabelCd(String protectionLabelCd) { - this.protectionLabelCd = protectionLabelCd; - } - - public String getDataProtCd() { - return dataProtCd; - } - - public void setDataProtCd(String dataProtCd) { - this.dataProtCd = dataProtCd; - } - - public String getHivemgmtCd() { - return hivemgmtCd; - } - - public void setHivemgmtCd(String hivemgmtCd) { - this.hivemgmtCd = hivemgmtCd; - } - - public String getPluginId() { - return pluginId; - } - - public void setPluginId(String pluginId) { - this.pluginId = pluginId; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.datavo.db; + +public class QtPriviledge { + + String protectionLabelCd; + String dataProtCd; + String hivemgmtCd; + String pluginId; + + public String getProtectionLabelCd() { + return protectionLabelCd; + } + + public void setProtectionLabelCd(String protectionLabelCd) { + this.protectionLabelCd = protectionLabelCd; + } + + public String getDataProtCd() { + return dataProtCd; + } + + public void setDataProtCd(String dataProtCd) { + this.dataProtCd = dataProtCd; + } + + public String getHivemgmtCd() { + return hivemgmtCd; + } + + public void setHivemgmtCd(String hivemgmtCd) { + this.hivemgmtCd = hivemgmtCd; + } + + public String getPluginId() { + return pluginId; + } + + public void setPluginId(String pluginId) { + this.pluginId = pluginId; + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/QtQueryBreakdownType.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/QtQueryBreakdownType.java old mode 100755 new mode 100644 similarity index 95% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/QtQueryBreakdownType.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/QtQueryBreakdownType.java index 360fadec..024578ea --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/QtQueryBreakdownType.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/QtQueryBreakdownType.java @@ -1,90 +1,90 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.datavo.db; - - -import java.util.Date; - -/** - * QtQueryBreakdownType - */ -public class QtQueryBreakdownType implements java.io.Serializable { - - // Fields - - private String name; - private String value; - private Date createDate; - private Date updateDate; - private String userId; - private String userRoleCd; - private String classname; - - // Constructors - - public String getClassname() { - return classname; - } - - public void setClassname(String classname) { - this.classname = classname; - } - - public String getUserRoleCd() { - return userRoleCd; - } - - public void setUserRoleCd(String userRoleCd) { - this.userRoleCd = userRoleCd; - } - - /** default constructor */ - public QtQueryBreakdownType() { - } - - public String getName() { - return this.name; - } - - public void setName(String name) { - this.name = name; - } - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } - - public Date getCreateDate() { - return createDate; - } - - public void setCreateDate(Date createDate) { - this.createDate = createDate; - } - - public Date getUpdateDate() { - return updateDate; - } - - public void setUpdateDate(Date updateDate) { - this.updateDate = updateDate; - } - - public String getUserId() { - return userId; - } - - public void setUserId(String userId) { - this.userId = userId; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.datavo.db; + + +import java.util.Date; + +/** + * QtQueryBreakdownType + */ +public class QtQueryBreakdownType implements java.io.Serializable { + + // Fields + + private String name; + private String value; + private Date createDate; + private Date updateDate; + private String userId; + private String userRoleCd; + private String classname; + + // Constructors + + public String getClassname() { + return classname; + } + + public void setClassname(String classname) { + this.classname = classname; + } + + public String getUserRoleCd() { + return userRoleCd; + } + + public void setUserRoleCd(String userRoleCd) { + this.userRoleCd = userRoleCd; + } + + /** default constructor */ + public QtQueryBreakdownType() { + } + + public String getName() { + return this.name; + } + + public void setName(String name) { + this.name = name; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + public Date getCreateDate() { + return createDate; + } + + public void setCreateDate(Date createDate) { + this.createDate = createDate; + } + + public Date getUpdateDate() { + return updateDate; + } + + public void setUpdateDate(Date updateDate) { + this.updateDate = updateDate; + } + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/QtQueryInstance.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/QtQueryInstance.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/QtQueryInstance.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/QtQueryInstance.java index 87f233fb..cb3eaec4 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/QtQueryInstance.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/QtQueryInstance.java @@ -1,160 +1,160 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.datavo.db; - -// Generated Oct 10, 2006 5:52:18 PM by Hibernate Tools 3.1.0.beta5 - -import java.util.Date; -import java.util.HashSet; -import java.util.Set; - -/** - * QtQueryInstance generated by hbm2java - */ -public class QtQueryInstance implements java.io.Serializable { - - // Fields - - private String queryInstanceId; - private QtQueryStatusType qtQueryStatusType; - private QtQueryMaster qtQueryMaster; - private String userId; - private String groupId; - private String batchMode; - private Date startDate; - private Date endDate; - private String message; - - private Set qtQueryResultInstances = new HashSet( - 0); - - private String deleteFlag; - - // Constructors - - /** default constructor */ - public QtQueryInstance() { - } - - /** minimal constructor */ - public QtQueryInstance(String queryInstanceId, String userId, - String groupId, Date startDate) { - this.queryInstanceId = queryInstanceId; - this.userId = userId; - this.groupId = groupId; - this.startDate = startDate; - } - - /** full constructor */ - public QtQueryInstance(String queryInstanceId, - QtQueryStatusType qtQueryStatusType, QtQueryMaster qtQueryMaster, - String userId, String groupId, String batchMode, Date startDate, - Date endDate, Set qtQueryResultInstances) { - this.queryInstanceId = queryInstanceId; - this.qtQueryStatusType = qtQueryStatusType; - this.qtQueryMaster = qtQueryMaster; - this.userId = userId; - this.groupId = groupId; - this.batchMode = batchMode; - this.startDate = startDate; - this.endDate = endDate; - this.qtQueryResultInstances = qtQueryResultInstances; - } - - // Property accessors - public String getQueryInstanceId() { - return this.queryInstanceId; - } - - public void setQueryInstanceId(String queryInstanceId) { - this.queryInstanceId = queryInstanceId; - } - - public QtQueryStatusType getQtQueryStatusType() { - return this.qtQueryStatusType; - } - - public void setQtQueryStatusType(QtQueryStatusType qtQueryStatusType) { - this.qtQueryStatusType = qtQueryStatusType; - } - - public QtQueryMaster getQtQueryMaster() { - return this.qtQueryMaster; - } - - public void setQtQueryMaster(QtQueryMaster qtQueryMaster) { - this.qtQueryMaster = qtQueryMaster; - } - - public String getUserId() { - return this.userId; - } - - public void setUserId(String userId) { - this.userId = userId; - } - - public String getGroupId() { - return this.groupId; - } - - public void setGroupId(String groupId) { - this.groupId = groupId; - } - - public String getBatchMode() { - return this.batchMode; - } - - public void setBatchMode(String batchMode) { - this.batchMode = batchMode; - } - - public Date getStartDate() { - return this.startDate; - } - - public void setStartDate(Date startDate) { - this.startDate = startDate; - } - - public Date getEndDate() { - return this.endDate; - } - - public void setEndDate(Date endDate) { - this.endDate = endDate; - } - - public Set getQtQueryResultInstances() { - return this.qtQueryResultInstances; - } - - public void setQtQueryResultInstances( - Set qtQueryResultInstances) { - this.qtQueryResultInstances = qtQueryResultInstances; - } - - public String getDeleteFlag() { - return deleteFlag; - } - - public void setDeleteFlag(String deleteFlag) { - this.deleteFlag = deleteFlag; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.datavo.db; + +// Generated Oct 10, 2006 5:52:18 PM by Hibernate Tools 3.1.0.beta5 + +import java.util.Date; +import java.util.HashSet; +import java.util.Set; + +/** + * QtQueryInstance generated by hbm2java + */ +public class QtQueryInstance implements java.io.Serializable { + + // Fields + + private String queryInstanceId; + private QtQueryStatusType qtQueryStatusType; + private QtQueryMaster qtQueryMaster; + private String userId; + private String groupId; + private String batchMode; + private Date startDate; + private Date endDate; + private String message; + + private Set qtQueryResultInstances = new HashSet( + 0); + + private String deleteFlag; + + // Constructors + + /** default constructor */ + public QtQueryInstance() { + } + + /** minimal constructor */ + public QtQueryInstance(String queryInstanceId, String userId, + String groupId, Date startDate) { + this.queryInstanceId = queryInstanceId; + this.userId = userId; + this.groupId = groupId; + this.startDate = startDate; + } + + /** full constructor */ + public QtQueryInstance(String queryInstanceId, + QtQueryStatusType qtQueryStatusType, QtQueryMaster qtQueryMaster, + String userId, String groupId, String batchMode, Date startDate, + Date endDate, Set qtQueryResultInstances) { + this.queryInstanceId = queryInstanceId; + this.qtQueryStatusType = qtQueryStatusType; + this.qtQueryMaster = qtQueryMaster; + this.userId = userId; + this.groupId = groupId; + this.batchMode = batchMode; + this.startDate = startDate; + this.endDate = endDate; + this.qtQueryResultInstances = qtQueryResultInstances; + } + + // Property accessors + public String getQueryInstanceId() { + return this.queryInstanceId; + } + + public void setQueryInstanceId(String queryInstanceId) { + this.queryInstanceId = queryInstanceId; + } + + public QtQueryStatusType getQtQueryStatusType() { + return this.qtQueryStatusType; + } + + public void setQtQueryStatusType(QtQueryStatusType qtQueryStatusType) { + this.qtQueryStatusType = qtQueryStatusType; + } + + public QtQueryMaster getQtQueryMaster() { + return this.qtQueryMaster; + } + + public void setQtQueryMaster(QtQueryMaster qtQueryMaster) { + this.qtQueryMaster = qtQueryMaster; + } + + public String getUserId() { + return this.userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public String getGroupId() { + return this.groupId; + } + + public void setGroupId(String groupId) { + this.groupId = groupId; + } + + public String getBatchMode() { + return this.batchMode; + } + + public void setBatchMode(String batchMode) { + this.batchMode = batchMode; + } + + public Date getStartDate() { + return this.startDate; + } + + public void setStartDate(Date startDate) { + this.startDate = startDate; + } + + public Date getEndDate() { + return this.endDate; + } + + public void setEndDate(Date endDate) { + this.endDate = endDate; + } + + public Set getQtQueryResultInstances() { + return this.qtQueryResultInstances; + } + + public void setQtQueryResultInstances( + Set qtQueryResultInstances) { + this.qtQueryResultInstances = qtQueryResultInstances; + } + + public String getDeleteFlag() { + return deleteFlag; + } + + public void setDeleteFlag(String deleteFlag) { + this.deleteFlag = deleteFlag; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/QtQueryMaster.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/QtQueryMaster.java old mode 100755 new mode 100644 similarity index 95% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/QtQueryMaster.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/QtQueryMaster.java index 1dd32261..b66c363d --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/QtQueryMaster.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/QtQueryMaster.java @@ -1,187 +1,187 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.datavo.db; - -// Generated Oct 10, 2006 5:52:18 PM by Hibernate Tools 3.1.0.beta5 - -import java.util.Date; -import java.util.HashSet; -import java.util.Set; - -/** - * QtQueryMaster generated by hbm2java - */ -public class QtQueryMaster implements java.io.Serializable { - - // Fields - - private String queryMasterId; - private String name; - private String userId; - private String groupId; - private Date createDate; - private Date deleteDate; - private String requestXml; - private String generatedSql; - private String masterTypeCd = null; - private String pluginId = null; - private Set qtQueryInstances = new HashSet( - 0); - - private String deleteFlag; - private String i2b2RequestXml; - private String pmXml; - - public String getPmXml() { - return pmXml; - } - - public void setPmXml(String pmXml) { - this.pmXml = pmXml; - } - - public final static String DELETE_ON_FLAG = "Y"; - public final static String DELETE_OFF_FLAG = "N"; - - // Constructors - - /** default constructor */ - public QtQueryMaster() { - } - - /** minimal constructor */ - public QtQueryMaster(String queryMasterId, String name, String userId, - String groupId, Date createDate) { - this.queryMasterId = queryMasterId; - this.name = name; - this.userId = userId; - this.groupId = groupId; - this.createDate = createDate; - } - - /** full constructor */ - public QtQueryMaster(String queryMasterId, String name, String userId, - String groupId, Date createDate, Date deleteDate, - String requestXml, Set qtQueryInstances) { - this.queryMasterId = queryMasterId; - this.name = name; - this.userId = userId; - this.groupId = groupId; - this.createDate = createDate; - this.deleteDate = deleteDate; - this.requestXml = requestXml; - this.qtQueryInstances = qtQueryInstances; - } - - // Property accessors - public String getQueryMasterId() { - return this.queryMasterId; - } - - public void setQueryMasterId(String queryMasterId) { - this.queryMasterId = queryMasterId; - } - - public String getName() { - return this.name; - } - - public void setName(String name) { - this.name = name; - } - - public String getUserId() { - return this.userId; - } - - public void setUserId(String userId) { - this.userId = userId; - } - - public String getGroupId() { - return this.groupId; - } - - public void setGroupId(String groupId) { - this.groupId = groupId; - } - - public Date getCreateDate() { - return this.createDate; - } - - public void setCreateDate(Date createDate) { - this.createDate = createDate; - } - - public Date getDeleteDate() { - return this.deleteDate; - } - - public void setDeleteDate(Date deleteDate) { - this.deleteDate = deleteDate; - } - - public String getRequestXml() { - return this.requestXml; - } - - public void setRequestXml(String requestXml) { - this.requestXml = requestXml; - } - - public String getGeneratedSql() { - return generatedSql; - } - - public void setGeneratedSql(String generatedSql) { - this.generatedSql = generatedSql; - } - - public String getDeleteFlag() { - return deleteFlag; - } - - public void setDeleteFlag(String deleteFlag) { - this.deleteFlag = deleteFlag; - } - - public Set getQtQueryInstances() { - return this.qtQueryInstances; - } - - public void setQtQueryInstances(Set qtQueryInstances) { - this.qtQueryInstances = qtQueryInstances; - } - - public String getI2b2RequestXml() { - return i2b2RequestXml; - } - - public void setI2b2RequestXml(String requestXml) { - i2b2RequestXml = requestXml; - } - - public String getMasterTypeCd() { - return masterTypeCd; - } - - public void setMasterTypeCd(String masterTypeCd) { - this.masterTypeCd = masterTypeCd; - } - - public String getPluginId() { - return pluginId; - } - - public void setPluginId(String pluginId) { - this.pluginId = pluginId; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.datavo.db; + +// Generated Oct 10, 2006 5:52:18 PM by Hibernate Tools 3.1.0.beta5 + +import java.util.Date; +import java.util.HashSet; +import java.util.Set; + +/** + * QtQueryMaster generated by hbm2java + */ +public class QtQueryMaster implements java.io.Serializable { + + // Fields + + private String queryMasterId; + private String name; + private String userId; + private String groupId; + private Date createDate; + private Date deleteDate; + private String requestXml; + private String generatedSql; + private String masterTypeCd = null; + private String pluginId = null; + private Set qtQueryInstances = new HashSet( + 0); + + private String deleteFlag; + private String i2b2RequestXml; + private String pmXml; + + public String getPmXml() { + return pmXml; + } + + public void setPmXml(String pmXml) { + this.pmXml = pmXml; + } + + public final static String DELETE_ON_FLAG = "Y"; + public final static String DELETE_OFF_FLAG = "N"; + + // Constructors + + /** default constructor */ + public QtQueryMaster() { + } + + /** minimal constructor */ + public QtQueryMaster(String queryMasterId, String name, String userId, + String groupId, Date createDate) { + this.queryMasterId = queryMasterId; + this.name = name; + this.userId = userId; + this.groupId = groupId; + this.createDate = createDate; + } + + /** full constructor */ + public QtQueryMaster(String queryMasterId, String name, String userId, + String groupId, Date createDate, Date deleteDate, + String requestXml, Set qtQueryInstances) { + this.queryMasterId = queryMasterId; + this.name = name; + this.userId = userId; + this.groupId = groupId; + this.createDate = createDate; + this.deleteDate = deleteDate; + this.requestXml = requestXml; + this.qtQueryInstances = qtQueryInstances; + } + + // Property accessors + public String getQueryMasterId() { + return this.queryMasterId; + } + + public void setQueryMasterId(String queryMasterId) { + this.queryMasterId = queryMasterId; + } + + public String getName() { + return this.name; + } + + public void setName(String name) { + this.name = name; + } + + public String getUserId() { + return this.userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public String getGroupId() { + return this.groupId; + } + + public void setGroupId(String groupId) { + this.groupId = groupId; + } + + public Date getCreateDate() { + return this.createDate; + } + + public void setCreateDate(Date createDate) { + this.createDate = createDate; + } + + public Date getDeleteDate() { + return this.deleteDate; + } + + public void setDeleteDate(Date deleteDate) { + this.deleteDate = deleteDate; + } + + public String getRequestXml() { + return this.requestXml; + } + + public void setRequestXml(String requestXml) { + this.requestXml = requestXml; + } + + public String getGeneratedSql() { + return generatedSql; + } + + public void setGeneratedSql(String generatedSql) { + this.generatedSql = generatedSql; + } + + public String getDeleteFlag() { + return deleteFlag; + } + + public void setDeleteFlag(String deleteFlag) { + this.deleteFlag = deleteFlag; + } + + public Set getQtQueryInstances() { + return this.qtQueryInstances; + } + + public void setQtQueryInstances(Set qtQueryInstances) { + this.qtQueryInstances = qtQueryInstances; + } + + public String getI2b2RequestXml() { + return i2b2RequestXml; + } + + public void setI2b2RequestXml(String requestXml) { + i2b2RequestXml = requestXml; + } + + public String getMasterTypeCd() { + return masterTypeCd; + } + + public void setMasterTypeCd(String masterTypeCd) { + this.masterTypeCd = masterTypeCd; + } + + public String getPluginId() { + return pluginId; + } + + public void setPluginId(String pluginId) { + this.pluginId = pluginId; + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/QtQueryResultInstance.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/QtQueryResultInstance.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/QtQueryResultInstance.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/QtQueryResultInstance.java index a54ff658..11017dd5 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/QtQueryResultInstance.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/QtQueryResultInstance.java @@ -1,204 +1,204 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.datavo.db; - -// Generated Oct 10, 2006 5:52:18 PM by Hibernate Tools 3.1.0.beta5 - -import java.util.Date; -import java.util.HashSet; -import java.util.Set; - -/** - * QtQueryResultInstance generated by hbm2java - */ -public class QtQueryResultInstance implements java.io.Serializable { - - // Fields - - private String resultInstanceId = null; - private QtQueryStatusType qtQueryStatusType = null; - private QtQueryResultType qtQueryResultType = null; - private QtQueryInstance qtQueryInstance = null; - private String description = null; - - private Integer setSize = null; - private Integer realSetSize = null; - - private Date startDate = null; - private Date endDate = null; - private String message = null; - private Set qtXmlResults = new HashSet(0); - private Set qtPatientSetCollections = new HashSet( - 0); - private Set qtPatientEncCollections = new HashSet( - 0); - - private String deleteFlag = null; - private String obfuscateMethod = null; - - // Constructors - - /** default constructor */ - public QtQueryResultInstance() { - } - - /** minimal constructor */ - public QtQueryResultInstance(String resultInstanceId, - QtQueryStatusType qtQueryStatusType, - QtQueryResultType qtQueryResultType, Date startDate) { - this.resultInstanceId = resultInstanceId; - this.qtQueryStatusType = qtQueryStatusType; - this.qtQueryResultType = qtQueryResultType; - this.startDate = startDate; - } - - /** full constructor */ - public QtQueryResultInstance(String resultInstanceId, - QtQueryStatusType qtQueryStatusType, - QtQueryResultType qtQueryResultType, - QtQueryInstance qtQueryInstance, Integer setSize, Date startDate, - Date endDate, Set qtXmlResults, - Set qtPatientSetCollections, - Set qtPatientEncCollections) { - this.resultInstanceId = resultInstanceId; - this.qtQueryStatusType = qtQueryStatusType; - this.qtQueryResultType = qtQueryResultType; - this.qtQueryInstance = qtQueryInstance; - this.setSize = setSize; - this.startDate = startDate; - this.endDate = endDate; - this.qtXmlResults = qtXmlResults; - this.qtPatientSetCollections = qtPatientSetCollections; - this.qtPatientEncCollections = qtPatientEncCollections; - } - - // Property accessors - public String getResultInstanceId() { - return this.resultInstanceId; - } - - public void setResultInstanceId(String resultInstanceId) { - this.resultInstanceId = resultInstanceId; - } - - public QtQueryStatusType getQtQueryStatusType() { - return this.qtQueryStatusType; - } - - public void setQtQueryStatusType(QtQueryStatusType qtQueryStatusType) { - this.qtQueryStatusType = qtQueryStatusType; - } - - public QtQueryResultType getQtQueryResultType() { - return this.qtQueryResultType; - } - - public void setQtQueryResultType(QtQueryResultType qtQueryResultType) { - this.qtQueryResultType = qtQueryResultType; - } - - public QtQueryInstance getQtQueryInstance() { - return this.qtQueryInstance; - } - - public void setQtQueryInstance(QtQueryInstance qtQueryInstance) { - this.qtQueryInstance = qtQueryInstance; - } - - public Integer getSetSize() { - return this.setSize; - } - - public void setSetSize(Integer setSize) { - this.setSize = setSize; - } - - public Date getStartDate() { - return this.startDate; - } - - public void setStartDate(Date startDate) { - this.startDate = startDate; - } - - public Date getEndDate() { - return this.endDate; - } - - public void setEndDate(Date endDate) { - this.endDate = endDate; - } - - public Set getQtXmlResults() { - return this.qtXmlResults; - } - - public void setQtXmlResults(Set qtXmlResults) { - this.qtXmlResults = qtXmlResults; - } - - public Set getQtPatientSetCollections() { - return this.qtPatientSetCollections; - } - - public void setQtPatientSetCollections( - Set qtPatientSetCollections) { - this.qtPatientSetCollections = qtPatientSetCollections; - } - - public Set getQtPatientEncCollections() { - return this.qtPatientEncCollections; - } - - public void setQtPatientEncCollections( - Set qtPatientEncCollections) { - this.qtPatientEncCollections = qtPatientEncCollections; - } - - public String getDeleteFlag() { - return deleteFlag; - } - - public void setDeleteFlag(String deleteFlag) { - this.deleteFlag = deleteFlag; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getObfuscateMethod() { - return obfuscateMethod; - } - - public void setObfuscateMethod(String obfuscateMethod) { - this.obfuscateMethod = obfuscateMethod; - } - - public Integer getRealSetSize() { - return realSetSize; - } - - public void setRealSetSize(Integer realSetSize) { - this.realSetSize = realSetSize; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.datavo.db; + +// Generated Oct 10, 2006 5:52:18 PM by Hibernate Tools 3.1.0.beta5 + +import java.util.Date; +import java.util.HashSet; +import java.util.Set; + +/** + * QtQueryResultInstance generated by hbm2java + */ +public class QtQueryResultInstance implements java.io.Serializable { + + // Fields + + private String resultInstanceId = null; + private QtQueryStatusType qtQueryStatusType = null; + private QtQueryResultType qtQueryResultType = null; + private QtQueryInstance qtQueryInstance = null; + private String description = null; + + private Integer setSize = null; + private Integer realSetSize = null; + + private Date startDate = null; + private Date endDate = null; + private String message = null; + private Set qtXmlResults = new HashSet(0); + private Set qtPatientSetCollections = new HashSet( + 0); + private Set qtPatientEncCollections = new HashSet( + 0); + + private String deleteFlag = null; + private String obfuscateMethod = null; + + // Constructors + + /** default constructor */ + public QtQueryResultInstance() { + } + + /** minimal constructor */ + public QtQueryResultInstance(String resultInstanceId, + QtQueryStatusType qtQueryStatusType, + QtQueryResultType qtQueryResultType, Date startDate) { + this.resultInstanceId = resultInstanceId; + this.qtQueryStatusType = qtQueryStatusType; + this.qtQueryResultType = qtQueryResultType; + this.startDate = startDate; + } + + /** full constructor */ + public QtQueryResultInstance(String resultInstanceId, + QtQueryStatusType qtQueryStatusType, + QtQueryResultType qtQueryResultType, + QtQueryInstance qtQueryInstance, Integer setSize, Date startDate, + Date endDate, Set qtXmlResults, + Set qtPatientSetCollections, + Set qtPatientEncCollections) { + this.resultInstanceId = resultInstanceId; + this.qtQueryStatusType = qtQueryStatusType; + this.qtQueryResultType = qtQueryResultType; + this.qtQueryInstance = qtQueryInstance; + this.setSize = setSize; + this.startDate = startDate; + this.endDate = endDate; + this.qtXmlResults = qtXmlResults; + this.qtPatientSetCollections = qtPatientSetCollections; + this.qtPatientEncCollections = qtPatientEncCollections; + } + + // Property accessors + public String getResultInstanceId() { + return this.resultInstanceId; + } + + public void setResultInstanceId(String resultInstanceId) { + this.resultInstanceId = resultInstanceId; + } + + public QtQueryStatusType getQtQueryStatusType() { + return this.qtQueryStatusType; + } + + public void setQtQueryStatusType(QtQueryStatusType qtQueryStatusType) { + this.qtQueryStatusType = qtQueryStatusType; + } + + public QtQueryResultType getQtQueryResultType() { + return this.qtQueryResultType; + } + + public void setQtQueryResultType(QtQueryResultType qtQueryResultType) { + this.qtQueryResultType = qtQueryResultType; + } + + public QtQueryInstance getQtQueryInstance() { + return this.qtQueryInstance; + } + + public void setQtQueryInstance(QtQueryInstance qtQueryInstance) { + this.qtQueryInstance = qtQueryInstance; + } + + public Integer getSetSize() { + return this.setSize; + } + + public void setSetSize(Integer setSize) { + this.setSize = setSize; + } + + public Date getStartDate() { + return this.startDate; + } + + public void setStartDate(Date startDate) { + this.startDate = startDate; + } + + public Date getEndDate() { + return this.endDate; + } + + public void setEndDate(Date endDate) { + this.endDate = endDate; + } + + public Set getQtXmlResults() { + return this.qtXmlResults; + } + + public void setQtXmlResults(Set qtXmlResults) { + this.qtXmlResults = qtXmlResults; + } + + public Set getQtPatientSetCollections() { + return this.qtPatientSetCollections; + } + + public void setQtPatientSetCollections( + Set qtPatientSetCollections) { + this.qtPatientSetCollections = qtPatientSetCollections; + } + + public Set getQtPatientEncCollections() { + return this.qtPatientEncCollections; + } + + public void setQtPatientEncCollections( + Set qtPatientEncCollections) { + this.qtPatientEncCollections = qtPatientEncCollections; + } + + public String getDeleteFlag() { + return deleteFlag; + } + + public void setDeleteFlag(String deleteFlag) { + this.deleteFlag = deleteFlag; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getObfuscateMethod() { + return obfuscateMethod; + } + + public void setObfuscateMethod(String obfuscateMethod) { + this.obfuscateMethod = obfuscateMethod; + } + + public Integer getRealSetSize() { + return realSetSize; + } + + public void setRealSetSize(Integer realSetSize) { + this.realSetSize = realSetSize; + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/QtQueryResultType.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/QtQueryResultType.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/QtQueryResultType.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/QtQueryResultType.java index cd4e3716..fe55ec55 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/QtQueryResultType.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/QtQueryResultType.java @@ -1,122 +1,122 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.datavo.db; - -// Generated Oct 10, 2006 5:52:18 PM by Hibernate Tools 3.1.0.beta5 - -import java.util.HashSet; -import java.util.Set; - -/** - * QtQueryResultType generated by hbm2java - */ -public class QtQueryResultType implements java.io.Serializable { - - // Fields - - private int resultTypeId; - private String name; - private String description; - private String displayType; - private String visualAttributeType; - private String userRoleCd; - private String classname; - - public String getClassname() { - return classname; - } - - public void setClassname(String classname) { - this.classname = classname; - } - - private Set qtQueryResultInstances = new HashSet( - 0); - - public final static String PATIENT_COUNT_XML = "PATIENT_COUNT_XML"; - // Constructors - - /** default constructor */ - public QtQueryResultType() { - } - - /** minimal constructor */ - public QtQueryResultType(int resultTypeId) { - this.resultTypeId = resultTypeId; - } - - /** full constructor */ - public QtQueryResultType(int resultTypeId, String name, String description, String userRoleCd, - Set qtQueryResultInstances) { - this.resultTypeId = resultTypeId; - this.name = name; - this.description = description; - this.userRoleCd = userRoleCd; - this.qtQueryResultInstances = qtQueryResultInstances; - } - - public String getUserRoleCd() { - return userRoleCd; - } - - public void setUserRoleCd(String userRoleCd) { - this.userRoleCd = userRoleCd; - } - - // Property accessors - public int getResultTypeId() { - return this.resultTypeId; - } - - public void setResultTypeId(int resultTypeId) { - this.resultTypeId = resultTypeId; - } - - public String getName() { - return this.name; - } - - public void setName(String name) { - this.name = name; - } - - public String getDescription() { - return this.description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getDisplayType() { - return displayType; - } - - public void setDisplayType(String displayType) { - this.displayType = displayType; - } - - public String getVisualAttributeType() { - return visualAttributeType; - } - - public void setVisualAttributeType(String visualAttributeType) { - this.visualAttributeType = visualAttributeType; - } - - public Set getQtQueryResultInstances() { - return this.qtQueryResultInstances; - } - - public void setQtQueryResultInstances( - Set qtQueryResultInstances) { - this.qtQueryResultInstances = qtQueryResultInstances; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.datavo.db; + +// Generated Oct 10, 2006 5:52:18 PM by Hibernate Tools 3.1.0.beta5 + +import java.util.HashSet; +import java.util.Set; + +/** + * QtQueryResultType generated by hbm2java + */ +public class QtQueryResultType implements java.io.Serializable { + + // Fields + + private int resultTypeId; + private String name; + private String description; + private String displayType; + private String visualAttributeType; + private String userRoleCd; + private String classname; + + public String getClassname() { + return classname; + } + + public void setClassname(String classname) { + this.classname = classname; + } + + private Set qtQueryResultInstances = new HashSet( + 0); + + public final static String PATIENT_COUNT_XML = "PATIENT_COUNT_XML"; + // Constructors + + /** default constructor */ + public QtQueryResultType() { + } + + /** minimal constructor */ + public QtQueryResultType(int resultTypeId) { + this.resultTypeId = resultTypeId; + } + + /** full constructor */ + public QtQueryResultType(int resultTypeId, String name, String description, String userRoleCd, + Set qtQueryResultInstances) { + this.resultTypeId = resultTypeId; + this.name = name; + this.description = description; + this.userRoleCd = userRoleCd; + this.qtQueryResultInstances = qtQueryResultInstances; + } + + public String getUserRoleCd() { + return userRoleCd; + } + + public void setUserRoleCd(String userRoleCd) { + this.userRoleCd = userRoleCd; + } + + // Property accessors + public int getResultTypeId() { + return this.resultTypeId; + } + + public void setResultTypeId(int resultTypeId) { + this.resultTypeId = resultTypeId; + } + + public String getName() { + return this.name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return this.description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getDisplayType() { + return displayType; + } + + public void setDisplayType(String displayType) { + this.displayType = displayType; + } + + public String getVisualAttributeType() { + return visualAttributeType; + } + + public void setVisualAttributeType(String visualAttributeType) { + this.visualAttributeType = visualAttributeType; + } + + public Set getQtQueryResultInstances() { + return this.qtQueryResultInstances; + } + + public void setQtQueryResultInstances( + Set qtQueryResultInstances) { + this.qtQueryResultInstances = qtQueryResultInstances; + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/QtQueryStatus.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/QtQueryStatus.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/QtQueryStatus.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/QtQueryStatus.java index d7ceed79..748d72ba --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/QtQueryStatus.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/QtQueryStatus.java @@ -1,94 +1,94 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.datavo.db; -// Generated Sep 25, 2006 1:09:02 PM by Hibernate Tools 3.1.0.beta5 - - -import java.util.Date; -import java.util.HashSet; -import java.util.Set; - -/** - * QtQueryStatus generated by hbm2java - */ -public class QtQueryStatus implements java.io.Serializable { - - // Fields - - private Integer statusId; - private QtQueryStatusType qtQueryStatusType; - private Date dateStarted; - private Date dateFinished; - private Set qtQueryInstances = new HashSet(0); - - // Constructors - - /** default constructor */ - public QtQueryStatus() { - } - - /** minimal constructor */ - public QtQueryStatus(Integer statusId, QtQueryStatusType qtQueryStatusType, Date dateStarted) { - this.statusId = statusId; - this.qtQueryStatusType = qtQueryStatusType; - this.dateStarted = dateStarted; - } - /** full constructor */ - public QtQueryStatus(Integer statusId, QtQueryStatusType qtQueryStatusType, Date dateStarted, Date dateFinished, Set qtQueryInstances) { - this.statusId = statusId; - this.qtQueryStatusType = qtQueryStatusType; - this.dateStarted = dateStarted; - this.dateFinished = dateFinished; - this.qtQueryInstances = qtQueryInstances; - } - - - // Property accessors - public Integer getStatusId() { - return this.statusId; - } - - public void setStatusId(Integer statusId) { - this.statusId = statusId; - } - public QtQueryStatusType getQtQueryStatusType() { - return this.qtQueryStatusType; - } - - public void setQtQueryStatusType(QtQueryStatusType qtQueryStatusType) { - this.qtQueryStatusType = qtQueryStatusType; - } - public Date getDateStarted() { - return this.dateStarted; - } - - public void setDateStarted(Date dateStarted) { - this.dateStarted = dateStarted; - } - public Date getDateFinished() { - return this.dateFinished; - } - - public void setDateFinished(Date dateFinished) { - this.dateFinished = dateFinished; - } - public Set getQtQueryInstances() { - return this.qtQueryInstances; - } - - public void setQtQueryInstances(Set qtQueryInstances) { - this.qtQueryInstances = qtQueryInstances; - } - - - - -} - - +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.datavo.db; +// Generated Sep 25, 2006 1:09:02 PM by Hibernate Tools 3.1.0.beta5 + + +import java.util.Date; +import java.util.HashSet; +import java.util.Set; + +/** + * QtQueryStatus generated by hbm2java + */ +public class QtQueryStatus implements java.io.Serializable { + + // Fields + + private Integer statusId; + private QtQueryStatusType qtQueryStatusType; + private Date dateStarted; + private Date dateFinished; + private Set qtQueryInstances = new HashSet(0); + + // Constructors + + /** default constructor */ + public QtQueryStatus() { + } + + /** minimal constructor */ + public QtQueryStatus(Integer statusId, QtQueryStatusType qtQueryStatusType, Date dateStarted) { + this.statusId = statusId; + this.qtQueryStatusType = qtQueryStatusType; + this.dateStarted = dateStarted; + } + /** full constructor */ + public QtQueryStatus(Integer statusId, QtQueryStatusType qtQueryStatusType, Date dateStarted, Date dateFinished, Set qtQueryInstances) { + this.statusId = statusId; + this.qtQueryStatusType = qtQueryStatusType; + this.dateStarted = dateStarted; + this.dateFinished = dateFinished; + this.qtQueryInstances = qtQueryInstances; + } + + + // Property accessors + public Integer getStatusId() { + return this.statusId; + } + + public void setStatusId(Integer statusId) { + this.statusId = statusId; + } + public QtQueryStatusType getQtQueryStatusType() { + return this.qtQueryStatusType; + } + + public void setQtQueryStatusType(QtQueryStatusType qtQueryStatusType) { + this.qtQueryStatusType = qtQueryStatusType; + } + public Date getDateStarted() { + return this.dateStarted; + } + + public void setDateStarted(Date dateStarted) { + this.dateStarted = dateStarted; + } + public Date getDateFinished() { + return this.dateFinished; + } + + public void setDateFinished(Date dateFinished) { + this.dateFinished = dateFinished; + } + public Set getQtQueryInstances() { + return this.qtQueryInstances; + } + + public void setQtQueryInstances(Set qtQueryInstances) { + this.qtQueryInstances = qtQueryInstances; + } + + + + +} + + diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/QtQueryStatusType.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/QtQueryStatusType.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/QtQueryStatusType.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/QtQueryStatusType.java index 3b7239fa..9e47cc61 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/QtQueryStatusType.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/QtQueryStatusType.java @@ -1,91 +1,91 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.datavo.db; -// Generated Oct 10, 2006 5:52:18 PM by Hibernate Tools 3.1.0.beta5 - - -import java.util.HashSet; -import java.util.Set; - -/** - * QtQueryStatusType generated by hbm2java - */ -public class QtQueryStatusType implements java.io.Serializable { - - // Fields - - private int statusTypeId; - private String name; - private String description; - private Set qtQueryInstances = new HashSet(0); - private Set qtQueryResultInstances = new HashSet(0); - - // Constructors - - /** default constructor */ - public QtQueryStatusType() { - } - - /** minimal constructor */ - public QtQueryStatusType(int statusTypeId) { - this.statusTypeId = statusTypeId; - } - /** full constructor */ - public QtQueryStatusType(int statusTypeId, String name, String description, Set qtQueryInstances, Set qtQueryResultInstances) { - this.statusTypeId = statusTypeId; - this.name = name; - this.description = description; - this.qtQueryInstances = qtQueryInstances; - this.qtQueryResultInstances = qtQueryResultInstances; - } - - - // Property accessors - public int getStatusTypeId() { - return this.statusTypeId; - } - - public void setStatusTypeId(int statusTypeId) { - this.statusTypeId = statusTypeId; - } - public String getName() { - return this.name; - } - - public void setName(String name) { - this.name = name; - } - public String getDescription() { - return this.description; - } - - public void setDescription(String description) { - this.description = description; - } - public Set getQtQueryInstances() { - return this.qtQueryInstances; - } - - public void setQtQueryInstances(Set qtQueryInstances) { - this.qtQueryInstances = qtQueryInstances; - } - public Set getQtQueryResultInstances() { - return this.qtQueryResultInstances; - } - - public void setQtQueryResultInstances(Set qtQueryResultInstances) { - this.qtQueryResultInstances = qtQueryResultInstances; - } - - - - -} - - +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.datavo.db; +// Generated Oct 10, 2006 5:52:18 PM by Hibernate Tools 3.1.0.beta5 + + +import java.util.HashSet; +import java.util.Set; + +/** + * QtQueryStatusType generated by hbm2java + */ +public class QtQueryStatusType implements java.io.Serializable { + + // Fields + + private int statusTypeId; + private String name; + private String description; + private Set qtQueryInstances = new HashSet(0); + private Set qtQueryResultInstances = new HashSet(0); + + // Constructors + + /** default constructor */ + public QtQueryStatusType() { + } + + /** minimal constructor */ + public QtQueryStatusType(int statusTypeId) { + this.statusTypeId = statusTypeId; + } + /** full constructor */ + public QtQueryStatusType(int statusTypeId, String name, String description, Set qtQueryInstances, Set qtQueryResultInstances) { + this.statusTypeId = statusTypeId; + this.name = name; + this.description = description; + this.qtQueryInstances = qtQueryInstances; + this.qtQueryResultInstances = qtQueryResultInstances; + } + + + // Property accessors + public int getStatusTypeId() { + return this.statusTypeId; + } + + public void setStatusTypeId(int statusTypeId) { + this.statusTypeId = statusTypeId; + } + public String getName() { + return this.name; + } + + public void setName(String name) { + this.name = name; + } + public String getDescription() { + return this.description; + } + + public void setDescription(String description) { + this.description = description; + } + public Set getQtQueryInstances() { + return this.qtQueryInstances; + } + + public void setQtQueryInstances(Set qtQueryInstances) { + this.qtQueryInstances = qtQueryInstances; + } + public Set getQtQueryResultInstances() { + return this.qtQueryResultInstances; + } + + public void setQtQueryResultInstances(Set qtQueryResultInstances) { + this.qtQueryResultInstances = qtQueryResultInstances; + } + + + + +} + + diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/QtXmlResult.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/QtXmlResult.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/QtXmlResult.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/QtXmlResult.java index c417dc21..9c075ef4 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/QtXmlResult.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/QtXmlResult.java @@ -1,71 +1,71 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.datavo.db; -// Generated Oct 10, 2006 5:52:18 PM by Hibernate Tools 3.1.0.beta5 - - - -/** - * QtXmlResult generated by hbm2java - */ -public class QtXmlResult implements java.io.Serializable { - - // Fields - - private String xmlResultId; - private QtQueryResultInstance qtQueryResultInstance; - private String xmlValue; - - // Constructors - - /** default constructor */ - public QtXmlResult() { - } - - /** minimal constructor */ - public QtXmlResult(String xmlResultId) { - this.xmlResultId = xmlResultId; - } - /** full constructor */ - public QtXmlResult(String xmlResultId, QtQueryResultInstance qtQueryResultInstance, String xmlValue) { - this.xmlResultId = xmlResultId; - this.qtQueryResultInstance = qtQueryResultInstance; - this.xmlValue = xmlValue; - } - - - // Property accessors - public String getXmlResultId() { - return this.xmlResultId; - } - - public void setXmlResultId(String xmlResultId) { - this.xmlResultId = xmlResultId; - } - public QtQueryResultInstance getQtQueryResultInstance() { - return this.qtQueryResultInstance; - } - - public void setQtQueryResultInstance(QtQueryResultInstance qtQueryResultInstance) { - this.qtQueryResultInstance = qtQueryResultInstance; - } - public String getXmlValue() { - return this.xmlValue; - } - - public void setXmlValue(String xmlValue) { - this.xmlValue = xmlValue; - } - - - - -} - - +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.datavo.db; +// Generated Oct 10, 2006 5:52:18 PM by Hibernate Tools 3.1.0.beta5 + + + +/** + * QtXmlResult generated by hbm2java + */ +public class QtXmlResult implements java.io.Serializable { + + // Fields + + private String xmlResultId; + private QtQueryResultInstance qtQueryResultInstance; + private String xmlValue; + + // Constructors + + /** default constructor */ + public QtXmlResult() { + } + + /** minimal constructor */ + public QtXmlResult(String xmlResultId) { + this.xmlResultId = xmlResultId; + } + /** full constructor */ + public QtXmlResult(String xmlResultId, QtQueryResultInstance qtQueryResultInstance, String xmlValue) { + this.xmlResultId = xmlResultId; + this.qtQueryResultInstance = qtQueryResultInstance; + this.xmlValue = xmlValue; + } + + + // Property accessors + public String getXmlResultId() { + return this.xmlResultId; + } + + public void setXmlResultId(String xmlResultId) { + this.xmlResultId = xmlResultId; + } + public QtQueryResultInstance getQtQueryResultInstance() { + return this.qtQueryResultInstance; + } + + public void setQtQueryResultInstance(QtQueryResultInstance qtQueryResultInstance) { + this.qtQueryResultInstance = qtQueryResultInstance; + } + public String getXmlValue() { + return this.xmlValue; + } + + public void setXmlValue(String xmlValue) { + this.xmlValue = xmlValue; + } + + + + +} + + diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/QtXmlResultId.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/QtXmlResultId.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/QtXmlResultId.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/QtXmlResultId.java index 4520f555..e09a75a2 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/QtXmlResultId.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/QtXmlResultId.java @@ -1,89 +1,89 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.datavo.db; -// Generated Sep 25, 2006 1:09:02 PM by Hibernate Tools 3.1.0.beta5 - - - -/** - * QtXmlResultId generated by hbm2java - */ -public class QtXmlResultId implements java.io.Serializable { - - - // Fields - - private String xmlResultId; - private Integer resultInstanceId; - private String xmlValue; - - // Constructors - - /** default constructor */ - public QtXmlResultId() { - } - - /** full constructor */ - public QtXmlResultId(String xmlResultId, Integer resultInstanceId, String xmlValue) { - this.xmlResultId = xmlResultId; - this.resultInstanceId = resultInstanceId; - this.xmlValue = xmlValue; - } - - - // Property accessors - public String getXmlResultId() { - return this.xmlResultId; - } - - public void setXmlResultId(String xmlResultId) { - this.xmlResultId = xmlResultId; - } - public Integer getResultInstanceId() { - return this.resultInstanceId; - } - - public void setResultInstanceId(Integer resultInstanceId) { - this.resultInstanceId = resultInstanceId; - } - public String getXmlValue() { - return this.xmlValue; - } - - public void setXmlValue(String xmlValue) { - this.xmlValue = xmlValue; - } - - - @Override -public boolean equals(Object other) { - if ( (this == other ) ) return true; - if ( (other == null ) ) return false; - if ( !(other instanceof QtXmlResultId) ) return false; - QtXmlResultId castOther = ( QtXmlResultId ) other; - - return ( (this.getXmlResultId()==castOther.getXmlResultId()) || ( this.getXmlResultId()!=null && castOther.getXmlResultId()!=null && this.getXmlResultId().equals(castOther.getXmlResultId()) ) ) - && ( (this.getResultInstanceId()==castOther.getResultInstanceId()) || ( this.getResultInstanceId()!=null && castOther.getResultInstanceId()!=null && this.getResultInstanceId().equals(castOther.getResultInstanceId()) ) ) - && ( (this.getXmlValue()==castOther.getXmlValue()) || ( this.getXmlValue()!=null && castOther.getXmlValue()!=null && this.getXmlValue().equals(castOther.getXmlValue()) ) ); - } - - @Override -public int hashCode() { - int result = 17; - - result = 37 * result + ( getXmlResultId() == null ? 0 : this.getXmlResultId().hashCode() ); - result = 37 * result + ( getResultInstanceId() == null ? 0 : this.getResultInstanceId().hashCode() ); - result = 37 * result + ( getXmlValue() == null ? 0 : this.getXmlValue().hashCode() ); - return result; - } - - -} - - +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.datavo.db; +// Generated Sep 25, 2006 1:09:02 PM by Hibernate Tools 3.1.0.beta5 + + + +/** + * QtXmlResultId generated by hbm2java + */ +public class QtXmlResultId implements java.io.Serializable { + + + // Fields + + private String xmlResultId; + private Integer resultInstanceId; + private String xmlValue; + + // Constructors + + /** default constructor */ + public QtXmlResultId() { + } + + /** full constructor */ + public QtXmlResultId(String xmlResultId, Integer resultInstanceId, String xmlValue) { + this.xmlResultId = xmlResultId; + this.resultInstanceId = resultInstanceId; + this.xmlValue = xmlValue; + } + + + // Property accessors + public String getXmlResultId() { + return this.xmlResultId; + } + + public void setXmlResultId(String xmlResultId) { + this.xmlResultId = xmlResultId; + } + public Integer getResultInstanceId() { + return this.resultInstanceId; + } + + public void setResultInstanceId(Integer resultInstanceId) { + this.resultInstanceId = resultInstanceId; + } + public String getXmlValue() { + return this.xmlValue; + } + + public void setXmlValue(String xmlValue) { + this.xmlValue = xmlValue; + } + + + @Override +public boolean equals(Object other) { + if ( (this == other ) ) return true; + if ( (other == null ) ) return false; + if ( !(other instanceof QtXmlResultId) ) return false; + QtXmlResultId castOther = ( QtXmlResultId ) other; + + return ( (this.getXmlResultId()==castOther.getXmlResultId()) || ( this.getXmlResultId()!=null && castOther.getXmlResultId()!=null && this.getXmlResultId().equals(castOther.getXmlResultId()) ) ) + && ( (this.getResultInstanceId()==castOther.getResultInstanceId()) || ( this.getResultInstanceId()!=null && castOther.getResultInstanceId()!=null && this.getResultInstanceId().equals(castOther.getResultInstanceId()) ) ) + && ( (this.getXmlValue()==castOther.getXmlValue()) || ( this.getXmlValue()!=null && castOther.getXmlValue()!=null && this.getXmlValue().equals(castOther.getXmlValue()) ) ); + } + + @Override +public int hashCode() { + int result = 17; + + result = 37 * result + ( getXmlResultId() == null ? 0 : this.getXmlResultId().hashCode() ); + result = 37 * result + ( getResultInstanceId() == null ? 0 : this.getResultInstanceId().hashCode() ); + result = 37 * result + ( getXmlValue() == null ? 0 : this.getXmlValue().hashCode() ); + return result; + } + + +} + + diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/StatusEnum.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/StatusEnum.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/StatusEnum.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/StatusEnum.java index 4af46d48..f920dd30 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/datavo/db/StatusEnum.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/datavo/db/StatusEnum.java @@ -1,15 +1,15 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.datavo.db; - -public enum StatusEnum { - - FILLER, QUEUED, PROCESSING, FINISHED, ERROR, INCOMPLETE, COMPLETED; - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.datavo.db; + +public enum StatusEnum { + + FILLER, QUEUED, PROCESSING, FINISHED, ERROR, INCOMPLETE, COMPLETED; + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/DbLookupReqHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/DbLookupReqHandler.java similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/DbLookupReqHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/DbLookupReqHandler.java index 6a3da162..8f92f805 100644 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/DbLookupReqHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/DbLookupReqHandler.java @@ -1,69 +1,69 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Wayne Chan - */ -package edu.harvard.i2b2.crc.delegate; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.crc.dao.DblookupDao; -import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; -import edu.harvard.i2b2.crc.loader.delegate.pm.PMResponseMessage; -import edu.harvard.i2b2.crc.loader.delegate.pm.PMServiceDriver; -import edu.harvard.i2b2.crc.datavo.pm.ConfigureType; -import edu.harvard.i2b2.crc.datavo.pm.GetUserConfigurationType; -import org.apache.axis2.AxisFault; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Top level class to process the request. There will be separate request handler - * class for each request type. The main processing of for the request will be - * done inside execute function - * - */ -public abstract class DbLookupReqHandler { - protected final Log log = LogFactory.getLog(getClass()); - protected static Log logesapi = LogFactory.getLog(DbLookupReqHandler.class); - - /** - * Function to perform operation on the given request - * - * @return response xml message - */ - public abstract String execute() throws I2B2Exception; - - public boolean isAdmin(MessageHeaderType header) { - try { - GetUserConfigurationType userConfigType = new GetUserConfigurationType(); - PMServiceDriver pmSrvDrvr = new PMServiceDriver(); - String response = pmSrvDrvr.getRoles(userConfigType, header); - logesapi.debug(response); - PMResponseMessage msg = new PMResponseMessage(); - StatusType procStatus = msg.processResult(response); - if(procStatus.getType().equals("ERROR")) return false; - ConfigureType pmConfigure = msg.readUserInfo(); - if (pmConfigure.getUser().isIsAdmin()) return true; - } catch (AxisFault e) { - log.error("Can't connect to PM service"); - } catch (I2B2Exception e) { - log.error("Problem processing PM service address"); - } catch (Exception e) { - log.error("General PM processing problem: "+ e.getMessage()); - } - return false; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Wayne Chan + */ +package edu.harvard.i2b2.crc.delegate; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.crc.dao.DblookupDao; +import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; +import edu.harvard.i2b2.crc.loader.delegate.pm.PMResponseMessage; +import edu.harvard.i2b2.crc.loader.delegate.pm.PMServiceDriver; +import edu.harvard.i2b2.crc.datavo.pm.ConfigureType; +import edu.harvard.i2b2.crc.datavo.pm.GetUserConfigurationType; +import org.apache.axis2.AxisFault; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +/** + * Top level class to process the request. There will be separate request handler + * class for each request type. The main processing of for the request will be + * done inside execute function + * + */ +public abstract class DbLookupReqHandler { + protected final Log log = LogFactory.getLog(getClass()); + protected static Log logesapi = LogFactory.getLog(DbLookupReqHandler.class); + + /** + * Function to perform operation on the given request + * + * @return response xml message + */ + public abstract String execute() throws I2B2Exception; + + public boolean isAdmin(MessageHeaderType header) { + try { + GetUserConfigurationType userConfigType = new GetUserConfigurationType(); + PMServiceDriver pmSrvDrvr = new PMServiceDriver(); + String response = pmSrvDrvr.getRoles(userConfigType, header); + logesapi.debug(response); + PMResponseMessage msg = new PMResponseMessage(); + StatusType procStatus = msg.processResult(response); + if(procStatus.getType().equals("ERROR")) return false; + ConfigureType pmConfigure = msg.readUserInfo(); + if (pmConfigure.getUser().isIsAdmin()) return true; + } catch (AxisFault e) { + log.error("Can't connect to PM service"); + } catch (I2B2Exception e) { + log.error("Problem processing PM service address"); + } catch (Exception e) { + log.error("General PM processing problem: "+ e.getMessage()); + } + return false; + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/DeleteDblookupHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/DeleteDblookupHandler.java similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/DeleteDblookupHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/DeleteDblookupHandler.java index aa242d1b..46b1aff1 100644 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/DeleteDblookupHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/DeleteDblookupHandler.java @@ -1,100 +1,100 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Wayne Chan - */ -package edu.harvard.i2b2.crc.delegate; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.dao.DblookupDao; -import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.crc.datavo.pdo.query.DeleteDblookupType; -import edu.harvard.i2b2.crc.axis2.DeleteDblookupDataMessage; -import edu.harvard.i2b2.crc.axis2.MessageFactory; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -public class DeleteDblookupHandler extends DbLookupReqHandler { - private static Log log = LogFactory.getLog(DeleteDblookupHandler.class); - private DeleteDblookupDataMessage deldblookupDataMsg = null; - private MessageHeaderType msgHdrType = null; - private DeleteDblookupType deldblookupType = null; - private DblookupDao dblookupDao = null; - private boolean isAdmin = false; - private int numDeleted = -1; - - public DeleteDblookupHandler(DeleteDblookupDataMessage requestMsg) throws I2B2Exception{ - try { - deldblookupDataMsg = requestMsg; - deldblookupType = deldblookupDataMsg.DeleteDblookupType(); - msgHdrType = deldblookupDataMsg.getMessageHeaderType(); - isAdmin = isAdmin(msgHdrType); - dblookupDao = new DblookupDao(msgHdrType); - } catch (JAXBUtilException e) { - log.error("error setting up DeleteDblookupHandler"); - throw new I2B2Exception("DeleteDblookupHandler not configured"); - } - } - - @Override - public String execute() throws I2B2Exception { - log.info(" execute()"); - MessageHeaderType msgHdr = MessageFactory.createResponseMessageHeader(msgHdrType); - ResponseMessageType responseMessageType = null; - String response = null; - if (!isAdmin) { - String accessDenied = "Access denied, user not an admin!"; - responseMessageType = MessageFactory.doBuildErrorResponse(msgHdr, accessDenied); - response = MessageFactory.convertToXMLString(responseMessageType); - log.warn(accessDenied); - return response; - } - log.info(deldblookupType.getProjectPath() + ", " + deldblookupType.getDomainId() + ", " + deldblookupType.getOwnerId()); - if (null == deldblookupType.getDomainId() || deldblookupType.getDomainId().trim().equals("") || - null == deldblookupType.getProjectPath() || deldblookupType.getProjectPath().trim().equals("") || - null == deldblookupType.getOwnerId() || deldblookupType.getOwnerId().trim().equals("")) { - String fields = "'project_path', 'domain_id', or 'owner_id' can't be missing or blank!"; - responseMessageType = MessageFactory.doBuildErrorResponse(msgHdr, fields); - response = MessageFactory.convertToXMLString(responseMessageType); - log.warn(fields); - return response; - } - try { - numDeleted = dblookupDao.deleteDblookup(deldblookupType); - } catch (I2B2DAOException e1) { - String dbError = "Database error"; - responseMessageType = MessageFactory.doBuildErrorResponse(msgHdr, dbError); - log.error(dbError); - } catch (I2B2Exception e1) { - String dbError = "Database error"; - responseMessageType = MessageFactory.doBuildErrorResponse(msgHdr, dbError); - log.error(dbError); - } - if (-1 == numDeleted) { - String dbError = "Database error"; - responseMessageType = MessageFactory.doBuildErrorResponse(msgHdr, dbError); - log.error(dbError); - } else if (0 == numDeleted) { - response = "no dblookup row was deleted (could be due to no target row found)!"; - log.warn(response); - responseMessageType = MessageFactory.createNonStandardResponse(msgHdr, response); - } else { - log.info(numDeleted + " row deleted"); - responseMessageType = MessageFactory.createBuildResponse(msgHdr); - } - response = MessageFactory.convertToXMLString(responseMessageType); - return response; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Wayne Chan + */ +package edu.harvard.i2b2.crc.delegate; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.dao.DblookupDao; +import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.crc.datavo.pdo.query.DeleteDblookupType; +import edu.harvard.i2b2.crc.axis2.DeleteDblookupDataMessage; +import edu.harvard.i2b2.crc.axis2.MessageFactory; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +public class DeleteDblookupHandler extends DbLookupReqHandler { + private static Log log = LogFactory.getLog(DeleteDblookupHandler.class); + private DeleteDblookupDataMessage deldblookupDataMsg = null; + private MessageHeaderType msgHdrType = null; + private DeleteDblookupType deldblookupType = null; + private DblookupDao dblookupDao = null; + private boolean isAdmin = false; + private int numDeleted = -1; + + public DeleteDblookupHandler(DeleteDblookupDataMessage requestMsg) throws I2B2Exception{ + try { + deldblookupDataMsg = requestMsg; + deldblookupType = deldblookupDataMsg.DeleteDblookupType(); + msgHdrType = deldblookupDataMsg.getMessageHeaderType(); + isAdmin = isAdmin(msgHdrType); + dblookupDao = new DblookupDao(msgHdrType); + } catch (JAXBUtilException e) { + log.error("error setting up DeleteDblookupHandler"); + throw new I2B2Exception("DeleteDblookupHandler not configured"); + } + } + + @Override + public String execute() throws I2B2Exception { + log.info(" execute()"); + MessageHeaderType msgHdr = MessageFactory.createResponseMessageHeader(msgHdrType); + ResponseMessageType responseMessageType = null; + String response = null; + if (!isAdmin) { + String accessDenied = "Access denied, user not an admin!"; + responseMessageType = MessageFactory.doBuildErrorResponse(msgHdr, accessDenied); + response = MessageFactory.convertToXMLString(responseMessageType); + log.warn(accessDenied); + return response; + } + log.info(deldblookupType.getProjectPath() + ", " + deldblookupType.getDomainId() + ", " + deldblookupType.getOwnerId()); + if (null == deldblookupType.getDomainId() || deldblookupType.getDomainId().trim().equals("") || + null == deldblookupType.getProjectPath() || deldblookupType.getProjectPath().trim().equals("") || + null == deldblookupType.getOwnerId() || deldblookupType.getOwnerId().trim().equals("")) { + String fields = "'project_path', 'domain_id', or 'owner_id' can't be missing or blank!"; + responseMessageType = MessageFactory.doBuildErrorResponse(msgHdr, fields); + response = MessageFactory.convertToXMLString(responseMessageType); + log.warn(fields); + return response; + } + try { + numDeleted = dblookupDao.deleteDblookup(deldblookupType); + } catch (I2B2DAOException e1) { + String dbError = "Database error"; + responseMessageType = MessageFactory.doBuildErrorResponse(msgHdr, dbError); + log.error(dbError); + } catch (I2B2Exception e1) { + String dbError = "Database error"; + responseMessageType = MessageFactory.doBuildErrorResponse(msgHdr, dbError); + log.error(dbError); + } + if (-1 == numDeleted) { + String dbError = "Database error"; + responseMessageType = MessageFactory.doBuildErrorResponse(msgHdr, dbError); + log.error(dbError); + } else if (0 == numDeleted) { + response = "no dblookup row was deleted (could be due to no target row found)!"; + log.warn(response); + responseMessageType = MessageFactory.createNonStandardResponse(msgHdr, response); + } else { + log.info(numDeleted + " row deleted"); + responseMessageType = MessageFactory.createBuildResponse(msgHdr); + } + response = MessageFactory.convertToXMLString(responseMessageType); + return response; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/GetAllDblookupsHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/GetAllDblookupsHandler.java similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/GetAllDblookupsHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/GetAllDblookupsHandler.java index d339aada..0991f14c 100644 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/GetAllDblookupsHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/GetAllDblookupsHandler.java @@ -1,97 +1,97 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Wayne Chan - */ -package edu.harvard.i2b2.crc.delegate; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.axis2.MessageFactory; -import edu.harvard.i2b2.crc.axis2.GetAllDblookupsDataMessage; -import edu.harvard.i2b2.crc.dao.DblookupDao; -import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.crc.datavo.pdo.query.DblookupType; -import edu.harvard.i2b2.crc.datavo.pdo.query.DblookupsType; -import java.util.Iterator; -import java.util.List; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -public class GetAllDblookupsHandler extends DbLookupReqHandler { - private static Log log = LogFactory.getLog(GetAllDblookupsHandler.class); - private GetAllDblookupsDataMessage dblookupsDataMsg = null; - private MessageHeaderType msgHdrType = null; - private DblookupDao dblookupDao = null; - private boolean isAdmin = false; - - public GetAllDblookupsHandler(GetAllDblookupsDataMessage requestMsg) throws I2B2Exception{ - try { - dblookupsDataMsg = requestMsg; - msgHdrType = dblookupsDataMsg.getMessageHeaderType(); - isAdmin = isAdmin(msgHdrType); - dblookupDao = new DblookupDao(msgHdrType); - } catch (JAXBUtilException e) { - log.error("error setting up GetAllDblookupsHandler"); - throw new I2B2Exception("GetAllDblookupsHandler not configured"); - } - } - - @Override - public String execute() throws I2B2Exception { - //log.info(" execute()"); - MessageHeaderType msgHdr = MessageFactory.createResponseMessageHeader(msgHdrType); - ResponseMessageType responseMessageType = null; - if (!isAdmin) { - String response = null; - String accessDenied = "Access denied, user not an admin!"; - responseMessageType = MessageFactory.doBuildErrorResponse(msgHdr, accessDenied); - response = MessageFactory.convertToXMLString(responseMessageType); - log.warn(accessDenied); - return response; - } - DblookupsType dblus = new DblookupsType(); - List response = null; - try { - response = dblookupDao.findDblookups(); - } catch (I2B2DAOException e1) { - String dbError = "Database error"; - responseMessageType = MessageFactory.doBuildErrorResponse(msgHdr, dbError); - log.error(dbError); - } - if (responseMessageType == null) { // no db error - if (null == response) { // but response is empty - String emptyResult = "query results are empty"; - log.warn(emptyResult); - responseMessageType = MessageFactory.doBuildErrorResponse(msgHdr, emptyResult); - } else { - Iterator it = response.iterator(); - if (it.hasNext()) { - do { - DblookupType dblu = it.next(); - dblus.getDblookup().add(dblu); - } while (it.hasNext()); - responseMessageType = MessageFactory.createBuildResponse(msgHdr, dblus); - } else { - String msg = "No dblookup row was found!"; - log.info(msg); - responseMessageType = MessageFactory.createNonStandardResponse(msgHdr, msg); - } - } - } - String responseVdo = null; - responseVdo = MessageFactory.convertToXMLString(responseMessageType); - return responseVdo; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Wayne Chan + */ +package edu.harvard.i2b2.crc.delegate; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.axis2.MessageFactory; +import edu.harvard.i2b2.crc.axis2.GetAllDblookupsDataMessage; +import edu.harvard.i2b2.crc.dao.DblookupDao; +import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.crc.datavo.pdo.query.DblookupType; +import edu.harvard.i2b2.crc.datavo.pdo.query.DblookupsType; +import java.util.Iterator; +import java.util.List; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +public class GetAllDblookupsHandler extends DbLookupReqHandler { + private static Log log = LogFactory.getLog(GetAllDblookupsHandler.class); + private GetAllDblookupsDataMessage dblookupsDataMsg = null; + private MessageHeaderType msgHdrType = null; + private DblookupDao dblookupDao = null; + private boolean isAdmin = false; + + public GetAllDblookupsHandler(GetAllDblookupsDataMessage requestMsg) throws I2B2Exception{ + try { + dblookupsDataMsg = requestMsg; + msgHdrType = dblookupsDataMsg.getMessageHeaderType(); + isAdmin = isAdmin(msgHdrType); + dblookupDao = new DblookupDao(msgHdrType); + } catch (JAXBUtilException e) { + log.error("error setting up GetAllDblookupsHandler"); + throw new I2B2Exception("GetAllDblookupsHandler not configured"); + } + } + + @Override + public String execute() throws I2B2Exception { + //log.info(" execute()"); + MessageHeaderType msgHdr = MessageFactory.createResponseMessageHeader(msgHdrType); + ResponseMessageType responseMessageType = null; + if (!isAdmin) { + String response = null; + String accessDenied = "Access denied, user not an admin!"; + responseMessageType = MessageFactory.doBuildErrorResponse(msgHdr, accessDenied); + response = MessageFactory.convertToXMLString(responseMessageType); + log.warn(accessDenied); + return response; + } + DblookupsType dblus = new DblookupsType(); + List response = null; + try { + response = dblookupDao.findDblookups(); + } catch (I2B2DAOException e1) { + String dbError = "Database error"; + responseMessageType = MessageFactory.doBuildErrorResponse(msgHdr, dbError); + log.error(dbError); + } + if (responseMessageType == null) { // no db error + if (null == response) { // but response is empty + String emptyResult = "query results are empty"; + log.warn(emptyResult); + responseMessageType = MessageFactory.doBuildErrorResponse(msgHdr, emptyResult); + } else { + Iterator it = response.iterator(); + if (it.hasNext()) { + do { + DblookupType dblu = it.next(); + dblus.getDblookup().add(dblu); + } while (it.hasNext()); + responseMessageType = MessageFactory.createBuildResponse(msgHdr, dblus); + } else { + String msg = "No dblookup row was found!"; + log.info(msg); + responseMessageType = MessageFactory.createNonStandardResponse(msgHdr, msg); + } + } + } + String responseVdo = null; + responseVdo = MessageFactory.convertToXMLString(responseMessageType); + return responseVdo; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/GetAllJobsHandlerMaybe.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/GetAllJobsHandlerMaybe.java similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/GetAllJobsHandlerMaybe.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/GetAllJobsHandlerMaybe.java index beb9b218..7b062d50 100644 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/GetAllJobsHandlerMaybe.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/GetAllJobsHandlerMaybe.java @@ -1,112 +1,112 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Wayne Chan - */ -package edu.harvard.i2b2.crc.delegate; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.axis2.MessageFactory; -import edu.harvard.i2b2.crc.axis2.GetAllDblookupsDataMessage; -import edu.harvard.i2b2.crc.axis2.GetAllJobsDataMessage; -import edu.harvard.i2b2.crc.dao.DblookupDao; -import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; -import edu.harvard.i2b2.crc.datavo.pdo.query.DblookupType; -import edu.harvard.i2b2.crc.datavo.pdo.query.DblookupsType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.JobType; -import edu.harvard.i2b2.crc.delegate.quartz.SchedulerFactory; -import edu.harvard.i2b2.crc.delegate.quartz.SchedulerInfoBean; - -import java.util.Iterator; -import java.util.List; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -public class GetAllJobsHandlerMaybe extends JobReqHandler { - private static Log log = LogFactory.getLog(GetAllJobsHandlerMaybe.class); - private GetAllJobsDataMessage jobsDataMsg = null; - private MessageHeaderType msgHdrType = null; - private SchedulerInfoBean scheduler = null; - private boolean isAdmin = false; - private SecurityType userRequestType = null; - - public GetAllJobsHandlerMaybe(GetAllJobsDataMessage requestMsg) throws I2B2Exception{ - try { - jobsDataMsg = requestMsg; - msgHdrType = jobsDataMsg.getMessageHeaderType(); - isAdmin = isAdmin(msgHdrType); - //dblookupDao = new DblookupDao(msgHdrType); - - - } catch (Exception e) { - log.error("error setting up GetAllDblookupsHandler"); - throw new I2B2Exception("GetAllDblookupsHandler not configured"); - } - } - - @Override - public String execute() throws I2B2Exception { - //log.info(" execute()"); - MessageHeaderType msgHdr = MessageFactory.createResponseMessageHeader(msgHdrType); - ResponseMessageType responseMessageType = null; - if (!isAdmin) { - String response = null; - String accessDenied = "Access denied, user not an admin!"; - responseMessageType = MessageFactory.doBuildErrorResponse(msgHdr, accessDenied); - response = MessageFactory.convertToXMLString(responseMessageType); - log.warn(accessDenied); - return response; - } - //DblookupsType dblus = new DblookupsType(); - - - //masterResponseType = scheduler.getAllJobsScheduler(SchedulerFactory.getDefaultScheduler(), getDataSourceLookup(),userRequestType); - - List response = null; - try { - scheduler = new SchedulerInfoBean(); -// response = scheduler.getAllJobsScheduler(SchedulerFactory.getDefaultScheduler(), getDataSourceLookup(),userRequestType); - //dblookupDao.findDblookups(); - } catch ( Exception e1) { - String dbError = "Database error"; - responseMessageType = MessageFactory.doBuildErrorResponse(msgHdr, dbError); - log.error(dbError); - } - if (responseMessageType == null) { // no db error - if (null == response) { // but response is empty - String emptyResult = "query results are empty"; - log.warn(emptyResult); - responseMessageType = MessageFactory.doBuildErrorResponse(msgHdr, emptyResult); - } /* else { - Iterator it = response.iterator(); - if (it.hasNext()) { - do { - DblookupType dblu = it.next(); - dblus.getDblookup().add(dblu); - } while (it.hasNext()); - responseMessageType = MessageFactory.createBuildResponse(msgHdr, dblus); - } else { - String msg = "No dblookup row was found!"; - log.info(msg); - responseMessageType = MessageFactory.createNonStandardResponse(msgHdr, msg); - } - } */ - } - String responseVdo = null; - responseVdo = MessageFactory.convertToXMLString(responseMessageType); - return responseVdo; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Wayne Chan + */ +package edu.harvard.i2b2.crc.delegate; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.axis2.MessageFactory; +import edu.harvard.i2b2.crc.axis2.GetAllDblookupsDataMessage; +import edu.harvard.i2b2.crc.axis2.GetAllJobsDataMessage; +import edu.harvard.i2b2.crc.dao.DblookupDao; +import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; +import edu.harvard.i2b2.crc.datavo.pdo.query.DblookupType; +import edu.harvard.i2b2.crc.datavo.pdo.query.DblookupsType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.JobType; +import edu.harvard.i2b2.crc.delegate.quartz.SchedulerFactory; +import edu.harvard.i2b2.crc.delegate.quartz.SchedulerInfoBean; + +import java.util.Iterator; +import java.util.List; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +public class GetAllJobsHandlerMaybe extends JobReqHandler { + private static Log log = LogFactory.getLog(GetAllJobsHandlerMaybe.class); + private GetAllJobsDataMessage jobsDataMsg = null; + private MessageHeaderType msgHdrType = null; + private SchedulerInfoBean scheduler = null; + private boolean isAdmin = false; + private SecurityType userRequestType = null; + + public GetAllJobsHandlerMaybe(GetAllJobsDataMessage requestMsg) throws I2B2Exception{ + try { + jobsDataMsg = requestMsg; + msgHdrType = jobsDataMsg.getMessageHeaderType(); + isAdmin = isAdmin(msgHdrType); + //dblookupDao = new DblookupDao(msgHdrType); + + + } catch (Exception e) { + log.error("error setting up GetAllDblookupsHandler"); + throw new I2B2Exception("GetAllDblookupsHandler not configured"); + } + } + + @Override + public String execute() throws I2B2Exception { + //log.info(" execute()"); + MessageHeaderType msgHdr = MessageFactory.createResponseMessageHeader(msgHdrType); + ResponseMessageType responseMessageType = null; + if (!isAdmin) { + String response = null; + String accessDenied = "Access denied, user not an admin!"; + responseMessageType = MessageFactory.doBuildErrorResponse(msgHdr, accessDenied); + response = MessageFactory.convertToXMLString(responseMessageType); + log.warn(accessDenied); + return response; + } + //DblookupsType dblus = new DblookupsType(); + + + //masterResponseType = scheduler.getAllJobsScheduler(SchedulerFactory.getDefaultScheduler(), getDataSourceLookup(),userRequestType); + + List response = null; + try { + scheduler = new SchedulerInfoBean(); +// response = scheduler.getAllJobsScheduler(SchedulerFactory.getDefaultScheduler(), getDataSourceLookup(),userRequestType); + //dblookupDao.findDblookups(); + } catch ( Exception e1) { + String dbError = "Database error"; + responseMessageType = MessageFactory.doBuildErrorResponse(msgHdr, dbError); + log.error(dbError); + } + if (responseMessageType == null) { // no db error + if (null == response) { // but response is empty + String emptyResult = "query results are empty"; + log.warn(emptyResult); + responseMessageType = MessageFactory.doBuildErrorResponse(msgHdr, emptyResult); + } /* else { + Iterator it = response.iterator(); + if (it.hasNext()) { + do { + DblookupType dblu = it.next(); + dblus.getDblookup().add(dblu); + } while (it.hasNext()); + responseMessageType = MessageFactory.createBuildResponse(msgHdr, dblus); + } else { + String msg = "No dblookup row was found!"; + log.info(msg); + responseMessageType = MessageFactory.createNonStandardResponse(msgHdr, msg); + } + } */ + } + String responseVdo = null; + responseVdo = MessageFactory.convertToXMLString(responseMessageType); + return responseVdo; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/GetAllRPDOsHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/GetAllRPDOsHandler.java similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/GetAllRPDOsHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/GetAllRPDOsHandler.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/GetDblookupHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/GetDblookupHandler.java similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/GetDblookupHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/GetDblookupHandler.java index ab282a80..f1a8e454 100644 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/GetDblookupHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/GetDblookupHandler.java @@ -1,109 +1,109 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Wayne Chan - */ -package edu.harvard.i2b2.crc.delegate; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.axis2.GetDblookupDataMessage; -import edu.harvard.i2b2.crc.axis2.MessageFactory; -import edu.harvard.i2b2.crc.dao.DblookupDao; -import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.crc.datavo.pdo.query.DblookupType; -import edu.harvard.i2b2.crc.datavo.pdo.query.DblookupsType; -import edu.harvard.i2b2.crc.datavo.pdo.query.GetDblookupType; -import java.util.Iterator; -import java.util.List; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -public class GetDblookupHandler extends DbLookupReqHandler { - private static Log log = LogFactory.getLog(GetDblookupHandler.class); - private GetDblookupDataMessage getdblookupDataMsg = null; - private MessageHeaderType msgHdrType = null; - private GetDblookupType getdblookupType = null; - private DblookupDao dblookupDao = null; - private boolean isAdmin = false; - - public GetDblookupHandler(GetDblookupDataMessage requestMsg) throws I2B2Exception{ - try { - getdblookupDataMsg = requestMsg; - getdblookupType = getdblookupDataMsg.getDblookupType(); - msgHdrType = getdblookupDataMsg.getMessageHeaderType(); - isAdmin = isAdmin(msgHdrType); - dblookupDao = new DblookupDao(msgHdrType); - } catch (JAXBUtilException e) { - log.error("error setting up GetDblookupHandler"); - throw new I2B2Exception("GetDblookupHandler not configured"); - } - } - - @Override - public String execute() throws I2B2Exception { - //log.info(" execute()"); - MessageHeaderType msgHdr = MessageFactory.createResponseMessageHeader(msgHdrType); - ResponseMessageType responseMessageType = null; - if (!isAdmin) { - String response = null; - String accessDenied = "Access denied, user not an admin!"; - responseMessageType = MessageFactory.doBuildErrorResponse(msgHdr, accessDenied); - response = MessageFactory.convertToXMLString(responseMessageType); - log.warn(accessDenied); - return response; - } - log.info(getdblookupType.getField() + ", " + getdblookupType.getValue()); - if (null == getdblookupType.getField() || getdblookupType.getField().trim().equals("") || - null == getdblookupType.getValue() || getdblookupType.getValue().trim().equals("")) { - String fields = "'field' can't be blank, or 'value' can't be missing or blank!"; //missing 'field' implies 'project_path - responseMessageType = MessageFactory.doBuildErrorResponse(msgHdr, fields); - String response = MessageFactory.convertToXMLString(responseMessageType); - log.warn(fields); - return response; - } - DblookupsType dblus = new DblookupsType(); - List response = null; - try { - response = dblookupDao.getDblookup(getdblookupType.getField(), getdblookupType.getValue()); - } catch (I2B2DAOException e1) { - String dbError = "Database error"; - responseMessageType = MessageFactory.doBuildErrorResponse(msgHdr, dbError); - log.error(dbError); - } - if (responseMessageType == null) { // no db error - if (null == response) { // but response is empty - String emptyResult = "query results are empty"; - log.warn(emptyResult); - responseMessageType = MessageFactory.doBuildErrorResponse(msgHdr, emptyResult); - } else { - Iterator it = response.iterator(); - if (it.hasNext()) { - do { - DblookupType dblu = it.next(); - dblus.getDblookup().add(dblu); - } while (it.hasNext()); - responseMessageType = MessageFactory.createBuildResponse(msgHdr, dblus); - } else { - String msg = "No dblookup row was found!"; - log.info(msg); - responseMessageType = MessageFactory.createNonStandardResponse(msgHdr, msg); - } - } - } - String responseVdo = null; - responseVdo = MessageFactory.convertToXMLString(responseMessageType); - return responseVdo; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Wayne Chan + */ +package edu.harvard.i2b2.crc.delegate; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.axis2.GetDblookupDataMessage; +import edu.harvard.i2b2.crc.axis2.MessageFactory; +import edu.harvard.i2b2.crc.dao.DblookupDao; +import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.crc.datavo.pdo.query.DblookupType; +import edu.harvard.i2b2.crc.datavo.pdo.query.DblookupsType; +import edu.harvard.i2b2.crc.datavo.pdo.query.GetDblookupType; +import java.util.Iterator; +import java.util.List; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +public class GetDblookupHandler extends DbLookupReqHandler { + private static Log log = LogFactory.getLog(GetDblookupHandler.class); + private GetDblookupDataMessage getdblookupDataMsg = null; + private MessageHeaderType msgHdrType = null; + private GetDblookupType getdblookupType = null; + private DblookupDao dblookupDao = null; + private boolean isAdmin = false; + + public GetDblookupHandler(GetDblookupDataMessage requestMsg) throws I2B2Exception{ + try { + getdblookupDataMsg = requestMsg; + getdblookupType = getdblookupDataMsg.getDblookupType(); + msgHdrType = getdblookupDataMsg.getMessageHeaderType(); + isAdmin = isAdmin(msgHdrType); + dblookupDao = new DblookupDao(msgHdrType); + } catch (JAXBUtilException e) { + log.error("error setting up GetDblookupHandler"); + throw new I2B2Exception("GetDblookupHandler not configured"); + } + } + + @Override + public String execute() throws I2B2Exception { + //log.info(" execute()"); + MessageHeaderType msgHdr = MessageFactory.createResponseMessageHeader(msgHdrType); + ResponseMessageType responseMessageType = null; + if (!isAdmin) { + String response = null; + String accessDenied = "Access denied, user not an admin!"; + responseMessageType = MessageFactory.doBuildErrorResponse(msgHdr, accessDenied); + response = MessageFactory.convertToXMLString(responseMessageType); + log.warn(accessDenied); + return response; + } + log.info(getdblookupType.getField() + ", " + getdblookupType.getValue()); + if (null == getdblookupType.getField() || getdblookupType.getField().trim().equals("") || + null == getdblookupType.getValue() || getdblookupType.getValue().trim().equals("")) { + String fields = "'field' can't be blank, or 'value' can't be missing or blank!"; //missing 'field' implies 'project_path + responseMessageType = MessageFactory.doBuildErrorResponse(msgHdr, fields); + String response = MessageFactory.convertToXMLString(responseMessageType); + log.warn(fields); + return response; + } + DblookupsType dblus = new DblookupsType(); + List response = null; + try { + response = dblookupDao.getDblookup(getdblookupType.getField(), getdblookupType.getValue()); + } catch (I2B2DAOException e1) { + String dbError = "Database error"; + responseMessageType = MessageFactory.doBuildErrorResponse(msgHdr, dbError); + log.error(dbError); + } + if (responseMessageType == null) { // no db error + if (null == response) { // but response is empty + String emptyResult = "query results are empty"; + log.warn(emptyResult); + responseMessageType = MessageFactory.doBuildErrorResponse(msgHdr, emptyResult); + } else { + Iterator it = response.iterator(); + if (it.hasNext()) { + do { + DblookupType dblu = it.next(); + dblus.getDblookup().add(dblu); + } while (it.hasNext()); + responseMessageType = MessageFactory.createBuildResponse(msgHdr, dblus); + } else { + String msg = "No dblookup row was found!"; + log.info(msg); + responseMessageType = MessageFactory.createNonStandardResponse(msgHdr, msg); + } + } + } + String responseVdo = null; + responseVdo = MessageFactory.convertToXMLString(responseMessageType); + return responseVdo; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/GetRPDODeleteHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/GetRPDODeleteHandler.java similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/GetRPDODeleteHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/GetRPDODeleteHandler.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/GetRPDOHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/GetRPDOHandler.java similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/GetRPDOHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/GetRPDOHandler.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/GetRPDORenameHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/GetRPDORenameHandler.java similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/GetRPDORenameHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/GetRPDORenameHandler.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/GetRPDOSetHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/GetRPDOSetHandler.java similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/GetRPDOSetHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/GetRPDOSetHandler.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/JobReqHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/JobReqHandler.java similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/JobReqHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/JobReqHandler.java index bb14983c..3c07ba9f 100644 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/JobReqHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/JobReqHandler.java @@ -1,247 +1,247 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Wayne Chan - */ -package edu.harvard.i2b2.crc.delegate; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.dao.DblookupDao; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.i2b2message.ApplicationType; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2message.InfoType; -import edu.harvard.i2b2.crc.datavo.i2b2message.MessageControlIdType; -import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.PollingUrlType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResultStatusType; -import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; -import edu.harvard.i2b2.crc.loader.delegate.pm.PMResponseMessage; -import edu.harvard.i2b2.crc.loader.delegate.pm.PMServiceDriver; -import edu.harvard.i2b2.crc.datavo.pm.ConfigureType; -import edu.harvard.i2b2.crc.datavo.pm.GetUserConfigurationType; - -import java.io.StringWriter; - -import jakarta.xml.bind.JAXBElement; - -import org.apache.axis2.AxisFault; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Top level class to process the request. There will be separate request handler - * class for each request type. The main processing of for the request will be - * done inside execute function - * - */ -public abstract class JobReqHandler { - protected final Log log = LogFactory.getLog(getClass()); - protected static Log logesapi = LogFactory.getLog(JobReqHandler.class); - - protected DataSourceLookup dataSourceLookup = null; - - /** - * Function to perform operation on the given request - * - * @return response xml message - */ - public abstract String execute() throws I2B2Exception; - - public boolean isAdmin(MessageHeaderType header) { - try { - GetUserConfigurationType userConfigType = new GetUserConfigurationType(); - PMServiceDriver pmSrvDrvr = new PMServiceDriver(); - String response = pmSrvDrvr.getRoles(userConfigType, header); - logesapi.debug(response); - PMResponseMessage msg = new PMResponseMessage(); - StatusType procStatus = msg.processResult(response); - if(procStatus.getType().equals("ERROR")) return false; - ConfigureType pmConfigure = msg.readUserInfo(); - if (pmConfigure.getUser().isIsAdmin()) return true; - } catch (AxisFault e) { - log.error("Can't connect to PM service"); - } catch (I2B2Exception e) { - log.error("Problem processing PM service address"); - } catch (Exception e) { - log.error("General PM processing problem: "+ e.getMessage()); - } - return false; - } - - /** - * Class to fetch specific request message from i2b2 message xml - * - * @param requestXml - * @param classname - * @return object which is of type classname - * @throws JAXBUtilException - */ - protected Object getRequestType(String requestXml, Class classname) - throws JAXBUtilException { - Object returnObject = null; - - JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); - JAXBElement jaxbElement = jaxbUtil.unMashallFromString(requestXml); - RequestMessageType requestMessageType = (RequestMessageType) jaxbElement - .getValue(); - BodyType bodyType = requestMessageType.getMessageBody(); - JAXBUnWrapHelper unWrapHelper = new JAXBUnWrapHelper(); - // get request header type - returnObject = unWrapHelper.getObjectByClass(bodyType.getAny(), - classname); - - return returnObject; - } - - /** - * Function to build response message type using given bodytype and request - * xml - * - * @param requestXml - * @param bodyType - * @return i2b2 response message xml - * @throws JAXBUtilException - */ - protected String buildResponseMessage(String requestXml, BodyType bodyType) - throws JAXBUtilException { - JAXBUtil util = CRCJAXBUtil.getJAXBUtil(); - RequestMessageType requestMsgType = getI2B2RequestMessageType(requestXml); - MessageHeaderType messageHeader = requestMsgType.getMessageHeader(); - - // reverse sending and receiving app - ApplicationType sendingApp = messageHeader.getSendingApplication(); - ApplicationType receiveApp = messageHeader.getReceivingApplication(); - messageHeader.setSendingApplication(receiveApp); - messageHeader.setReceivingApplication(sendingApp); - - // set instance num - MessageControlIdType messageControlIdType = messageHeader - .getMessageControlId(); - - if (messageControlIdType != null) { - messageControlIdType.setInstanceNum(1); - } - - StatusType statusType = new StatusType(); - statusType.setType("DONE"); - - // :TODO statusType.setValue(sessionId); - PollingUrlType pollingType = new PollingUrlType(); - pollingType.setIntervalMs(100); - - // :TODO value come from property file - // pollingType.setValue( - // "http://host:port/QueryProcessor/getResult"); - ResultStatusType resultStatusType = new ResultStatusType(); - resultStatusType.setStatus(statusType); - resultStatusType.setPollingUrl(pollingType); - - InfoType infoType = new InfoType(); - // :TODO value come from property file - //infoType.setUrl("http://host:port/QueryProcessor/getStatus"); - infoType.setValue("Log information"); - - ResponseHeaderType responseHeader = new ResponseHeaderType(); - responseHeader.setResultStatus(resultStatusType); - responseHeader.setInfo(infoType); - - ResponseMessageType responseMessageType = new ResponseMessageType(); - responseMessageType.setMessageHeader(messageHeader); - responseMessageType.setResponseHeader(responseHeader); - responseMessageType.setMessageBody(bodyType); - - edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory(); - StringWriter strWriter = new StringWriter(); - util.marshaller(of.createResponse(responseMessageType), strWriter); - - return strWriter.toString(); - } - - /** - * Function to unmarshall i2b2 request message type - * - * @param requestXml - * @return RequestMessageType - * @throws JAXBUtilException - */ - protected RequestMessageType getI2B2RequestMessageType(String requestXml) - throws JAXBUtilException { - JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); - JAXBElement jaxbElement = jaxbUtil.unMashallFromString(requestXml); - RequestMessageType requestMessageType = (RequestMessageType) jaxbElement - .getValue(); - - return requestMessageType; - } - - /** - * Function marshall i2b2 response message type - * - * @param responseMessageType - * @return - */ - protected String getResponseString(ResponseMessageType responseMessageType) { - StringWriter strWriter = new StringWriter(); - - try { - edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory(); - JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); - jaxbUtil.marshaller(of.createResponse(responseMessageType), - strWriter); - } catch (JAXBUtilException e) { - log.error("Error while generating response message" - + e.getMessage()); - } - - return strWriter.toString(); - } - - protected edu.harvard.i2b2.crc.datavo.setfinder.query.StatusType buildCRCStausType( - String statusType, String message) { - edu.harvard.i2b2.crc.datavo.setfinder.query.StatusType st = new edu.harvard.i2b2.crc.datavo.setfinder.query.StatusType(); - edu.harvard.i2b2.crc.datavo.setfinder.query.StatusType.Condition condition = new edu.harvard.i2b2.crc.datavo.setfinder.query.StatusType.Condition(); - condition.setType(statusType); - condition.setValue(message); - st.getCondition().add(condition); - return st; - } - - protected void setDataSourceLookup(String requestXml) - throws JAXBUtilException { - RequestMessageType reqMessage = getI2B2RequestMessageType(requestXml); - String projectId = reqMessage.getMessageHeader().getProjectId(); - String domainId = reqMessage.getMessageHeader().getSecurity() - .getDomain(); - String userId = reqMessage.getMessageHeader().getSecurity() - .getUsername(); - dataSourceLookup = new DataSourceLookup(); - dataSourceLookup.setProjectPath(projectId); - dataSourceLookup.setDomainId(domainId); - dataSourceLookup.setOwnerId(userId); - - } - - protected DataSourceLookup getDataSourceLookup() { - return dataSourceLookup; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Wayne Chan + */ +package edu.harvard.i2b2.crc.delegate; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.dao.DblookupDao; +import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.i2b2message.ApplicationType; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2message.InfoType; +import edu.harvard.i2b2.crc.datavo.i2b2message.MessageControlIdType; +import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.PollingUrlType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResultStatusType; +import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; +import edu.harvard.i2b2.crc.loader.delegate.pm.PMResponseMessage; +import edu.harvard.i2b2.crc.loader.delegate.pm.PMServiceDriver; +import edu.harvard.i2b2.crc.datavo.pm.ConfigureType; +import edu.harvard.i2b2.crc.datavo.pm.GetUserConfigurationType; + +import java.io.StringWriter; + +import jakarta.xml.bind.JAXBElement; + +import org.apache.axis2.AxisFault; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +/** + * Top level class to process the request. There will be separate request handler + * class for each request type. The main processing of for the request will be + * done inside execute function + * + */ +public abstract class JobReqHandler { + protected final Log log = LogFactory.getLog(getClass()); + protected static Log logesapi = LogFactory.getLog(JobReqHandler.class); + + protected DataSourceLookup dataSourceLookup = null; + + /** + * Function to perform operation on the given request + * + * @return response xml message + */ + public abstract String execute() throws I2B2Exception; + + public boolean isAdmin(MessageHeaderType header) { + try { + GetUserConfigurationType userConfigType = new GetUserConfigurationType(); + PMServiceDriver pmSrvDrvr = new PMServiceDriver(); + String response = pmSrvDrvr.getRoles(userConfigType, header); + logesapi.debug(response); + PMResponseMessage msg = new PMResponseMessage(); + StatusType procStatus = msg.processResult(response); + if(procStatus.getType().equals("ERROR")) return false; + ConfigureType pmConfigure = msg.readUserInfo(); + if (pmConfigure.getUser().isIsAdmin()) return true; + } catch (AxisFault e) { + log.error("Can't connect to PM service"); + } catch (I2B2Exception e) { + log.error("Problem processing PM service address"); + } catch (Exception e) { + log.error("General PM processing problem: "+ e.getMessage()); + } + return false; + } + + /** + * Class to fetch specific request message from i2b2 message xml + * + * @param requestXml + * @param classname + * @return object which is of type classname + * @throws JAXBUtilException + */ + protected Object getRequestType(String requestXml, Class classname) + throws JAXBUtilException { + Object returnObject = null; + + JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); + JAXBElement jaxbElement = jaxbUtil.unMashallFromString(requestXml); + RequestMessageType requestMessageType = (RequestMessageType) jaxbElement + .getValue(); + BodyType bodyType = requestMessageType.getMessageBody(); + JAXBUnWrapHelper unWrapHelper = new JAXBUnWrapHelper(); + // get request header type + returnObject = unWrapHelper.getObjectByClass(bodyType.getAny(), + classname); + + return returnObject; + } + + /** + * Function to build response message type using given bodytype and request + * xml + * + * @param requestXml + * @param bodyType + * @return i2b2 response message xml + * @throws JAXBUtilException + */ + protected String buildResponseMessage(String requestXml, BodyType bodyType) + throws JAXBUtilException { + JAXBUtil util = CRCJAXBUtil.getJAXBUtil(); + RequestMessageType requestMsgType = getI2B2RequestMessageType(requestXml); + MessageHeaderType messageHeader = requestMsgType.getMessageHeader(); + + // reverse sending and receiving app + ApplicationType sendingApp = messageHeader.getSendingApplication(); + ApplicationType receiveApp = messageHeader.getReceivingApplication(); + messageHeader.setSendingApplication(receiveApp); + messageHeader.setReceivingApplication(sendingApp); + + // set instance num + MessageControlIdType messageControlIdType = messageHeader + .getMessageControlId(); + + if (messageControlIdType != null) { + messageControlIdType.setInstanceNum(1); + } + + StatusType statusType = new StatusType(); + statusType.setType("DONE"); + + // :TODO statusType.setValue(sessionId); + PollingUrlType pollingType = new PollingUrlType(); + pollingType.setIntervalMs(100); + + // :TODO value come from property file + // pollingType.setValue( + // "http://host:port/QueryProcessor/getResult"); + ResultStatusType resultStatusType = new ResultStatusType(); + resultStatusType.setStatus(statusType); + resultStatusType.setPollingUrl(pollingType); + + InfoType infoType = new InfoType(); + // :TODO value come from property file + //infoType.setUrl("http://host:port/QueryProcessor/getStatus"); + infoType.setValue("Log information"); + + ResponseHeaderType responseHeader = new ResponseHeaderType(); + responseHeader.setResultStatus(resultStatusType); + responseHeader.setInfo(infoType); + + ResponseMessageType responseMessageType = new ResponseMessageType(); + responseMessageType.setMessageHeader(messageHeader); + responseMessageType.setResponseHeader(responseHeader); + responseMessageType.setMessageBody(bodyType); + + edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory(); + StringWriter strWriter = new StringWriter(); + util.marshaller(of.createResponse(responseMessageType), strWriter); + + return strWriter.toString(); + } + + /** + * Function to unmarshall i2b2 request message type + * + * @param requestXml + * @return RequestMessageType + * @throws JAXBUtilException + */ + protected RequestMessageType getI2B2RequestMessageType(String requestXml) + throws JAXBUtilException { + JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); + JAXBElement jaxbElement = jaxbUtil.unMashallFromString(requestXml); + RequestMessageType requestMessageType = (RequestMessageType) jaxbElement + .getValue(); + + return requestMessageType; + } + + /** + * Function marshall i2b2 response message type + * + * @param responseMessageType + * @return + */ + protected String getResponseString(ResponseMessageType responseMessageType) { + StringWriter strWriter = new StringWriter(); + + try { + edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory(); + JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); + jaxbUtil.marshaller(of.createResponse(responseMessageType), + strWriter); + } catch (JAXBUtilException e) { + log.error("Error while generating response message" + + e.getMessage()); + } + + return strWriter.toString(); + } + + protected edu.harvard.i2b2.crc.datavo.setfinder.query.StatusType buildCRCStausType( + String statusType, String message) { + edu.harvard.i2b2.crc.datavo.setfinder.query.StatusType st = new edu.harvard.i2b2.crc.datavo.setfinder.query.StatusType(); + edu.harvard.i2b2.crc.datavo.setfinder.query.StatusType.Condition condition = new edu.harvard.i2b2.crc.datavo.setfinder.query.StatusType.Condition(); + condition.setType(statusType); + condition.setValue(message); + st.getCondition().add(condition); + return st; + } + + protected void setDataSourceLookup(String requestXml) + throws JAXBUtilException { + RequestMessageType reqMessage = getI2B2RequestMessageType(requestXml); + String projectId = reqMessage.getMessageHeader().getProjectId(); + String domainId = reqMessage.getMessageHeader().getSecurity() + .getDomain(); + String userId = reqMessage.getMessageHeader().getSecurity() + .getUsername(); + dataSourceLookup = new DataSourceLookup(); + dataSourceLookup.setProjectPath(projectId); + dataSourceLookup.setDomainId(domainId); + dataSourceLookup.setOwnerId(userId); + + } + + protected DataSourceLookup getDataSourceLookup() { + return dataSourceLookup; + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/QTBreakdownHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/QTBreakdownHandler.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/QTBreakdownHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/QTBreakdownHandler.java index 1ba0f78c..35105ead --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/QTBreakdownHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/QTBreakdownHandler.java @@ -1,97 +1,97 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.delegate; - - -import edu.harvard.i2b2.crc.datavo.setfinder.query.CrcXmlResultResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionRequestType; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; -import edu.harvard.i2b2.crc.delegate.RequestHandler; -import edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate; -import edu.harvard.i2b2.crc.ejb.QueryInfoBean; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - - -/** - * GetObservationFactFromPrimaryKeyHandler class. - * $Id: GetObservationFactFromPrimaryKeyHandler.java,v 1.8 2008/07/21 19:56:56 rk903 Exp $ - * @author rkuttan - */ -public class QTBreakdownHandler extends RequestHandler { - private QueryDefinitionRequestType getRequestMessageType = - null; - private SecurityType userRequestType = null; - - - /** - * Constuctor which accepts i2b2 request message xml - * @param requestXml - * @throws I2B2Exception - */ - public QTBreakdownHandler(String requestXml) - throws I2B2Exception { - try { - this.getRequestMessageType = (QueryDefinitionRequestType) this.getRequestType(requestXml, - QueryDefinitionRequestType.class); - RequestMessageType requestMsg = getI2B2RequestMessageType( requestXml); - this.userRequestType = requestMsg.getMessageHeader() - .getSecurity(); - this.setDataSourceLookup(requestXml); - } catch (JAXBUtilException jaxbUtilEx) { - throw new I2B2Exception("Error ", jaxbUtilEx); - } - } - - /** - * Perform operation for the given request and - * return response - */ - @Override - public BodyType execute() throws I2B2Exception { - // call ejb and pass input object - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - String responseString = null; - BodyType bodyType = new BodyType(); - CrcXmlResultResponseType masterResponseType = null; - try { - long initialTime = System.currentTimeMillis(); - // masterResponseType = queryInfoLocal.getQueryMasterListFromUserId(getDataSourceLookup(),userRequestType); - QueryInfoBean query = new QueryInfoBean(); - - masterResponseType = query.getQTBreakdownForAdmin(getDataSourceLookup(),userRequestType, getRequestMessageType.getResultOutputList()); - long finalTime = System.currentTimeMillis(); - long diffTimeMill = finalTime - initialTime; - long diffTime = diffTimeMill / 1000; - log.debug(" EJB Diff mill =" + diffTimeMill + " diffTime =" + - diffTime); - masterResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.DONE_TYPE, "DONE")); - } catch (Exception e) { - log.debug(e.getMessage()); - masterResponseType = new CrcXmlResultResponseType(); - masterResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.ERROR_TYPE, e.getMessage())); - } finally { - edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); - bodyType.getAny().add(of.createResponse(masterResponseType)); - } - - return bodyType; - } -} - - +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.delegate; + + +import edu.harvard.i2b2.crc.datavo.setfinder.query.CrcXmlResultResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionRequestType; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; +import edu.harvard.i2b2.crc.delegate.RequestHandler; +import edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate; +import edu.harvard.i2b2.crc.ejb.QueryInfoBean; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + + +/** + * GetObservationFactFromPrimaryKeyHandler class. + * $Id: GetObservationFactFromPrimaryKeyHandler.java,v 1.8 2008/07/21 19:56:56 rk903 Exp $ + * @author rkuttan + */ +public class QTBreakdownHandler extends RequestHandler { + private QueryDefinitionRequestType getRequestMessageType = + null; + private SecurityType userRequestType = null; + + + /** + * Constuctor which accepts i2b2 request message xml + * @param requestXml + * @throws I2B2Exception + */ + public QTBreakdownHandler(String requestXml) + throws I2B2Exception { + try { + this.getRequestMessageType = (QueryDefinitionRequestType) this.getRequestType(requestXml, + QueryDefinitionRequestType.class); + RequestMessageType requestMsg = getI2B2RequestMessageType( requestXml); + this.userRequestType = requestMsg.getMessageHeader() + .getSecurity(); + this.setDataSourceLookup(requestXml); + } catch (JAXBUtilException jaxbUtilEx) { + throw new I2B2Exception("Error ", jaxbUtilEx); + } + } + + /** + * Perform operation for the given request and + * return response + */ + @Override + public BodyType execute() throws I2B2Exception { + // call ejb and pass input object + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + String responseString = null; + BodyType bodyType = new BodyType(); + CrcXmlResultResponseType masterResponseType = null; + try { + long initialTime = System.currentTimeMillis(); + // masterResponseType = queryInfoLocal.getQueryMasterListFromUserId(getDataSourceLookup(),userRequestType); + QueryInfoBean query = new QueryInfoBean(); + + masterResponseType = query.getQTBreakdownForAdmin(getDataSourceLookup(),userRequestType, getRequestMessageType.getResultOutputList()); + long finalTime = System.currentTimeMillis(); + long diffTimeMill = finalTime - initialTime; + long diffTime = diffTimeMill / 1000; + log.debug(" EJB Diff mill =" + diffTimeMill + " diffTime =" + + diffTime); + masterResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.DONE_TYPE, "DONE")); + } catch (Exception e) { + log.debug(e.getMessage()); + masterResponseType = new CrcXmlResultResponseType(); + masterResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.ERROR_TYPE, e.getMessage())); + } finally { + edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); + bodyType.getAny().add(of.createResponse(masterResponseType)); + } + + return bodyType; + } +} + + diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/QTBreakdownRequestDelegate.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/QTBreakdownRequestDelegate.java similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/QTBreakdownRequestDelegate.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/QTBreakdownRequestDelegate.java index 432c23c1..d1e34b74 100644 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/QTBreakdownRequestDelegate.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/QTBreakdownRequestDelegate.java @@ -1,252 +1,252 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Mike Mendis - */ -package edu.harvard.i2b2.crc.delegate; - -import jakarta.xml.bind.JAXBElement; - -import org.apache.axis2.AxisFault; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.exception.StackTraceUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.I2B2MessageResponseFactory; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; -import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; -import edu.harvard.i2b2.crc.delegate.pm.PMServiceDriver; - - -public class QTBreakdownRequestDelegate extends RequestHandlerDelegate { - /** log **/ - protected final Log log = LogFactory.getLog(getClass()); - - /** - * @see edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate#handleRequest(java.lang.String) - */ - @Override - public String handleRequest(String requestXml) throws I2B2Exception { -// PdoQryHeaderType headerType = null; PsmQryHeaderType - //FindByChildType childType = null; - String response = null; - JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); - - try { - JAXBElement jaxbElement = jaxbUtil.unMashallFromString(requestXml); - RequestMessageType requestMessageType = (RequestMessageType) jaxbElement - .getValue(); - BodyType bodyType = requestMessageType.getMessageBody(); - - if (bodyType == null) { - log.error("null value in body type"); - throw new I2B2Exception("null value in body type"); - } - - // Call PM cell to validate user - - StatusType procStatus = null; - boolean isAdmin = false; - try { - SecurityType securityType = null; - String projectId = null; - if (requestMessageType.getMessageHeader() != null) { - if (requestMessageType.getMessageHeader().getSecurity() != null) { - securityType = requestMessageType.getMessageHeader() - .getSecurity(); - } - projectId = requestMessageType.getMessageHeader() - .getProjectId(); - } - - if (securityType == null) { - procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus - .setValue("Request message missing user/password"); - response = I2B2MessageResponseFactory.buildResponseMessage( - requestXml, procStatus, bodyType); - return response; - } - if (projectId == null) { - procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus.setValue("Missing "); - response = I2B2MessageResponseFactory.buildResponseMessage( - requestXml, procStatus, bodyType); - return response; - } - - PMServiceDriver pmServiceDriver = new PMServiceDriver(); - isAdmin = pmServiceDriver.isAdmin(securityType, projectId); - // ProjectType projectType = pmServiceDriver.checkValidUser( - // securityType, projectId); - // projectType.getRole() - /* if (projectType == null) { - procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus - .setValue("Invalid user/password for the given project [" - + projectId + "]"); - response = I2B2MessageResponseFactory.buildResponseMessage( - requestXml, procStatus, bodyType); - return response; - } - - log.debug("project name from PM " + projectType.getName()); - log.debug("project id from PM " + projectType.getId()); - - if (isAdmin) { - //TODO removed cache - //Node rootNode = CacheUtil.getCache().getRoot(); - //List roles = (List) rootNode - // .get(securityType.getDomain() + "/" + projectId - // + "/" + securityType.getUsername()); - List roles = (List) CacheUtil - .get(securityType.getDomain() + "/" + projectId - + "/" + securityType.getUsername()); - if (roles != null) { - log.debug("User Roles count " + roles.size()); - } - - ParamUtil paramUtil = new ParamUtil(); - paramUtil.clearParam(projectId, securityType.getUsername(), securityType.getDomain(), ParamUtil.CRC_ENABLE_UNITCD_CONVERSION); - if (projectType.getParam() != null) { - for (ParamType param : projectType.getParam()) { - if (param.getName() != null && param.getName().trim().equalsIgnoreCase(ParamUtil.CRC_ENABLE_UNITCD_CONVERSION)) { - paramUtil.putParam(projectId, securityType.getUsername(), securityType.getDomain(),ParamUtil.CRC_ENABLE_UNITCD_CONVERSION,param); - String unitCdCache = paramUtil.getParam(projectId, securityType.getUsername(), securityType.getDomain(),ParamUtil.CRC_ENABLE_UNITCD_CONVERSION); - log.debug("CRC param stored in the cache Project Id [" + projectId + "] user [" + securityType.getUsername() + "] domain [" + securityType.getDomain() + "] " + ParamUtil.CRC_ENABLE_UNITCD_CONVERSION + "[" + unitCdCache + "]" ); - break; - } - } - } - - - } else { - - log.error("Project role not set for the user "); - - } - */ - } catch (AxisFault e) { - procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus.setValue("Could not connect to server[" - + e.getDetail() + "]"); - response = I2B2MessageResponseFactory.buildResponseMessage( - requestXml, procStatus, bodyType); - return response; - } catch (I2B2Exception e) { - procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus - .setValue("Project Management cell interface error: [" - + e.getMessage() + "]"); - response = I2B2MessageResponseFactory.buildResponseMessage( - requestXml, procStatus, bodyType); - return response; - } catch (JAXBUtilException e) { - procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus - .setValue("Message error from Project Management cell[" - + e.getMessage() + "]"); - response = I2B2MessageResponseFactory.buildResponseMessage( - requestXml, procStatus, bodyType); - return response; - } - - // JAXBUnWrapHelper unWrapHelper = new JAXBUnWrapHelper(); -// childType = (FindByChildType) unWrapHelper - // .getObjectByClass( - // bodyType.getAny(), - // edu.harvard.i2b2.crc.datavo.setfinder.query.FindByChildType.class); - - BodyType responseBodyType = null; - - QTBreakdownHandler handler = new QTBreakdownHandler( - requestXml); - responseBodyType = handler.execute(); - /* - if (childType.getRequestType().equals( - PdoRequestTypeType.GET_PDO_FROM_INPUT_LIST)) { - GetPDOFromInputListHandler handler = new GetPDOFromInputListHandler( - requestXml); - responseBodyType = handler.execute(); - } else if (headerType.getRequestType().equals( - PdoRequestTypeType.GET_OBSERVATIONFACT_BY_PRIMARY_KEY)) { - GetObservationFactFromPrimaryKeyHandler handler = new GetObservationFactFromPrimaryKeyHandler( - requestXml); - responseBodyType = handler.execute(); - } else if (headerType.getRequestType().equals( - PdoRequestTypeType.GET_PDO_TEMPLATE)) { - GetPDOTemplateHandler handler = new GetPDOTemplateHandler( - requestXml); - responseBodyType = handler.execute(); - } - */ - procStatus = new StatusType(); - procStatus.setType("DONE"); - procStatus.setValue("DONE"); - - long startTime = System.currentTimeMillis(); - response = I2B2MessageResponseFactory.buildResponseMessage( - requestXml, procStatus, responseBodyType, true); - long endTime = System.currentTimeMillis(); - long totalTime = endTime - startTime; - log.debug("Total time to pdo jaxb " + totalTime); - - } catch (JAXBUtilException e) { - log.error("JAXBUtil exception", e); - StatusType procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus.setValue(requestXml + "\n\n" - + StackTraceUtil.getStackTrace(e)); - try { - response = I2B2MessageResponseFactory.buildResponseMessage( - null, procStatus, null); - } catch (JAXBUtilException e1) { - e1.printStackTrace(); - } - } catch (I2B2Exception e) { - log.error("I2B2Exception", e); - StatusType procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus.setValue(StackTraceUtil.getStackTrace(e)); - try { - response = I2B2MessageResponseFactory.buildResponseMessage( - requestXml, procStatus, null); - } catch (JAXBUtilException e1) { - e1.printStackTrace(); - } - } catch (Throwable e) { - log.error("Throwable", e); - StatusType procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus.setValue(StackTraceUtil.getStackTrace(e)); - try { - response = I2B2MessageResponseFactory.buildResponseMessage( - requestXml, procStatus, null); - } catch (JAXBUtilException e1) { - e1.printStackTrace(); - } - } - return response; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Mike Mendis + */ +package edu.harvard.i2b2.crc.delegate; + +import jakarta.xml.bind.JAXBElement; + +import org.apache.axis2.AxisFault; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.exception.StackTraceUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; +import edu.harvard.i2b2.crc.datavo.I2B2MessageResponseFactory; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; +import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; +import edu.harvard.i2b2.crc.delegate.pm.PMServiceDriver; + + +public class QTBreakdownRequestDelegate extends RequestHandlerDelegate { + /** log **/ + protected final Log log = LogFactory.getLog(getClass()); + + /** + * @see edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate#handleRequest(java.lang.String) + */ + @Override + public String handleRequest(String requestXml) throws I2B2Exception { +// PdoQryHeaderType headerType = null; PsmQryHeaderType + //FindByChildType childType = null; + String response = null; + JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); + + try { + JAXBElement jaxbElement = jaxbUtil.unMashallFromString(requestXml); + RequestMessageType requestMessageType = (RequestMessageType) jaxbElement + .getValue(); + BodyType bodyType = requestMessageType.getMessageBody(); + + if (bodyType == null) { + log.error("null value in body type"); + throw new I2B2Exception("null value in body type"); + } + + // Call PM cell to validate user + + StatusType procStatus = null; + boolean isAdmin = false; + try { + SecurityType securityType = null; + String projectId = null; + if (requestMessageType.getMessageHeader() != null) { + if (requestMessageType.getMessageHeader().getSecurity() != null) { + securityType = requestMessageType.getMessageHeader() + .getSecurity(); + } + projectId = requestMessageType.getMessageHeader() + .getProjectId(); + } + + if (securityType == null) { + procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus + .setValue("Request message missing user/password"); + response = I2B2MessageResponseFactory.buildResponseMessage( + requestXml, procStatus, bodyType); + return response; + } + if (projectId == null) { + procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus.setValue("Missing "); + response = I2B2MessageResponseFactory.buildResponseMessage( + requestXml, procStatus, bodyType); + return response; + } + + PMServiceDriver pmServiceDriver = new PMServiceDriver(); + isAdmin = pmServiceDriver.isAdmin(securityType, projectId); + // ProjectType projectType = pmServiceDriver.checkValidUser( + // securityType, projectId); + // projectType.getRole() + /* if (projectType == null) { + procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus + .setValue("Invalid user/password for the given project [" + + projectId + "]"); + response = I2B2MessageResponseFactory.buildResponseMessage( + requestXml, procStatus, bodyType); + return response; + } + + log.debug("project name from PM " + projectType.getName()); + log.debug("project id from PM " + projectType.getId()); + + if (isAdmin) { + //TODO removed cache + //Node rootNode = CacheUtil.getCache().getRoot(); + //List roles = (List) rootNode + // .get(securityType.getDomain() + "/" + projectId + // + "/" + securityType.getUsername()); + List roles = (List) CacheUtil + .get(securityType.getDomain() + "/" + projectId + + "/" + securityType.getUsername()); + if (roles != null) { + log.debug("User Roles count " + roles.size()); + } + + ParamUtil paramUtil = new ParamUtil(); + paramUtil.clearParam(projectId, securityType.getUsername(), securityType.getDomain(), ParamUtil.CRC_ENABLE_UNITCD_CONVERSION); + if (projectType.getParam() != null) { + for (ParamType param : projectType.getParam()) { + if (param.getName() != null && param.getName().trim().equalsIgnoreCase(ParamUtil.CRC_ENABLE_UNITCD_CONVERSION)) { + paramUtil.putParam(projectId, securityType.getUsername(), securityType.getDomain(),ParamUtil.CRC_ENABLE_UNITCD_CONVERSION,param); + String unitCdCache = paramUtil.getParam(projectId, securityType.getUsername(), securityType.getDomain(),ParamUtil.CRC_ENABLE_UNITCD_CONVERSION); + log.debug("CRC param stored in the cache Project Id [" + projectId + "] user [" + securityType.getUsername() + "] domain [" + securityType.getDomain() + "] " + ParamUtil.CRC_ENABLE_UNITCD_CONVERSION + "[" + unitCdCache + "]" ); + break; + } + } + } + + + } else { + + log.error("Project role not set for the user "); + + } + */ + } catch (AxisFault e) { + procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus.setValue("Could not connect to server[" + + e.getDetail() + "]"); + response = I2B2MessageResponseFactory.buildResponseMessage( + requestXml, procStatus, bodyType); + return response; + } catch (I2B2Exception e) { + procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus + .setValue("Project Management cell interface error: [" + + e.getMessage() + "]"); + response = I2B2MessageResponseFactory.buildResponseMessage( + requestXml, procStatus, bodyType); + return response; + } catch (JAXBUtilException e) { + procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus + .setValue("Message error from Project Management cell[" + + e.getMessage() + "]"); + response = I2B2MessageResponseFactory.buildResponseMessage( + requestXml, procStatus, bodyType); + return response; + } + + // JAXBUnWrapHelper unWrapHelper = new JAXBUnWrapHelper(); +// childType = (FindByChildType) unWrapHelper + // .getObjectByClass( + // bodyType.getAny(), + // edu.harvard.i2b2.crc.datavo.setfinder.query.FindByChildType.class); + + BodyType responseBodyType = null; + + QTBreakdownHandler handler = new QTBreakdownHandler( + requestXml); + responseBodyType = handler.execute(); + /* + if (childType.getRequestType().equals( + PdoRequestTypeType.GET_PDO_FROM_INPUT_LIST)) { + GetPDOFromInputListHandler handler = new GetPDOFromInputListHandler( + requestXml); + responseBodyType = handler.execute(); + } else if (headerType.getRequestType().equals( + PdoRequestTypeType.GET_OBSERVATIONFACT_BY_PRIMARY_KEY)) { + GetObservationFactFromPrimaryKeyHandler handler = new GetObservationFactFromPrimaryKeyHandler( + requestXml); + responseBodyType = handler.execute(); + } else if (headerType.getRequestType().equals( + PdoRequestTypeType.GET_PDO_TEMPLATE)) { + GetPDOTemplateHandler handler = new GetPDOTemplateHandler( + requestXml); + responseBodyType = handler.execute(); + } + */ + procStatus = new StatusType(); + procStatus.setType("DONE"); + procStatus.setValue("DONE"); + + long startTime = System.currentTimeMillis(); + response = I2B2MessageResponseFactory.buildResponseMessage( + requestXml, procStatus, responseBodyType, true); + long endTime = System.currentTimeMillis(); + long totalTime = endTime - startTime; + log.debug("Total time to pdo jaxb " + totalTime); + + } catch (JAXBUtilException e) { + log.error("JAXBUtil exception", e); + StatusType procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus.setValue(requestXml + "\n\n" + + StackTraceUtil.getStackTrace(e)); + try { + response = I2B2MessageResponseFactory.buildResponseMessage( + null, procStatus, null); + } catch (JAXBUtilException e1) { + e1.printStackTrace(); + } + } catch (I2B2Exception e) { + log.error("I2B2Exception", e); + StatusType procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus.setValue(StackTraceUtil.getStackTrace(e)); + try { + response = I2B2MessageResponseFactory.buildResponseMessage( + requestXml, procStatus, null); + } catch (JAXBUtilException e1) { + e1.printStackTrace(); + } + } catch (Throwable e) { + log.error("Throwable", e); + StatusType procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus.setValue(StackTraceUtil.getStackTrace(e)); + try { + response = I2B2MessageResponseFactory.buildResponseMessage( + requestXml, procStatus, null); + } catch (JAXBUtilException e1) { + e1.printStackTrace(); + } + } + return response; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/RPDOReqHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/RPDOReqHandler.java similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/RPDOReqHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/RPDOReqHandler.java index d88c1a73..19c22727 100644 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/RPDOReqHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/RPDOReqHandler.java @@ -1,247 +1,247 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Mike Mendis - */ -package edu.harvard.i2b2.crc.delegate; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.dao.DblookupDao; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.i2b2message.ApplicationType; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2message.InfoType; -import edu.harvard.i2b2.crc.datavo.i2b2message.MessageControlIdType; -import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.PollingUrlType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResultStatusType; -import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; -import edu.harvard.i2b2.crc.loader.delegate.pm.PMResponseMessage; -import edu.harvard.i2b2.crc.loader.delegate.pm.PMServiceDriver; -import edu.harvard.i2b2.crc.datavo.pm.ConfigureType; -import edu.harvard.i2b2.crc.datavo.pm.GetUserConfigurationType; - -import java.io.StringWriter; - -import jakarta.xml.bind.JAXBElement; - -import org.apache.axis2.AxisFault; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Top level class to process the request. There will be separate request handler - * class for each request type. The main processing of for the request will be - * done inside execute function - * - */ -public abstract class RPDOReqHandler { - protected final Log log = LogFactory.getLog(getClass()); - protected static Log logesapi = LogFactory.getLog(RPDOReqHandler.class); - - protected DataSourceLookup dataSourceLookup = null; - - /** - * Function to perform operation on the given request - * - * @return response xml message - */ - public abstract String execute() throws I2B2Exception; - - public boolean isAdmin(MessageHeaderType header) { - try { - GetUserConfigurationType userConfigType = new GetUserConfigurationType(); - PMServiceDriver pmSrvDrvr = new PMServiceDriver(); - String response = pmSrvDrvr.getRoles(userConfigType, header); - logesapi.debug(response); - PMResponseMessage msg = new PMResponseMessage(); - StatusType procStatus = msg.processResult(response); - if(procStatus.getType().equals("ERROR")) return false; - ConfigureType pmConfigure = msg.readUserInfo(); - if (pmConfigure.getUser().isIsAdmin()) return true; - } catch (AxisFault e) { - log.error("Can't connect to PM service"); - } catch (I2B2Exception e) { - log.error("Problem processing PM service address"); - } catch (Exception e) { - log.error("General PM processing problem: "+ e.getMessage()); - } - return false; - } - - /** - * Class to fetch specific request message from i2b2 message xml - * - * @param requestXml - * @param classname - * @return object which is of type classname - * @throws JAXBUtilException - */ - protected Object getRequestType(String requestXml, Class classname) - throws JAXBUtilException { - Object returnObject = null; - - JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); - JAXBElement jaxbElement = jaxbUtil.unMashallFromString(requestXml); - RequestMessageType requestMessageType = (RequestMessageType) jaxbElement - .getValue(); - BodyType bodyType = requestMessageType.getMessageBody(); - JAXBUnWrapHelper unWrapHelper = new JAXBUnWrapHelper(); - // get request header type - returnObject = unWrapHelper.getObjectByClass(bodyType.getAny(), - classname); - - return returnObject; - } - - /** - * Function to build response message type using given bodytype and request - * xml - * - * @param requestXml - * @param bodyType - * @return i2b2 response message xml - * @throws JAXBUtilException - */ - protected String buildResponseMessage(String requestXml, BodyType bodyType) - throws JAXBUtilException { - JAXBUtil util = CRCJAXBUtil.getJAXBUtil(); - RequestMessageType requestMsgType = getI2B2RequestMessageType(requestXml); - MessageHeaderType messageHeader = requestMsgType.getMessageHeader(); - - // reverse sending and receiving app - ApplicationType sendingApp = messageHeader.getSendingApplication(); - ApplicationType receiveApp = messageHeader.getReceivingApplication(); - messageHeader.setSendingApplication(receiveApp); - messageHeader.setReceivingApplication(sendingApp); - - // set instance num - MessageControlIdType messageControlIdType = messageHeader - .getMessageControlId(); - - if (messageControlIdType != null) { - messageControlIdType.setInstanceNum(1); - } - - StatusType statusType = new StatusType(); - statusType.setType("DONE"); - - // :TODO statusType.setValue(sessionId); - PollingUrlType pollingType = new PollingUrlType(); - pollingType.setIntervalMs(100); - - // :TODO value come from property file - // pollingType.setValue( - // "http://host:port/QueryProcessor/getResult"); - ResultStatusType resultStatusType = new ResultStatusType(); - resultStatusType.setStatus(statusType); - resultStatusType.setPollingUrl(pollingType); - - InfoType infoType = new InfoType(); - // :TODO value come from property file - //infoType.setUrl("http://host:port/QueryProcessor/getStatus"); - infoType.setValue("Log information"); - - ResponseHeaderType responseHeader = new ResponseHeaderType(); - responseHeader.setResultStatus(resultStatusType); - responseHeader.setInfo(infoType); - - ResponseMessageType responseMessageType = new ResponseMessageType(); - responseMessageType.setMessageHeader(messageHeader); - responseMessageType.setResponseHeader(responseHeader); - responseMessageType.setMessageBody(bodyType); - - edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory(); - StringWriter strWriter = new StringWriter(); - util.marshaller(of.createResponse(responseMessageType), strWriter); - - return strWriter.toString(); - } - - /** - * Function to unmarshall i2b2 request message type - * - * @param requestXml - * @return RequestMessageType - * @throws JAXBUtilException - */ - protected RequestMessageType getI2B2RequestMessageType(String requestXml) - throws JAXBUtilException { - JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); - JAXBElement jaxbElement = jaxbUtil.unMashallFromString(requestXml); - RequestMessageType requestMessageType = (RequestMessageType) jaxbElement - .getValue(); - - return requestMessageType; - } - - /** - * Function marshall i2b2 response message type - * - * @param responseMessageType - * @return - */ - protected String getResponseString(ResponseMessageType responseMessageType) { - StringWriter strWriter = new StringWriter(); - - try { - edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory(); - JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); - jaxbUtil.marshaller(of.createResponse(responseMessageType), - strWriter); - } catch (JAXBUtilException e) { - log.error("Error while generating response message" - + e.getMessage()); - } - - return strWriter.toString(); - } - - protected edu.harvard.i2b2.crc.datavo.setfinder.query.StatusType buildCRCStausType( - String statusType, String message) { - edu.harvard.i2b2.crc.datavo.setfinder.query.StatusType st = new edu.harvard.i2b2.crc.datavo.setfinder.query.StatusType(); - edu.harvard.i2b2.crc.datavo.setfinder.query.StatusType.Condition condition = new edu.harvard.i2b2.crc.datavo.setfinder.query.StatusType.Condition(); - condition.setType(statusType); - condition.setValue(message); - st.getCondition().add(condition); - return st; - } - - protected void setDataSourceLookup(String requestXml) - throws JAXBUtilException { - RequestMessageType reqMessage = getI2B2RequestMessageType(requestXml); - String projectId = reqMessage.getMessageHeader().getProjectId(); - String domainId = reqMessage.getMessageHeader().getSecurity() - .getDomain(); - String userId = reqMessage.getMessageHeader().getSecurity() - .getUsername(); - dataSourceLookup = new DataSourceLookup(); - dataSourceLookup.setProjectPath(projectId); - dataSourceLookup.setDomainId(domainId); - dataSourceLookup.setOwnerId(userId); - - } - - protected DataSourceLookup getDataSourceLookup() { - return dataSourceLookup; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Mike Mendis + */ +package edu.harvard.i2b2.crc.delegate; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.dao.DblookupDao; +import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.i2b2message.ApplicationType; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2message.InfoType; +import edu.harvard.i2b2.crc.datavo.i2b2message.MessageControlIdType; +import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.PollingUrlType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResultStatusType; +import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; +import edu.harvard.i2b2.crc.loader.delegate.pm.PMResponseMessage; +import edu.harvard.i2b2.crc.loader.delegate.pm.PMServiceDriver; +import edu.harvard.i2b2.crc.datavo.pm.ConfigureType; +import edu.harvard.i2b2.crc.datavo.pm.GetUserConfigurationType; + +import java.io.StringWriter; + +import jakarta.xml.bind.JAXBElement; + +import org.apache.axis2.AxisFault; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +/** + * Top level class to process the request. There will be separate request handler + * class for each request type. The main processing of for the request will be + * done inside execute function + * + */ +public abstract class RPDOReqHandler { + protected final Log log = LogFactory.getLog(getClass()); + protected static Log logesapi = LogFactory.getLog(RPDOReqHandler.class); + + protected DataSourceLookup dataSourceLookup = null; + + /** + * Function to perform operation on the given request + * + * @return response xml message + */ + public abstract String execute() throws I2B2Exception; + + public boolean isAdmin(MessageHeaderType header) { + try { + GetUserConfigurationType userConfigType = new GetUserConfigurationType(); + PMServiceDriver pmSrvDrvr = new PMServiceDriver(); + String response = pmSrvDrvr.getRoles(userConfigType, header); + logesapi.debug(response); + PMResponseMessage msg = new PMResponseMessage(); + StatusType procStatus = msg.processResult(response); + if(procStatus.getType().equals("ERROR")) return false; + ConfigureType pmConfigure = msg.readUserInfo(); + if (pmConfigure.getUser().isIsAdmin()) return true; + } catch (AxisFault e) { + log.error("Can't connect to PM service"); + } catch (I2B2Exception e) { + log.error("Problem processing PM service address"); + } catch (Exception e) { + log.error("General PM processing problem: "+ e.getMessage()); + } + return false; + } + + /** + * Class to fetch specific request message from i2b2 message xml + * + * @param requestXml + * @param classname + * @return object which is of type classname + * @throws JAXBUtilException + */ + protected Object getRequestType(String requestXml, Class classname) + throws JAXBUtilException { + Object returnObject = null; + + JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); + JAXBElement jaxbElement = jaxbUtil.unMashallFromString(requestXml); + RequestMessageType requestMessageType = (RequestMessageType) jaxbElement + .getValue(); + BodyType bodyType = requestMessageType.getMessageBody(); + JAXBUnWrapHelper unWrapHelper = new JAXBUnWrapHelper(); + // get request header type + returnObject = unWrapHelper.getObjectByClass(bodyType.getAny(), + classname); + + return returnObject; + } + + /** + * Function to build response message type using given bodytype and request + * xml + * + * @param requestXml + * @param bodyType + * @return i2b2 response message xml + * @throws JAXBUtilException + */ + protected String buildResponseMessage(String requestXml, BodyType bodyType) + throws JAXBUtilException { + JAXBUtil util = CRCJAXBUtil.getJAXBUtil(); + RequestMessageType requestMsgType = getI2B2RequestMessageType(requestXml); + MessageHeaderType messageHeader = requestMsgType.getMessageHeader(); + + // reverse sending and receiving app + ApplicationType sendingApp = messageHeader.getSendingApplication(); + ApplicationType receiveApp = messageHeader.getReceivingApplication(); + messageHeader.setSendingApplication(receiveApp); + messageHeader.setReceivingApplication(sendingApp); + + // set instance num + MessageControlIdType messageControlIdType = messageHeader + .getMessageControlId(); + + if (messageControlIdType != null) { + messageControlIdType.setInstanceNum(1); + } + + StatusType statusType = new StatusType(); + statusType.setType("DONE"); + + // :TODO statusType.setValue(sessionId); + PollingUrlType pollingType = new PollingUrlType(); + pollingType.setIntervalMs(100); + + // :TODO value come from property file + // pollingType.setValue( + // "http://host:port/QueryProcessor/getResult"); + ResultStatusType resultStatusType = new ResultStatusType(); + resultStatusType.setStatus(statusType); + resultStatusType.setPollingUrl(pollingType); + + InfoType infoType = new InfoType(); + // :TODO value come from property file + //infoType.setUrl("http://host:port/QueryProcessor/getStatus"); + infoType.setValue("Log information"); + + ResponseHeaderType responseHeader = new ResponseHeaderType(); + responseHeader.setResultStatus(resultStatusType); + responseHeader.setInfo(infoType); + + ResponseMessageType responseMessageType = new ResponseMessageType(); + responseMessageType.setMessageHeader(messageHeader); + responseMessageType.setResponseHeader(responseHeader); + responseMessageType.setMessageBody(bodyType); + + edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory(); + StringWriter strWriter = new StringWriter(); + util.marshaller(of.createResponse(responseMessageType), strWriter); + + return strWriter.toString(); + } + + /** + * Function to unmarshall i2b2 request message type + * + * @param requestXml + * @return RequestMessageType + * @throws JAXBUtilException + */ + protected RequestMessageType getI2B2RequestMessageType(String requestXml) + throws JAXBUtilException { + JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); + JAXBElement jaxbElement = jaxbUtil.unMashallFromString(requestXml); + RequestMessageType requestMessageType = (RequestMessageType) jaxbElement + .getValue(); + + return requestMessageType; + } + + /** + * Function marshall i2b2 response message type + * + * @param responseMessageType + * @return + */ + protected String getResponseString(ResponseMessageType responseMessageType) { + StringWriter strWriter = new StringWriter(); + + try { + edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory(); + JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); + jaxbUtil.marshaller(of.createResponse(responseMessageType), + strWriter); + } catch (JAXBUtilException e) { + log.error("Error while generating response message" + + e.getMessage()); + } + + return strWriter.toString(); + } + + protected edu.harvard.i2b2.crc.datavo.setfinder.query.StatusType buildCRCStausType( + String statusType, String message) { + edu.harvard.i2b2.crc.datavo.setfinder.query.StatusType st = new edu.harvard.i2b2.crc.datavo.setfinder.query.StatusType(); + edu.harvard.i2b2.crc.datavo.setfinder.query.StatusType.Condition condition = new edu.harvard.i2b2.crc.datavo.setfinder.query.StatusType.Condition(); + condition.setType(statusType); + condition.setValue(message); + st.getCondition().add(condition); + return st; + } + + protected void setDataSourceLookup(String requestXml) + throws JAXBUtilException { + RequestMessageType reqMessage = getI2B2RequestMessageType(requestXml); + String projectId = reqMessage.getMessageHeader().getProjectId(); + String domainId = reqMessage.getMessageHeader().getSecurity() + .getDomain(); + String userId = reqMessage.getMessageHeader().getSecurity() + .getUsername(); + dataSourceLookup = new DataSourceLookup(); + dataSourceLookup.setProjectPath(projectId); + dataSourceLookup.setDomainId(domainId); + dataSourceLookup.setOwnerId(userId); + + } + + protected DataSourceLookup getDataSourceLookup() { + return dataSourceLookup; + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/RequestHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/RequestHandler.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/RequestHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/RequestHandler.java index 576f748c..dddb2f22 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/RequestHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/RequestHandler.java @@ -1,219 +1,219 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.delegate; - -import java.io.StringWriter; - -import jakarta.xml.bind.JAXBElement; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.i2b2message.ApplicationType; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2message.InfoType; -import edu.harvard.i2b2.crc.datavo.i2b2message.MessageControlIdType; -import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.PollingUrlType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResultStatusType; -import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; - -/** - * Top level class to process the request. There will be seperate requesthandler - * class for each request type. The main processing of for the request will be - * done inside execute function $Id: RequestHandler.java,v 1.10 2008/03/19 - * 22:38:24 rk903 Exp $ - * - * @author rkuttan - */ -public abstract class RequestHandler { - /** log **/ - protected final Log log = LogFactory.getLog(getClass()); - protected DataSourceLookup dataSourceLookup = null; - - /** - * Function to perform operation on the given request - * - * @return response xml message - */ - public abstract BodyType execute() throws I2B2Exception; - - /** - * Class to fetch specific request message from i2b2 message xml - * - * @param requestXml - * @param classname - * @return object which is of type classname - * @throws JAXBUtilException - */ - protected Object getRequestType(String requestXml, Class classname) - throws JAXBUtilException { - Object returnObject = null; - - JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); - JAXBElement jaxbElement = jaxbUtil.unMashallFromString(requestXml); - RequestMessageType requestMessageType = (RequestMessageType) jaxbElement - .getValue(); - BodyType bodyType = requestMessageType.getMessageBody(); - JAXBUnWrapHelper unWrapHelper = new JAXBUnWrapHelper(); - // get request header type - returnObject = unWrapHelper.getObjectByClass(bodyType.getAny(), - classname); - - return returnObject; - } - - /** - * Function to build response message type using given bodytype and request - * xml - * - * @param requestXml - * @param bodyType - * @return i2b2 response message xml - * @throws JAXBUtilException - */ - protected String buildResponseMessage(String requestXml, BodyType bodyType) - throws JAXBUtilException { - JAXBUtil util = CRCJAXBUtil.getJAXBUtil(); - RequestMessageType requestMsgType = getI2B2RequestMessageType(requestXml); - MessageHeaderType messageHeader = requestMsgType.getMessageHeader(); - - // reverse sending and receiving app - ApplicationType sendingApp = messageHeader.getSendingApplication(); - ApplicationType receiveApp = messageHeader.getReceivingApplication(); - messageHeader.setSendingApplication(receiveApp); - messageHeader.setReceivingApplication(sendingApp); - - // set instance num - MessageControlIdType messageControlIdType = messageHeader - .getMessageControlId(); - - if (messageControlIdType != null) { - messageControlIdType.setInstanceNum(1); - } - - StatusType statusType = new StatusType(); - statusType.setType("DONE"); - - // :TODO statusType.setValue(sessionId); - PollingUrlType pollingType = new PollingUrlType(); - pollingType.setIntervalMs(100); - - // :TODO value come from property file - // pollingType.setValue( - // "http://host:port/QueryProcessor/getResult"); - ResultStatusType resultStatusType = new ResultStatusType(); - resultStatusType.setStatus(statusType); - resultStatusType.setPollingUrl(pollingType); - - InfoType infoType = new InfoType(); - // :TODO value come from property file - //infoType.setUrl("http://host:port/QueryProcessor/getStatus"); - infoType.setValue("Log information"); - - ResponseHeaderType responseHeader = new ResponseHeaderType(); - responseHeader.setResultStatus(resultStatusType); - responseHeader.setInfo(infoType); - - ResponseMessageType responseMessageType = new ResponseMessageType(); - responseMessageType.setMessageHeader(messageHeader); - responseMessageType.setResponseHeader(responseHeader); - responseMessageType.setMessageBody(bodyType); - - edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory(); - StringWriter strWriter = new StringWriter(); - util.marshaller(of.createResponse(responseMessageType), strWriter); - - return strWriter.toString(); - } - - /** - * Function to unmarshall i2b2 request message type - * - * @param requestXml - * @return RequestMessageType - * @throws JAXBUtilException - */ - protected RequestMessageType getI2B2RequestMessageType(String requestXml) - throws JAXBUtilException { - JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); - JAXBElement jaxbElement = jaxbUtil.unMashallFromString(requestXml); - RequestMessageType requestMessageType = (RequestMessageType) jaxbElement - .getValue(); - - return requestMessageType; - } - - /** - * Function marshall i2b2 response message type - * - * @param responseMessageType - * @return - */ - protected String getResponseString(ResponseMessageType responseMessageType) { - StringWriter strWriter = new StringWriter(); - - try { - edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory(); - JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); - jaxbUtil.marshaller(of.createResponse(responseMessageType), - strWriter); - } catch (JAXBUtilException e) { - log.error("Error while generating response message" - + e.getMessage()); - } - - return strWriter.toString(); - } - - protected edu.harvard.i2b2.crc.datavo.setfinder.query.StatusType buildCRCStausType( - String statusType, String message) { - edu.harvard.i2b2.crc.datavo.setfinder.query.StatusType st = new edu.harvard.i2b2.crc.datavo.setfinder.query.StatusType(); - edu.harvard.i2b2.crc.datavo.setfinder.query.StatusType.Condition condition = new edu.harvard.i2b2.crc.datavo.setfinder.query.StatusType.Condition(); - condition.setType(statusType); - condition.setValue(message); - st.getCondition().add(condition); - return st; - } - - protected void setDataSourceLookup(String requestXml) - throws JAXBUtilException { - RequestMessageType reqMessage = getI2B2RequestMessageType(requestXml); - String projectId = reqMessage.getMessageHeader().getProjectId(); - String domainId = reqMessage.getMessageHeader().getSecurity() - .getDomain(); - String userId = reqMessage.getMessageHeader().getSecurity() - .getUsername(); - dataSourceLookup = new DataSourceLookup(); - dataSourceLookup.setProjectPath(projectId); - dataSourceLookup.setDomainId(domainId); - dataSourceLookup.setOwnerId(userId); - - } - - protected DataSourceLookup getDataSourceLookup() { - return dataSourceLookup; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.delegate; + +import java.io.StringWriter; + +import jakarta.xml.bind.JAXBElement; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.i2b2message.ApplicationType; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2message.InfoType; +import edu.harvard.i2b2.crc.datavo.i2b2message.MessageControlIdType; +import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.PollingUrlType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResultStatusType; +import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; + +/** + * Top level class to process the request. There will be seperate requesthandler + * class for each request type. The main processing of for the request will be + * done inside execute function $Id: RequestHandler.java,v 1.10 2008/03/19 + * 22:38:24 rk903 Exp $ + * + * @author rkuttan + */ +public abstract class RequestHandler { + /** log **/ + protected final Log log = LogFactory.getLog(getClass()); + protected DataSourceLookup dataSourceLookup = null; + + /** + * Function to perform operation on the given request + * + * @return response xml message + */ + public abstract BodyType execute() throws I2B2Exception; + + /** + * Class to fetch specific request message from i2b2 message xml + * + * @param requestXml + * @param classname + * @return object which is of type classname + * @throws JAXBUtilException + */ + protected Object getRequestType(String requestXml, Class classname) + throws JAXBUtilException { + Object returnObject = null; + + JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); + JAXBElement jaxbElement = jaxbUtil.unMashallFromString(requestXml); + RequestMessageType requestMessageType = (RequestMessageType) jaxbElement + .getValue(); + BodyType bodyType = requestMessageType.getMessageBody(); + JAXBUnWrapHelper unWrapHelper = new JAXBUnWrapHelper(); + // get request header type + returnObject = unWrapHelper.getObjectByClass(bodyType.getAny(), + classname); + + return returnObject; + } + + /** + * Function to build response message type using given bodytype and request + * xml + * + * @param requestXml + * @param bodyType + * @return i2b2 response message xml + * @throws JAXBUtilException + */ + protected String buildResponseMessage(String requestXml, BodyType bodyType) + throws JAXBUtilException { + JAXBUtil util = CRCJAXBUtil.getJAXBUtil(); + RequestMessageType requestMsgType = getI2B2RequestMessageType(requestXml); + MessageHeaderType messageHeader = requestMsgType.getMessageHeader(); + + // reverse sending and receiving app + ApplicationType sendingApp = messageHeader.getSendingApplication(); + ApplicationType receiveApp = messageHeader.getReceivingApplication(); + messageHeader.setSendingApplication(receiveApp); + messageHeader.setReceivingApplication(sendingApp); + + // set instance num + MessageControlIdType messageControlIdType = messageHeader + .getMessageControlId(); + + if (messageControlIdType != null) { + messageControlIdType.setInstanceNum(1); + } + + StatusType statusType = new StatusType(); + statusType.setType("DONE"); + + // :TODO statusType.setValue(sessionId); + PollingUrlType pollingType = new PollingUrlType(); + pollingType.setIntervalMs(100); + + // :TODO value come from property file + // pollingType.setValue( + // "http://host:port/QueryProcessor/getResult"); + ResultStatusType resultStatusType = new ResultStatusType(); + resultStatusType.setStatus(statusType); + resultStatusType.setPollingUrl(pollingType); + + InfoType infoType = new InfoType(); + // :TODO value come from property file + //infoType.setUrl("http://host:port/QueryProcessor/getStatus"); + infoType.setValue("Log information"); + + ResponseHeaderType responseHeader = new ResponseHeaderType(); + responseHeader.setResultStatus(resultStatusType); + responseHeader.setInfo(infoType); + + ResponseMessageType responseMessageType = new ResponseMessageType(); + responseMessageType.setMessageHeader(messageHeader); + responseMessageType.setResponseHeader(responseHeader); + responseMessageType.setMessageBody(bodyType); + + edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory(); + StringWriter strWriter = new StringWriter(); + util.marshaller(of.createResponse(responseMessageType), strWriter); + + return strWriter.toString(); + } + + /** + * Function to unmarshall i2b2 request message type + * + * @param requestXml + * @return RequestMessageType + * @throws JAXBUtilException + */ + protected RequestMessageType getI2B2RequestMessageType(String requestXml) + throws JAXBUtilException { + JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); + JAXBElement jaxbElement = jaxbUtil.unMashallFromString(requestXml); + RequestMessageType requestMessageType = (RequestMessageType) jaxbElement + .getValue(); + + return requestMessageType; + } + + /** + * Function marshall i2b2 response message type + * + * @param responseMessageType + * @return + */ + protected String getResponseString(ResponseMessageType responseMessageType) { + StringWriter strWriter = new StringWriter(); + + try { + edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory(); + JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); + jaxbUtil.marshaller(of.createResponse(responseMessageType), + strWriter); + } catch (JAXBUtilException e) { + log.error("Error while generating response message" + + e.getMessage()); + } + + return strWriter.toString(); + } + + protected edu.harvard.i2b2.crc.datavo.setfinder.query.StatusType buildCRCStausType( + String statusType, String message) { + edu.harvard.i2b2.crc.datavo.setfinder.query.StatusType st = new edu.harvard.i2b2.crc.datavo.setfinder.query.StatusType(); + edu.harvard.i2b2.crc.datavo.setfinder.query.StatusType.Condition condition = new edu.harvard.i2b2.crc.datavo.setfinder.query.StatusType.Condition(); + condition.setType(statusType); + condition.setValue(message); + st.getCondition().add(condition); + return st; + } + + protected void setDataSourceLookup(String requestXml) + throws JAXBUtilException { + RequestMessageType reqMessage = getI2B2RequestMessageType(requestXml); + String projectId = reqMessage.getMessageHeader().getProjectId(); + String domainId = reqMessage.getMessageHeader().getSecurity() + .getDomain(); + String userId = reqMessage.getMessageHeader().getSecurity() + .getUsername(); + dataSourceLookup = new DataSourceLookup(); + dataSourceLookup.setProjectPath(projectId); + dataSourceLookup.setDomainId(domainId); + dataSourceLookup.setOwnerId(userId); + + } + + protected DataSourceLookup getDataSourceLookup() { + return dataSourceLookup; + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/RequestHandlerDelegate.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/RequestHandlerDelegate.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/RequestHandlerDelegate.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/RequestHandlerDelegate.java index ab506c71..af1107d4 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/RequestHandlerDelegate.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/RequestHandlerDelegate.java @@ -1,133 +1,133 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.delegate; - -import java.io.StringWriter; -import java.util.List; - -import jakarta.xml.bind.JAXBElement; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -//import org.jboss.cache.Cache; -//import org.jboss.cache.Node; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.crc.datavo.pm.ParamType; -import edu.harvard.i2b2.crc.util.CacheUtil; - -/** - * Class to delegate i2b2 requests to appropriate {@link RequestHandler} Class - * unwraps i2b2 request message and based on the request type, the request will - * be delegated to appropriate request handler by calling execute function. The - * return value from execute function is just passed back to the client $Id: - * RequestHandlerDelegate.java,v 1.6 2007/10/15 17:29:19 rk903 Exp $ - * - * @author rkuttan - */ -public abstract class RequestHandlerDelegate { - /** log **/ - protected final Log log = LogFactory.getLog(getClass()); - - public static final String ERROR_TYPE = "ERROR"; - public static final String DONE_TYPE = "DONE"; - - /** - * Function to delegate request to appropriate request handler class and - * passes back the response message output back to client - * - * @param requestXml - * @return response message xml - * @throws I2B2Exception - */ - public abstract String handleRequest(String requestXml) - throws I2B2Exception; - - /** - * Function to unmarshall i2b2 request message type - * - * @param requestXml - * @return RequestMessageType - * @throws JAXBUtilException - */ - protected RequestMessageType getI2B2RequestMessageType(String requestXml) - throws JAXBUtilException { - JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); - JAXBElement jaxbElement = jaxbUtil.unMashallFromString(requestXml); - RequestMessageType requestMessageType = (RequestMessageType) jaxbElement - .getValue(); - - return requestMessageType; - } - - /** - * Function marshall i2b2 response message type - * - * @param responseMessageType - * @return - */ - protected String getResponseString(ResponseMessageType responseMessageType) { - StringWriter strWriter = new StringWriter(); - - try { - edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory(); - JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); - jaxbUtil.marshaller(of.createResponse(responseMessageType), - strWriter); - } catch (JAXBUtilException e) { - log.error("Error while generating response message" - + e.getMessage()); - } - - return strWriter.toString(); - } - - protected void putRoles(String projectId, String userId, String domainId, - List roles) { - // get cache - try { - //TODO removed cache - //Cache cache = CacheUtil.getCache(); - //Node rootNode = cache.getRoot(); - String roleTree = domainId + "/" + projectId + "/" + userId; - //rootNode.put(roleTree, roles); - CacheUtil.put(roleTree, roles); - - } catch (Exception e) { - e.printStackTrace(); - } - } - - protected void putPocessTiming(String projectId, String userId, String domainId, - ParamType paramType) { - // get cache - try { - //TODO removed cache - //Cache cache = CacheUtil.getCache(); - //Node rootNode = cache.getRoot(); - String roleTree = domainId + "/" + projectId + "/" + userId + "/" + paramType.getName(); - //rootNode.put(roleTree, paramType.getValue()); - CacheUtil.put(roleTree, paramType.getValue()); - - } catch (Exception e) { - e.printStackTrace(); - } - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.delegate; + +import java.io.StringWriter; +import java.util.List; + +import jakarta.xml.bind.JAXBElement; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +//import org.jboss.cache.Cache; +//import org.jboss.cache.Node; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.crc.datavo.pm.ParamType; +import edu.harvard.i2b2.crc.util.CacheUtil; + +/** + * Class to delegate i2b2 requests to appropriate {@link RequestHandler} Class + * unwraps i2b2 request message and based on the request type, the request will + * be delegated to appropriate request handler by calling execute function. The + * return value from execute function is just passed back to the client $Id: + * RequestHandlerDelegate.java,v 1.6 2007/10/15 17:29:19 rk903 Exp $ + * + * @author rkuttan + */ +public abstract class RequestHandlerDelegate { + /** log **/ + protected final Log log = LogFactory.getLog(getClass()); + + public static final String ERROR_TYPE = "ERROR"; + public static final String DONE_TYPE = "DONE"; + + /** + * Function to delegate request to appropriate request handler class and + * passes back the response message output back to client + * + * @param requestXml + * @return response message xml + * @throws I2B2Exception + */ + public abstract String handleRequest(String requestXml) + throws I2B2Exception; + + /** + * Function to unmarshall i2b2 request message type + * + * @param requestXml + * @return RequestMessageType + * @throws JAXBUtilException + */ + protected RequestMessageType getI2B2RequestMessageType(String requestXml) + throws JAXBUtilException { + JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); + JAXBElement jaxbElement = jaxbUtil.unMashallFromString(requestXml); + RequestMessageType requestMessageType = (RequestMessageType) jaxbElement + .getValue(); + + return requestMessageType; + } + + /** + * Function marshall i2b2 response message type + * + * @param responseMessageType + * @return + */ + protected String getResponseString(ResponseMessageType responseMessageType) { + StringWriter strWriter = new StringWriter(); + + try { + edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory(); + JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); + jaxbUtil.marshaller(of.createResponse(responseMessageType), + strWriter); + } catch (JAXBUtilException e) { + log.error("Error while generating response message" + + e.getMessage()); + } + + return strWriter.toString(); + } + + protected void putRoles(String projectId, String userId, String domainId, + List roles) { + // get cache + try { + //TODO removed cache + //Cache cache = CacheUtil.getCache(); + //Node rootNode = cache.getRoot(); + String roleTree = domainId + "/" + projectId + "/" + userId; + //rootNode.put(roleTree, roles); + CacheUtil.put(roleTree, roles); + + } catch (Exception e) { + e.printStackTrace(); + } + } + + protected void putPocessTiming(String projectId, String userId, String domainId, + ParamType paramType) { + // get cache + try { + //TODO removed cache + //Cache cache = CacheUtil.getCache(); + //Node rootNode = cache.getRoot(); + String roleTree = domainId + "/" + projectId + "/" + userId + "/" + paramType.getName(); + //rootNode.put(roleTree, paramType.getValue()); + CacheUtil.put(roleTree, paramType.getValue()); + + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/SetDblookupHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/SetDblookupHandler.java similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/SetDblookupHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/SetDblookupHandler.java index 24795128..c886414a 100644 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/SetDblookupHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/SetDblookupHandler.java @@ -1,105 +1,105 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Wayne Chan - */ -package edu.harvard.i2b2.crc.delegate; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.axis2.MessageFactory; -import edu.harvard.i2b2.crc.axis2.SetDblookupDataMessage; -import edu.harvard.i2b2.crc.dao.DblookupDao; -import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.crc.datavo.pdo.query.SetDblookupType; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -public class SetDblookupHandler extends DbLookupReqHandler { - private static Log log = LogFactory.getLog(SetDblookupHandler.class); - private SetDblookupDataMessage setdblookupDataMsg = null; - private MessageHeaderType msgHdrType = null; - private SetDblookupType dblookupType = null; - private DblookupDao dblookupDao = null; - private boolean isAdmin = false; - private int numInserted = -1; - - public SetDblookupHandler(SetDblookupDataMessage requestMsg) throws I2B2Exception{ - try { - setdblookupDataMsg = requestMsg; - dblookupType = requestMsg.setDblookupType(); - msgHdrType = setdblookupDataMsg.getMessageHeaderType(); - isAdmin = isAdmin(msgHdrType); - dblookupDao = new DblookupDao(msgHdrType); - } catch (JAXBUtilException e) { - log.error("error setting up SetDblookupHandler"); - throw new I2B2Exception("SetDblookupHandler not configured"); - } - } - - @Override - public String execute() throws I2B2Exception { - MessageHeaderType msgHdr = MessageFactory.createResponseMessageHeader(msgHdrType); - ResponseMessageType responseMessageType = null; - String response = null; - if (!isAdmin) { - String accessDenied = "Access denied, user not an admin!"; - responseMessageType = MessageFactory.doBuildErrorResponse(msgHdr, accessDenied); - response = MessageFactory.convertToXMLString(responseMessageType); - log.warn(accessDenied); - return response; - } - log.info(dblookupType.getProjectPath() + ", " + dblookupType.getDomainId() + ", " + dblookupType.getOwnerId() + ", " + - dblookupType.getDbFullschema() + ", " + dblookupType.getDbDatasource() + ", " + dblookupType.getDbServertype() + ", " + - dblookupType.getDbNicename()); - if (null == dblookupType.getDomainId() || dblookupType.getDomainId().trim().equals("") || - null == dblookupType.getProjectPath() || dblookupType.getProjectPath().trim().equals("") || - null == dblookupType.getOwnerId() || dblookupType.getOwnerId().trim().equals("") || - null == dblookupType.getDbFullschema() || dblookupType.getDbFullschema().trim().equals("") || - null == dblookupType.getDbDatasource() || dblookupType.getDbDatasource().trim().equals("") || - null == dblookupType.getDbServertype() || dblookupType.getDbServertype().trim().equals("") || - null == dblookupType.getDbNicename() || dblookupType.getDbNicename().trim().equals("")) { - String fields = "'project_path', 'domain_id', 'owner_id', 'db_fullschema', 'db_datasource', 'db_servertype', or 'db_nicename' can't be missing or blank!"; - responseMessageType = MessageFactory.doBuildErrorResponse(msgHdr, fields); - response = MessageFactory.convertToXMLString(responseMessageType); - log.warn(fields); - return response; - } - try { - numInserted = dblookupDao.setDblookup(dblookupType); - } catch (I2B2DAOException e1) { - String dbError = "Database error"; - responseMessageType = MessageFactory.doBuildErrorResponse(msgHdr, dbError); - log.error(dbError); - } catch (I2B2Exception e1) { - String dbError = "Database error"; - responseMessageType = MessageFactory.doBuildErrorResponse(msgHdr, dbError); - log.error(dbError); - } - if (-1 == numInserted) { - String dbError = "Database error"; - responseMessageType = MessageFactory.doBuildErrorResponse(msgHdr, dbError); - log.error(dbError); - } else if (0 == numInserted) { - String notInserted = "dblookup row not inserted!"; - log.error(notInserted); - responseMessageType = MessageFactory.doBuildErrorResponse(msgHdr, notInserted); - } else { - log.info(numInserted + " row set"); - responseMessageType = MessageFactory.createBuildResponse(msgHdr); - } - response = MessageFactory.convertToXMLString(responseMessageType); - return response; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Wayne Chan + */ +package edu.harvard.i2b2.crc.delegate; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.axis2.MessageFactory; +import edu.harvard.i2b2.crc.axis2.SetDblookupDataMessage; +import edu.harvard.i2b2.crc.dao.DblookupDao; +import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.crc.datavo.pdo.query.SetDblookupType; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +public class SetDblookupHandler extends DbLookupReqHandler { + private static Log log = LogFactory.getLog(SetDblookupHandler.class); + private SetDblookupDataMessage setdblookupDataMsg = null; + private MessageHeaderType msgHdrType = null; + private SetDblookupType dblookupType = null; + private DblookupDao dblookupDao = null; + private boolean isAdmin = false; + private int numInserted = -1; + + public SetDblookupHandler(SetDblookupDataMessage requestMsg) throws I2B2Exception{ + try { + setdblookupDataMsg = requestMsg; + dblookupType = requestMsg.setDblookupType(); + msgHdrType = setdblookupDataMsg.getMessageHeaderType(); + isAdmin = isAdmin(msgHdrType); + dblookupDao = new DblookupDao(msgHdrType); + } catch (JAXBUtilException e) { + log.error("error setting up SetDblookupHandler"); + throw new I2B2Exception("SetDblookupHandler not configured"); + } + } + + @Override + public String execute() throws I2B2Exception { + MessageHeaderType msgHdr = MessageFactory.createResponseMessageHeader(msgHdrType); + ResponseMessageType responseMessageType = null; + String response = null; + if (!isAdmin) { + String accessDenied = "Access denied, user not an admin!"; + responseMessageType = MessageFactory.doBuildErrorResponse(msgHdr, accessDenied); + response = MessageFactory.convertToXMLString(responseMessageType); + log.warn(accessDenied); + return response; + } + log.info(dblookupType.getProjectPath() + ", " + dblookupType.getDomainId() + ", " + dblookupType.getOwnerId() + ", " + + dblookupType.getDbFullschema() + ", " + dblookupType.getDbDatasource() + ", " + dblookupType.getDbServertype() + ", " + + dblookupType.getDbNicename()); + if (null == dblookupType.getDomainId() || dblookupType.getDomainId().trim().equals("") || + null == dblookupType.getProjectPath() || dblookupType.getProjectPath().trim().equals("") || + null == dblookupType.getOwnerId() || dblookupType.getOwnerId().trim().equals("") || + null == dblookupType.getDbFullschema() || dblookupType.getDbFullschema().trim().equals("") || + null == dblookupType.getDbDatasource() || dblookupType.getDbDatasource().trim().equals("") || + null == dblookupType.getDbServertype() || dblookupType.getDbServertype().trim().equals("") || + null == dblookupType.getDbNicename() || dblookupType.getDbNicename().trim().equals("")) { + String fields = "'project_path', 'domain_id', 'owner_id', 'db_fullschema', 'db_datasource', 'db_servertype', or 'db_nicename' can't be missing or blank!"; + responseMessageType = MessageFactory.doBuildErrorResponse(msgHdr, fields); + response = MessageFactory.convertToXMLString(responseMessageType); + log.warn(fields); + return response; + } + try { + numInserted = dblookupDao.setDblookup(dblookupType); + } catch (I2B2DAOException e1) { + String dbError = "Database error"; + responseMessageType = MessageFactory.doBuildErrorResponse(msgHdr, dbError); + log.error(dbError); + } catch (I2B2Exception e1) { + String dbError = "Database error"; + responseMessageType = MessageFactory.doBuildErrorResponse(msgHdr, dbError); + log.error(dbError); + } + if (-1 == numInserted) { + String dbError = "Database error"; + responseMessageType = MessageFactory.doBuildErrorResponse(msgHdr, dbError); + log.error(dbError); + } else if (0 == numInserted) { + String notInserted = "dblookup row not inserted!"; + log.error(notInserted); + responseMessageType = MessageFactory.doBuildErrorResponse(msgHdr, notInserted); + } else { + log.info(numInserted + " row set"); + responseMessageType = MessageFactory.createBuildResponse(msgHdr); + } + response = MessageFactory.convertToXMLString(responseMessageType); + return response; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/ejbpm/EJBPMUtil.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/ejbpm/EJBPMUtil.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/ejbpm/EJBPMUtil.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/ejbpm/EJBPMUtil.java index e657e731..8068a805 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/ejbpm/EJBPMUtil.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/ejbpm/EJBPMUtil.java @@ -1,325 +1,325 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.delegate.ejbpm; - -import java.io.StringReader; -import java.io.StringWriter; -import java.util.List; - -import jakarta.xml.bind.JAXBElement; -import javax.xml.stream.XMLInputFactory; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamReader; - -import org.apache.axiom.om.OMAbstractFactory; -import org.apache.axiom.om.OMElement; -import org.apache.axiom.om.OMFactory; -import org.apache.axiom.om.OMXMLBuilderFactory; -import org.apache.axis2.AxisFault; -import edu.harvard.i2b2.common.util.axis2.ServiceClient; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.exception.StackTraceUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.dao.DblookupDao; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2message.FacilityType; -import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; -import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; -import edu.harvard.i2b2.crc.datavo.pm.ConfigureType; -import edu.harvard.i2b2.crc.datavo.pm.GetUserConfigurationType; -import edu.harvard.i2b2.crc.datavo.pm.ObjectFactory; -import edu.harvard.i2b2.crc.datavo.pm.ParamType; -import edu.harvard.i2b2.crc.datavo.pm.ProjectType; -import edu.harvard.i2b2.crc.datavo.pm.RoleType; -import edu.harvard.i2b2.crc.datavo.pm.RolesType; -import edu.harvard.i2b2.crc.datavo.pm.UserType; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - -public class EJBPMUtil { - - public static String LOCKEDOUT = "LOCKEDOUT"; - - private static Log log = LogFactory.getLog(EJBPMUtil.class); - protected static Log logesapi = LogFactory.getLog(EJBPMUtil.class); - - public static void setUserLockedParam(String userName, - String paramName, String lockDate, SecurityType securityType, String projectId, String ontologyUrl ) throws I2B2Exception { - - ParamType paramType = new ParamType(); - paramType.setName(LOCKEDOUT); - paramType.setValue(lockDate); - paramType.setDatatype("T"); - - ObjectFactory of = new ObjectFactory(); - BodyType bodyType = new BodyType(); - - ProjectType projectType1 = of.createProjectType(); - projectType1.getParam().add(paramType); - projectType1.setUserName(userName); - projectType1.setId(projectId); - bodyType.getAny().add(of.createSetProjectUserParam(projectType1)); - RequestMessageType requestMessageType = getI2B2RequestMessage(bodyType, securityType, projectId); - OMElement requestElement = null; - - try { - requestElement = buildOMElement(requestMessageType); - log.debug("CRC PM call's request xml " + requestElement); - //OMElement response = getServiceClient().sendReceive(requestElement); - String response = ServiceClient.sendREST(ontologyUrl, requestElement); - // :TODO check the status in the response - - // projectType = getUserProjectFromResponse(response.toString()); - } catch (XMLStreamException e) { - e.printStackTrace(); - throw new I2B2Exception("" + StackTraceUtil.getStackTrace(e)); - } catch (JAXBUtilException e) { - e.printStackTrace(); - throw new I2B2Exception("" + StackTraceUtil.getStackTrace(e)); - } catch (Exception e) { - e.printStackTrace(); - throw new I2B2Exception( - "AxisFault error when setting lockedout param for user " - + StackTraceUtil.getStackTrace(e)); - } - } - - public static ProjectType callUserProject(SecurityType securityType, String projectId, String ontologyUrl ) throws AxisFault, I2B2Exception { - // build message body - // GetUserInfoType getUserInfoType = null; - GetUserConfigurationType userConfig = new GetUserConfigurationType(); - userConfig.getProject().add(projectId); - - ObjectFactory of = new ObjectFactory(); - BodyType bodyType = new BodyType(); - bodyType.getAny().add(of.createGetUserConfiguration(userConfig)); - RequestMessageType requestMessageType = getI2B2RequestMessage(bodyType, securityType, projectId); - OMElement requestElement = null; - ProjectType projectType = null; - try { - requestElement = buildOMElement(requestMessageType); - log.debug("CRC PM call's request xml " + requestElement); - //OMElement response = getServiceClient().sendReceive(requestElement); - String response = ServiceClient.sendREST(ontologyUrl, requestElement ); - projectType = getUserProjectFromResponse(response, securityType, projectId); - } catch (XMLStreamException e) { - e.printStackTrace(); - throw new I2B2Exception("" + StackTraceUtil.getStackTrace(e)); - } catch (Exception e) { - e.printStackTrace(); - throw new I2B2Exception("" + StackTraceUtil.getStackTrace(e)); - } - - return projectType; - } - - public static RolesType callGetRole(String userId, SecurityType securityType, String projectId, String ontologyUrl ) - throws AxisFault, I2B2Exception { - RolesType rolesType = new RolesType(); - String pmBypassRole = null, pmBypassProject = null; - // boolean pmBypass = false; - // try { - // pmBypass = QueryProcessorUtil.getInstance() - // .getProjectManagementByPassFlag(); - // pmBypassRole = QueryProcessorUtil.getInstance() - // .getProjectManagementByPassRole(); - - // log.debug("Project Management bypass flag from property file :[" - // + pmBypass + "] bypass role [" + pmBypassRole - // + "] project [" + pmBypassProject + "]"); - // } catch (I2B2Exception e1) { - // e1.printStackTrace(); - // log - // .info("Could not read Project Management bypass setting, trying PM without bypass option"); - // } -/* - if (pmBypass == true) { - log.info("Using Project Management by pass option "); - log - .info("Using project Management bypass flag from property file :[" - + pmBypass - + "] bypass role [" - + pmBypassRole - + "] project [" + pmBypassProject + "]"); - - if (pmBypassRole != null) { - String[] roles = pmBypassRole.split(","); - RoleType role = null; - for (int i = 0; i < roles.length; i++) { - role = new RoleType(); - role.setRole(roles[i]); - rolesType.getRole().add(role); - } - } - - } else { - */ - RoleType roleType = new RoleType(); - roleType.setUserName(userId); - roleType.setProjectId(projectId); - ObjectFactory of = new ObjectFactory(); - BodyType bodyType = new BodyType(); - bodyType.getAny().add(of.createGetAllRole(roleType)); - RequestMessageType requestMessageType = getI2B2RequestMessage(bodyType, securityType, projectId); - OMElement requestElement = null; - - try { - requestElement = buildOMElement(requestMessageType); - log.debug("CRC PM call's request xml " + requestElement); - //OMElement response = getServiceClient().sendReceive( - // requestElement); - String response = ServiceClient.sendREST(ontologyUrl,requestElement); - - rolesType = getUserRolesFromResponse(response); - } catch (XMLStreamException e) { - e.printStackTrace(); - throw new I2B2Exception("" + StackTraceUtil.getStackTrace(e)); - } catch (Exception e) { - e.printStackTrace(); - throw new I2B2Exception("" + StackTraceUtil.getStackTrace(e)); - } - // } - - return rolesType; - } - - private static ProjectType getUserProjectFromResponse(String responseXml, SecurityType securityType, String projectId ) - throws JAXBUtilException, I2B2Exception { - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil() - .unMashallFromString(responseXml); - ResponseMessageType pmRespMessageType = (ResponseMessageType) responseJaxb - .getValue(); - logesapi.debug("CRC's PM call response xml" + responseXml); - - ResponseHeaderType responseHeader = pmRespMessageType - .getResponseHeader(); - StatusType status = responseHeader.getResultStatus().getStatus(); - String procStatus = status.getType(); - String procMessage = status.getValue(); - - if (procStatus.equals("ERROR")) { - logesapi.info("PM Error reported by CRC web Service " + procMessage); - throw new I2B2Exception("PM Error reported by CRC web Service " - + procMessage); - } else if (procStatus.equals("WARNING")) { - logesapi.info("PM Warning reported by CRC web Service" + procMessage); - throw new I2B2Exception("PM Warning reported by CRC web Service" - + procMessage); - } - - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - ConfigureType configureType = (ConfigureType) helper.getObjectByClass( - pmRespMessageType.getMessageBody().getAny(), - ConfigureType.class); - UserType userType = configureType.getUser(); - List projectTypeList = userType.getProject(); - - ProjectType projectType = null; - if (projectTypeList != null && projectTypeList.size() > 0) { - for (ProjectType pType : projectTypeList) { - if (pType.getId().equalsIgnoreCase(projectId)) { - projectType = pType; - - break; - } - } - if (projectType == null) { - throw new I2B2Exception("User not registered to the project[" - + projectId + "]"); - } - } - - return projectType; - } - - private static RolesType getUserRolesFromResponse(String responseXml) - throws JAXBUtilException, I2B2Exception { - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil() - .unMashallFromString(responseXml); - ResponseMessageType pmRespMessageType = (ResponseMessageType) responseJaxb - .getValue(); - logesapi.debug("CRC's PM call response xml" + responseXml); - - ResponseHeaderType responseHeader = pmRespMessageType - .getResponseHeader(); - StatusType status = responseHeader.getResultStatus().getStatus(); - String procStatus = status.getType(); - String procMessage = status.getValue(); - - if (procStatus.equals("ERROR")) { - logesapi.info("PM Error reported by CRC web Service " + procMessage); - throw new I2B2Exception("PM Error reported by CRC web Service " - + procMessage); - } else if (procStatus.equals("WARNING")) { - logesapi.info("PM Warning reported by CRC web Service" + procMessage); - throw new I2B2Exception("PM Warning reported by CRC web Service" - + procMessage); - } - - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - RolesType rolesType = (RolesType) helper.getObjectByClass( - pmRespMessageType.getMessageBody().getAny(), RolesType.class); - return rolesType; - - } - - private static OMElement buildOMElement(RequestMessageType requestMessageType) - throws XMLStreamException, JAXBUtilException { - StringWriter strWriter = new StringWriter(); - edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory hiveof = new edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory(); - CRCJAXBUtil.getJAXBUtil().marshaller( - hiveof.createRequest(requestMessageType), strWriter); - // getOMElement from message - OMFactory fac = OMAbstractFactory.getOMFactory(); - - StringReader strReader = new StringReader(strWriter.toString()); - XMLInputFactory xif = XMLInputFactory.newInstance(); - XMLStreamReader reader = xif.createXMLStreamReader(strReader); - OMElement request = OMXMLBuilderFactory.createStAXOMBuilder(reader).getDocumentElement(); - - return request; - } - - private static RequestMessageType getI2B2RequestMessage(BodyType bodyType, SecurityType securityType, String projectId ) { - QueryProcessorUtil queryUtil = QueryProcessorUtil.getInstance(); - MessageHeaderType messageHeaderType = queryUtil.getMessageHeader(); - messageHeaderType.setSecurity(securityType); - messageHeaderType.setProjectId(projectId); - - messageHeaderType.setReceivingApplication(messageHeaderType - .getSendingApplication()); - FacilityType facilityType = new FacilityType(); - facilityType.setFacilityName("sample"); - messageHeaderType.setSendingFacility(facilityType); - messageHeaderType.setReceivingFacility(facilityType); - RequestMessageType requestMessageType = new RequestMessageType(); - requestMessageType.setMessageBody(bodyType); - - requestMessageType.setMessageHeader(messageHeaderType); - - RequestHeaderType requestHeader = new RequestHeaderType(); - requestHeader.setResultWaittimeMs(180000); - requestMessageType.setRequestHeader(requestHeader); - - return requestMessageType; - - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.delegate.ejbpm; + +import java.io.StringReader; +import java.io.StringWriter; +import java.util.List; + +import jakarta.xml.bind.JAXBElement; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import org.apache.axiom.om.OMAbstractFactory; +import org.apache.axiom.om.OMElement; +import org.apache.axiom.om.OMFactory; +import org.apache.axiom.om.OMXMLBuilderFactory; +import org.apache.axis2.AxisFault; +import edu.harvard.i2b2.common.util.axis2.ServiceClient; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.exception.StackTraceUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.dao.DblookupDao; +import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2message.FacilityType; +import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; +import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; +import edu.harvard.i2b2.crc.datavo.pm.ConfigureType; +import edu.harvard.i2b2.crc.datavo.pm.GetUserConfigurationType; +import edu.harvard.i2b2.crc.datavo.pm.ObjectFactory; +import edu.harvard.i2b2.crc.datavo.pm.ParamType; +import edu.harvard.i2b2.crc.datavo.pm.ProjectType; +import edu.harvard.i2b2.crc.datavo.pm.RoleType; +import edu.harvard.i2b2.crc.datavo.pm.RolesType; +import edu.harvard.i2b2.crc.datavo.pm.UserType; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + +public class EJBPMUtil { + + public static String LOCKEDOUT = "LOCKEDOUT"; + + private static Log log = LogFactory.getLog(EJBPMUtil.class); + protected static Log logesapi = LogFactory.getLog(EJBPMUtil.class); + + public static void setUserLockedParam(String userName, + String paramName, String lockDate, SecurityType securityType, String projectId, String ontologyUrl ) throws I2B2Exception { + + ParamType paramType = new ParamType(); + paramType.setName(LOCKEDOUT); + paramType.setValue(lockDate); + paramType.setDatatype("T"); + + ObjectFactory of = new ObjectFactory(); + BodyType bodyType = new BodyType(); + + ProjectType projectType1 = of.createProjectType(); + projectType1.getParam().add(paramType); + projectType1.setUserName(userName); + projectType1.setId(projectId); + bodyType.getAny().add(of.createSetProjectUserParam(projectType1)); + RequestMessageType requestMessageType = getI2B2RequestMessage(bodyType, securityType, projectId); + OMElement requestElement = null; + + try { + requestElement = buildOMElement(requestMessageType); + log.debug("CRC PM call's request xml " + requestElement); + //OMElement response = getServiceClient().sendReceive(requestElement); + String response = ServiceClient.sendREST(ontologyUrl, requestElement); + // :TODO check the status in the response + + // projectType = getUserProjectFromResponse(response.toString()); + } catch (XMLStreamException e) { + e.printStackTrace(); + throw new I2B2Exception("" + StackTraceUtil.getStackTrace(e)); + } catch (JAXBUtilException e) { + e.printStackTrace(); + throw new I2B2Exception("" + StackTraceUtil.getStackTrace(e)); + } catch (Exception e) { + e.printStackTrace(); + throw new I2B2Exception( + "AxisFault error when setting lockedout param for user " + + StackTraceUtil.getStackTrace(e)); + } + } + + public static ProjectType callUserProject(SecurityType securityType, String projectId, String ontologyUrl ) throws AxisFault, I2B2Exception { + // build message body + // GetUserInfoType getUserInfoType = null; + GetUserConfigurationType userConfig = new GetUserConfigurationType(); + userConfig.getProject().add(projectId); + + ObjectFactory of = new ObjectFactory(); + BodyType bodyType = new BodyType(); + bodyType.getAny().add(of.createGetUserConfiguration(userConfig)); + RequestMessageType requestMessageType = getI2B2RequestMessage(bodyType, securityType, projectId); + OMElement requestElement = null; + ProjectType projectType = null; + try { + requestElement = buildOMElement(requestMessageType); + log.debug("CRC PM call's request xml " + requestElement); + //OMElement response = getServiceClient().sendReceive(requestElement); + String response = ServiceClient.sendREST(ontologyUrl, requestElement ); + projectType = getUserProjectFromResponse(response, securityType, projectId); + } catch (XMLStreamException e) { + e.printStackTrace(); + throw new I2B2Exception("" + StackTraceUtil.getStackTrace(e)); + } catch (Exception e) { + e.printStackTrace(); + throw new I2B2Exception("" + StackTraceUtil.getStackTrace(e)); + } + + return projectType; + } + + public static RolesType callGetRole(String userId, SecurityType securityType, String projectId, String ontologyUrl ) + throws AxisFault, I2B2Exception { + RolesType rolesType = new RolesType(); + String pmBypassRole = null, pmBypassProject = null; + // boolean pmBypass = false; + // try { + // pmBypass = QueryProcessorUtil.getInstance() + // .getProjectManagementByPassFlag(); + // pmBypassRole = QueryProcessorUtil.getInstance() + // .getProjectManagementByPassRole(); + + // log.debug("Project Management bypass flag from property file :[" + // + pmBypass + "] bypass role [" + pmBypassRole + // + "] project [" + pmBypassProject + "]"); + // } catch (I2B2Exception e1) { + // e1.printStackTrace(); + // log + // .info("Could not read Project Management bypass setting, trying PM without bypass option"); + // } +/* + if (pmBypass == true) { + log.info("Using Project Management by pass option "); + log + .info("Using project Management bypass flag from property file :[" + + pmBypass + + "] bypass role [" + + pmBypassRole + + "] project [" + pmBypassProject + "]"); + + if (pmBypassRole != null) { + String[] roles = pmBypassRole.split(","); + RoleType role = null; + for (int i = 0; i < roles.length; i++) { + role = new RoleType(); + role.setRole(roles[i]); + rolesType.getRole().add(role); + } + } + + } else { + */ + RoleType roleType = new RoleType(); + roleType.setUserName(userId); + roleType.setProjectId(projectId); + ObjectFactory of = new ObjectFactory(); + BodyType bodyType = new BodyType(); + bodyType.getAny().add(of.createGetAllRole(roleType)); + RequestMessageType requestMessageType = getI2B2RequestMessage(bodyType, securityType, projectId); + OMElement requestElement = null; + + try { + requestElement = buildOMElement(requestMessageType); + log.debug("CRC PM call's request xml " + requestElement); + //OMElement response = getServiceClient().sendReceive( + // requestElement); + String response = ServiceClient.sendREST(ontologyUrl,requestElement); + + rolesType = getUserRolesFromResponse(response); + } catch (XMLStreamException e) { + e.printStackTrace(); + throw new I2B2Exception("" + StackTraceUtil.getStackTrace(e)); + } catch (Exception e) { + e.printStackTrace(); + throw new I2B2Exception("" + StackTraceUtil.getStackTrace(e)); + } + // } + + return rolesType; + } + + private static ProjectType getUserProjectFromResponse(String responseXml, SecurityType securityType, String projectId ) + throws JAXBUtilException, I2B2Exception { + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil() + .unMashallFromString(responseXml); + ResponseMessageType pmRespMessageType = (ResponseMessageType) responseJaxb + .getValue(); + logesapi.debug("CRC's PM call response xml" + responseXml); + + ResponseHeaderType responseHeader = pmRespMessageType + .getResponseHeader(); + StatusType status = responseHeader.getResultStatus().getStatus(); + String procStatus = status.getType(); + String procMessage = status.getValue(); + + if (procStatus.equals("ERROR")) { + logesapi.info("PM Error reported by CRC web Service " + procMessage); + throw new I2B2Exception("PM Error reported by CRC web Service " + + procMessage); + } else if (procStatus.equals("WARNING")) { + logesapi.info("PM Warning reported by CRC web Service" + procMessage); + throw new I2B2Exception("PM Warning reported by CRC web Service" + + procMessage); + } + + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + ConfigureType configureType = (ConfigureType) helper.getObjectByClass( + pmRespMessageType.getMessageBody().getAny(), + ConfigureType.class); + UserType userType = configureType.getUser(); + List projectTypeList = userType.getProject(); + + ProjectType projectType = null; + if (projectTypeList != null && projectTypeList.size() > 0) { + for (ProjectType pType : projectTypeList) { + if (pType.getId().equalsIgnoreCase(projectId)) { + projectType = pType; + + break; + } + } + if (projectType == null) { + throw new I2B2Exception("User not registered to the project[" + + projectId + "]"); + } + } + + return projectType; + } + + private static RolesType getUserRolesFromResponse(String responseXml) + throws JAXBUtilException, I2B2Exception { + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil() + .unMashallFromString(responseXml); + ResponseMessageType pmRespMessageType = (ResponseMessageType) responseJaxb + .getValue(); + logesapi.debug("CRC's PM call response xml" + responseXml); + + ResponseHeaderType responseHeader = pmRespMessageType + .getResponseHeader(); + StatusType status = responseHeader.getResultStatus().getStatus(); + String procStatus = status.getType(); + String procMessage = status.getValue(); + + if (procStatus.equals("ERROR")) { + logesapi.info("PM Error reported by CRC web Service " + procMessage); + throw new I2B2Exception("PM Error reported by CRC web Service " + + procMessage); + } else if (procStatus.equals("WARNING")) { + logesapi.info("PM Warning reported by CRC web Service" + procMessage); + throw new I2B2Exception("PM Warning reported by CRC web Service" + + procMessage); + } + + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + RolesType rolesType = (RolesType) helper.getObjectByClass( + pmRespMessageType.getMessageBody().getAny(), RolesType.class); + return rolesType; + + } + + private static OMElement buildOMElement(RequestMessageType requestMessageType) + throws XMLStreamException, JAXBUtilException { + StringWriter strWriter = new StringWriter(); + edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory hiveof = new edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory(); + CRCJAXBUtil.getJAXBUtil().marshaller( + hiveof.createRequest(requestMessageType), strWriter); + // getOMElement from message + OMFactory fac = OMAbstractFactory.getOMFactory(); + + StringReader strReader = new StringReader(strWriter.toString()); + XMLInputFactory xif = XMLInputFactory.newInstance(); + XMLStreamReader reader = xif.createXMLStreamReader(strReader); + OMElement request = OMXMLBuilderFactory.createStAXOMBuilder(reader).getDocumentElement(); + + return request; + } + + private static RequestMessageType getI2B2RequestMessage(BodyType bodyType, SecurityType securityType, String projectId ) { + QueryProcessorUtil queryUtil = QueryProcessorUtil.getInstance(); + MessageHeaderType messageHeaderType = queryUtil.getMessageHeader(); + messageHeaderType.setSecurity(securityType); + messageHeaderType.setProjectId(projectId); + + messageHeaderType.setReceivingApplication(messageHeaderType + .getSendingApplication()); + FacilityType facilityType = new FacilityType(); + facilityType.setFacilityName("sample"); + messageHeaderType.setSendingFacility(facilityType); + messageHeaderType.setReceivingFacility(facilityType); + RequestMessageType requestMessageType = new RequestMessageType(); + requestMessageType.setMessageBody(bodyType); + + requestMessageType.setMessageHeader(messageHeaderType); + + RequestHeaderType requestHeader = new RequestHeaderType(); + requestHeader.setResultWaittimeMs(180000); + requestMessageType.setRequestHeader(requestHeader); + + return requestMessageType; + + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/getnameinfo/GeNameInfoHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/getnameinfo/GeNameInfoHandler.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/getnameinfo/GeNameInfoHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/getnameinfo/GeNameInfoHandler.java index d948909e..419b80e3 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/getnameinfo/GeNameInfoHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/getnameinfo/GeNameInfoHandler.java @@ -1,95 +1,95 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.delegate.getnameinfo; - - -import edu.harvard.i2b2.crc.datavo.setfinder.query.FindByChildType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterResponseType; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; -import edu.harvard.i2b2.crc.delegate.RequestHandler; -import edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate; -import edu.harvard.i2b2.crc.ejb.QueryInfoBean; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - - -/** - * GetObservationFactFromPrimaryKeyHandler class. - * $Id: GetObservationFactFromPrimaryKeyHandler.java,v 1.8 2008/07/21 19:56:56 rk903 Exp $ - * @author rkuttan - */ -public class GeNameInfoHandler extends RequestHandler { - private FindByChildType getFindByChildType = - null; - private SecurityType userRequestType = null; - - /** - * Constuctor which accepts i2b2 request message xml - * @param requestXml - * @throws I2B2Exception - */ - public GeNameInfoHandler(String requestXml) - throws I2B2Exception { - try { - this.getFindByChildType = (FindByChildType) this.getRequestType(requestXml, - edu.harvard.i2b2.crc.datavo.setfinder.query.FindByChildType.class); - RequestMessageType requestMsg = getI2B2RequestMessageType( requestXml); - this.userRequestType = requestMsg.getMessageHeader() - .getSecurity(); - this.setDataSourceLookup(requestXml); - } catch (JAXBUtilException jaxbUtilEx) { - throw new I2B2Exception("Error ", jaxbUtilEx); - } - } - - /** - * Perform operation for the given request and - * return response - */ - @Override - public BodyType execute() throws I2B2Exception { - // call ejb and pass input object - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - String responseString = null; - BodyType bodyType = new BodyType(); - MasterResponseType masterResponseType = null; - try { - long initialTime = System.currentTimeMillis(); - // masterResponseType = queryInfoLocal.getQueryMasterListFromUserId(getDataSourceLookup(),userRequestType); - QueryInfoBean query = new QueryInfoBean(); - masterResponseType = query.getQueryMasterListFromNameInfo(getDataSourceLookup(),userRequestType, getFindByChildType); - long finalTime = System.currentTimeMillis(); - long diffTimeMill = finalTime - initialTime; - long diffTime = diffTimeMill / 1000; - log.debug(" EJB Diff mill =" + diffTimeMill + " diffTime =" + - diffTime); - masterResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.DONE_TYPE, "DONE")); - } catch (Exception e) { - log.debug(e.getMessage()); - masterResponseType = new MasterResponseType(); - masterResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.ERROR_TYPE, e.getMessage())); - } finally { - edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); - bodyType.getAny().add(of.createResponse(masterResponseType)); - } - - return bodyType; - } -} - - +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.delegate.getnameinfo; + + +import edu.harvard.i2b2.crc.datavo.setfinder.query.FindByChildType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterResponseType; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; +import edu.harvard.i2b2.crc.delegate.RequestHandler; +import edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate; +import edu.harvard.i2b2.crc.ejb.QueryInfoBean; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + + +/** + * GetObservationFactFromPrimaryKeyHandler class. + * $Id: GetObservationFactFromPrimaryKeyHandler.java,v 1.8 2008/07/21 19:56:56 rk903 Exp $ + * @author rkuttan + */ +public class GeNameInfoHandler extends RequestHandler { + private FindByChildType getFindByChildType = + null; + private SecurityType userRequestType = null; + + /** + * Constuctor which accepts i2b2 request message xml + * @param requestXml + * @throws I2B2Exception + */ + public GeNameInfoHandler(String requestXml) + throws I2B2Exception { + try { + this.getFindByChildType = (FindByChildType) this.getRequestType(requestXml, + edu.harvard.i2b2.crc.datavo.setfinder.query.FindByChildType.class); + RequestMessageType requestMsg = getI2B2RequestMessageType( requestXml); + this.userRequestType = requestMsg.getMessageHeader() + .getSecurity(); + this.setDataSourceLookup(requestXml); + } catch (JAXBUtilException jaxbUtilEx) { + throw new I2B2Exception("Error ", jaxbUtilEx); + } + } + + /** + * Perform operation for the given request and + * return response + */ + @Override + public BodyType execute() throws I2B2Exception { + // call ejb and pass input object + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + String responseString = null; + BodyType bodyType = new BodyType(); + MasterResponseType masterResponseType = null; + try { + long initialTime = System.currentTimeMillis(); + // masterResponseType = queryInfoLocal.getQueryMasterListFromUserId(getDataSourceLookup(),userRequestType); + QueryInfoBean query = new QueryInfoBean(); + masterResponseType = query.getQueryMasterListFromNameInfo(getDataSourceLookup(),userRequestType, getFindByChildType); + long finalTime = System.currentTimeMillis(); + long diffTimeMill = finalTime - initialTime; + long diffTime = diffTimeMill / 1000; + log.debug(" EJB Diff mill =" + diffTimeMill + " diffTime =" + + diffTime); + masterResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.DONE_TYPE, "DONE")); + } catch (Exception e) { + log.debug(e.getMessage()); + masterResponseType = new MasterResponseType(); + masterResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.ERROR_TYPE, e.getMessage())); + } finally { + edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); + bodyType.getAny().add(of.createResponse(masterResponseType)); + } + + return bodyType; + } +} + + diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/getnameinfo/GetNameInfoRequestDelegate.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/getnameinfo/GetNameInfoRequestDelegate.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/getnameinfo/GetNameInfoRequestDelegate.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/getnameinfo/GetNameInfoRequestDelegate.java index c19ee0fb..90238f42 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/getnameinfo/GetNameInfoRequestDelegate.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/getnameinfo/GetNameInfoRequestDelegate.java @@ -1,266 +1,266 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Mike Mendis - */ -package edu.harvard.i2b2.crc.delegate.getnameinfo; - -import java.util.List; - -import jakarta.xml.bind.JAXBElement; - -import org.apache.axis2.AxisFault; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.exception.StackTraceUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.I2B2MessageResponseFactory; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; -import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; -import edu.harvard.i2b2.crc.datavo.pm.ParamType; -import edu.harvard.i2b2.crc.datavo.pm.ProjectType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.FindByChildType; -import edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate; -import edu.harvard.i2b2.crc.delegate.pm.PMServiceDriver; -import edu.harvard.i2b2.crc.ejb.ExecRunnable; -import edu.harvard.i2b2.crc.util.CacheUtil; -import edu.harvard.i2b2.crc.util.ParamUtil; - - -public class GetNameInfoRequestDelegate extends RequestHandlerDelegate { - /** log **/ - protected final Log log = LogFactory.getLog(getClass()); - protected static Log logesapi = LogFactory.getLog(GetNameInfoRequestDelegate.class); - - /** - * @see edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate#handleRequest(java.lang.String) - */ - @Override - public String handleRequest(String requestXml) throws I2B2Exception { -// PdoQryHeaderType headerType = null; PsmQryHeaderType - FindByChildType childType = null; - String response = null; - JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); - - try { - JAXBElement jaxbElement = jaxbUtil.unMashallFromString(requestXml); - RequestMessageType requestMessageType = (RequestMessageType) jaxbElement - .getValue(); - BodyType bodyType = requestMessageType.getMessageBody(); - - if (bodyType == null) { - log.error("null value in body type"); - throw new I2B2Exception("null value in body type"); - } - - // Call PM cell to validate user - - StatusType procStatus = null; - try { - SecurityType securityType = null; - String projectId = null; - if (requestMessageType.getMessageHeader() != null) { - if (requestMessageType.getMessageHeader().getSecurity() != null) { - securityType = requestMessageType.getMessageHeader() - .getSecurity(); - } - projectId = requestMessageType.getMessageHeader() - .getProjectId(); - } - - if (securityType == null) { - procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus - .setValue("Request message missing user/password"); - response = I2B2MessageResponseFactory.buildResponseMessage( - requestXml, procStatus, bodyType); - return response; - } - if (projectId == null) { - procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus.setValue("Missing "); - response = I2B2MessageResponseFactory.buildResponseMessage( - requestXml, procStatus, bodyType); - return response; - } - - PMServiceDriver pmServiceDriver = new PMServiceDriver(); - ProjectType projectType = pmServiceDriver.checkValidUser( - securityType, projectId); - // projectType.getRole() - if (projectType == null) { - procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus - .setValue("Invalid user/password for the given project [" - + projectId + "]"); - response = I2B2MessageResponseFactory.buildResponseMessage( - requestXml, procStatus, bodyType); - return response; - } - - log.debug("project name from PM " + projectType.getName()); - logesapi.debug("project id from PM " + projectType.getId()); - if (projectType.getRole() != null) { - log.debug("project role from PM " - + projectType.getRole().get(0)); - this.putRoles(projectId, securityType.getUsername(), - securityType.getDomain(), projectType.getRole()); - - //TODO removed cache - //Node rootNode = CacheUtil.getCache().getRoot(); - //List roles = (List) rootNode - // .get(securityType.getDomain() + "/" + projectId - // + "/" + securityType.getUsername()); - List roles = (List) CacheUtil - .get(securityType.getDomain() + "/" + projectId - + "/" + securityType.getUsername()); - if (roles != null) { - log.debug("User Roles count " + roles.size()); - } - - ParamUtil paramUtil = new ParamUtil(); - paramUtil.clearParam(projectId, securityType.getUsername(), securityType.getDomain(), ParamUtil.CRC_ENABLE_UNITCD_CONVERSION); - if (projectType.getParam() != null) { - for (ParamType param : projectType.getParam()) { - if (param.getName() != null && param.getName().trim().equalsIgnoreCase(ParamUtil.CRC_ENABLE_UNITCD_CONVERSION)) { - paramUtil.putParam(projectId, securityType.getUsername(), securityType.getDomain(),ParamUtil.CRC_ENABLE_UNITCD_CONVERSION,param); - String unitCdCache = paramUtil.getParam(projectId, securityType.getUsername(), securityType.getDomain(),ParamUtil.CRC_ENABLE_UNITCD_CONVERSION); - logesapi.debug("CRC param stored in the cache Project Id [" + projectId + "] user [" + securityType.getUsername() + "] domain [" + securityType.getDomain() + "] " + ParamUtil.CRC_ENABLE_UNITCD_CONVERSION + "[" + unitCdCache + "]" ); - break; - } - } - } - - - } else { - - log.error("Project role not set for the user "); - - } - } catch (AxisFault e) { - procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus.setValue("Could not connect to server[" - + e.getDetail() + "]"); - response = I2B2MessageResponseFactory.buildResponseMessage( - requestXml, procStatus, bodyType); - return response; - } catch (I2B2Exception e) { - procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus - .setValue("Project Management cell interface error: [" - + e.getMessage() + "]"); - response = I2B2MessageResponseFactory.buildResponseMessage( - requestXml, procStatus, bodyType); - return response; - } catch (JAXBUtilException e) { - procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus - .setValue("Message error from Project Management cell[" - + e.getMessage() + "]"); - response = I2B2MessageResponseFactory.buildResponseMessage( - requestXml, procStatus, bodyType); - return response; - } - - JAXBUnWrapHelper unWrapHelper = new JAXBUnWrapHelper(); - childType = (FindByChildType) unWrapHelper - .getObjectByClass( - bodyType.getAny(), - edu.harvard.i2b2.crc.datavo.setfinder.query.FindByChildType.class); - - BodyType responseBodyType = null; - - GeNameInfoHandler handler = new GeNameInfoHandler( - requestXml); - responseBodyType = handler.execute(); - /* - if (childType.getRequestType().equals( - PdoRequestTypeType.GET_PDO_FROM_INPUT_LIST)) { - GetPDOFromInputListHandler handler = new GetPDOFromInputListHandler( - requestXml); - responseBodyType = handler.execute(); - } else if (headerType.getRequestType().equals( - PdoRequestTypeType.GET_OBSERVATIONFACT_BY_PRIMARY_KEY)) { - GetObservationFactFromPrimaryKeyHandler handler = new GetObservationFactFromPrimaryKeyHandler( - requestXml); - responseBodyType = handler.execute(); - } else if (headerType.getRequestType().equals( - PdoRequestTypeType.GET_PDO_TEMPLATE)) { - GetPDOTemplateHandler handler = new GetPDOTemplateHandler( - requestXml); - responseBodyType = handler.execute(); - } - */ - procStatus = new StatusType(); - procStatus.setType("DONE"); - procStatus.setValue("DONE"); - - long startTime = System.currentTimeMillis(); - response = I2B2MessageResponseFactory.buildResponseMessage( - requestXml, procStatus, responseBodyType, true); - long endTime = System.currentTimeMillis(); - long totalTime = endTime - startTime; - log.debug("Total time to pdo jaxb " + totalTime); - - } catch (JAXBUtilException e) { - log.error("JAXBUtil exception", e); - StatusType procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus.setValue(requestXml + "\n\n" - + StackTraceUtil.getStackTrace(e)); - try { - response = I2B2MessageResponseFactory.buildResponseMessage( - null, procStatus, null); - } catch (JAXBUtilException e1) { - e1.printStackTrace(); - } - } catch (I2B2Exception e) { - log.error("I2B2Exception", e); - StatusType procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus.setValue(StackTraceUtil.getStackTrace(e)); - try { - response = I2B2MessageResponseFactory.buildResponseMessage( - requestXml, procStatus, null); - } catch (JAXBUtilException e1) { - e1.printStackTrace(); - } - } catch (Throwable e) { - log.error("Throwable", e); - StatusType procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus.setValue(StackTraceUtil.getStackTrace(e)); - try { - response = I2B2MessageResponseFactory.buildResponseMessage( - requestXml, procStatus, null); - } catch (JAXBUtilException e1) { - e1.printStackTrace(); - } - } - return response; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Mike Mendis + */ +package edu.harvard.i2b2.crc.delegate.getnameinfo; + +import java.util.List; + +import jakarta.xml.bind.JAXBElement; + +import org.apache.axis2.AxisFault; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.exception.StackTraceUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; +import edu.harvard.i2b2.crc.datavo.I2B2MessageResponseFactory; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; +import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; +import edu.harvard.i2b2.crc.datavo.pm.ParamType; +import edu.harvard.i2b2.crc.datavo.pm.ProjectType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.FindByChildType; +import edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate; +import edu.harvard.i2b2.crc.delegate.pm.PMServiceDriver; +import edu.harvard.i2b2.crc.ejb.ExecRunnable; +import edu.harvard.i2b2.crc.util.CacheUtil; +import edu.harvard.i2b2.crc.util.ParamUtil; + + +public class GetNameInfoRequestDelegate extends RequestHandlerDelegate { + /** log **/ + protected final Log log = LogFactory.getLog(getClass()); + protected static Log logesapi = LogFactory.getLog(GetNameInfoRequestDelegate.class); + + /** + * @see edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate#handleRequest(java.lang.String) + */ + @Override + public String handleRequest(String requestXml) throws I2B2Exception { +// PdoQryHeaderType headerType = null; PsmQryHeaderType + FindByChildType childType = null; + String response = null; + JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); + + try { + JAXBElement jaxbElement = jaxbUtil.unMashallFromString(requestXml); + RequestMessageType requestMessageType = (RequestMessageType) jaxbElement + .getValue(); + BodyType bodyType = requestMessageType.getMessageBody(); + + if (bodyType == null) { + log.error("null value in body type"); + throw new I2B2Exception("null value in body type"); + } + + // Call PM cell to validate user + + StatusType procStatus = null; + try { + SecurityType securityType = null; + String projectId = null; + if (requestMessageType.getMessageHeader() != null) { + if (requestMessageType.getMessageHeader().getSecurity() != null) { + securityType = requestMessageType.getMessageHeader() + .getSecurity(); + } + projectId = requestMessageType.getMessageHeader() + .getProjectId(); + } + + if (securityType == null) { + procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus + .setValue("Request message missing user/password"); + response = I2B2MessageResponseFactory.buildResponseMessage( + requestXml, procStatus, bodyType); + return response; + } + if (projectId == null) { + procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus.setValue("Missing "); + response = I2B2MessageResponseFactory.buildResponseMessage( + requestXml, procStatus, bodyType); + return response; + } + + PMServiceDriver pmServiceDriver = new PMServiceDriver(); + ProjectType projectType = pmServiceDriver.checkValidUser( + securityType, projectId); + // projectType.getRole() + if (projectType == null) { + procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus + .setValue("Invalid user/password for the given project [" + + projectId + "]"); + response = I2B2MessageResponseFactory.buildResponseMessage( + requestXml, procStatus, bodyType); + return response; + } + + log.debug("project name from PM " + projectType.getName()); + logesapi.debug("project id from PM " + projectType.getId()); + if (projectType.getRole() != null) { + log.debug("project role from PM " + + projectType.getRole().get(0)); + this.putRoles(projectId, securityType.getUsername(), + securityType.getDomain(), projectType.getRole()); + + //TODO removed cache + //Node rootNode = CacheUtil.getCache().getRoot(); + //List roles = (List) rootNode + // .get(securityType.getDomain() + "/" + projectId + // + "/" + securityType.getUsername()); + List roles = (List) CacheUtil + .get(securityType.getDomain() + "/" + projectId + + "/" + securityType.getUsername()); + if (roles != null) { + log.debug("User Roles count " + roles.size()); + } + + ParamUtil paramUtil = new ParamUtil(); + paramUtil.clearParam(projectId, securityType.getUsername(), securityType.getDomain(), ParamUtil.CRC_ENABLE_UNITCD_CONVERSION); + if (projectType.getParam() != null) { + for (ParamType param : projectType.getParam()) { + if (param.getName() != null && param.getName().trim().equalsIgnoreCase(ParamUtil.CRC_ENABLE_UNITCD_CONVERSION)) { + paramUtil.putParam(projectId, securityType.getUsername(), securityType.getDomain(),ParamUtil.CRC_ENABLE_UNITCD_CONVERSION,param); + String unitCdCache = paramUtil.getParam(projectId, securityType.getUsername(), securityType.getDomain(),ParamUtil.CRC_ENABLE_UNITCD_CONVERSION); + logesapi.debug("CRC param stored in the cache Project Id [" + projectId + "] user [" + securityType.getUsername() + "] domain [" + securityType.getDomain() + "] " + ParamUtil.CRC_ENABLE_UNITCD_CONVERSION + "[" + unitCdCache + "]" ); + break; + } + } + } + + + } else { + + log.error("Project role not set for the user "); + + } + } catch (AxisFault e) { + procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus.setValue("Could not connect to server[" + + e.getDetail() + "]"); + response = I2B2MessageResponseFactory.buildResponseMessage( + requestXml, procStatus, bodyType); + return response; + } catch (I2B2Exception e) { + procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus + .setValue("Project Management cell interface error: [" + + e.getMessage() + "]"); + response = I2B2MessageResponseFactory.buildResponseMessage( + requestXml, procStatus, bodyType); + return response; + } catch (JAXBUtilException e) { + procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus + .setValue("Message error from Project Management cell[" + + e.getMessage() + "]"); + response = I2B2MessageResponseFactory.buildResponseMessage( + requestXml, procStatus, bodyType); + return response; + } + + JAXBUnWrapHelper unWrapHelper = new JAXBUnWrapHelper(); + childType = (FindByChildType) unWrapHelper + .getObjectByClass( + bodyType.getAny(), + edu.harvard.i2b2.crc.datavo.setfinder.query.FindByChildType.class); + + BodyType responseBodyType = null; + + GeNameInfoHandler handler = new GeNameInfoHandler( + requestXml); + responseBodyType = handler.execute(); + /* + if (childType.getRequestType().equals( + PdoRequestTypeType.GET_PDO_FROM_INPUT_LIST)) { + GetPDOFromInputListHandler handler = new GetPDOFromInputListHandler( + requestXml); + responseBodyType = handler.execute(); + } else if (headerType.getRequestType().equals( + PdoRequestTypeType.GET_OBSERVATIONFACT_BY_PRIMARY_KEY)) { + GetObservationFactFromPrimaryKeyHandler handler = new GetObservationFactFromPrimaryKeyHandler( + requestXml); + responseBodyType = handler.execute(); + } else if (headerType.getRequestType().equals( + PdoRequestTypeType.GET_PDO_TEMPLATE)) { + GetPDOTemplateHandler handler = new GetPDOTemplateHandler( + requestXml); + responseBodyType = handler.execute(); + } + */ + procStatus = new StatusType(); + procStatus.setType("DONE"); + procStatus.setValue("DONE"); + + long startTime = System.currentTimeMillis(); + response = I2B2MessageResponseFactory.buildResponseMessage( + requestXml, procStatus, responseBodyType, true); + long endTime = System.currentTimeMillis(); + long totalTime = endTime - startTime; + log.debug("Total time to pdo jaxb " + totalTime); + + } catch (JAXBUtilException e) { + log.error("JAXBUtil exception", e); + StatusType procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus.setValue(requestXml + "\n\n" + + StackTraceUtil.getStackTrace(e)); + try { + response = I2B2MessageResponseFactory.buildResponseMessage( + null, procStatus, null); + } catch (JAXBUtilException e1) { + e1.printStackTrace(); + } + } catch (I2B2Exception e) { + log.error("I2B2Exception", e); + StatusType procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus.setValue(StackTraceUtil.getStackTrace(e)); + try { + response = I2B2MessageResponseFactory.buildResponseMessage( + requestXml, procStatus, null); + } catch (JAXBUtilException e1) { + e1.printStackTrace(); + } + } catch (Throwable e) { + log.error("Throwable", e); + StatusType procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus.setValue(StackTraceUtil.getStackTrace(e)); + try { + response = I2B2MessageResponseFactory.buildResponseMessage( + requestXml, procStatus, null); + } catch (JAXBUtilException e1) { + e1.printStackTrace(); + } + } + return response; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/ontology/CallOntologyUtil.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/ontology/CallOntologyUtil.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/ontology/CallOntologyUtil.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/ontology/CallOntologyUtil.java index d0906c9b..4cd4c7c9 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/ontology/CallOntologyUtil.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/ontology/CallOntologyUtil.java @@ -1,722 +1,722 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.delegate.ontology; - -import java.io.IOException; -import java.io.StringReader; -import java.io.StringWriter; -import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import jakarta.xml.bind.JAXBElement; -import javax.xml.stream.XMLInputFactory; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamReader; - -import org.apache.axiom.om.OMAbstractFactory; -import org.apache.axiom.om.OMElement; -import org.apache.axiom.om.OMFactory; -import org.apache.axiom.om.OMXMLBuilderFactory; -import org.apache.axis2.AxisFault; -import edu.harvard.i2b2.common.util.axis2.ServiceClient; -//import org.apache.commons.httpclient.HttpClient; -//import org.apache.commons.httpclient.HttpException; -//import org.apache.commons.httpclient.methods.PostMethod; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.hc.core5.http.HttpException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2message.FacilityType; -import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; -import edu.harvard.i2b2.crc.datavo.ontology.ConceptType; -import edu.harvard.i2b2.crc.datavo.ontology.ConceptsType; -import edu.harvard.i2b2.crc.datavo.ontology.DeleteChildType; -import edu.harvard.i2b2.crc.datavo.ontology.DerivedFactColumnsType; -import edu.harvard.i2b2.crc.datavo.ontology.GetChildrenType; -import edu.harvard.i2b2.crc.datavo.ontology.GetModifierInfoType; -import edu.harvard.i2b2.crc.datavo.ontology.GetTermInfoType; -import edu.harvard.i2b2.crc.datavo.ontology.MatchStrType; -import edu.harvard.i2b2.crc.datavo.ontology.MetadataLoadType; -import edu.harvard.i2b2.crc.datavo.ontology.ModifierType; -import edu.harvard.i2b2.crc.datavo.ontology.ModifiersType; -import edu.harvard.i2b2.crc.datavo.ontology.ObjectFactory; -import edu.harvard.i2b2.crc.datavo.ontology.OntologyDataType; -import edu.harvard.i2b2.crc.datavo.ontology.VocabRequestType; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - -public class CallOntologyUtil { - - // private SecurityType securityType = null; - // private String projectId = null; - // private String ontologyUrl = null; - - private static Log log = LogFactory.getLog(CallOntologyUtil.class); - protected static Log logesapi = LogFactory.getLog(CallOntologyUtil.class); - - private static JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); - - - public static ConceptType callOntology(String itemKey, SecurityType securityType, String projectId, String ontologyUrl ) throws XMLStreamException, - JAXBUtilException, AxisFault, I2B2Exception { - RequestMessageType requestMessageType = getI2B2RequestMessage(itemKey, securityType, projectId.replaceAll("/", "")); - OMElement requestElement = buildOMElement(requestMessageType); - log.debug("CRC Ontology call's request xml from callOntology: " + requestElement); - log.debug("URL: " + ontologyUrl); - ConceptType conceptType = null; - try { - String response = ServiceClient.sendREST(ontologyUrl, requestElement); - conceptType = getConceptFromResponse(response); - } catch (Exception e) - { - - } - return conceptType; - } - - - public static MetadataLoadType callLoadData(String tablename, List c, SecurityType securityType, String projectId, String ontologyUrl ) throws XMLStreamException, - JAXBUtilException, AxisFault, I2B2Exception { - - RequestMessageType requestMessageType = getLoadDataI2B2RequestLoadDataMessage(tablename,c, securityType, projectId.replaceAll("/", "")); - OMElement requestElement = buildOMElement(requestMessageType); - log.debug("CRC Ontology call's request xml from callLoadData: " + requestElement); - log.debug("URL: " + ontologyUrl); - MetadataLoadType metadataLoadType = null; - try { - String response = ServiceClient.sendREST(ontologyUrl, requestElement); - metadataLoadType = getLoadDataFromResponse(response); - } catch (Exception e) - { - - } - return metadataLoadType; - - - } - - public static DeleteChildType callDeleteChild( DeleteChildType c, SecurityType securityType, String projectId, String ontologyUrl ) throws XMLStreamException, - JAXBUtilException, AxisFault, I2B2Exception { - - RequestMessageType requestMessageType = getI2B2RequestDeleteChildMessage(c, securityType, projectId.replaceAll("/", "")); - OMElement requestElement = buildOMElement(requestMessageType); - log.debug("CRC Ontology call's request xml from callLoadData: " + requestElement); - log.debug("URL: " + ontologyUrl); - DeleteChildType metadataLoadType = null; - try { - String response = ServiceClient.sendREST(ontologyUrl, requestElement); - metadataLoadType = getDeleteChildFromResponse(response); - } catch (Exception e) - { - - } - return metadataLoadType; - - - } - - - - - - - public static DerivedFactColumnsType callGetFactColumns(String itemKey, SecurityType securityType, String projectId, String ontologyUrl ) - throws XMLStreamException, JAXBUtilException, AxisFault,I2B2Exception { - - RequestMessageType requestMessageType = getDerivedFactColumnsI2B2RequestMessage(itemKey, securityType, projectId.replaceAll("/", "")); - OMElement requestElement = buildOMElement(requestMessageType); - DerivedFactColumnsType factColumns = null; - try { - String response = ServiceClient.sendREST(ontologyUrl, requestElement); - logesapi.debug("TEST callGetFactColumns:" + response ); - factColumns = getFactColumnsFromResponse(response); - } catch (Exception e) { - log.error(e.getMessage()); - } - return factColumns; - } - - - public static DerivedFactColumnsType callGetFactColumnsByConceptCd(String conceptCd, SecurityType securityType, String projectId, String ontologyUrl ) - throws XMLStreamException, JAXBUtilException, AxisFault,I2B2Exception { - RequestMessageType requestMessageType = getConceptsByCodeI2B2RequestMessage(conceptCd, securityType, projectId.replaceAll("/", "")); - OMElement requestElement = buildOMElement(requestMessageType); - DerivedFactColumnsType factColumns = null; - try { - String response = ServiceClient.sendREST(ontologyUrl, requestElement); - logesapi.debug("TEST callGetFactColumnsByConceptCd: " + ontologyUrl +" "+ response ); - factColumns = getFactColumnsFromResponse2(response); - } catch (Exception e) { - log.error(e.getMessage()); - } - if(factColumns == null) - log.info("factColumns is null"); - return factColumns; - } - - - public static ConceptsType callGetChildren(String itemKey, SecurityType securityType, String projectId, String ontologyUrl ) - throws XMLStreamException, JAXBUtilException, AxisFault,I2B2Exception { - RequestMessageType requestMessageType = getChildrenI2B2RequestMessage(itemKey, securityType, projectId.replaceAll("/", "")); - OMElement requestElement = buildOMElement(requestMessageType); - ConceptsType conceptsType = null; - logesapi.debug("CRC Ontology call's request xml from callGetChildren: " + requestElement); - logesapi.debug("URL: " + ontologyUrl); - try { - String response = ServiceClient.sendREST(ontologyUrl, requestElement); - conceptsType = getChildrenFromResponse(response); - } catch (Exception e) - { - log.error(e.getMessage()); - } - return conceptsType; - } - - public static ModifierType callGetModifierInfo(String modifierKey, String appliedPath, SecurityType securityType, String projectId, String ontologyUrl ) - throws XMLStreamException, JAXBUtilException, AxisFault, I2B2Exception { - RequestMessageType requestMessageType = getModifierI2B2RequestMessage(modifierKey,appliedPath, securityType, projectId.replaceAll("/", "")); - OMElement requestElement = buildOMElement(requestMessageType); - log.debug("CRC Ontology call's request xml from callGetModifierInfo: " + requestElement); - log.debug("URL: " + ontologyUrl); - ModifierType modifierType = null; - try { - String response = ServiceClient.sendREST(ontologyUrl, requestElement); - modifierType = getModifierFromResponse(response); - } catch (Exception e) - { - - } - return modifierType; - } - - - public static ConceptsType callGetChildrenWithHttpClient(String itemKey, SecurityType securityType, String projectId ) - throws XMLStreamException, JAXBUtilException,I2B2Exception, HttpException, IOException { - /*HttpClient client = new HttpClient(); - PostMethod postMethod = new PostMethod(QueryProcessorUtil.getInstance().getOntologyUrl()); - - client.setConnectionTimeout(8000); - - // Send any XML file as the body of the POST request - - // postMethod.setRequestBody(new FileInputStream(f)); - RequestMessageType requestMessageType = getChildrenI2B2RequestMessage(itemKey, securityType, projectId.replaceAll("/", "")); - String requestXml = buildRequestXml(requestMessageType); - postMethod.setRequestBody(requestXml); - postMethod.setRequestHeader("Content-type", - "text/xml; charset=ISO-8859-1"); - String responseXml = null; - int statusCode1 = client.executeMethod(postMethod); - responseXml = postMethod.getResponseBodyAsString(); - - log.debug("CRC's Ontology call response xml " + responseXml); - - postMethod.releaseConnection(); - ConceptsType conceptsType = getChildrenFromResponse(responseXml); - return conceptsType; - */ - return null; - } - - - private static ModifierType getModifierFromResponse(String responseXml) - throws JAXBUtilException, I2B2DAOException { - JAXBElement responseJaxb = - jaxbUtil.unMashallFromString(responseXml); //CRCJAXBUtil.getJAXBUtil() - ResponseMessageType r = (ResponseMessageType) responseJaxb.getValue(); - logesapi.debug("CRC's ontology call response xml from ModiferType: " + responseXml); - if (r.getResponseHeader() != null && r.getResponseHeader().getResultStatus() !=null) { - if (r.getResponseHeader().getResultStatus().getStatus().getType().equalsIgnoreCase("ERROR")) { - throw new I2B2DAOException("Error when getting modifier from ontology [" + r.getResponseHeader().getResultStatus().getStatus().getValue() +"]"); - } - } - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - ModifiersType modifiersType = (ModifiersType) helper.getObjectByClass(r - .getMessageBody().getAny(), ModifiersType.class); - - if (modifiersType != null && modifiersType.getModifier() != null - && modifiersType.getModifier().size() > 0) { - return modifiersType.getModifier().get(0); - } else { - return null; - } - - } - - private static ConceptsType getChildrenFromResponse(String responseXml) - throws JAXBUtilException, I2B2DAOException { - JAXBElement responseJaxb = - jaxbUtil.unMashallFromString(responseXml); //CRCJAXBUtil.getJAXBUtil() - ResponseMessageType r = (ResponseMessageType) responseJaxb.getValue(); - logesapi.debug("CRC's ontology call response xml from getChildrenFromResponse: " + responseXml); - - if (r.getResponseHeader() != null && r.getResponseHeader().getResultStatus() !=null) { - if (r.getResponseHeader().getResultStatus().getStatus().getType().equalsIgnoreCase("ERROR")) { - throw new I2B2DAOException("Error when getting children from ontology [" + r.getResponseHeader().getResultStatus().getStatus().getValue() +"]"); - } - } - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - ConceptsType conceptsType = (ConceptsType) helper.getObjectByClass(r - .getMessageBody().getAny(), ConceptsType.class); - return conceptsType; - } - - - - private static MetadataLoadType getLoadDataFromResponse(String responseXml) - throws JAXBUtilException, I2B2DAOException { - JAXBElement responseJaxb = - jaxbUtil.unMashallFromString(responseXml); //CRCJAXBUtil.getJAXBUtil() - ResponseMessageType r = (ResponseMessageType) responseJaxb.getValue(); - logesapi.debug("CRC's ontology call response xml from getLoadDataFromResponse: " + responseXml); - - if (r.getResponseHeader() != null && r.getResponseHeader().getResultStatus() !=null) { - if (r.getResponseHeader().getResultStatus().getStatus().getType().equalsIgnoreCase("ERROR")) { - throw new I2B2DAOException("Error when getting Metadata Load from ontology [" + r.getResponseHeader().getResultStatus().getStatus().getValue() +"]"); - } - } - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - MetadataLoadType metadataLoadType = (MetadataLoadType) helper.getObjectByClass(r - .getMessageBody().getAny(), MetadataLoadType.class); - return metadataLoadType; - } - - - private static DeleteChildType getDeleteChildFromResponse(String responseXml) - throws JAXBUtilException, I2B2DAOException { - JAXBElement responseJaxb = - jaxbUtil.unMashallFromString(responseXml); //CRCJAXBUtil.getJAXBUtil() - ResponseMessageType r = (ResponseMessageType) responseJaxb.getValue(); - logesapi.debug("CRC's ontology call response xml from getDeleteChildFromResponse: " + responseXml); - - if (r.getResponseHeader() != null && r.getResponseHeader().getResultStatus() !=null) { - if (r.getResponseHeader().getResultStatus().getStatus().getType().equalsIgnoreCase("ERROR")) { - throw new I2B2DAOException("Error when getting Metadata Load from ontology [" + r.getResponseHeader().getResultStatus().getStatus().getValue() +"]"); - } - } - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - DeleteChildType metadataLoadType = (DeleteChildType) helper.getObjectByClass(r - .getMessageBody().getAny(), DeleteChildType.class); - return metadataLoadType; - } - - - - private static DerivedFactColumnsType getFactColumnsFromResponse(String response) - throws JAXBUtilException, I2B2DAOException { - JAXBElement responseJaxb =// CRCJAXBUtil.getJAXBUtil() - jaxbUtil.unMashallFromString(response); - ResponseMessageType r = (ResponseMessageType) responseJaxb.getValue(); - logesapi.debug("CRC's ontology call response xml from getFactColumnsFromResponse: " + response); - if (r.getResponseHeader() != null && r.getResponseHeader().getResultStatus() !=null) { - if (r.getResponseHeader().getResultStatus().getStatus().getType().equalsIgnoreCase("ERROR")) { - throw new I2B2DAOException("Error when getting factColumns/concepts by code from ontology [" + r.getResponseHeader().getResultStatus().getStatus().getValue() +"]"); - } - } - - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - DerivedFactColumnsType factColumns = (DerivedFactColumnsType) helper.getObjectByClass(r - .getMessageBody().getAny(), DerivedFactColumnsType.class); - if (factColumns != null) { - return factColumns; - } else { - return null; - } - - - } - - private static DerivedFactColumnsType getFactColumnsFromResponse2(String response) - throws JAXBUtilException, I2B2DAOException { - - log.info("IN getFactColumnsFromResponse2"); - JAXBElement responseJaxb =// CRCJAXBUtil.getJAXBUtil() - jaxbUtil.unMashallFromString(response); - ResponseMessageType r = (ResponseMessageType) responseJaxb.getValue(); - logesapi.info("CRC's ontology call response xml from getFactColumnsFromResponse2: " + response); - if (r.getResponseHeader() != null && r.getResponseHeader().getResultStatus() !=null) { - if (r.getResponseHeader().getResultStatus().getStatus().getType().equalsIgnoreCase("ERROR")) { - throw new I2B2DAOException("Error when getting factColumns/concepts by code from ontology [" + r.getResponseHeader().getResultStatus().getStatus().getValue() +"]"); - } - } - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - ConceptsType concepts = (ConceptsType) helper.getObjectByClass(r - .getMessageBody().getAny(), ConceptsType.class); - - Map factColumnMap = new HashMap(); - - if(concepts == null){ - log.error("concepts is null"); - return null; - } - - - else if(concepts.getConcept().size() == 0){ - log.error("no concepts found for concept code"); - return null; - } - - else{ - // go thru the list of concepts and get unique factTableColumns - Iterator i = concepts.getConcept().iterator(); - ConceptType concept = (ConceptType)i.next(); - factColumnMap.put(concept.getFacttablecolumn(), concept); - - while(i.hasNext()){ - concept = (ConceptType)i.next(); - if(!(factColumnMap.containsKey(concept.getFacttablecolumn()))) - factColumnMap.put(concept.getFacttablecolumn(), concept); - } - - } - //Grab all the unique fact columns and put them in a list to return. - DerivedFactColumnsType factColumns = new DerivedFactColumnsType(); - - Iterator it = factColumnMap.keySet().iterator(); - while(it.hasNext()){ - String column = (String)it.next(); - factColumns.getDerivedFactTableColumn().add(column); - } - -// log.info("Key set size: " + factColumnMap.keySet().size()); -// log.info("fact columns size: " + factColumns.getDerivedFactTableColumn().size()); - - if (factColumns.getDerivedFactTableColumn().isEmpty()) { - return null; - } else { - return factColumns; - } - - } - - private static ConceptType getConceptFromResponse(String response) - throws JAXBUtilException, I2B2DAOException { - JAXBElement responseJaxb =// CRCJAXBUtil.getJAXBUtil() - jaxbUtil.unMashallFromString(response); - ResponseMessageType r = (ResponseMessageType) responseJaxb.getValue(); - logesapi.debug("CRC's ontology call response xml from getConceptFromResponse: " + response); - if (r.getResponseHeader() != null && r.getResponseHeader().getResultStatus() !=null) { - if (r.getResponseHeader().getResultStatus().getStatus().getType().equalsIgnoreCase("ERROR")) { - throw new I2B2DAOException("Error when getting metadata from ontology [" + r.getResponseHeader().getResultStatus().getStatus().getValue() +"]"); - } - } - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - ConceptsType conceptsType = (ConceptsType) helper.getObjectByClass(r - .getMessageBody().getAny(), ConceptsType.class); - if (conceptsType != null && conceptsType.getConcept() != null - && conceptsType.getConcept().size() > 0) { - return conceptsType.getConcept().get(0); - } else { - return null; - } - - } - - - private static OMElement buildOMElement(RequestMessageType requestMessageType) - throws XMLStreamException, JAXBUtilException { - StringWriter strWriter = new StringWriter(); - edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory hiveof = new edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory(); - //CRCJAXBUtil.getJAXBUtil() - jaxbUtil.marshaller( - hiveof.createRequest(requestMessageType), strWriter); - // getOMElement from message - OMFactory fac = OMAbstractFactory.getOMFactory(); - - StringReader strReader = new StringReader(strWriter.toString()); - XMLInputFactory xif = XMLInputFactory.newInstance(); - XMLStreamReader reader = xif.createXMLStreamReader(strReader); - OMElement request = OMXMLBuilderFactory.createStAXOMBuilder(reader).getDocumentElement(); - - return request; - } - - private static String buildRequestXml(RequestMessageType requestMessageType) - throws XMLStreamException, JAXBUtilException { - StringWriter strWriter = new StringWriter(); - edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory hiveof = new edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory(); - //CRCJAXBUtil.getJAXBUtil() - jaxbUtil.marshaller( - hiveof.createRequest(requestMessageType), strWriter); - - return strWriter.toString(); - } - - private static RequestMessageType getI2B2RequestMessage(String conceptPath, SecurityType securityType, String projectId ) { - QueryProcessorUtil queryUtil = QueryProcessorUtil.getInstance(); - MessageHeaderType messageHeaderType = queryUtil.getMessageHeader(); - messageHeaderType.setSecurity(securityType); - messageHeaderType.setProjectId(projectId); - - messageHeaderType.setReceivingApplication(messageHeaderType - .getSendingApplication()); - FacilityType facilityType = new FacilityType(); - facilityType.setFacilityName("sample"); - messageHeaderType.setSendingFacility(facilityType); - messageHeaderType.setReceivingFacility(facilityType); - // build message body - GetTermInfoType getTermInfo = new GetTermInfoType(); - getTermInfo.setSelf(conceptPath); - // max="300" hiddens="false" synonyms="false" type="core" blob="true" - getTermInfo.setMax(300); - getTermInfo.setHiddens(true); - getTermInfo.setSynonyms(false); - getTermInfo.setType("core"); - getTermInfo.setBlob(true); - - RequestMessageType requestMessageType = new RequestMessageType(); - ObjectFactory of = new ObjectFactory(); - BodyType bodyType = new BodyType(); - bodyType.getAny().add(of.createGetTermInfo(getTermInfo)); - requestMessageType.setMessageBody(bodyType); - - requestMessageType.setMessageHeader(messageHeaderType); - - RequestHeaderType requestHeader = new RequestHeaderType(); - requestHeader.setResultWaittimeMs(180000); - requestMessageType.setRequestHeader(requestHeader); - - return requestMessageType; - - } - - private static RequestMessageType getChildrenI2B2RequestMessage(String conceptPath, SecurityType securityType, String projectId ) { - QueryProcessorUtil queryUtil = QueryProcessorUtil.getInstance(); - MessageHeaderType messageHeaderType = queryUtil.getMessageHeader(); - messageHeaderType.setSecurity(securityType); - messageHeaderType.setProjectId(projectId); - - messageHeaderType.setReceivingApplication(messageHeaderType - .getSendingApplication()); - FacilityType facilityType = new FacilityType(); - facilityType.setFacilityName("sample"); - messageHeaderType.setSendingFacility(facilityType); - messageHeaderType.setReceivingFacility(facilityType); - // build message body - GetChildrenType getChildren = new GetChildrenType(); - getChildren.setParent(conceptPath); - // max="300" hiddens="false" synonyms="false" type="core" blob="true" - // getChildren.setMax(300); - getChildren.setHiddens(true); - getChildren.setSynonyms(false); - // getChildren.setType("core"); - getChildren.setBlob(true); - - RequestMessageType requestMessageType = new RequestMessageType(); - ObjectFactory of = new ObjectFactory(); - BodyType bodyType = new BodyType(); - bodyType.getAny().add(of.createGetChildren(getChildren)); - requestMessageType.setMessageBody(bodyType); - - requestMessageType.setMessageHeader(messageHeaderType); - - RequestHeaderType requestHeader = new RequestHeaderType(); - requestHeader.setResultWaittimeMs(180000); - requestMessageType.setRequestHeader(requestHeader); - - return requestMessageType; - - } - - private static RequestMessageType getConceptsByCodeI2B2RequestMessage(String conceptCd, SecurityType securityType, String projectId ) { - QueryProcessorUtil queryUtil = QueryProcessorUtil.getInstance(); - MessageHeaderType messageHeaderType = queryUtil.getMessageHeader(); - messageHeaderType.setSecurity(securityType); - messageHeaderType.setProjectId(projectId); - - messageHeaderType.setReceivingApplication(messageHeaderType - .getSendingApplication()); - FacilityType facilityType = new FacilityType(); - facilityType.setFacilityName("sample"); - messageHeaderType.setSendingFacility(facilityType); - messageHeaderType.setReceivingFacility(facilityType); - // build message body - VocabRequestType getCodeInfo = new VocabRequestType(); - getCodeInfo.setHiddens(true); - getCodeInfo.setSynonyms(false); - getCodeInfo.setType("core"); - getCodeInfo.setBlob(false); - - MatchStrType match = new MatchStrType(); - match.setStrategy("exact"); - match.setValue(conceptCd); - getCodeInfo.setMatchStr(match); - - RequestMessageType requestMessageType = new RequestMessageType(); - ObjectFactory of = new ObjectFactory(); - BodyType bodyType = new BodyType(); - bodyType.getAny().add(of.createGetCodeInfo(getCodeInfo)); - requestMessageType.setMessageBody(bodyType); - - requestMessageType.setMessageHeader(messageHeaderType); - - RequestHeaderType requestHeader = new RequestHeaderType(); - requestHeader.setResultWaittimeMs(120000); - requestMessageType.setRequestHeader(requestHeader); - - return requestMessageType; - - } - - private static RequestMessageType getI2B2RequestDeleteChildMessage( DeleteChildType c, SecurityType securityType, String projectId) { - QueryProcessorUtil queryUtil = QueryProcessorUtil.getInstance(); - MessageHeaderType messageHeaderType = queryUtil.getMessageHeader(); - messageHeaderType.setSecurity(securityType); - messageHeaderType.setProjectId(projectId); - - messageHeaderType.setReceivingApplication(messageHeaderType - .getSendingApplication()); - FacilityType facilityType = new FacilityType(); - facilityType.setFacilityName("sample"); - messageHeaderType.setSendingFacility(facilityType); - messageHeaderType.setReceivingFacility(facilityType); - // build message body - - - RequestMessageType requestMessageType = new RequestMessageType(); - ObjectFactory of = new ObjectFactory(); - BodyType bodyType = new BodyType(); - bodyType.getAny().add(of.createDeleteChild(c)); - requestMessageType.setMessageBody(bodyType); - - requestMessageType.setMessageHeader(messageHeaderType); - - RequestHeaderType requestHeader = new RequestHeaderType(); - requestHeader.setResultWaittimeMs(180000); - requestMessageType.setRequestHeader(requestHeader); - - return requestMessageType; - } - - private static RequestMessageType getLoadDataI2B2RequestLoadDataMessage(String tablename, List c, SecurityType securityType, String projectId) { - QueryProcessorUtil queryUtil = QueryProcessorUtil.getInstance(); - MessageHeaderType messageHeaderType = queryUtil.getMessageHeader(); - messageHeaderType.setSecurity(securityType); - messageHeaderType.setProjectId(projectId); - - messageHeaderType.setReceivingApplication(messageHeaderType - .getSendingApplication()); - FacilityType facilityType = new FacilityType(); - facilityType.setFacilityName("sample"); - messageHeaderType.setSendingFacility(facilityType); - messageHeaderType.setReceivingFacility(facilityType); - // build message body - MetadataLoadType getMetadataLoad = new MetadataLoadType(); - getMetadataLoad.setTableName(tablename); - getMetadataLoad.setTruncateTable(true); - getMetadataLoad.getMetadata().addAll(c); - - RequestMessageType requestMessageType = new RequestMessageType(); - ObjectFactory of = new ObjectFactory(); - BodyType bodyType = new BodyType(); - bodyType.getAny().add(of.createLoadMetadata(getMetadataLoad)); - requestMessageType.setMessageBody(bodyType); - - requestMessageType.setMessageHeader(messageHeaderType); - - RequestHeaderType requestHeader = new RequestHeaderType(); - requestHeader.setResultWaittimeMs(180000); - requestMessageType.setRequestHeader(requestHeader); - - return requestMessageType; - } - - private static RequestMessageType getDerivedFactColumnsI2B2RequestMessage(String conceptPath, SecurityType securityType, String projectId ) { - QueryProcessorUtil queryUtil = QueryProcessorUtil.getInstance(); - MessageHeaderType messageHeaderType = queryUtil.getMessageHeader(); - messageHeaderType.setSecurity(securityType); - messageHeaderType.setProjectId(projectId); - - messageHeaderType.setReceivingApplication(messageHeaderType - .getSendingApplication()); - FacilityType facilityType = new FacilityType(); - facilityType.setFacilityName("sample"); - messageHeaderType.setSendingFacility(facilityType); - messageHeaderType.setReceivingFacility(facilityType); - // build message body - GetTermInfoType getTermInfo = new GetTermInfoType(); - getTermInfo.setSelf(conceptPath); - getTermInfo.setHiddens(true); - getTermInfo.setSynonyms(false); - getTermInfo.setType("core"); - getTermInfo.setBlob(false); - - RequestMessageType requestMessageType = new RequestMessageType(); - ObjectFactory of = new ObjectFactory(); - BodyType bodyType = new BodyType(); - bodyType.getAny().add(of.createGetTermInfo(getTermInfo)); - requestMessageType.setMessageBody(bodyType); - - requestMessageType.setMessageHeader(messageHeaderType); - - RequestHeaderType requestHeader = new RequestHeaderType(); - requestHeader.setResultWaittimeMs(180000); - requestMessageType.setRequestHeader(requestHeader); - - return requestMessageType; - - } - - private static RequestMessageType getModifierI2B2RequestMessage(String modifierPath, String appliedPath, SecurityType securityType, String projectId ) { - QueryProcessorUtil queryUtil = QueryProcessorUtil.getInstance(); - MessageHeaderType messageHeaderType = queryUtil.getMessageHeader(); - messageHeaderType.setSecurity(securityType); - messageHeaderType.setProjectId(projectId); - - messageHeaderType.setReceivingApplication(messageHeaderType - .getSendingApplication()); - FacilityType facilityType = new FacilityType(); - facilityType.setFacilityName("sample"); - messageHeaderType.setSendingFacility(facilityType); - messageHeaderType.setReceivingFacility(facilityType); - // build message body - - GetModifierInfoType modifierInfoType = new GetModifierInfoType(); - modifierInfoType.setSelf(modifierPath); - modifierInfoType.setAppliedPath(appliedPath); - - // max="300" hiddens="false" synonyms="false" type="core" blob="true" - // getChildren.setMax(300); - modifierInfoType.setHiddens(true); - modifierInfoType.setBlob(true); - modifierInfoType.setSynonyms(false); - - RequestMessageType requestMessageType = new RequestMessageType(); - ObjectFactory of = new ObjectFactory(); - BodyType bodyType = new BodyType(); - bodyType.getAny().add(of.createGetModifierInfo(modifierInfoType)); - requestMessageType.setMessageBody(bodyType); - - requestMessageType.setMessageHeader(messageHeaderType); - - RequestHeaderType requestHeader = new RequestHeaderType(); - requestHeader.setResultWaittimeMs(180000); - requestMessageType.setRequestHeader(requestHeader); - - return requestMessageType; - - } - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.delegate.ontology; + +import java.io.IOException; +import java.io.StringReader; +import java.io.StringWriter; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import jakarta.xml.bind.JAXBElement; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import org.apache.axiom.om.OMAbstractFactory; +import org.apache.axiom.om.OMElement; +import org.apache.axiom.om.OMFactory; +import org.apache.axiom.om.OMXMLBuilderFactory; +import org.apache.axis2.AxisFault; +import edu.harvard.i2b2.common.util.axis2.ServiceClient; +//import org.apache.commons.httpclient.HttpClient; +//import org.apache.commons.httpclient.HttpException; +//import org.apache.commons.httpclient.methods.PostMethod; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.hc.core5.http.HttpException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2message.FacilityType; +import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; +import edu.harvard.i2b2.crc.datavo.ontology.ConceptType; +import edu.harvard.i2b2.crc.datavo.ontology.ConceptsType; +import edu.harvard.i2b2.crc.datavo.ontology.DeleteChildType; +import edu.harvard.i2b2.crc.datavo.ontology.DerivedFactColumnsType; +import edu.harvard.i2b2.crc.datavo.ontology.GetChildrenType; +import edu.harvard.i2b2.crc.datavo.ontology.GetModifierInfoType; +import edu.harvard.i2b2.crc.datavo.ontology.GetTermInfoType; +import edu.harvard.i2b2.crc.datavo.ontology.MatchStrType; +import edu.harvard.i2b2.crc.datavo.ontology.MetadataLoadType; +import edu.harvard.i2b2.crc.datavo.ontology.ModifierType; +import edu.harvard.i2b2.crc.datavo.ontology.ModifiersType; +import edu.harvard.i2b2.crc.datavo.ontology.ObjectFactory; +import edu.harvard.i2b2.crc.datavo.ontology.OntologyDataType; +import edu.harvard.i2b2.crc.datavo.ontology.VocabRequestType; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + +public class CallOntologyUtil { + + // private SecurityType securityType = null; + // private String projectId = null; + // private String ontologyUrl = null; + + private static Log log = LogFactory.getLog(CallOntologyUtil.class); + protected static Log logesapi = LogFactory.getLog(CallOntologyUtil.class); + + private static JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); + + + public static ConceptType callOntology(String itemKey, SecurityType securityType, String projectId, String ontologyUrl ) throws XMLStreamException, + JAXBUtilException, AxisFault, I2B2Exception { + RequestMessageType requestMessageType = getI2B2RequestMessage(itemKey, securityType, projectId.replaceAll("/", "")); + OMElement requestElement = buildOMElement(requestMessageType); + log.debug("CRC Ontology call's request xml from callOntology: " + requestElement); + log.debug("URL: " + ontologyUrl); + ConceptType conceptType = null; + try { + String response = ServiceClient.sendREST(ontologyUrl, requestElement); + conceptType = getConceptFromResponse(response); + } catch (Exception e) + { + + } + return conceptType; + } + + + public static MetadataLoadType callLoadData(String tablename, List c, SecurityType securityType, String projectId, String ontologyUrl ) throws XMLStreamException, + JAXBUtilException, AxisFault, I2B2Exception { + + RequestMessageType requestMessageType = getLoadDataI2B2RequestLoadDataMessage(tablename,c, securityType, projectId.replaceAll("/", "")); + OMElement requestElement = buildOMElement(requestMessageType); + log.debug("CRC Ontology call's request xml from callLoadData: " + requestElement); + log.debug("URL: " + ontologyUrl); + MetadataLoadType metadataLoadType = null; + try { + String response = ServiceClient.sendREST(ontologyUrl, requestElement); + metadataLoadType = getLoadDataFromResponse(response); + } catch (Exception e) + { + + } + return metadataLoadType; + + + } + + public static DeleteChildType callDeleteChild( DeleteChildType c, SecurityType securityType, String projectId, String ontologyUrl ) throws XMLStreamException, + JAXBUtilException, AxisFault, I2B2Exception { + + RequestMessageType requestMessageType = getI2B2RequestDeleteChildMessage(c, securityType, projectId.replaceAll("/", "")); + OMElement requestElement = buildOMElement(requestMessageType); + log.debug("CRC Ontology call's request xml from callLoadData: " + requestElement); + log.debug("URL: " + ontologyUrl); + DeleteChildType metadataLoadType = null; + try { + String response = ServiceClient.sendREST(ontologyUrl, requestElement); + metadataLoadType = getDeleteChildFromResponse(response); + } catch (Exception e) + { + + } + return metadataLoadType; + + + } + + + + + + + public static DerivedFactColumnsType callGetFactColumns(String itemKey, SecurityType securityType, String projectId, String ontologyUrl ) + throws XMLStreamException, JAXBUtilException, AxisFault,I2B2Exception { + + RequestMessageType requestMessageType = getDerivedFactColumnsI2B2RequestMessage(itemKey, securityType, projectId.replaceAll("/", "")); + OMElement requestElement = buildOMElement(requestMessageType); + DerivedFactColumnsType factColumns = null; + try { + String response = ServiceClient.sendREST(ontologyUrl, requestElement); + logesapi.debug("TEST callGetFactColumns:" + response ); + factColumns = getFactColumnsFromResponse(response); + } catch (Exception e) { + log.error(e.getMessage()); + } + return factColumns; + } + + + public static DerivedFactColumnsType callGetFactColumnsByConceptCd(String conceptCd, SecurityType securityType, String projectId, String ontologyUrl ) + throws XMLStreamException, JAXBUtilException, AxisFault,I2B2Exception { + RequestMessageType requestMessageType = getConceptsByCodeI2B2RequestMessage(conceptCd, securityType, projectId.replaceAll("/", "")); + OMElement requestElement = buildOMElement(requestMessageType); + DerivedFactColumnsType factColumns = null; + try { + String response = ServiceClient.sendREST(ontologyUrl, requestElement); + logesapi.debug("TEST callGetFactColumnsByConceptCd: " + ontologyUrl +" "+ response ); + factColumns = getFactColumnsFromResponse2(response); + } catch (Exception e) { + log.error(e.getMessage()); + } + if(factColumns == null) + log.info("factColumns is null"); + return factColumns; + } + + + public static ConceptsType callGetChildren(String itemKey, SecurityType securityType, String projectId, String ontologyUrl ) + throws XMLStreamException, JAXBUtilException, AxisFault,I2B2Exception { + RequestMessageType requestMessageType = getChildrenI2B2RequestMessage(itemKey, securityType, projectId.replaceAll("/", "")); + OMElement requestElement = buildOMElement(requestMessageType); + ConceptsType conceptsType = null; + logesapi.debug("CRC Ontology call's request xml from callGetChildren: " + requestElement); + logesapi.debug("URL: " + ontologyUrl); + try { + String response = ServiceClient.sendREST(ontologyUrl, requestElement); + conceptsType = getChildrenFromResponse(response); + } catch (Exception e) + { + log.error(e.getMessage()); + } + return conceptsType; + } + + public static ModifierType callGetModifierInfo(String modifierKey, String appliedPath, SecurityType securityType, String projectId, String ontologyUrl ) + throws XMLStreamException, JAXBUtilException, AxisFault, I2B2Exception { + RequestMessageType requestMessageType = getModifierI2B2RequestMessage(modifierKey,appliedPath, securityType, projectId.replaceAll("/", "")); + OMElement requestElement = buildOMElement(requestMessageType); + log.debug("CRC Ontology call's request xml from callGetModifierInfo: " + requestElement); + log.debug("URL: " + ontologyUrl); + ModifierType modifierType = null; + try { + String response = ServiceClient.sendREST(ontologyUrl, requestElement); + modifierType = getModifierFromResponse(response); + } catch (Exception e) + { + + } + return modifierType; + } + + + public static ConceptsType callGetChildrenWithHttpClient(String itemKey, SecurityType securityType, String projectId ) + throws XMLStreamException, JAXBUtilException,I2B2Exception, HttpException, IOException { + /*HttpClient client = new HttpClient(); + PostMethod postMethod = new PostMethod(QueryProcessorUtil.getInstance().getOntologyUrl()); + + client.setConnectionTimeout(8000); + + // Send any XML file as the body of the POST request + + // postMethod.setRequestBody(new FileInputStream(f)); + RequestMessageType requestMessageType = getChildrenI2B2RequestMessage(itemKey, securityType, projectId.replaceAll("/", "")); + String requestXml = buildRequestXml(requestMessageType); + postMethod.setRequestBody(requestXml); + postMethod.setRequestHeader("Content-type", + "text/xml; charset=ISO-8859-1"); + String responseXml = null; + int statusCode1 = client.executeMethod(postMethod); + responseXml = postMethod.getResponseBodyAsString(); + + log.debug("CRC's Ontology call response xml " + responseXml); + + postMethod.releaseConnection(); + ConceptsType conceptsType = getChildrenFromResponse(responseXml); + return conceptsType; + */ + return null; + } + + + private static ModifierType getModifierFromResponse(String responseXml) + throws JAXBUtilException, I2B2DAOException { + JAXBElement responseJaxb = + jaxbUtil.unMashallFromString(responseXml); //CRCJAXBUtil.getJAXBUtil() + ResponseMessageType r = (ResponseMessageType) responseJaxb.getValue(); + logesapi.debug("CRC's ontology call response xml from ModiferType: " + responseXml); + if (r.getResponseHeader() != null && r.getResponseHeader().getResultStatus() !=null) { + if (r.getResponseHeader().getResultStatus().getStatus().getType().equalsIgnoreCase("ERROR")) { + throw new I2B2DAOException("Error when getting modifier from ontology [" + r.getResponseHeader().getResultStatus().getStatus().getValue() +"]"); + } + } + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + ModifiersType modifiersType = (ModifiersType) helper.getObjectByClass(r + .getMessageBody().getAny(), ModifiersType.class); + + if (modifiersType != null && modifiersType.getModifier() != null + && modifiersType.getModifier().size() > 0) { + return modifiersType.getModifier().get(0); + } else { + return null; + } + + } + + private static ConceptsType getChildrenFromResponse(String responseXml) + throws JAXBUtilException, I2B2DAOException { + JAXBElement responseJaxb = + jaxbUtil.unMashallFromString(responseXml); //CRCJAXBUtil.getJAXBUtil() + ResponseMessageType r = (ResponseMessageType) responseJaxb.getValue(); + logesapi.debug("CRC's ontology call response xml from getChildrenFromResponse: " + responseXml); + + if (r.getResponseHeader() != null && r.getResponseHeader().getResultStatus() !=null) { + if (r.getResponseHeader().getResultStatus().getStatus().getType().equalsIgnoreCase("ERROR")) { + throw new I2B2DAOException("Error when getting children from ontology [" + r.getResponseHeader().getResultStatus().getStatus().getValue() +"]"); + } + } + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + ConceptsType conceptsType = (ConceptsType) helper.getObjectByClass(r + .getMessageBody().getAny(), ConceptsType.class); + return conceptsType; + } + + + + private static MetadataLoadType getLoadDataFromResponse(String responseXml) + throws JAXBUtilException, I2B2DAOException { + JAXBElement responseJaxb = + jaxbUtil.unMashallFromString(responseXml); //CRCJAXBUtil.getJAXBUtil() + ResponseMessageType r = (ResponseMessageType) responseJaxb.getValue(); + logesapi.debug("CRC's ontology call response xml from getLoadDataFromResponse: " + responseXml); + + if (r.getResponseHeader() != null && r.getResponseHeader().getResultStatus() !=null) { + if (r.getResponseHeader().getResultStatus().getStatus().getType().equalsIgnoreCase("ERROR")) { + throw new I2B2DAOException("Error when getting Metadata Load from ontology [" + r.getResponseHeader().getResultStatus().getStatus().getValue() +"]"); + } + } + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + MetadataLoadType metadataLoadType = (MetadataLoadType) helper.getObjectByClass(r + .getMessageBody().getAny(), MetadataLoadType.class); + return metadataLoadType; + } + + + private static DeleteChildType getDeleteChildFromResponse(String responseXml) + throws JAXBUtilException, I2B2DAOException { + JAXBElement responseJaxb = + jaxbUtil.unMashallFromString(responseXml); //CRCJAXBUtil.getJAXBUtil() + ResponseMessageType r = (ResponseMessageType) responseJaxb.getValue(); + logesapi.debug("CRC's ontology call response xml from getDeleteChildFromResponse: " + responseXml); + + if (r.getResponseHeader() != null && r.getResponseHeader().getResultStatus() !=null) { + if (r.getResponseHeader().getResultStatus().getStatus().getType().equalsIgnoreCase("ERROR")) { + throw new I2B2DAOException("Error when getting Metadata Load from ontology [" + r.getResponseHeader().getResultStatus().getStatus().getValue() +"]"); + } + } + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + DeleteChildType metadataLoadType = (DeleteChildType) helper.getObjectByClass(r + .getMessageBody().getAny(), DeleteChildType.class); + return metadataLoadType; + } + + + + private static DerivedFactColumnsType getFactColumnsFromResponse(String response) + throws JAXBUtilException, I2B2DAOException { + JAXBElement responseJaxb =// CRCJAXBUtil.getJAXBUtil() + jaxbUtil.unMashallFromString(response); + ResponseMessageType r = (ResponseMessageType) responseJaxb.getValue(); + logesapi.debug("CRC's ontology call response xml from getFactColumnsFromResponse: " + response); + if (r.getResponseHeader() != null && r.getResponseHeader().getResultStatus() !=null) { + if (r.getResponseHeader().getResultStatus().getStatus().getType().equalsIgnoreCase("ERROR")) { + throw new I2B2DAOException("Error when getting factColumns/concepts by code from ontology [" + r.getResponseHeader().getResultStatus().getStatus().getValue() +"]"); + } + } + + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + DerivedFactColumnsType factColumns = (DerivedFactColumnsType) helper.getObjectByClass(r + .getMessageBody().getAny(), DerivedFactColumnsType.class); + if (factColumns != null) { + return factColumns; + } else { + return null; + } + + + } + + private static DerivedFactColumnsType getFactColumnsFromResponse2(String response) + throws JAXBUtilException, I2B2DAOException { + + log.info("IN getFactColumnsFromResponse2"); + JAXBElement responseJaxb =// CRCJAXBUtil.getJAXBUtil() + jaxbUtil.unMashallFromString(response); + ResponseMessageType r = (ResponseMessageType) responseJaxb.getValue(); + logesapi.info("CRC's ontology call response xml from getFactColumnsFromResponse2: " + response); + if (r.getResponseHeader() != null && r.getResponseHeader().getResultStatus() !=null) { + if (r.getResponseHeader().getResultStatus().getStatus().getType().equalsIgnoreCase("ERROR")) { + throw new I2B2DAOException("Error when getting factColumns/concepts by code from ontology [" + r.getResponseHeader().getResultStatus().getStatus().getValue() +"]"); + } + } + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + ConceptsType concepts = (ConceptsType) helper.getObjectByClass(r + .getMessageBody().getAny(), ConceptsType.class); + + Map factColumnMap = new HashMap(); + + if(concepts == null){ + log.error("concepts is null"); + return null; + } + + + else if(concepts.getConcept().size() == 0){ + log.error("no concepts found for concept code"); + return null; + } + + else{ + // go thru the list of concepts and get unique factTableColumns + Iterator i = concepts.getConcept().iterator(); + ConceptType concept = (ConceptType)i.next(); + factColumnMap.put(concept.getFacttablecolumn(), concept); + + while(i.hasNext()){ + concept = (ConceptType)i.next(); + if(!(factColumnMap.containsKey(concept.getFacttablecolumn()))) + factColumnMap.put(concept.getFacttablecolumn(), concept); + } + + } + //Grab all the unique fact columns and put them in a list to return. + DerivedFactColumnsType factColumns = new DerivedFactColumnsType(); + + Iterator it = factColumnMap.keySet().iterator(); + while(it.hasNext()){ + String column = (String)it.next(); + factColumns.getDerivedFactTableColumn().add(column); + } + +// log.info("Key set size: " + factColumnMap.keySet().size()); +// log.info("fact columns size: " + factColumns.getDerivedFactTableColumn().size()); + + if (factColumns.getDerivedFactTableColumn().isEmpty()) { + return null; + } else { + return factColumns; + } + + } + + private static ConceptType getConceptFromResponse(String response) + throws JAXBUtilException, I2B2DAOException { + JAXBElement responseJaxb =// CRCJAXBUtil.getJAXBUtil() + jaxbUtil.unMashallFromString(response); + ResponseMessageType r = (ResponseMessageType) responseJaxb.getValue(); + logesapi.debug("CRC's ontology call response xml from getConceptFromResponse: " + response); + if (r.getResponseHeader() != null && r.getResponseHeader().getResultStatus() !=null) { + if (r.getResponseHeader().getResultStatus().getStatus().getType().equalsIgnoreCase("ERROR")) { + throw new I2B2DAOException("Error when getting metadata from ontology [" + r.getResponseHeader().getResultStatus().getStatus().getValue() +"]"); + } + } + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + ConceptsType conceptsType = (ConceptsType) helper.getObjectByClass(r + .getMessageBody().getAny(), ConceptsType.class); + if (conceptsType != null && conceptsType.getConcept() != null + && conceptsType.getConcept().size() > 0) { + return conceptsType.getConcept().get(0); + } else { + return null; + } + + } + + + private static OMElement buildOMElement(RequestMessageType requestMessageType) + throws XMLStreamException, JAXBUtilException { + StringWriter strWriter = new StringWriter(); + edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory hiveof = new edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory(); + //CRCJAXBUtil.getJAXBUtil() + jaxbUtil.marshaller( + hiveof.createRequest(requestMessageType), strWriter); + // getOMElement from message + OMFactory fac = OMAbstractFactory.getOMFactory(); + + StringReader strReader = new StringReader(strWriter.toString()); + XMLInputFactory xif = XMLInputFactory.newInstance(); + XMLStreamReader reader = xif.createXMLStreamReader(strReader); + OMElement request = OMXMLBuilderFactory.createStAXOMBuilder(reader).getDocumentElement(); + + return request; + } + + private static String buildRequestXml(RequestMessageType requestMessageType) + throws XMLStreamException, JAXBUtilException { + StringWriter strWriter = new StringWriter(); + edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory hiveof = new edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory(); + //CRCJAXBUtil.getJAXBUtil() + jaxbUtil.marshaller( + hiveof.createRequest(requestMessageType), strWriter); + + return strWriter.toString(); + } + + private static RequestMessageType getI2B2RequestMessage(String conceptPath, SecurityType securityType, String projectId ) { + QueryProcessorUtil queryUtil = QueryProcessorUtil.getInstance(); + MessageHeaderType messageHeaderType = queryUtil.getMessageHeader(); + messageHeaderType.setSecurity(securityType); + messageHeaderType.setProjectId(projectId); + + messageHeaderType.setReceivingApplication(messageHeaderType + .getSendingApplication()); + FacilityType facilityType = new FacilityType(); + facilityType.setFacilityName("sample"); + messageHeaderType.setSendingFacility(facilityType); + messageHeaderType.setReceivingFacility(facilityType); + // build message body + GetTermInfoType getTermInfo = new GetTermInfoType(); + getTermInfo.setSelf(conceptPath); + // max="300" hiddens="false" synonyms="false" type="core" blob="true" + getTermInfo.setMax(300); + getTermInfo.setHiddens(true); + getTermInfo.setSynonyms(false); + getTermInfo.setType("core"); + getTermInfo.setBlob(true); + + RequestMessageType requestMessageType = new RequestMessageType(); + ObjectFactory of = new ObjectFactory(); + BodyType bodyType = new BodyType(); + bodyType.getAny().add(of.createGetTermInfo(getTermInfo)); + requestMessageType.setMessageBody(bodyType); + + requestMessageType.setMessageHeader(messageHeaderType); + + RequestHeaderType requestHeader = new RequestHeaderType(); + requestHeader.setResultWaittimeMs(180000); + requestMessageType.setRequestHeader(requestHeader); + + return requestMessageType; + + } + + private static RequestMessageType getChildrenI2B2RequestMessage(String conceptPath, SecurityType securityType, String projectId ) { + QueryProcessorUtil queryUtil = QueryProcessorUtil.getInstance(); + MessageHeaderType messageHeaderType = queryUtil.getMessageHeader(); + messageHeaderType.setSecurity(securityType); + messageHeaderType.setProjectId(projectId); + + messageHeaderType.setReceivingApplication(messageHeaderType + .getSendingApplication()); + FacilityType facilityType = new FacilityType(); + facilityType.setFacilityName("sample"); + messageHeaderType.setSendingFacility(facilityType); + messageHeaderType.setReceivingFacility(facilityType); + // build message body + GetChildrenType getChildren = new GetChildrenType(); + getChildren.setParent(conceptPath); + // max="300" hiddens="false" synonyms="false" type="core" blob="true" + // getChildren.setMax(300); + getChildren.setHiddens(true); + getChildren.setSynonyms(false); + // getChildren.setType("core"); + getChildren.setBlob(true); + + RequestMessageType requestMessageType = new RequestMessageType(); + ObjectFactory of = new ObjectFactory(); + BodyType bodyType = new BodyType(); + bodyType.getAny().add(of.createGetChildren(getChildren)); + requestMessageType.setMessageBody(bodyType); + + requestMessageType.setMessageHeader(messageHeaderType); + + RequestHeaderType requestHeader = new RequestHeaderType(); + requestHeader.setResultWaittimeMs(180000); + requestMessageType.setRequestHeader(requestHeader); + + return requestMessageType; + + } + + private static RequestMessageType getConceptsByCodeI2B2RequestMessage(String conceptCd, SecurityType securityType, String projectId ) { + QueryProcessorUtil queryUtil = QueryProcessorUtil.getInstance(); + MessageHeaderType messageHeaderType = queryUtil.getMessageHeader(); + messageHeaderType.setSecurity(securityType); + messageHeaderType.setProjectId(projectId); + + messageHeaderType.setReceivingApplication(messageHeaderType + .getSendingApplication()); + FacilityType facilityType = new FacilityType(); + facilityType.setFacilityName("sample"); + messageHeaderType.setSendingFacility(facilityType); + messageHeaderType.setReceivingFacility(facilityType); + // build message body + VocabRequestType getCodeInfo = new VocabRequestType(); + getCodeInfo.setHiddens(true); + getCodeInfo.setSynonyms(false); + getCodeInfo.setType("core"); + getCodeInfo.setBlob(false); + + MatchStrType match = new MatchStrType(); + match.setStrategy("exact"); + match.setValue(conceptCd); + getCodeInfo.setMatchStr(match); + + RequestMessageType requestMessageType = new RequestMessageType(); + ObjectFactory of = new ObjectFactory(); + BodyType bodyType = new BodyType(); + bodyType.getAny().add(of.createGetCodeInfo(getCodeInfo)); + requestMessageType.setMessageBody(bodyType); + + requestMessageType.setMessageHeader(messageHeaderType); + + RequestHeaderType requestHeader = new RequestHeaderType(); + requestHeader.setResultWaittimeMs(120000); + requestMessageType.setRequestHeader(requestHeader); + + return requestMessageType; + + } + + private static RequestMessageType getI2B2RequestDeleteChildMessage( DeleteChildType c, SecurityType securityType, String projectId) { + QueryProcessorUtil queryUtil = QueryProcessorUtil.getInstance(); + MessageHeaderType messageHeaderType = queryUtil.getMessageHeader(); + messageHeaderType.setSecurity(securityType); + messageHeaderType.setProjectId(projectId); + + messageHeaderType.setReceivingApplication(messageHeaderType + .getSendingApplication()); + FacilityType facilityType = new FacilityType(); + facilityType.setFacilityName("sample"); + messageHeaderType.setSendingFacility(facilityType); + messageHeaderType.setReceivingFacility(facilityType); + // build message body + + + RequestMessageType requestMessageType = new RequestMessageType(); + ObjectFactory of = new ObjectFactory(); + BodyType bodyType = new BodyType(); + bodyType.getAny().add(of.createDeleteChild(c)); + requestMessageType.setMessageBody(bodyType); + + requestMessageType.setMessageHeader(messageHeaderType); + + RequestHeaderType requestHeader = new RequestHeaderType(); + requestHeader.setResultWaittimeMs(180000); + requestMessageType.setRequestHeader(requestHeader); + + return requestMessageType; + } + + private static RequestMessageType getLoadDataI2B2RequestLoadDataMessage(String tablename, List c, SecurityType securityType, String projectId) { + QueryProcessorUtil queryUtil = QueryProcessorUtil.getInstance(); + MessageHeaderType messageHeaderType = queryUtil.getMessageHeader(); + messageHeaderType.setSecurity(securityType); + messageHeaderType.setProjectId(projectId); + + messageHeaderType.setReceivingApplication(messageHeaderType + .getSendingApplication()); + FacilityType facilityType = new FacilityType(); + facilityType.setFacilityName("sample"); + messageHeaderType.setSendingFacility(facilityType); + messageHeaderType.setReceivingFacility(facilityType); + // build message body + MetadataLoadType getMetadataLoad = new MetadataLoadType(); + getMetadataLoad.setTableName(tablename); + getMetadataLoad.setTruncateTable(true); + getMetadataLoad.getMetadata().addAll(c); + + RequestMessageType requestMessageType = new RequestMessageType(); + ObjectFactory of = new ObjectFactory(); + BodyType bodyType = new BodyType(); + bodyType.getAny().add(of.createLoadMetadata(getMetadataLoad)); + requestMessageType.setMessageBody(bodyType); + + requestMessageType.setMessageHeader(messageHeaderType); + + RequestHeaderType requestHeader = new RequestHeaderType(); + requestHeader.setResultWaittimeMs(180000); + requestMessageType.setRequestHeader(requestHeader); + + return requestMessageType; + } + + private static RequestMessageType getDerivedFactColumnsI2B2RequestMessage(String conceptPath, SecurityType securityType, String projectId ) { + QueryProcessorUtil queryUtil = QueryProcessorUtil.getInstance(); + MessageHeaderType messageHeaderType = queryUtil.getMessageHeader(); + messageHeaderType.setSecurity(securityType); + messageHeaderType.setProjectId(projectId); + + messageHeaderType.setReceivingApplication(messageHeaderType + .getSendingApplication()); + FacilityType facilityType = new FacilityType(); + facilityType.setFacilityName("sample"); + messageHeaderType.setSendingFacility(facilityType); + messageHeaderType.setReceivingFacility(facilityType); + // build message body + GetTermInfoType getTermInfo = new GetTermInfoType(); + getTermInfo.setSelf(conceptPath); + getTermInfo.setHiddens(true); + getTermInfo.setSynonyms(false); + getTermInfo.setType("core"); + getTermInfo.setBlob(false); + + RequestMessageType requestMessageType = new RequestMessageType(); + ObjectFactory of = new ObjectFactory(); + BodyType bodyType = new BodyType(); + bodyType.getAny().add(of.createGetTermInfo(getTermInfo)); + requestMessageType.setMessageBody(bodyType); + + requestMessageType.setMessageHeader(messageHeaderType); + + RequestHeaderType requestHeader = new RequestHeaderType(); + requestHeader.setResultWaittimeMs(180000); + requestMessageType.setRequestHeader(requestHeader); + + return requestMessageType; + + } + + private static RequestMessageType getModifierI2B2RequestMessage(String modifierPath, String appliedPath, SecurityType securityType, String projectId ) { + QueryProcessorUtil queryUtil = QueryProcessorUtil.getInstance(); + MessageHeaderType messageHeaderType = queryUtil.getMessageHeader(); + messageHeaderType.setSecurity(securityType); + messageHeaderType.setProjectId(projectId); + + messageHeaderType.setReceivingApplication(messageHeaderType + .getSendingApplication()); + FacilityType facilityType = new FacilityType(); + facilityType.setFacilityName("sample"); + messageHeaderType.setSendingFacility(facilityType); + messageHeaderType.setReceivingFacility(facilityType); + // build message body + + GetModifierInfoType modifierInfoType = new GetModifierInfoType(); + modifierInfoType.setSelf(modifierPath); + modifierInfoType.setAppliedPath(appliedPath); + + // max="300" hiddens="false" synonyms="false" type="core" blob="true" + // getChildren.setMax(300); + modifierInfoType.setHiddens(true); + modifierInfoType.setBlob(true); + modifierInfoType.setSynonyms(false); + + RequestMessageType requestMessageType = new RequestMessageType(); + ObjectFactory of = new ObjectFactory(); + BodyType bodyType = new BodyType(); + bodyType.getAny().add(of.createGetModifierInfo(modifierInfoType)); + requestMessageType.setMessageBody(bodyType); + + requestMessageType.setMessageHeader(messageHeaderType); + + RequestHeaderType requestHeader = new RequestHeaderType(); + requestHeader.setResultWaittimeMs(180000); + requestMessageType.setRequestHeader(requestHeader); + + return requestMessageType; + + } + + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/pdo/GetObservationFactFromPrimaryKeyHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/pdo/GetObservationFactFromPrimaryKeyHandler.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/pdo/GetObservationFactFromPrimaryKeyHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/pdo/GetObservationFactFromPrimaryKeyHandler.java index 114b82af..7b101374 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/pdo/GetObservationFactFromPrimaryKeyHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/pdo/GetObservationFactFromPrimaryKeyHandler.java @@ -1,91 +1,91 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.delegate.pdo; - - -import java.util.List; - -import edu.harvard.i2b2.crc.datavo.pdo.PatientDataType; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.pdo.query.GetObservationFactByPrimaryKeyRequestType; -import edu.harvard.i2b2.crc.delegate.RequestHandler; -import edu.harvard.i2b2.crc.ejb.PdoQueryBean; -//import edu.harvard.i2b2.crc.ejb.PdoQueryLocal; -//import edu.harvard.i2b2.crc.ejb.PdoQueryLocalHome; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - - -/** - * GetObservationFactFromPrimaryKeyHandler class. - * $Id: GetObservationFactFromPrimaryKeyHandler.java,v 1.8 2008/07/21 19:56:56 rk903 Exp $ - * @author rkuttan - */ -public class GetObservationFactFromPrimaryKeyHandler extends RequestHandler { - private GetObservationFactByPrimaryKeyRequestType getObservationFactByPrimaryKeyRequestType = - null; - - - /** - * Constuctor which accepts i2b2 request message xml - * @param requestXml - * @throws I2B2Exception - */ - public GetObservationFactFromPrimaryKeyHandler(String requestXml, List roles) - throws I2B2Exception { - try { - this.getObservationFactByPrimaryKeyRequestType = (GetObservationFactByPrimaryKeyRequestType) this.getRequestType(requestXml, - edu.harvard.i2b2.crc.datavo.pdo.query.GetObservationFactByPrimaryKeyRequestType.class); - this.setDataSourceLookup(requestXml); - if ( getObservationFactByPrimaryKeyRequestType.getFactOutputOption().isBlob() && - !roles.contains("DATA_DEID")) - throw new I2B2Exception("Access denied need DATA_DEID or DATA_PROT to get notes"); - } catch (JAXBUtilException jaxbUtilEx) { - throw new I2B2Exception("Error ", jaxbUtilEx); - } - } - - /** - * Perform operation for the given request and - * return response - */ - @Override - public BodyType execute() throws I2B2Exception { - // call ejb and pass input object - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - String responseString = null; - BodyType bodyType = new BodyType(); - PatientDataType patientDataType = null; - try { - //TODO mm removed EJBs - // PdoQueryLocalHome pdoQueryLocalHome = qpUtil.getPdoQueryLocalHome(); - // PdoQueryLocal pdoQueryInfoLocal = pdoQueryLocalHome.create(); - PdoQueryBean query = new PdoQueryBean(); - patientDataType = query.getObservationFactByPrimaryKey(getDataSourceLookup(),getObservationFactByPrimaryKeyRequestType); - - } catch (Exception e) { - throw new I2B2Exception("", e); - } finally { - edu.harvard.i2b2.crc.datavo.pdo.query.PatientDataResponseType pdoResponseType = new edu.harvard.i2b2.crc.datavo.pdo.query.PatientDataResponseType(); - pdoResponseType.setPatientData(patientDataType); - edu.harvard.i2b2.crc.datavo.pdo.query.ObjectFactory objectFactory = new edu.harvard.i2b2.crc.datavo.pdo.query.ObjectFactory(); - bodyType.getAny() - .add(objectFactory.createResponse(pdoResponseType)); - } - - return bodyType; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.delegate.pdo; + + +import java.util.List; + +import edu.harvard.i2b2.crc.datavo.pdo.PatientDataType; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.pdo.query.GetObservationFactByPrimaryKeyRequestType; +import edu.harvard.i2b2.crc.delegate.RequestHandler; +import edu.harvard.i2b2.crc.ejb.PdoQueryBean; +//import edu.harvard.i2b2.crc.ejb.PdoQueryLocal; +//import edu.harvard.i2b2.crc.ejb.PdoQueryLocalHome; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + + +/** + * GetObservationFactFromPrimaryKeyHandler class. + * $Id: GetObservationFactFromPrimaryKeyHandler.java,v 1.8 2008/07/21 19:56:56 rk903 Exp $ + * @author rkuttan + */ +public class GetObservationFactFromPrimaryKeyHandler extends RequestHandler { + private GetObservationFactByPrimaryKeyRequestType getObservationFactByPrimaryKeyRequestType = + null; + + + /** + * Constuctor which accepts i2b2 request message xml + * @param requestXml + * @throws I2B2Exception + */ + public GetObservationFactFromPrimaryKeyHandler(String requestXml, List roles) + throws I2B2Exception { + try { + this.getObservationFactByPrimaryKeyRequestType = (GetObservationFactByPrimaryKeyRequestType) this.getRequestType(requestXml, + edu.harvard.i2b2.crc.datavo.pdo.query.GetObservationFactByPrimaryKeyRequestType.class); + this.setDataSourceLookup(requestXml); + if ( getObservationFactByPrimaryKeyRequestType.getFactOutputOption().isBlob() && + !roles.contains("DATA_DEID")) + throw new I2B2Exception("Access denied need DATA_DEID or DATA_PROT to get notes"); + } catch (JAXBUtilException jaxbUtilEx) { + throw new I2B2Exception("Error ", jaxbUtilEx); + } + } + + /** + * Perform operation for the given request and + * return response + */ + @Override + public BodyType execute() throws I2B2Exception { + // call ejb and pass input object + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + String responseString = null; + BodyType bodyType = new BodyType(); + PatientDataType patientDataType = null; + try { + //TODO mm removed EJBs + // PdoQueryLocalHome pdoQueryLocalHome = qpUtil.getPdoQueryLocalHome(); + // PdoQueryLocal pdoQueryInfoLocal = pdoQueryLocalHome.create(); + PdoQueryBean query = new PdoQueryBean(); + patientDataType = query.getObservationFactByPrimaryKey(getDataSourceLookup(),getObservationFactByPrimaryKeyRequestType); + + } catch (Exception e) { + throw new I2B2Exception("", e); + } finally { + edu.harvard.i2b2.crc.datavo.pdo.query.PatientDataResponseType pdoResponseType = new edu.harvard.i2b2.crc.datavo.pdo.query.PatientDataResponseType(); + pdoResponseType.setPatientData(patientDataType); + edu.harvard.i2b2.crc.datavo.pdo.query.ObjectFactory objectFactory = new edu.harvard.i2b2.crc.datavo.pdo.query.ObjectFactory(); + bodyType.getAny() + .add(objectFactory.createResponse(pdoResponseType)); + } + + return bodyType; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/pdo/GetPDOFromInputListHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/pdo/GetPDOFromInputListHandler.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/pdo/GetPDOFromInputListHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/pdo/GetPDOFromInputListHandler.java index 21b26544..7539b7a4 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/pdo/GetPDOFromInputListHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/pdo/GetPDOFromInputListHandler.java @@ -1,98 +1,98 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.delegate.pdo; - - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.dao.IDAOFactory; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.pdo.query.GetPDOFromInputListRequestType; -import edu.harvard.i2b2.crc.datavo.pdo.query.PatientDataResponseType; -import edu.harvard.i2b2.crc.delegate.RequestHandler; -import edu.harvard.i2b2.crc.ejb.PdoQueryBean; -import edu.harvard.i2b2.crc.role.AuthrizationHelper; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - -/** - * GetPDOFromInputListHandler class. $Id: GetPDOFromInputListHandler.java,v 1.10 - * 2008/07/21 19:56:56 rk903 Exp $ - * - * @author rkuttan - */ -public class GetPDOFromInputListHandler extends RequestHandler { - private GetPDOFromInputListRequestType getPDOFromInputListRequestType = null; - private String requestXml = null; - - /** - * Constuctor which accepts i2b2 request message xml - * - * @param requestXml - * @throws I2B2Exception - */ - public GetPDOFromInputListHandler(String requestXml) throws I2B2Exception { - this.requestXml = requestXml; - try { - getPDOFromInputListRequestType = (GetPDOFromInputListRequestType) this - .getRequestType( - requestXml, - edu.harvard.i2b2.crc.datavo.pdo.query.GetPDOFromInputListRequestType.class); - setDataSourceLookup(requestXml); - } catch (JAXBUtilException jaxbUtilEx) { - throw new I2B2Exception("Error ", jaxbUtilEx); - } - } - - /** - * Perform operation for the given request using business class(ejb) and - * return response - */ - @Override - public BodyType execute() throws I2B2Exception { - // call ejb and pass input object - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - String responseString = null; - BodyType bodyType = new BodyType(); - try { - String domainId = getDataSourceLookup().getDomainId(); - String projectId = getDataSourceLookup().getProjectPath(); - String userId = getDataSourceLookup().getOwnerId(); - DAOFactoryHelper daoFactoryHelper = new DAOFactoryHelper(this - .getDataSourceLookup().getDomainId(), getDataSourceLookup() - .getProjectPath(), getDataSourceLookup().getOwnerId()); - IDAOFactory daoFactory = daoFactoryHelper.getDAOFactory(); - AuthrizationHelper authHelper = new AuthrizationHelper(domainId, - projectId, userId, daoFactory); - authHelper.checkRoleForProtectionLabel("PDO_WITHOUT_BLOB"); - - //TODO removed EJBs - // PdoQueryLocalHome pdoQueryLocalHome = qpUtil.getPdoQueryLocalHome(); - // PdoQueryLocal pdoQueryInfoLocal = pdoQueryLocalHome.create(); - PdoQueryBean query = new PdoQueryBean(); - PatientDataResponseType pdoResponseType = query - .getPlainPatientData(getDataSourceLookup(), - getPDOFromInputListRequestType, requestXml); - - edu.harvard.i2b2.crc.datavo.pdo.query.ObjectFactory objectFactory = new edu.harvard.i2b2.crc.datavo.pdo.query.ObjectFactory(); - bodyType.getAny() - .add(objectFactory.createResponse(pdoResponseType)); - } catch (Exception e) { - log.error(e.getMessage()); - throw new I2B2Exception("", e); - } - return bodyType; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.delegate.pdo; + + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.dao.IDAOFactory; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.pdo.query.GetPDOFromInputListRequestType; +import edu.harvard.i2b2.crc.datavo.pdo.query.PatientDataResponseType; +import edu.harvard.i2b2.crc.delegate.RequestHandler; +import edu.harvard.i2b2.crc.ejb.PdoQueryBean; +import edu.harvard.i2b2.crc.role.AuthrizationHelper; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + +/** + * GetPDOFromInputListHandler class. $Id: GetPDOFromInputListHandler.java,v 1.10 + * 2008/07/21 19:56:56 rk903 Exp $ + * + * @author rkuttan + */ +public class GetPDOFromInputListHandler extends RequestHandler { + private GetPDOFromInputListRequestType getPDOFromInputListRequestType = null; + private String requestXml = null; + + /** + * Constuctor which accepts i2b2 request message xml + * + * @param requestXml + * @throws I2B2Exception + */ + public GetPDOFromInputListHandler(String requestXml) throws I2B2Exception { + this.requestXml = requestXml; + try { + getPDOFromInputListRequestType = (GetPDOFromInputListRequestType) this + .getRequestType( + requestXml, + edu.harvard.i2b2.crc.datavo.pdo.query.GetPDOFromInputListRequestType.class); + setDataSourceLookup(requestXml); + } catch (JAXBUtilException jaxbUtilEx) { + throw new I2B2Exception("Error ", jaxbUtilEx); + } + } + + /** + * Perform operation for the given request using business class(ejb) and + * return response + */ + @Override + public BodyType execute() throws I2B2Exception { + // call ejb and pass input object + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + String responseString = null; + BodyType bodyType = new BodyType(); + try { + String domainId = getDataSourceLookup().getDomainId(); + String projectId = getDataSourceLookup().getProjectPath(); + String userId = getDataSourceLookup().getOwnerId(); + DAOFactoryHelper daoFactoryHelper = new DAOFactoryHelper(this + .getDataSourceLookup().getDomainId(), getDataSourceLookup() + .getProjectPath(), getDataSourceLookup().getOwnerId()); + IDAOFactory daoFactory = daoFactoryHelper.getDAOFactory(); + AuthrizationHelper authHelper = new AuthrizationHelper(domainId, + projectId, userId, daoFactory); + authHelper.checkRoleForProtectionLabel("PDO_WITHOUT_BLOB"); + + //TODO removed EJBs + // PdoQueryLocalHome pdoQueryLocalHome = qpUtil.getPdoQueryLocalHome(); + // PdoQueryLocal pdoQueryInfoLocal = pdoQueryLocalHome.create(); + PdoQueryBean query = new PdoQueryBean(); + PatientDataResponseType pdoResponseType = query + .getPlainPatientData(getDataSourceLookup(), + getPDOFromInputListRequestType, requestXml); + + edu.harvard.i2b2.crc.datavo.pdo.query.ObjectFactory objectFactory = new edu.harvard.i2b2.crc.datavo.pdo.query.ObjectFactory(); + bodyType.getAny() + .add(objectFactory.createResponse(pdoResponseType)); + } catch (Exception e) { + log.error(e.getMessage()); + throw new I2B2Exception("", e); + } + return bodyType; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/pdo/GetPDOTemplateHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/pdo/GetPDOTemplateHandler.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/pdo/GetPDOTemplateHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/pdo/GetPDOTemplateHandler.java index 01995a39..08ba998f --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/pdo/GetPDOTemplateHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/pdo/GetPDOTemplateHandler.java @@ -1,159 +1,159 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.delegate.pdo; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.List; - -import jakarta.xml.bind.JAXBElement; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.pdo.ParamType; -import edu.harvard.i2b2.crc.datavo.pdo.PatientDataType; -import edu.harvard.i2b2.crc.datavo.pdo.query.GetPDOTemplateRequestType; -import edu.harvard.i2b2.crc.datavo.pdo.query.PatientDataResponseType; -import edu.harvard.i2b2.crc.delegate.RequestHandler; -import edu.harvard.i2b2.crc.ejb.PdoQueryBean; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - -/** - * GetPDOFromInputListHandler class. $Id: GetPDOFromInputListHandler.java,v 1.10 - * 2008/07/21 19:56:56 rk903 Exp $ - * - * @author rkuttan - */ -public class GetPDOTemplateHandler extends RequestHandler { - private GetPDOTemplateRequestType getPDOTemplateRequestType = null; - /** log **/ - protected final Log log = LogFactory.getLog(getClass()); - - /** - * Constuctor which accepts i2b2 request message xml - * - * @param requestXml - * @throws I2B2Exception - */ - public GetPDOTemplateHandler(String requestXml) throws I2B2Exception { - try { - getPDOTemplateRequestType = (GetPDOTemplateRequestType) this - .getRequestType( - requestXml, - edu.harvard.i2b2.crc.datavo.pdo.query.GetPDOTemplateRequestType.class); - setDataSourceLookup(requestXml); - } catch (JAXBUtilException jaxbUtilEx) { - throw new I2B2Exception("Error ", jaxbUtilEx); - } - } - - /** - * Perform operation for the given request using business class(ejb) and - * return response - */ - @Override - public BodyType execute() throws I2B2Exception { - // call ejb and pass input object - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - String responseString = null; - BodyType bodyType = new BodyType(); - - try { - InputStream resourceAsStream = getClass().getResourceAsStream("pdo_template.xml"); - //.getContextClassLoader().getResourceAsStream( - // "pdo_template.xml"); - - if (resourceAsStream == null) { - log.debug("Unable to read pdo_template.xml, the inputstream is null"); - } else { - log.debug("pdo_template.xml, the inputstream is not null"); - } - // .currentThread() - // .getContextClassLoader() - // .getResourceAsStream( - // ); - String pdoXmlContent = convertStreamToString(resourceAsStream); - JAXBElement pdoJaxb = null; - - pdoJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString( - pdoXmlContent); - - PatientDataType patientDataType = (PatientDataType) pdoJaxb - .getValue(); - - //TODO removed EJBs - //PdoQueryLocalHome pdoQueryLocalHome = qpUtil.getPdoQueryLocalHome(); - //PdoQueryLocal pdoQueryInfoLocal = pdoQueryLocalHome.create(); - PdoQueryBean query = new PdoQueryBean(); - List patientParamList = query.getPDOTemplate("patient_dimension",this.getDataSourceLookup(),false); - patientDataType.getPatientSet().getPatient().get(0).getParam().clear(); - patientDataType.getPatientSet().getPatient().get(0).getParam().addAll(patientParamList); - - - List visitParamList = query.getPDOTemplate("visit_dimension",this.getDataSourceLookup(),false); - patientDataType.getEventSet().getEvent().get(0).getParam().clear(); - patientDataType.getEventSet().getEvent().get(0).getParam().addAll(visitParamList); - - PatientDataResponseType patientDataResponseType = new PatientDataResponseType(); - patientDataResponseType.setPatientData(patientDataType); - edu.harvard.i2b2.crc.datavo.pdo.query.ObjectFactory objectFactory = new edu.harvard.i2b2.crc.datavo.pdo.query.ObjectFactory(); - - bodyType.getAny().add( - objectFactory.createResponse(patientDataResponseType)); - - - } catch (JAXBUtilException e) { - log.error("", e); - throw new I2B2Exception("", e); - } catch (Exception e) { - log.error("", e); - throw new I2B2Exception("", e); - } - return bodyType; - } - - private String convertStreamToString(InputStream is) { - - - BufferedReader reader = new BufferedReader(new InputStreamReader(is)); - StringBuilder sb = new StringBuilder(); - - String line = null; - try { - while ((line = reader.readLine()) != null) { - sb.append(line + "\n"); - } - } catch (IOException e) { - e.printStackTrace(); - } finally { - try { - is.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - return sb.toString(); - } - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.delegate.pdo; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.List; + +import jakarta.xml.bind.JAXBElement; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.pdo.ParamType; +import edu.harvard.i2b2.crc.datavo.pdo.PatientDataType; +import edu.harvard.i2b2.crc.datavo.pdo.query.GetPDOTemplateRequestType; +import edu.harvard.i2b2.crc.datavo.pdo.query.PatientDataResponseType; +import edu.harvard.i2b2.crc.delegate.RequestHandler; +import edu.harvard.i2b2.crc.ejb.PdoQueryBean; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + +/** + * GetPDOFromInputListHandler class. $Id: GetPDOFromInputListHandler.java,v 1.10 + * 2008/07/21 19:56:56 rk903 Exp $ + * + * @author rkuttan + */ +public class GetPDOTemplateHandler extends RequestHandler { + private GetPDOTemplateRequestType getPDOTemplateRequestType = null; + /** log **/ + protected final Log log = LogFactory.getLog(getClass()); + + /** + * Constuctor which accepts i2b2 request message xml + * + * @param requestXml + * @throws I2B2Exception + */ + public GetPDOTemplateHandler(String requestXml) throws I2B2Exception { + try { + getPDOTemplateRequestType = (GetPDOTemplateRequestType) this + .getRequestType( + requestXml, + edu.harvard.i2b2.crc.datavo.pdo.query.GetPDOTemplateRequestType.class); + setDataSourceLookup(requestXml); + } catch (JAXBUtilException jaxbUtilEx) { + throw new I2B2Exception("Error ", jaxbUtilEx); + } + } + + /** + * Perform operation for the given request using business class(ejb) and + * return response + */ + @Override + public BodyType execute() throws I2B2Exception { + // call ejb and pass input object + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + String responseString = null; + BodyType bodyType = new BodyType(); + + try { + InputStream resourceAsStream = getClass().getResourceAsStream("pdo_template.xml"); + //.getContextClassLoader().getResourceAsStream( + // "pdo_template.xml"); + + if (resourceAsStream == null) { + log.debug("Unable to read pdo_template.xml, the inputstream is null"); + } else { + log.debug("pdo_template.xml, the inputstream is not null"); + } + // .currentThread() + // .getContextClassLoader() + // .getResourceAsStream( + // ); + String pdoXmlContent = convertStreamToString(resourceAsStream); + JAXBElement pdoJaxb = null; + + pdoJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString( + pdoXmlContent); + + PatientDataType patientDataType = (PatientDataType) pdoJaxb + .getValue(); + + //TODO removed EJBs + //PdoQueryLocalHome pdoQueryLocalHome = qpUtil.getPdoQueryLocalHome(); + //PdoQueryLocal pdoQueryInfoLocal = pdoQueryLocalHome.create(); + PdoQueryBean query = new PdoQueryBean(); + List patientParamList = query.getPDOTemplate("patient_dimension",this.getDataSourceLookup(),false); + patientDataType.getPatientSet().getPatient().get(0).getParam().clear(); + patientDataType.getPatientSet().getPatient().get(0).getParam().addAll(patientParamList); + + + List visitParamList = query.getPDOTemplate("visit_dimension",this.getDataSourceLookup(),false); + patientDataType.getEventSet().getEvent().get(0).getParam().clear(); + patientDataType.getEventSet().getEvent().get(0).getParam().addAll(visitParamList); + + PatientDataResponseType patientDataResponseType = new PatientDataResponseType(); + patientDataResponseType.setPatientData(patientDataType); + edu.harvard.i2b2.crc.datavo.pdo.query.ObjectFactory objectFactory = new edu.harvard.i2b2.crc.datavo.pdo.query.ObjectFactory(); + + bodyType.getAny().add( + objectFactory.createResponse(patientDataResponseType)); + + + } catch (JAXBUtilException e) { + log.error("", e); + throw new I2B2Exception("", e); + } catch (Exception e) { + log.error("", e); + throw new I2B2Exception("", e); + } + return bodyType; + } + + private String convertStreamToString(InputStream is) { + + + BufferedReader reader = new BufferedReader(new InputStreamReader(is)); + StringBuilder sb = new StringBuilder(); + + String line = null; + try { + while ((line = reader.readLine()) != null) { + sb.append(line + "\n"); + } + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + is.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + return sb.toString(); + } + + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/pdo/PdoQueryRequestDelegate.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/pdo/PdoQueryRequestDelegate.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/pdo/PdoQueryRequestDelegate.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/pdo/PdoQueryRequestDelegate.java index 1f38f522..b1e172ae --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/pdo/PdoQueryRequestDelegate.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/pdo/PdoQueryRequestDelegate.java @@ -1,272 +1,272 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.delegate.pdo; - -import java.util.List; - -import jakarta.xml.bind.JAXBElement; - -import org.apache.axis2.AxisFault; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.exception.StackTraceUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.dao.pdo.PdoQueryEidDao; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.I2B2MessageResponseFactory; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; -import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; -import edu.harvard.i2b2.crc.datavo.pdo.query.PdoQryHeaderType; -import edu.harvard.i2b2.crc.datavo.pdo.query.PdoRequestTypeType; -import edu.harvard.i2b2.crc.datavo.pm.ParamType; -import edu.harvard.i2b2.crc.datavo.pm.ProjectType; -import edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate; -import edu.harvard.i2b2.crc.delegate.pm.PMServiceDriver; -import edu.harvard.i2b2.crc.util.CacheUtil; -import edu.harvard.i2b2.crc.util.ParamUtil; - -/** - * PDO query request delegate class $Id: PdoQueryRequestDelegate.java,v 1.16 - * 2007/09/14 19:33:37 rk903 Exp $ - * - * @author rkuttan - */ -public class PdoQueryRequestDelegate extends RequestHandlerDelegate { - /** log **/ - protected final Log log = LogFactory.getLog(getClass()); - protected static Log logesapi = LogFactory.getLog(PdoQueryRequestDelegate.class); - - /** - * @see edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate#handleRequest(java.lang.String) - */ - @Override - public String handleRequest(String requestXml) throws I2B2Exception { - PdoQryHeaderType headerType = null; - String response = null; - JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); - List roles = null; - try { - JAXBElement jaxbElement = jaxbUtil.unMashallFromString(requestXml); - RequestMessageType requestMessageType = (RequestMessageType) jaxbElement - .getValue(); - BodyType bodyType = requestMessageType.getMessageBody(); - - if (bodyType == null) { - log.error("null value in body type"); - throw new I2B2Exception("null value in body type"); - } - - // Call PM cell to validate user - - StatusType procStatus = null; - try { - SecurityType securityType = null; - String projectId = null; - if (requestMessageType.getMessageHeader() != null) { - if (requestMessageType.getMessageHeader().getSecurity() != null) { - securityType = requestMessageType.getMessageHeader() - .getSecurity(); - } - projectId = requestMessageType.getMessageHeader() - .getProjectId(); - } - - if (securityType == null) { - procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus - .setValue("Request message missing user/password"); - response = I2B2MessageResponseFactory.buildResponseMessage( - requestXml, procStatus, bodyType); - return response; - } - if (projectId == null) { - procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus.setValue("Missing "); - response = I2B2MessageResponseFactory.buildResponseMessage( - requestXml, procStatus, bodyType); - return response; - } - - PMServiceDriver pmServiceDriver = new PMServiceDriver(); - ProjectType projectType = pmServiceDriver.checkValidUser( - securityType, projectId); - // projectType.getRole() - if (projectType == null) { - procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus - .setValue("Invalid user/password for the given project [" - + projectId + "]"); - response = I2B2MessageResponseFactory.buildResponseMessage( - requestXml, procStatus, bodyType); - return response; - } - - log.debug("project name from PM " + projectType.getName()); - logesapi.debug("project id from PM " + projectType.getId()); - if (projectType.getRole() != null) { - log.debug("project role from PM " - + projectType.getRole().get(0)); - this.putRoles(projectId, securityType.getUsername(), - securityType.getDomain(), projectType.getRole()); - - //TODO removed cache - //Node rootNode = CacheUtil.getCache().getRoot(); - //List roles = (List) rootNode - // .get(securityType.getDomain() + "/" + projectId - // + "/" + securityType.getUsername()); - roles = (List) CacheUtil - .get(securityType.getDomain() + "/" + projectId - + "/" + securityType.getUsername()); - if (roles != null) { - log.debug("User Roles count " + roles.size()); - } - if (!roles.contains("DATA_LDS")) - throw new I2B2Exception("Access Denied need at least DATA_LDS"); - ParamUtil paramUtil = new ParamUtil(); - paramUtil.clearParam(projectId, securityType.getUsername(), securityType.getDomain(), ParamUtil.CRC_ENABLE_UNITCD_CONVERSION); - if (projectType.getParam() != null) { - for (ParamType param : projectType.getParam()) { - if (param.getName() != null && param.getName().trim().equalsIgnoreCase(ParamUtil.CRC_ENABLE_UNITCD_CONVERSION)) { - paramUtil.putParam(projectId, securityType.getUsername(), securityType.getDomain(),ParamUtil.CRC_ENABLE_UNITCD_CONVERSION,param); - String unitCdCache = paramUtil.getParam(projectId, securityType.getUsername(), securityType.getDomain(),ParamUtil.CRC_ENABLE_UNITCD_CONVERSION); - logesapi.debug("CRC param stored in the cache Project Id [" + projectId + "] user [" + securityType.getUsername() + "] domain [" + securityType.getDomain() + "] " + ParamUtil.CRC_ENABLE_UNITCD_CONVERSION + "[" + unitCdCache + "]" ); - break; - } - } - } - - - } else { - - log.error("Project role not set for the user "); - - } - } catch (AxisFault e) { - procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus.setValue("Could not connect to server[" - + e.getDetail() + "]"); - response = I2B2MessageResponseFactory.buildResponseMessage( - requestXml, procStatus, bodyType); - return response; - } catch (I2B2Exception e) { - procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus - .setValue("Project Management cell interface error: [" - + e.getMessage() + "]"); - response = I2B2MessageResponseFactory.buildResponseMessage( - requestXml, procStatus, bodyType); - return response; - } catch (JAXBUtilException e) { - procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus - .setValue("Message error from Project Management cell[" - + e.getMessage() + "]"); - response = I2B2MessageResponseFactory.buildResponseMessage( - requestXml, procStatus, bodyType); - return response; - } - - JAXBUnWrapHelper unWrapHelper = new JAXBUnWrapHelper(); - headerType = (PdoQryHeaderType) unWrapHelper - .getObjectByClass( - bodyType.getAny(), - edu.harvard.i2b2.crc.datavo.pdo.query.PdoQryHeaderType.class); - - BodyType responseBodyType = null; - if (headerType.getRequestType().equals( - PdoRequestTypeType.GET_PDO_FROM_INPUT_LIST)) { - GetPDOFromInputListHandler handler = new GetPDOFromInputListHandler( - requestXml); - responseBodyType = handler.execute(); - } else if (headerType.getRequestType().equals( - PdoRequestTypeType.GET_OBSERVATIONFACT_BY_PRIMARY_KEY)) { - - - - - //List roles = (List) cache.getRoot().get(rolePath); - - GetObservationFactFromPrimaryKeyHandler handler = new GetObservationFactFromPrimaryKeyHandler( - requestXml, roles); - responseBodyType = handler.execute(); - } else if (headerType.getRequestType().equals( - PdoRequestTypeType.GET_PDO_TEMPLATE)) { - GetPDOTemplateHandler handler = new GetPDOTemplateHandler( - requestXml); - responseBodyType = handler.execute(); - } - procStatus = new StatusType(); - procStatus.setType("DONE"); - procStatus.setValue("DONE"); - - long startTime = System.currentTimeMillis(); - response = I2B2MessageResponseFactory.buildResponseMessage( - requestXml, procStatus, responseBodyType, true); - long endTime = System.currentTimeMillis(); - long totalTime = endTime - startTime; - log.debug("Total time to pdo jaxb " + totalTime); - - } catch (JAXBUtilException e) { - log.error("JAXBUtil exception", e); - StatusType procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus.setValue(requestXml + "\n\n" - + StackTraceUtil.getStackTrace(e)); - try { - response = I2B2MessageResponseFactory.buildResponseMessage( - null, procStatus, null); - } catch (JAXBUtilException e1) { - e1.printStackTrace(); - } - } catch (I2B2Exception e) { - log.error("I2B2Exception", e); - StatusType procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus.setValue(StackTraceUtil.getStackTrace(e)); - try { - response = I2B2MessageResponseFactory.buildResponseMessage( - requestXml, procStatus, null); - } catch (JAXBUtilException e1) { - e1.printStackTrace(); - } - } catch (Throwable e) { - log.error("Throwable", e); - StatusType procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus.setValue(StackTraceUtil.getStackTrace(e)); - try { - response = I2B2MessageResponseFactory.buildResponseMessage( - requestXml, procStatus, null); - } catch (JAXBUtilException e1) { - e1.printStackTrace(); - } - } - return response; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.delegate.pdo; + +import java.util.List; + +import jakarta.xml.bind.JAXBElement; + +import org.apache.axis2.AxisFault; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.exception.StackTraceUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.dao.pdo.PdoQueryEidDao; +import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; +import edu.harvard.i2b2.crc.datavo.I2B2MessageResponseFactory; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; +import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; +import edu.harvard.i2b2.crc.datavo.pdo.query.PdoQryHeaderType; +import edu.harvard.i2b2.crc.datavo.pdo.query.PdoRequestTypeType; +import edu.harvard.i2b2.crc.datavo.pm.ParamType; +import edu.harvard.i2b2.crc.datavo.pm.ProjectType; +import edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate; +import edu.harvard.i2b2.crc.delegate.pm.PMServiceDriver; +import edu.harvard.i2b2.crc.util.CacheUtil; +import edu.harvard.i2b2.crc.util.ParamUtil; + +/** + * PDO query request delegate class $Id: PdoQueryRequestDelegate.java,v 1.16 + * 2007/09/14 19:33:37 rk903 Exp $ + * + * @author rkuttan + */ +public class PdoQueryRequestDelegate extends RequestHandlerDelegate { + /** log **/ + protected final Log log = LogFactory.getLog(getClass()); + protected static Log logesapi = LogFactory.getLog(PdoQueryRequestDelegate.class); + + /** + * @see edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate#handleRequest(java.lang.String) + */ + @Override + public String handleRequest(String requestXml) throws I2B2Exception { + PdoQryHeaderType headerType = null; + String response = null; + JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); + List roles = null; + try { + JAXBElement jaxbElement = jaxbUtil.unMashallFromString(requestXml); + RequestMessageType requestMessageType = (RequestMessageType) jaxbElement + .getValue(); + BodyType bodyType = requestMessageType.getMessageBody(); + + if (bodyType == null) { + log.error("null value in body type"); + throw new I2B2Exception("null value in body type"); + } + + // Call PM cell to validate user + + StatusType procStatus = null; + try { + SecurityType securityType = null; + String projectId = null; + if (requestMessageType.getMessageHeader() != null) { + if (requestMessageType.getMessageHeader().getSecurity() != null) { + securityType = requestMessageType.getMessageHeader() + .getSecurity(); + } + projectId = requestMessageType.getMessageHeader() + .getProjectId(); + } + + if (securityType == null) { + procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus + .setValue("Request message missing user/password"); + response = I2B2MessageResponseFactory.buildResponseMessage( + requestXml, procStatus, bodyType); + return response; + } + if (projectId == null) { + procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus.setValue("Missing "); + response = I2B2MessageResponseFactory.buildResponseMessage( + requestXml, procStatus, bodyType); + return response; + } + + PMServiceDriver pmServiceDriver = new PMServiceDriver(); + ProjectType projectType = pmServiceDriver.checkValidUser( + securityType, projectId); + // projectType.getRole() + if (projectType == null) { + procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus + .setValue("Invalid user/password for the given project [" + + projectId + "]"); + response = I2B2MessageResponseFactory.buildResponseMessage( + requestXml, procStatus, bodyType); + return response; + } + + log.debug("project name from PM " + projectType.getName()); + logesapi.debug("project id from PM " + projectType.getId()); + if (projectType.getRole() != null) { + log.debug("project role from PM " + + projectType.getRole().get(0)); + this.putRoles(projectId, securityType.getUsername(), + securityType.getDomain(), projectType.getRole()); + + //TODO removed cache + //Node rootNode = CacheUtil.getCache().getRoot(); + //List roles = (List) rootNode + // .get(securityType.getDomain() + "/" + projectId + // + "/" + securityType.getUsername()); + roles = (List) CacheUtil + .get(securityType.getDomain() + "/" + projectId + + "/" + securityType.getUsername()); + if (roles != null) { + log.debug("User Roles count " + roles.size()); + } + if (!roles.contains("DATA_LDS")) + throw new I2B2Exception("Access Denied need at least DATA_LDS"); + ParamUtil paramUtil = new ParamUtil(); + paramUtil.clearParam(projectId, securityType.getUsername(), securityType.getDomain(), ParamUtil.CRC_ENABLE_UNITCD_CONVERSION); + if (projectType.getParam() != null) { + for (ParamType param : projectType.getParam()) { + if (param.getName() != null && param.getName().trim().equalsIgnoreCase(ParamUtil.CRC_ENABLE_UNITCD_CONVERSION)) { + paramUtil.putParam(projectId, securityType.getUsername(), securityType.getDomain(),ParamUtil.CRC_ENABLE_UNITCD_CONVERSION,param); + String unitCdCache = paramUtil.getParam(projectId, securityType.getUsername(), securityType.getDomain(),ParamUtil.CRC_ENABLE_UNITCD_CONVERSION); + logesapi.debug("CRC param stored in the cache Project Id [" + projectId + "] user [" + securityType.getUsername() + "] domain [" + securityType.getDomain() + "] " + ParamUtil.CRC_ENABLE_UNITCD_CONVERSION + "[" + unitCdCache + "]" ); + break; + } + } + } + + + } else { + + log.error("Project role not set for the user "); + + } + } catch (AxisFault e) { + procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus.setValue("Could not connect to server[" + + e.getDetail() + "]"); + response = I2B2MessageResponseFactory.buildResponseMessage( + requestXml, procStatus, bodyType); + return response; + } catch (I2B2Exception e) { + procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus + .setValue("Project Management cell interface error: [" + + e.getMessage() + "]"); + response = I2B2MessageResponseFactory.buildResponseMessage( + requestXml, procStatus, bodyType); + return response; + } catch (JAXBUtilException e) { + procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus + .setValue("Message error from Project Management cell[" + + e.getMessage() + "]"); + response = I2B2MessageResponseFactory.buildResponseMessage( + requestXml, procStatus, bodyType); + return response; + } + + JAXBUnWrapHelper unWrapHelper = new JAXBUnWrapHelper(); + headerType = (PdoQryHeaderType) unWrapHelper + .getObjectByClass( + bodyType.getAny(), + edu.harvard.i2b2.crc.datavo.pdo.query.PdoQryHeaderType.class); + + BodyType responseBodyType = null; + if (headerType.getRequestType().equals( + PdoRequestTypeType.GET_PDO_FROM_INPUT_LIST)) { + GetPDOFromInputListHandler handler = new GetPDOFromInputListHandler( + requestXml); + responseBodyType = handler.execute(); + } else if (headerType.getRequestType().equals( + PdoRequestTypeType.GET_OBSERVATIONFACT_BY_PRIMARY_KEY)) { + + + + + //List roles = (List) cache.getRoot().get(rolePath); + + GetObservationFactFromPrimaryKeyHandler handler = new GetObservationFactFromPrimaryKeyHandler( + requestXml, roles); + responseBodyType = handler.execute(); + } else if (headerType.getRequestType().equals( + PdoRequestTypeType.GET_PDO_TEMPLATE)) { + GetPDOTemplateHandler handler = new GetPDOTemplateHandler( + requestXml); + responseBodyType = handler.execute(); + } + procStatus = new StatusType(); + procStatus.setType("DONE"); + procStatus.setValue("DONE"); + + long startTime = System.currentTimeMillis(); + response = I2B2MessageResponseFactory.buildResponseMessage( + requestXml, procStatus, responseBodyType, true); + long endTime = System.currentTimeMillis(); + long totalTime = endTime - startTime; + log.debug("Total time to pdo jaxb " + totalTime); + + } catch (JAXBUtilException e) { + log.error("JAXBUtil exception", e); + StatusType procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus.setValue(requestXml + "\n\n" + + StackTraceUtil.getStackTrace(e)); + try { + response = I2B2MessageResponseFactory.buildResponseMessage( + null, procStatus, null); + } catch (JAXBUtilException e1) { + e1.printStackTrace(); + } + } catch (I2B2Exception e) { + log.error("I2B2Exception", e); + StatusType procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus.setValue(StackTraceUtil.getStackTrace(e)); + try { + response = I2B2MessageResponseFactory.buildResponseMessage( + requestXml, procStatus, null); + } catch (JAXBUtilException e1) { + e1.printStackTrace(); + } + } catch (Throwable e) { + log.error("Throwable", e); + StatusType procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus.setValue(StackTraceUtil.getStackTrace(e)); + try { + response = I2B2MessageResponseFactory.buildResponseMessage( + requestXml, procStatus, null); + } catch (JAXBUtilException e1) { + e1.printStackTrace(); + } + } + return response; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/pdo/pdo_template.xml b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/pdo/pdo_template.xml old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/pdo/pdo_template.xml rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/pdo/pdo_template.xml index bc719c8f..96f5597a --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/pdo/pdo_template.xml +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/pdo/pdo_template.xml @@ -1,106 +1,106 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/pm/CallPMUtil.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/pm/CallPMUtil.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/pm/CallPMUtil.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/pm/CallPMUtil.java index c53f6e67..632d5373 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/pm/CallPMUtil.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/pm/CallPMUtil.java @@ -1,456 +1,456 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.delegate.pm; - -import java.io.StringReader; -import java.io.StringWriter; -import java.util.List; - -import jakarta.xml.bind.JAXBElement; -import javax.xml.stream.XMLInputFactory; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamReader; - -import org.apache.axiom.om.OMAbstractFactory; -import org.apache.axiom.om.OMElement; -import org.apache.axiom.om.OMFactory; -import org.apache.axiom.om.OMXMLBuilderFactory; -import org.apache.axis2.AxisFault; -import edu.harvard.i2b2.common.util.axis2.ServiceClient; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.exception.StackTraceUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2message.FacilityType; -import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; -import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; -import edu.harvard.i2b2.crc.datavo.pm.ConfigureType; -import edu.harvard.i2b2.crc.datavo.pm.GetUserConfigurationType; -import edu.harvard.i2b2.crc.datavo.pm.ObjectFactory; -import edu.harvard.i2b2.crc.datavo.pm.ParamType; -import edu.harvard.i2b2.crc.datavo.pm.ProjectType; -import edu.harvard.i2b2.crc.datavo.pm.UserType; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - -public class CallPMUtil { - - private static JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); - private static Log log = LogFactory.getLog(CallPMUtil.class); - protected static Log logesapi = LogFactory.getLog(CallPMUtil.class); - - public static String callUserResponse(SecurityType securityType, String projectId ) throws AxisFault, I2B2Exception { - RequestMessageType requestMessageType = getI2B2RequestMessage(securityType, projectId); - OMElement requestElement = null; - String response = null; - try { - requestElement = buildOMElement(requestMessageType); - log.debug("CRC PM call's request xml " + requestElement); - response = ServiceClient.sendREST(QueryProcessorUtil.getInstance() - .getProjectManagementCellUrl(), requestElement); - log.debug("Got Response"); - } catch (XMLStreamException e) { - e.printStackTrace(); - throw new I2B2Exception("" + StackTraceUtil.getStackTrace(e)); - } catch (Exception e) { - e.printStackTrace(); - throw new I2B2Exception("" + StackTraceUtil.getStackTrace(e)); - } - - log.debug("Returning ProjectType"); - return response; - } - - public static ProjectType callUserProjectRedcap(SecurityType securityType, String projectId ) throws AxisFault, I2B2Exception { - - RequestMessageType requestMessageType = getI2B2Hive(securityType, null); - OMElement requestElement = null; - ProjectType projectType = null; - String hive = null; - try { - requestElement = buildOMElement(requestMessageType); - log.debug("CRC PM call's request xml " + requestElement); - String response = ServiceClient.sendREST(QueryProcessorUtil.getInstance() - .getProjectManagementCellUrl(), requestElement); - log.debug("Got Response"); - - JAXBElement responseJaxb = jaxbUtil.unMashallFromString(response); - - //CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseXml); - ResponseMessageType pmRespMessageType = (ResponseMessageType) responseJaxb - .getValue(); - logesapi.debug("CRC's PM call response xml" + response); - - ResponseHeaderType responseHeader = pmRespMessageType - .getResponseHeader(); - StatusType status = responseHeader.getResultStatus().getStatus(); - String procStatus = status.getType(); - String procMessage = status.getValue(); - - if (procStatus.equals("ERROR")) { - logesapi.info("PM Error reported by CRC web Service " + procMessage); - - - - - int startstr = procMessage.indexOf("this domain") + 12; - int endstr = procMessage.indexOf(" ", startstr+1) -1; - hive = procMessage.substring(startstr, endstr); - } - - } catch (XMLStreamException e) { - e.printStackTrace(); - throw new I2B2Exception("" + StackTraceUtil.getStackTrace(e)); - } catch (Exception e) { - e.printStackTrace(); - throw new I2B2Exception("" + StackTraceUtil.getStackTrace(e)); - } - - securityType.setDomain(hive); - requestMessageType = getI2B2RequestMessage(securityType, null); - requestElement = null; - projectType = null; - try { - requestElement = buildOMElement(requestMessageType); - log.debug("CRC PM call's request xml " + requestElement); - String response = ServiceClient.sendREST(QueryProcessorUtil.getInstance() - .getProjectManagementCellUrl(), requestElement); - log.debug("Got Response"); - projectType = getUserProjectFromResponseRedcap(response, securityType, projectId); - log.debug("Parsed Projcet Type: " + projectType.getName()); - } catch (XMLStreamException e) { - e.printStackTrace(); - throw new I2B2Exception("" + StackTraceUtil.getStackTrace(e)); - } catch (Exception e) { - e.printStackTrace(); - throw new I2B2Exception("" + StackTraceUtil.getStackTrace(e)); - } - - log.debug("Returning ProjectType"); - return projectType; - } - - - public static ProjectType callUserProject(SecurityType securityType, String projectId ) throws AxisFault, I2B2Exception { - RequestMessageType requestMessageType = getI2B2RequestMessage(securityType, projectId); - OMElement requestElement = null; - ProjectType projectType = null; - try { - requestElement = buildOMElement(requestMessageType); - log.debug("CRC PM call's request xml " + requestElement); - String response = ServiceClient.sendREST(QueryProcessorUtil.getInstance() - .getProjectManagementCellUrl(), requestElement); - log.debug("Got Response"); - projectType = getUserProjectFromResponse(response, securityType, projectId); - log.debug("Parsed Projcet Type: " + projectType.getName()); - } catch (XMLStreamException e) { - e.printStackTrace(); - throw new I2B2Exception("" + StackTraceUtil.getStackTrace(e)); - } catch (Exception e) { - e.printStackTrace(); - throw new I2B2Exception("" + StackTraceUtil.getStackTrace(e)); - } - - log.debug("Returning ProjectType"); - return projectType; - } - - - public static ProjectType getUserProjectFromResponseRedcap(String responseXml, SecurityType securityType, String projectId) - throws JAXBUtilException, I2B2Exception { - JAXBElement responseJaxb = jaxbUtil.unMashallFromString(responseXml); - - //CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseXml); - ResponseMessageType pmRespMessageType = (ResponseMessageType) responseJaxb - .getValue(); - logesapi.debug("CRC's PM call response xml" + responseXml); - - ResponseHeaderType responseHeader = pmRespMessageType - .getResponseHeader(); - StatusType status = responseHeader.getResultStatus().getStatus(); - String procStatus = status.getType(); - String procMessage = status.getValue(); - - if (procStatus.equals("ERROR")) { - logesapi.info("PM Error reported by CRC web Service " + procMessage); - throw new I2B2Exception("PM Error reported by CRC web Service " - + procMessage); - } else if (procStatus.equals("WARNING")) { - logesapi.info("PM Warning reported by CRC web Service" + procMessage); - throw new I2B2Exception("PM Warning reported by CRC web Service" - + procMessage); - } - - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - ConfigureType configureType = (ConfigureType) helper.getObjectByClass( - pmRespMessageType.getMessageBody().getAny(), - ConfigureType.class); - UserType userType = configureType.getUser(); - List projectTypeList = userType.getProject(); - - ProjectType projectType = null; - if (projectTypeList != null && projectTypeList.size() > 0) { - for (ProjectType pType : projectTypeList) { - for (ParamType paramType : pType.getParam()) - if ((paramType.getName().equalsIgnoreCase("REDCAP_SURVEY_PROJECT") - && (paramType.getValue().equalsIgnoreCase(projectId)))) { - projectType = pType; - - // Add user params to porject params - projectType.getParam().addAll(userType.getParam()); - break; - } - } - if (projectType == null) { - throw new I2B2Exception("Redcap not registered to the project[" - + projectId + "]"); - } - } - - return projectType; - } - - public static ProjectType getUserProjectFromResponse(String responseXml, SecurityType securityType, String projectId) - throws JAXBUtilException, I2B2Exception { - JAXBElement responseJaxb = jaxbUtil.unMashallFromString(responseXml); - - //CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseXml); - ResponseMessageType pmRespMessageType = (ResponseMessageType) responseJaxb - .getValue(); - logesapi.debug("CRC's PM call response xml" + responseXml); - - ResponseHeaderType responseHeader = pmRespMessageType - .getResponseHeader(); - StatusType status = responseHeader.getResultStatus().getStatus(); - String procStatus = status.getType(); - String procMessage = status.getValue(); - - if (procStatus.equals("ERROR")) { - logesapi.info("PM Error reported by CRC web Service " + procMessage); - throw new I2B2Exception("PM Error reported by CRC web Service " - + procMessage); - } else if (procStatus.equals("WARNING")) { - logesapi.info("PM Warning reported by CRC web Service" + procMessage); - throw new I2B2Exception("PM Warning reported by CRC web Service" - + procMessage); - } - - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - ConfigureType configureType = (ConfigureType) helper.getObjectByClass( - pmRespMessageType.getMessageBody().getAny(), - ConfigureType.class); - UserType userType = configureType.getUser(); - List projectTypeList = userType.getProject(); - - ProjectType projectType = null; - if (projectTypeList != null && projectTypeList.size() > 0) { - for (ProjectType pType : projectTypeList) { - if (pType.getId().equalsIgnoreCase(projectId)) { - projectType = pType; - - break; - } - } - if (projectType == null) { - throw new I2B2Exception("User not registered to the project[" - + projectId + "]"); - } - } - - return projectType; - } - - public static boolean getUserIsAdminFromResponse(String responseXml, SecurityType securityType, String projectId) - throws JAXBUtilException, I2B2Exception { - JAXBElement responseJaxb = jaxbUtil.unMashallFromString(responseXml); - - //CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseXml); - ResponseMessageType pmRespMessageType = (ResponseMessageType) responseJaxb - .getValue(); - logesapi.debug("CRC's PM call response xml" + responseXml); - - ResponseHeaderType responseHeader = pmRespMessageType - .getResponseHeader(); - StatusType status = responseHeader.getResultStatus().getStatus(); - String procStatus = status.getType(); - String procMessage = status.getValue(); - - if (procStatus.equals("ERROR")) { - logesapi.info("PM Error reported by CRC web Service " + procMessage); - throw new I2B2Exception("PM Error reported by CRC web Service " - + procMessage); - } else if (procStatus.equals("WARNING")) { - logesapi.info("PM Warning reported by CRC web Service" + procMessage); - throw new I2B2Exception("PM Warning reported by CRC web Service" - + procMessage); - } - - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - ConfigureType configureType = (ConfigureType) helper.getObjectByClass( - pmRespMessageType.getMessageBody().getAny(), - ConfigureType.class); - UserType userType = configureType.getUser(); - return userType.isIsAdmin(); - } - - public static UserType getUserFromResponse(String responseXml) - throws JAXBUtilException, I2B2Exception { - JAXBElement responseJaxb = jaxbUtil.unMashallFromString(responseXml); - - //CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseXml); - ResponseMessageType pmRespMessageType = (ResponseMessageType) responseJaxb - .getValue(); - logesapi.debug("CRC's PM call response xml" + responseXml); - - ResponseHeaderType responseHeader = pmRespMessageType - .getResponseHeader(); - StatusType status = responseHeader.getResultStatus().getStatus(); - String procStatus = status.getType(); - String procMessage = status.getValue(); - - if (procStatus.equals("ERROR")) { - logesapi.info("PM Error reported by CRC web Service " + procMessage); - throw new I2B2Exception("PM Error reported by CRC web Service " - + procMessage); - } else if (procStatus.equals("WARNING")) { - logesapi.info("PM Warning reported by CRC web Service" + procMessage); - throw new I2B2Exception("PM Warning reported by CRC web Service" - + procMessage); - } - - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - ConfigureType configureType = (ConfigureType) helper.getObjectByClass( - pmRespMessageType.getMessageBody().getAny(), - ConfigureType.class); - return configureType.getUser(); - //return userType.isIsAdmin(); - } - - private static OMElement buildOMElement(RequestMessageType requestMessageType) - throws XMLStreamException, JAXBUtilException { - StringWriter strWriter = new StringWriter(); - edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory hiveof = new edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory(); - //CRCJAXBUtil.getJAXBUtil() - jaxbUtil.marshaller( - hiveof.createRequest(requestMessageType), strWriter); - // getOMElement from message - OMFactory fac = OMAbstractFactory.getOMFactory(); - - StringReader strReader = new StringReader(strWriter.toString()); - XMLInputFactory xif = XMLInputFactory.newInstance(); - XMLStreamReader reader = xif.createXMLStreamReader(strReader); - OMElement request = OMXMLBuilderFactory.createStAXOMBuilder(reader).getDocumentElement(); - - return request; - } - - - private static RequestMessageType getI2B2Hive(SecurityType securityType, String projectId) { - QueryProcessorUtil queryUtil = QueryProcessorUtil.getInstance(); - MessageHeaderType messageHeaderType = queryUtil.getMessageHeader(); - messageHeaderType.setSecurity(securityType); - messageHeaderType.setProjectId(projectId); - - messageHeaderType.setReceivingApplication(messageHeaderType - .getSendingApplication()); - FacilityType facilityType = new FacilityType(); - facilityType.setFacilityName("sample"); - messageHeaderType.setSendingFacility(facilityType); - messageHeaderType.setReceivingFacility(facilityType); - // build message body - // GetUserInfoType getUserInfoType = null; - - - RequestMessageType requestMessageType = new RequestMessageType(); - ObjectFactory of = new ObjectFactory(); - BodyType bodyType = new BodyType(); - bodyType.getAny().add(of.createGetAllHive(null)); - requestMessageType.setMessageBody(bodyType); - - requestMessageType.setMessageHeader(messageHeaderType); - - RequestHeaderType requestHeader = new RequestHeaderType(); - requestHeader.setResultWaittimeMs(180000); - requestMessageType.setRequestHeader(requestHeader); - - return requestMessageType; - - } - private static RequestMessageType getI2B2RequestMessage(SecurityType securityType, String projectId) { - QueryProcessorUtil queryUtil = QueryProcessorUtil.getInstance(); - MessageHeaderType messageHeaderType = queryUtil.getMessageHeader(); - messageHeaderType.setSecurity(securityType); - messageHeaderType.setProjectId(projectId); - - messageHeaderType.setReceivingApplication(messageHeaderType - .getSendingApplication()); - FacilityType facilityType = new FacilityType(); - facilityType.setFacilityName("sample"); - messageHeaderType.setSendingFacility(facilityType); - messageHeaderType.setReceivingFacility(facilityType); - // build message body - // GetUserInfoType getUserInfoType = null; - GetUserConfigurationType userConfig = new GetUserConfigurationType(); - if (projectId != null) { - userConfig.getProject().add(projectId); - } - - RequestMessageType requestMessageType = new RequestMessageType(); - ObjectFactory of = new ObjectFactory(); - BodyType bodyType = new BodyType(); - bodyType.getAny().add(of.createGetUserConfiguration(userConfig)); - requestMessageType.setMessageBody(bodyType); - - requestMessageType.setMessageHeader(messageHeaderType); - - RequestHeaderType requestHeader = new RequestHeaderType(); - requestHeader.setResultWaittimeMs(180000); - requestMessageType.setRequestHeader(requestHeader); - - return requestMessageType; - - } - - public static boolean callIsAdmin(SecurityType securityType, String projectId) throws AxisFault, I2B2Exception { - RequestMessageType requestMessageType = getI2B2RequestMessage(securityType, projectId); - OMElement requestElement = null; - boolean projectType = false; - try { - requestElement = buildOMElement(requestMessageType); - log.debug("CRC PM call's request xml " + requestElement); - String response = ServiceClient.sendREST(QueryProcessorUtil.getInstance() - .getProjectManagementCellUrl(), requestElement); - log.debug("Got Response"); - projectType = getUserIsAdminFromResponse(response, securityType, projectId); - } catch (XMLStreamException e) { - e.printStackTrace(); - throw new I2B2Exception("" + StackTraceUtil.getStackTrace(e)); - } catch (Exception e) { - e.printStackTrace(); - throw new I2B2Exception("" + StackTraceUtil.getStackTrace(e)); - } - - log.debug("Returning ProjectType"); - return projectType; - } - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.delegate.pm; + +import java.io.StringReader; +import java.io.StringWriter; +import java.util.List; + +import jakarta.xml.bind.JAXBElement; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import org.apache.axiom.om.OMAbstractFactory; +import org.apache.axiom.om.OMElement; +import org.apache.axiom.om.OMFactory; +import org.apache.axiom.om.OMXMLBuilderFactory; +import org.apache.axis2.AxisFault; +import edu.harvard.i2b2.common.util.axis2.ServiceClient; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.exception.StackTraceUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2message.FacilityType; +import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; +import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; +import edu.harvard.i2b2.crc.datavo.pm.ConfigureType; +import edu.harvard.i2b2.crc.datavo.pm.GetUserConfigurationType; +import edu.harvard.i2b2.crc.datavo.pm.ObjectFactory; +import edu.harvard.i2b2.crc.datavo.pm.ParamType; +import edu.harvard.i2b2.crc.datavo.pm.ProjectType; +import edu.harvard.i2b2.crc.datavo.pm.UserType; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + +public class CallPMUtil { + + private static JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); + private static Log log = LogFactory.getLog(CallPMUtil.class); + protected static Log logesapi = LogFactory.getLog(CallPMUtil.class); + + public static String callUserResponse(SecurityType securityType, String projectId ) throws AxisFault, I2B2Exception { + RequestMessageType requestMessageType = getI2B2RequestMessage(securityType, projectId); + OMElement requestElement = null; + String response = null; + try { + requestElement = buildOMElement(requestMessageType); + log.debug("CRC PM call's request xml " + requestElement); + response = ServiceClient.sendREST(QueryProcessorUtil.getInstance() + .getProjectManagementCellUrl(), requestElement); + log.debug("Got Response"); + } catch (XMLStreamException e) { + e.printStackTrace(); + throw new I2B2Exception("" + StackTraceUtil.getStackTrace(e)); + } catch (Exception e) { + e.printStackTrace(); + throw new I2B2Exception("" + StackTraceUtil.getStackTrace(e)); + } + + log.debug("Returning ProjectType"); + return response; + } + + public static ProjectType callUserProjectRedcap(SecurityType securityType, String projectId ) throws AxisFault, I2B2Exception { + + RequestMessageType requestMessageType = getI2B2Hive(securityType, null); + OMElement requestElement = null; + ProjectType projectType = null; + String hive = null; + try { + requestElement = buildOMElement(requestMessageType); + log.debug("CRC PM call's request xml " + requestElement); + String response = ServiceClient.sendREST(QueryProcessorUtil.getInstance() + .getProjectManagementCellUrl(), requestElement); + log.debug("Got Response"); + + JAXBElement responseJaxb = jaxbUtil.unMashallFromString(response); + + //CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseXml); + ResponseMessageType pmRespMessageType = (ResponseMessageType) responseJaxb + .getValue(); + logesapi.debug("CRC's PM call response xml" + response); + + ResponseHeaderType responseHeader = pmRespMessageType + .getResponseHeader(); + StatusType status = responseHeader.getResultStatus().getStatus(); + String procStatus = status.getType(); + String procMessage = status.getValue(); + + if (procStatus.equals("ERROR")) { + logesapi.info("PM Error reported by CRC web Service " + procMessage); + + + + + int startstr = procMessage.indexOf("this domain") + 12; + int endstr = procMessage.indexOf(" ", startstr+1) -1; + hive = procMessage.substring(startstr, endstr); + } + + } catch (XMLStreamException e) { + e.printStackTrace(); + throw new I2B2Exception("" + StackTraceUtil.getStackTrace(e)); + } catch (Exception e) { + e.printStackTrace(); + throw new I2B2Exception("" + StackTraceUtil.getStackTrace(e)); + } + + securityType.setDomain(hive); + requestMessageType = getI2B2RequestMessage(securityType, null); + requestElement = null; + projectType = null; + try { + requestElement = buildOMElement(requestMessageType); + log.debug("CRC PM call's request xml " + requestElement); + String response = ServiceClient.sendREST(QueryProcessorUtil.getInstance() + .getProjectManagementCellUrl(), requestElement); + log.debug("Got Response"); + projectType = getUserProjectFromResponseRedcap(response, securityType, projectId); + log.debug("Parsed Projcet Type: " + projectType.getName()); + } catch (XMLStreamException e) { + e.printStackTrace(); + throw new I2B2Exception("" + StackTraceUtil.getStackTrace(e)); + } catch (Exception e) { + e.printStackTrace(); + throw new I2B2Exception("" + StackTraceUtil.getStackTrace(e)); + } + + log.debug("Returning ProjectType"); + return projectType; + } + + + public static ProjectType callUserProject(SecurityType securityType, String projectId ) throws AxisFault, I2B2Exception { + RequestMessageType requestMessageType = getI2B2RequestMessage(securityType, projectId); + OMElement requestElement = null; + ProjectType projectType = null; + try { + requestElement = buildOMElement(requestMessageType); + log.debug("CRC PM call's request xml " + requestElement); + String response = ServiceClient.sendREST(QueryProcessorUtil.getInstance() + .getProjectManagementCellUrl(), requestElement); + log.debug("Got Response"); + projectType = getUserProjectFromResponse(response, securityType, projectId); + log.debug("Parsed Projcet Type: " + projectType.getName()); + } catch (XMLStreamException e) { + e.printStackTrace(); + throw new I2B2Exception("" + StackTraceUtil.getStackTrace(e)); + } catch (Exception e) { + e.printStackTrace(); + throw new I2B2Exception("" + StackTraceUtil.getStackTrace(e)); + } + + log.debug("Returning ProjectType"); + return projectType; + } + + + public static ProjectType getUserProjectFromResponseRedcap(String responseXml, SecurityType securityType, String projectId) + throws JAXBUtilException, I2B2Exception { + JAXBElement responseJaxb = jaxbUtil.unMashallFromString(responseXml); + + //CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseXml); + ResponseMessageType pmRespMessageType = (ResponseMessageType) responseJaxb + .getValue(); + logesapi.debug("CRC's PM call response xml" + responseXml); + + ResponseHeaderType responseHeader = pmRespMessageType + .getResponseHeader(); + StatusType status = responseHeader.getResultStatus().getStatus(); + String procStatus = status.getType(); + String procMessage = status.getValue(); + + if (procStatus.equals("ERROR")) { + logesapi.info("PM Error reported by CRC web Service " + procMessage); + throw new I2B2Exception("PM Error reported by CRC web Service " + + procMessage); + } else if (procStatus.equals("WARNING")) { + logesapi.info("PM Warning reported by CRC web Service" + procMessage); + throw new I2B2Exception("PM Warning reported by CRC web Service" + + procMessage); + } + + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + ConfigureType configureType = (ConfigureType) helper.getObjectByClass( + pmRespMessageType.getMessageBody().getAny(), + ConfigureType.class); + UserType userType = configureType.getUser(); + List projectTypeList = userType.getProject(); + + ProjectType projectType = null; + if (projectTypeList != null && projectTypeList.size() > 0) { + for (ProjectType pType : projectTypeList) { + for (ParamType paramType : pType.getParam()) + if ((paramType.getName().equalsIgnoreCase("REDCAP_SURVEY_PROJECT") + && (paramType.getValue().equalsIgnoreCase(projectId)))) { + projectType = pType; + + // Add user params to porject params + projectType.getParam().addAll(userType.getParam()); + break; + } + } + if (projectType == null) { + throw new I2B2Exception("Redcap not registered to the project[" + + projectId + "]"); + } + } + + return projectType; + } + + public static ProjectType getUserProjectFromResponse(String responseXml, SecurityType securityType, String projectId) + throws JAXBUtilException, I2B2Exception { + JAXBElement responseJaxb = jaxbUtil.unMashallFromString(responseXml); + + //CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseXml); + ResponseMessageType pmRespMessageType = (ResponseMessageType) responseJaxb + .getValue(); + logesapi.debug("CRC's PM call response xml" + responseXml); + + ResponseHeaderType responseHeader = pmRespMessageType + .getResponseHeader(); + StatusType status = responseHeader.getResultStatus().getStatus(); + String procStatus = status.getType(); + String procMessage = status.getValue(); + + if (procStatus.equals("ERROR")) { + logesapi.info("PM Error reported by CRC web Service " + procMessage); + throw new I2B2Exception("PM Error reported by CRC web Service " + + procMessage); + } else if (procStatus.equals("WARNING")) { + logesapi.info("PM Warning reported by CRC web Service" + procMessage); + throw new I2B2Exception("PM Warning reported by CRC web Service" + + procMessage); + } + + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + ConfigureType configureType = (ConfigureType) helper.getObjectByClass( + pmRespMessageType.getMessageBody().getAny(), + ConfigureType.class); + UserType userType = configureType.getUser(); + List projectTypeList = userType.getProject(); + + ProjectType projectType = null; + if (projectTypeList != null && projectTypeList.size() > 0) { + for (ProjectType pType : projectTypeList) { + if (pType.getId().equalsIgnoreCase(projectId)) { + projectType = pType; + + break; + } + } + if (projectType == null) { + throw new I2B2Exception("User not registered to the project[" + + projectId + "]"); + } + } + + return projectType; + } + + public static boolean getUserIsAdminFromResponse(String responseXml, SecurityType securityType, String projectId) + throws JAXBUtilException, I2B2Exception { + JAXBElement responseJaxb = jaxbUtil.unMashallFromString(responseXml); + + //CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseXml); + ResponseMessageType pmRespMessageType = (ResponseMessageType) responseJaxb + .getValue(); + logesapi.debug("CRC's PM call response xml" + responseXml); + + ResponseHeaderType responseHeader = pmRespMessageType + .getResponseHeader(); + StatusType status = responseHeader.getResultStatus().getStatus(); + String procStatus = status.getType(); + String procMessage = status.getValue(); + + if (procStatus.equals("ERROR")) { + logesapi.info("PM Error reported by CRC web Service " + procMessage); + throw new I2B2Exception("PM Error reported by CRC web Service " + + procMessage); + } else if (procStatus.equals("WARNING")) { + logesapi.info("PM Warning reported by CRC web Service" + procMessage); + throw new I2B2Exception("PM Warning reported by CRC web Service" + + procMessage); + } + + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + ConfigureType configureType = (ConfigureType) helper.getObjectByClass( + pmRespMessageType.getMessageBody().getAny(), + ConfigureType.class); + UserType userType = configureType.getUser(); + return userType.isIsAdmin(); + } + + public static UserType getUserFromResponse(String responseXml) + throws JAXBUtilException, I2B2Exception { + JAXBElement responseJaxb = jaxbUtil.unMashallFromString(responseXml); + + //CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseXml); + ResponseMessageType pmRespMessageType = (ResponseMessageType) responseJaxb + .getValue(); + logesapi.debug("CRC's PM call response xml" + responseXml); + + ResponseHeaderType responseHeader = pmRespMessageType + .getResponseHeader(); + StatusType status = responseHeader.getResultStatus().getStatus(); + String procStatus = status.getType(); + String procMessage = status.getValue(); + + if (procStatus.equals("ERROR")) { + logesapi.info("PM Error reported by CRC web Service " + procMessage); + throw new I2B2Exception("PM Error reported by CRC web Service " + + procMessage); + } else if (procStatus.equals("WARNING")) { + logesapi.info("PM Warning reported by CRC web Service" + procMessage); + throw new I2B2Exception("PM Warning reported by CRC web Service" + + procMessage); + } + + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + ConfigureType configureType = (ConfigureType) helper.getObjectByClass( + pmRespMessageType.getMessageBody().getAny(), + ConfigureType.class); + return configureType.getUser(); + //return userType.isIsAdmin(); + } + + private static OMElement buildOMElement(RequestMessageType requestMessageType) + throws XMLStreamException, JAXBUtilException { + StringWriter strWriter = new StringWriter(); + edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory hiveof = new edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory(); + //CRCJAXBUtil.getJAXBUtil() + jaxbUtil.marshaller( + hiveof.createRequest(requestMessageType), strWriter); + // getOMElement from message + OMFactory fac = OMAbstractFactory.getOMFactory(); + + StringReader strReader = new StringReader(strWriter.toString()); + XMLInputFactory xif = XMLInputFactory.newInstance(); + XMLStreamReader reader = xif.createXMLStreamReader(strReader); + OMElement request = OMXMLBuilderFactory.createStAXOMBuilder(reader).getDocumentElement(); + + return request; + } + + + private static RequestMessageType getI2B2Hive(SecurityType securityType, String projectId) { + QueryProcessorUtil queryUtil = QueryProcessorUtil.getInstance(); + MessageHeaderType messageHeaderType = queryUtil.getMessageHeader(); + messageHeaderType.setSecurity(securityType); + messageHeaderType.setProjectId(projectId); + + messageHeaderType.setReceivingApplication(messageHeaderType + .getSendingApplication()); + FacilityType facilityType = new FacilityType(); + facilityType.setFacilityName("sample"); + messageHeaderType.setSendingFacility(facilityType); + messageHeaderType.setReceivingFacility(facilityType); + // build message body + // GetUserInfoType getUserInfoType = null; + + + RequestMessageType requestMessageType = new RequestMessageType(); + ObjectFactory of = new ObjectFactory(); + BodyType bodyType = new BodyType(); + bodyType.getAny().add(of.createGetAllHive(null)); + requestMessageType.setMessageBody(bodyType); + + requestMessageType.setMessageHeader(messageHeaderType); + + RequestHeaderType requestHeader = new RequestHeaderType(); + requestHeader.setResultWaittimeMs(180000); + requestMessageType.setRequestHeader(requestHeader); + + return requestMessageType; + + } + private static RequestMessageType getI2B2RequestMessage(SecurityType securityType, String projectId) { + QueryProcessorUtil queryUtil = QueryProcessorUtil.getInstance(); + MessageHeaderType messageHeaderType = queryUtil.getMessageHeader(); + messageHeaderType.setSecurity(securityType); + messageHeaderType.setProjectId(projectId); + + messageHeaderType.setReceivingApplication(messageHeaderType + .getSendingApplication()); + FacilityType facilityType = new FacilityType(); + facilityType.setFacilityName("sample"); + messageHeaderType.setSendingFacility(facilityType); + messageHeaderType.setReceivingFacility(facilityType); + // build message body + // GetUserInfoType getUserInfoType = null; + GetUserConfigurationType userConfig = new GetUserConfigurationType(); + if (projectId != null) { + userConfig.getProject().add(projectId); + } + + RequestMessageType requestMessageType = new RequestMessageType(); + ObjectFactory of = new ObjectFactory(); + BodyType bodyType = new BodyType(); + bodyType.getAny().add(of.createGetUserConfiguration(userConfig)); + requestMessageType.setMessageBody(bodyType); + + requestMessageType.setMessageHeader(messageHeaderType); + + RequestHeaderType requestHeader = new RequestHeaderType(); + requestHeader.setResultWaittimeMs(180000); + requestMessageType.setRequestHeader(requestHeader); + + return requestMessageType; + + } + + public static boolean callIsAdmin(SecurityType securityType, String projectId) throws AxisFault, I2B2Exception { + RequestMessageType requestMessageType = getI2B2RequestMessage(securityType, projectId); + OMElement requestElement = null; + boolean projectType = false; + try { + requestElement = buildOMElement(requestMessageType); + log.debug("CRC PM call's request xml " + requestElement); + String response = ServiceClient.sendREST(QueryProcessorUtil.getInstance() + .getProjectManagementCellUrl(), requestElement); + log.debug("Got Response"); + projectType = getUserIsAdminFromResponse(response, securityType, projectId); + } catch (XMLStreamException e) { + e.printStackTrace(); + throw new I2B2Exception("" + StackTraceUtil.getStackTrace(e)); + } catch (Exception e) { + e.printStackTrace(); + throw new I2B2Exception("" + StackTraceUtil.getStackTrace(e)); + } + + log.debug("Returning ProjectType"); + return projectType; + } + + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/pm/PMServiceDriver.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/pm/PMServiceDriver.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/pm/PMServiceDriver.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/pm/PMServiceDriver.java index 01cf536a..55a7f9d6 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/pm/PMServiceDriver.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/pm/PMServiceDriver.java @@ -1,52 +1,52 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.delegate.pm; - -import java.util.Arrays; - -import org.apache.axis2.AxisFault; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; -import edu.harvard.i2b2.crc.datavo.pm.ProjectType; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - -public class PMServiceDriver { - private static Log log = LogFactory.getLog(PMServiceDriver.class); - - public ProjectType checkValidUser(SecurityType security, String projectId) - throws I2B2Exception, AxisFault, JAXBUtilException { - ProjectType projectType = null; - - - // CallPMUtil callPMUtil = new CallPMUtil(security, projectId); - projectType = CallPMUtil.callUserProject(security, projectId); - - return projectType; - } - - public boolean isAdmin(SecurityType securityType, String projectId) - throws I2B2Exception, AxisFault, JAXBUtilException { - boolean isAdmin = false; - //projectType = null; - - - - return CallPMUtil.callIsAdmin(securityType, projectId); - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.delegate.pm; + +import java.util.Arrays; + +import org.apache.axis2.AxisFault; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; +import edu.harvard.i2b2.crc.datavo.pm.ProjectType; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + +public class PMServiceDriver { + private static Log log = LogFactory.getLog(PMServiceDriver.class); + + public ProjectType checkValidUser(SecurityType security, String projectId) + throws I2B2Exception, AxisFault, JAXBUtilException { + ProjectType projectType = null; + + + // CallPMUtil callPMUtil = new CallPMUtil(security, projectId); + projectType = CallPMUtil.callUserProject(security, projectId); + + return projectType; + } + + public boolean isAdmin(SecurityType securityType, String projectId) + throws I2B2Exception, AxisFault, JAXBUtilException { + boolean isAdmin = false; + //projectType = null; + + + + return CallPMUtil.callIsAdmin(securityType, projectId); + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/quartz/GetAllJobsHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/quartz/GetAllJobsHandler.java similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/quartz/GetAllJobsHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/quartz/GetAllJobsHandler.java index f7d44950..3003660e 100644 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/quartz/GetAllJobsHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/quartz/GetAllJobsHandler.java @@ -1,228 +1,228 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Mike Mendis - */ -package edu.harvard.i2b2.crc.delegate.quartz; - - -import java.sql.Connection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.quartz.Job; -import org.quartz.JobDetail; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.axis2.MessageFactory; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; -import edu.harvard.i2b2.crc.dao.setfinder.IQueryBreakdownTypeDao; -import edu.harvard.i2b2.crc.dao.setfinder.SetFinderConnection; -import edu.harvard.i2b2.crc.datavo.db.QtQueryBreakdownType; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; -import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; -import edu.harvard.i2b2.crc.datavo.pdo.query.DblookupType; -import edu.harvard.i2b2.crc.datavo.pdo.query.DblookupsType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.FindByChildType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceRequestType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceResultResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.JobType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.JobsType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterResponseType; -import edu.harvard.i2b2.crc.delegate.JobReqHandler; -import edu.harvard.i2b2.crc.delegate.RequestHandler; -import edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate; -import edu.harvard.i2b2.crc.ejb.QueryInfoBean; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - -/** - * GetQuartzJobHandler class implements execute method $Id: - * GetQuartzJobHandler.java,v - * - * - */ -public class GetAllJobsHandler extends JobReqHandler { - private JobType setJobRequestType = null; - private SecurityType userRequestType = null; - private MessageHeaderType msgHdrType = null; - - /** - * Constuctor which accepts i2b2 request message xml - * - * @param requestXml - * @throws I2B2Exception - */ - public GetAllJobsHandler(String requestXml) throws I2B2Exception { - try { - setJobRequestType = (JobType) this - .getRequestType( - requestXml, - edu.harvard.i2b2.crc.datavo.setfinder.query.JobType.class); - this.setDataSourceLookup(requestXml); - - - - RequestMessageType requestMsg = getI2B2RequestMessageType( requestXml); - this.userRequestType = requestMsg.getMessageHeader() - .getSecurity(); - //requestMsg. - - } catch (JAXBUtilException jaxbUtilEx) { - throw new I2B2Exception("Error ", jaxbUtilEx); - } - } - - /** - * Perform operation for the given request using business class(ejb) and - * return response - * @throws I2B2Exception - * - * @see edu.harvard.i2b2.crc.delegate.GetQuartzJobHandler#execute() - */ - @Override - public String execute() throws I2B2Exception { - //log.info(" execute()"); - MessageHeaderType msgHdr = MessageFactory.createResponseMessageHeader(msgHdrType); - ResponseMessageType responseMessageType = null; - - //JobsType dblus = new JobsType(); - JobsType response = null; - SchedulerInfoBean scheduler = new SchedulerInfoBean(); - - try { - scheduler = new SchedulerInfoBean(); - response = scheduler.getAllJobsScheduler(SchedulerFactory.getDefaultScheduler(), getDataSourceLookup(),userRequestType); - - //response = dblookupDao.findDblookups(); - } catch ( Exception e1) { - String dbError = "Database error"; - responseMessageType = MessageFactory.doBuildErrorResponse(msgHdr, dbError); - log.error(dbError); - } - if (responseMessageType == null) { // no db error - if (null == response) { // but response is empty - String emptyResult = "query results are empty"; - log.warn(emptyResult); - responseMessageType = MessageFactory.doBuildErrorResponse(msgHdr, emptyResult); - } else { - //Iterator it = response.iterator(); - if (response.getJob() != null) { - - responseMessageType = MessageFactory.createBuildResponse(msgHdr, response); - } else { - String msg = "No dblookup row was found!"; - log.info(msg); - responseMessageType = MessageFactory.createNonStandardResponse(msgHdr, msg); - } - } - } - String responseVdo = null; - responseVdo = MessageFactory.convertToXMLString(responseMessageType); - return responseVdo; - } - /* - @Override - public String execute() throws I2B2Exception { - MessageHeaderType msgHdr = MessageFactory.createResponseMessageHeader(msgHdrType); - - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - String responseString = null; - BodyType bodyType = new BodyType(); - JobsType masterResponseType = null; - - SchedulerInfoBean scheduler = new SchedulerInfoBean(); - - // MessageHeaderType msgHdr = MessageFactory.createResponseMessageHeader(msgHdrType); - ResponseMessageType responseMessageType = null; - JobsType dblus = new JobsType(); - - List response = null; - try { - scheduler = new SchedulerInfoBean(); -// response = scheduler.getAllJobsScheduler(SchedulerFactory.getDefaultScheduler(), getDataSourceLookup(),userRequestType); - //dblookupDao.findDblookups(); - } catch ( Exception e1) { - String dbError = "Database error"; - responseMessageType = MessageFactory.doBuildErrorResponse(msgHdr, dbError); - log.error(dbError); - } - if (responseMessageType == null) { // no db error - if (null == response) { // but response is empty - String emptyResult = "query results are empty"; - log.warn(emptyResult); - responseMessageType = MessageFactory.doBuildErrorResponse(msgHdr, emptyResult); - } else { - Iterator it = response.iterator(); - if (it.hasNext()) { - do { - JobType dblu = it.next(); - dblus.getJob().add(dblu); - } while (it.hasNext()); - responseMessageType = MessageFactory.createBuildResponse(msgHdr, dblus); - } else { - String msg = "No dblookup row was found!"; - log.info(msg); - responseMessageType = MessageFactory.createNonStandardResponse(msgHdr, msg); - } - } - } - String responseVdo = null; - responseVdo = MessageFactory.convertToXMLString(responseMessageType); - return responseVdo; - - - - /* - - try { - long initialTime = System.currentTimeMillis(); - // masterResponseType = queryInfoLocal.getQueryMasterListFromUserId(getDataSourceLookup(),userRequestType); - //SchedulerInfoBean scheduler = new SchedulerInfoBean(); - masterResponseType = scheduler.getAllJobsScheduler(SchedulerFactory.getDefaultScheduler(), getDataSourceLookup(),userRequestType); - long finalTime = System.currentTimeMillis(); - long diffTimeMill = finalTime - initialTime; - long diffTime = diffTimeMill / 1000; - log.debug(" EJB Diff mill =" + diffTimeMill + " diffTime =" + - diffTime); - //masterResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.DONE_TYPE, "DONE")); - } catch (Exception e) { - log.debug(e.getMessage()); - //masterResponseType = new MasterResponseType(); - //masterResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.ERROR_TYPE, e.getMessage())); - } finally { - edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); - bodyType.getAny().add(masterResponseType); //of.createResponse(masterResponseType)); - } - - return bodyType; - */ - //} - - - // function to build StatusType for the given message - private StatusType buildStatusType(String statusTypeString, String message) { - StatusType statusType = new StatusType(); - statusType.setType(statusTypeString); - statusType.setValue(message); - - return statusType; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Mike Mendis + */ +package edu.harvard.i2b2.crc.delegate.quartz; + + +import java.sql.Connection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.quartz.Job; +import org.quartz.JobDetail; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.axis2.MessageFactory; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; +import edu.harvard.i2b2.crc.dao.setfinder.IQueryBreakdownTypeDao; +import edu.harvard.i2b2.crc.dao.setfinder.SetFinderConnection; +import edu.harvard.i2b2.crc.datavo.db.QtQueryBreakdownType; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; +import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; +import edu.harvard.i2b2.crc.datavo.pdo.query.DblookupType; +import edu.harvard.i2b2.crc.datavo.pdo.query.DblookupsType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.FindByChildType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceRequestType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceResultResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.JobType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.JobsType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterResponseType; +import edu.harvard.i2b2.crc.delegate.JobReqHandler; +import edu.harvard.i2b2.crc.delegate.RequestHandler; +import edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate; +import edu.harvard.i2b2.crc.ejb.QueryInfoBean; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + +/** + * GetQuartzJobHandler class implements execute method $Id: + * GetQuartzJobHandler.java,v + * + * + */ +public class GetAllJobsHandler extends JobReqHandler { + private JobType setJobRequestType = null; + private SecurityType userRequestType = null; + private MessageHeaderType msgHdrType = null; + + /** + * Constuctor which accepts i2b2 request message xml + * + * @param requestXml + * @throws I2B2Exception + */ + public GetAllJobsHandler(String requestXml) throws I2B2Exception { + try { + setJobRequestType = (JobType) this + .getRequestType( + requestXml, + edu.harvard.i2b2.crc.datavo.setfinder.query.JobType.class); + this.setDataSourceLookup(requestXml); + + + + RequestMessageType requestMsg = getI2B2RequestMessageType( requestXml); + this.userRequestType = requestMsg.getMessageHeader() + .getSecurity(); + //requestMsg. + + } catch (JAXBUtilException jaxbUtilEx) { + throw new I2B2Exception("Error ", jaxbUtilEx); + } + } + + /** + * Perform operation for the given request using business class(ejb) and + * return response + * @throws I2B2Exception + * + * @see edu.harvard.i2b2.crc.delegate.GetQuartzJobHandler#execute() + */ + @Override + public String execute() throws I2B2Exception { + //log.info(" execute()"); + MessageHeaderType msgHdr = MessageFactory.createResponseMessageHeader(msgHdrType); + ResponseMessageType responseMessageType = null; + + //JobsType dblus = new JobsType(); + JobsType response = null; + SchedulerInfoBean scheduler = new SchedulerInfoBean(); + + try { + scheduler = new SchedulerInfoBean(); + response = scheduler.getAllJobsScheduler(SchedulerFactory.getDefaultScheduler(), getDataSourceLookup(),userRequestType); + + //response = dblookupDao.findDblookups(); + } catch ( Exception e1) { + String dbError = "Database error"; + responseMessageType = MessageFactory.doBuildErrorResponse(msgHdr, dbError); + log.error(dbError); + } + if (responseMessageType == null) { // no db error + if (null == response) { // but response is empty + String emptyResult = "query results are empty"; + log.warn(emptyResult); + responseMessageType = MessageFactory.doBuildErrorResponse(msgHdr, emptyResult); + } else { + //Iterator it = response.iterator(); + if (response.getJob() != null) { + + responseMessageType = MessageFactory.createBuildResponse(msgHdr, response); + } else { + String msg = "No dblookup row was found!"; + log.info(msg); + responseMessageType = MessageFactory.createNonStandardResponse(msgHdr, msg); + } + } + } + String responseVdo = null; + responseVdo = MessageFactory.convertToXMLString(responseMessageType); + return responseVdo; + } + /* + @Override + public String execute() throws I2B2Exception { + MessageHeaderType msgHdr = MessageFactory.createResponseMessageHeader(msgHdrType); + + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + String responseString = null; + BodyType bodyType = new BodyType(); + JobsType masterResponseType = null; + + SchedulerInfoBean scheduler = new SchedulerInfoBean(); + + // MessageHeaderType msgHdr = MessageFactory.createResponseMessageHeader(msgHdrType); + ResponseMessageType responseMessageType = null; + JobsType dblus = new JobsType(); + + List response = null; + try { + scheduler = new SchedulerInfoBean(); +// response = scheduler.getAllJobsScheduler(SchedulerFactory.getDefaultScheduler(), getDataSourceLookup(),userRequestType); + //dblookupDao.findDblookups(); + } catch ( Exception e1) { + String dbError = "Database error"; + responseMessageType = MessageFactory.doBuildErrorResponse(msgHdr, dbError); + log.error(dbError); + } + if (responseMessageType == null) { // no db error + if (null == response) { // but response is empty + String emptyResult = "query results are empty"; + log.warn(emptyResult); + responseMessageType = MessageFactory.doBuildErrorResponse(msgHdr, emptyResult); + } else { + Iterator it = response.iterator(); + if (it.hasNext()) { + do { + JobType dblu = it.next(); + dblus.getJob().add(dblu); + } while (it.hasNext()); + responseMessageType = MessageFactory.createBuildResponse(msgHdr, dblus); + } else { + String msg = "No dblookup row was found!"; + log.info(msg); + responseMessageType = MessageFactory.createNonStandardResponse(msgHdr, msg); + } + } + } + String responseVdo = null; + responseVdo = MessageFactory.convertToXMLString(responseMessageType); + return responseVdo; + + + + /* + + try { + long initialTime = System.currentTimeMillis(); + // masterResponseType = queryInfoLocal.getQueryMasterListFromUserId(getDataSourceLookup(),userRequestType); + //SchedulerInfoBean scheduler = new SchedulerInfoBean(); + masterResponseType = scheduler.getAllJobsScheduler(SchedulerFactory.getDefaultScheduler(), getDataSourceLookup(),userRequestType); + long finalTime = System.currentTimeMillis(); + long diffTimeMill = finalTime - initialTime; + long diffTime = diffTimeMill / 1000; + log.debug(" EJB Diff mill =" + diffTimeMill + " diffTime =" + + diffTime); + //masterResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.DONE_TYPE, "DONE")); + } catch (Exception e) { + log.debug(e.getMessage()); + //masterResponseType = new MasterResponseType(); + //masterResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.ERROR_TYPE, e.getMessage())); + } finally { + edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); + bodyType.getAny().add(masterResponseType); //of.createResponse(masterResponseType)); + } + + return bodyType; + */ + //} + + + // function to build StatusType for the given message + private StatusType buildStatusType(String statusTypeString, String message) { + StatusType statusType = new StatusType(); + statusType.setType(statusTypeString); + statusType.setValue(message); + + return statusType; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/quartz/GetQuartzJobHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/quartz/GetQuartzJobHandler.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/quartz/GetQuartzJobHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/quartz/GetQuartzJobHandler.java index f03f0adb..417d5c0c --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/quartz/GetQuartzJobHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/quartz/GetQuartzJobHandler.java @@ -1,105 +1,105 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Mike Mendis - */ -package edu.harvard.i2b2.crc.delegate.quartz; - - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceRequestType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceResultResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.JobType; -import edu.harvard.i2b2.crc.delegate.RequestHandler; -import edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate; -import edu.harvard.i2b2.crc.ejb.QueryInfoBean; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - -/** - * GetQuartzJobHandler class implements execute method $Id: - * GetQuartzJobHandler.java,v - * - * - */ -public class GetQuartzJobHandler extends RequestHandler { - private JobType setJobRequestType = null; - - /** - * Constuctor which accepts i2b2 request message xml - * - * @param requestXml - * @throws I2B2Exception - */ - public GetQuartzJobHandler(String requestXml) throws I2B2Exception { - try { - setJobRequestType = (JobType) this - .getRequestType( - requestXml, - edu.harvard.i2b2.crc.datavo.setfinder.query.JobType.class); - this.setDataSourceLookup(requestXml); - } catch (JAXBUtilException jaxbUtilEx) { - throw new I2B2Exception("Error ", jaxbUtilEx); - } - } - - /** - * Perform operation for the given request using business class(ejb) and - * return response - * - * @see edu.harvard.i2b2.crc.delegate.GetQuartzJobHandler#execute() - */ - @Override - public BodyType execute() { - // call ejb and pass input object - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - ResponseMessageType responseMessageType = new ResponseMessageType(); - StatusType statusType = null; - String responseString = null; - InstanceResultResponseType instanceResultResponseType = null; - BodyType bodyType = new BodyType(); - try { - //TODO removed ejbs - // QueryInfoLocalHome queryInfoLocalHome = qpUtil - // .getQueryInfoLocalHome(); - // QueryInfoLocal queryInfoLocal = queryInfoLocalHome.create(); - //JobType job = setJobRequestType.getName(); //.getJob(); - - QueryInfoBean query = new QueryInfoBean(); - - - - } catch (Exception e) { - instanceResultResponseType = new InstanceResultResponseType(); - instanceResultResponseType.setStatus(this.buildCRCStausType( - RequestHandlerDelegate.ERROR_TYPE, e.getMessage())); - } finally { - edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); - bodyType.getAny() - .add(of.createResponse(instanceResultResponseType)); - - } - return bodyType; - } - - // function to build StatusType for the given message - private StatusType buildStatusType(String statusTypeString, String message) { - StatusType statusType = new StatusType(); - statusType.setType(statusTypeString); - statusType.setValue(message); - - return statusType; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Mike Mendis + */ +package edu.harvard.i2b2.crc.delegate.quartz; + + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceRequestType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceResultResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.JobType; +import edu.harvard.i2b2.crc.delegate.RequestHandler; +import edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate; +import edu.harvard.i2b2.crc.ejb.QueryInfoBean; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + +/** + * GetQuartzJobHandler class implements execute method $Id: + * GetQuartzJobHandler.java,v + * + * + */ +public class GetQuartzJobHandler extends RequestHandler { + private JobType setJobRequestType = null; + + /** + * Constuctor which accepts i2b2 request message xml + * + * @param requestXml + * @throws I2B2Exception + */ + public GetQuartzJobHandler(String requestXml) throws I2B2Exception { + try { + setJobRequestType = (JobType) this + .getRequestType( + requestXml, + edu.harvard.i2b2.crc.datavo.setfinder.query.JobType.class); + this.setDataSourceLookup(requestXml); + } catch (JAXBUtilException jaxbUtilEx) { + throw new I2B2Exception("Error ", jaxbUtilEx); + } + } + + /** + * Perform operation for the given request using business class(ejb) and + * return response + * + * @see edu.harvard.i2b2.crc.delegate.GetQuartzJobHandler#execute() + */ + @Override + public BodyType execute() { + // call ejb and pass input object + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + ResponseMessageType responseMessageType = new ResponseMessageType(); + StatusType statusType = null; + String responseString = null; + InstanceResultResponseType instanceResultResponseType = null; + BodyType bodyType = new BodyType(); + try { + //TODO removed ejbs + // QueryInfoLocalHome queryInfoLocalHome = qpUtil + // .getQueryInfoLocalHome(); + // QueryInfoLocal queryInfoLocal = queryInfoLocalHome.create(); + //JobType job = setJobRequestType.getName(); //.getJob(); + + QueryInfoBean query = new QueryInfoBean(); + + + + } catch (Exception e) { + instanceResultResponseType = new InstanceResultResponseType(); + instanceResultResponseType.setStatus(this.buildCRCStausType( + RequestHandlerDelegate.ERROR_TYPE, e.getMessage())); + } finally { + edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); + bodyType.getAny() + .add(of.createResponse(instanceResultResponseType)); + + } + return bodyType; + } + + // function to build StatusType for the given message + private StatusType buildStatusType(String statusTypeString, String message) { + StatusType statusType = new StatusType(); + statusType.setType(statusTypeString); + statusType.setValue(message); + + return statusType; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/quartz/SchedulerFactory.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/quartz/SchedulerFactory.java similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/quartz/SchedulerFactory.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/quartz/SchedulerFactory.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/quartz/SchedulerInfoBean.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/quartz/SchedulerInfoBean.java similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/quartz/SchedulerInfoBean.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/quartz/SchedulerInfoBean.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/quartz/SetJobHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/quartz/SetJobHandler.java similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/quartz/SetJobHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/quartz/SetJobHandler.java index 7375f45b..88089bd0 100644 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/quartz/SetJobHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/quartz/SetJobHandler.java @@ -1,153 +1,153 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Mike Mendis - */ -package edu.harvard.i2b2.crc.delegate.quartz; - - -import java.sql.Connection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.quartz.Job; -import org.quartz.JobDetail; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.axis2.MessageFactory; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; -import edu.harvard.i2b2.crc.dao.setfinder.IQueryBreakdownTypeDao; -import edu.harvard.i2b2.crc.dao.setfinder.SetFinderConnection; -import edu.harvard.i2b2.crc.datavo.db.QtQueryBreakdownType; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; -import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; -import edu.harvard.i2b2.crc.datavo.pdo.query.DblookupType; -import edu.harvard.i2b2.crc.datavo.pdo.query.DblookupsType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.FindByChildType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceRequestType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceResultResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.JobType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.JobsType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterResponseType; -import edu.harvard.i2b2.crc.delegate.JobReqHandler; -import edu.harvard.i2b2.crc.delegate.RequestHandler; -import edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate; -import edu.harvard.i2b2.crc.ejb.QueryInfoBean; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - -/** - * GetQuartzJobHandler class implements execute method $Id: - * GetQuartzJobHandler.java,v - * - * - */ -public class SetJobHandler extends JobReqHandler { - private JobType setJobRequestType = null; - private SecurityType userRequestType = null; - private MessageHeaderType msgHdrType = null; - - /** - * Constuctor which accepts i2b2 request message xml - * - * @param requestXml - * @throws I2B2Exception - */ - public SetJobHandler(String requestXml) throws I2B2Exception { - try { - setJobRequestType = (JobType) this - .getRequestType( - requestXml, - edu.harvard.i2b2.crc.datavo.setfinder.query.JobType.class); - this.setDataSourceLookup(requestXml); - - - - RequestMessageType requestMsg = getI2B2RequestMessageType( requestXml); - this.userRequestType = requestMsg.getMessageHeader() - .getSecurity(); - //requestMsg. - - } catch (JAXBUtilException jaxbUtilEx) { - throw new I2B2Exception("Error ", jaxbUtilEx); - } - } - - /** - * Perform operation for the given request using business class(ejb) and - * return response - * @throws I2B2Exception - * - * @see edu.harvard.i2b2.crc.delegate.GetQuartzJobHandler#execute() - */ - @Override - public String execute() throws I2B2Exception { - //log.info(" execute()"); - MessageHeaderType msgHdr = MessageFactory.createResponseMessageHeader(msgHdrType); - ResponseMessageType responseMessageType = null; - - //JobsType dblus = new JobsType(); - JobsType response = null; - SchedulerInfoBean scheduler = new SchedulerInfoBean(); - - MasterResponseType masterResponseType = null; - - try { - scheduler = new SchedulerInfoBean(); - masterResponseType = scheduler.setScheduler(SchedulerFactory.getDefaultScheduler(), getDataSourceLookup(),userRequestType, setJobRequestType); -// masterResponseType = scheduler.setScheduler(SchedulerFactory.getDefaultScheduler(), getDataSourceLookup(),userRequestType, setJobRequestType); - - //response = dblookupDao.findDblookups(); - } catch ( Exception e1) { - String dbError = "Database error"; - responseMessageType = MessageFactory.doBuildErrorResponse(msgHdr, dbError); - log.error(dbError); - } - if (responseMessageType == null) { // no db error - if (null == response) { // but response is empty - String emptyResult = "query results are empty"; - log.warn(emptyResult); - responseMessageType = MessageFactory.doBuildErrorResponse(msgHdr, emptyResult); - } else { - //Iterator it = response.iterator(); - if (response.getJob() != null) { - - responseMessageType = MessageFactory.createBuildResponse(msgHdr, response); - } else { - String msg = "No dblookup row was found!"; - log.info(msg); - responseMessageType = MessageFactory.createNonStandardResponse(msgHdr, msg); - } - } - } - String responseVdo = null; - responseVdo = MessageFactory.convertToXMLString(responseMessageType); - return responseVdo; - } - - // function to build StatusType for the given message - private StatusType buildStatusType(String statusTypeString, String message) { - StatusType statusType = new StatusType(); - statusType.setType(statusTypeString); - statusType.setValue(message); - - return statusType; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Mike Mendis + */ +package edu.harvard.i2b2.crc.delegate.quartz; + + +import java.sql.Connection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.quartz.Job; +import org.quartz.JobDetail; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.axis2.MessageFactory; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; +import edu.harvard.i2b2.crc.dao.setfinder.IQueryBreakdownTypeDao; +import edu.harvard.i2b2.crc.dao.setfinder.SetFinderConnection; +import edu.harvard.i2b2.crc.datavo.db.QtQueryBreakdownType; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; +import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; +import edu.harvard.i2b2.crc.datavo.pdo.query.DblookupType; +import edu.harvard.i2b2.crc.datavo.pdo.query.DblookupsType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.FindByChildType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceRequestType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceResultResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.JobType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.JobsType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterResponseType; +import edu.harvard.i2b2.crc.delegate.JobReqHandler; +import edu.harvard.i2b2.crc.delegate.RequestHandler; +import edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate; +import edu.harvard.i2b2.crc.ejb.QueryInfoBean; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + +/** + * GetQuartzJobHandler class implements execute method $Id: + * GetQuartzJobHandler.java,v + * + * + */ +public class SetJobHandler extends JobReqHandler { + private JobType setJobRequestType = null; + private SecurityType userRequestType = null; + private MessageHeaderType msgHdrType = null; + + /** + * Constuctor which accepts i2b2 request message xml + * + * @param requestXml + * @throws I2B2Exception + */ + public SetJobHandler(String requestXml) throws I2B2Exception { + try { + setJobRequestType = (JobType) this + .getRequestType( + requestXml, + edu.harvard.i2b2.crc.datavo.setfinder.query.JobType.class); + this.setDataSourceLookup(requestXml); + + + + RequestMessageType requestMsg = getI2B2RequestMessageType( requestXml); + this.userRequestType = requestMsg.getMessageHeader() + .getSecurity(); + //requestMsg. + + } catch (JAXBUtilException jaxbUtilEx) { + throw new I2B2Exception("Error ", jaxbUtilEx); + } + } + + /** + * Perform operation for the given request using business class(ejb) and + * return response + * @throws I2B2Exception + * + * @see edu.harvard.i2b2.crc.delegate.GetQuartzJobHandler#execute() + */ + @Override + public String execute() throws I2B2Exception { + //log.info(" execute()"); + MessageHeaderType msgHdr = MessageFactory.createResponseMessageHeader(msgHdrType); + ResponseMessageType responseMessageType = null; + + //JobsType dblus = new JobsType(); + JobsType response = null; + SchedulerInfoBean scheduler = new SchedulerInfoBean(); + + MasterResponseType masterResponseType = null; + + try { + scheduler = new SchedulerInfoBean(); + masterResponseType = scheduler.setScheduler(SchedulerFactory.getDefaultScheduler(), getDataSourceLookup(),userRequestType, setJobRequestType); +// masterResponseType = scheduler.setScheduler(SchedulerFactory.getDefaultScheduler(), getDataSourceLookup(),userRequestType, setJobRequestType); + + //response = dblookupDao.findDblookups(); + } catch ( Exception e1) { + String dbError = "Database error"; + responseMessageType = MessageFactory.doBuildErrorResponse(msgHdr, dbError); + log.error(dbError); + } + if (responseMessageType == null) { // no db error + if (null == response) { // but response is empty + String emptyResult = "query results are empty"; + log.warn(emptyResult); + responseMessageType = MessageFactory.doBuildErrorResponse(msgHdr, emptyResult); + } else { + //Iterator it = response.iterator(); + if (response.getJob() != null) { + + responseMessageType = MessageFactory.createBuildResponse(msgHdr, response); + } else { + String msg = "No dblookup row was found!"; + log.info(msg); + responseMessageType = MessageFactory.createNonStandardResponse(msgHdr, msg); + } + } + } + String responseVdo = null; + responseVdo = MessageFactory.convertToXMLString(responseMessageType); + return responseVdo; + } + + // function to build StatusType for the given message + private StatusType buildStatusType(String statusTypeString, String message) { + StatusType statusType = new StatusType(); + statusType.setType(statusTypeString); + statusType.setValue(message); + + return statusType; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/quartz/SetJobHandlerMaybe.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/quartz/SetJobHandlerMaybe.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/quartz/SetJobHandlerMaybe.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/quartz/SetJobHandlerMaybe.java index 84561489..322bb86f --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/quartz/SetJobHandlerMaybe.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/quartz/SetJobHandlerMaybe.java @@ -1,164 +1,164 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Mike Mendis - */ -package edu.harvard.i2b2.crc.delegate.quartz; - - -import java.sql.Connection; -import java.util.HashMap; -import java.util.Map; - -import org.quartz.Job; -import org.quartz.JobDetail; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; -import edu.harvard.i2b2.crc.dao.setfinder.IQueryBreakdownTypeDao; -import edu.harvard.i2b2.crc.dao.setfinder.SetFinderConnection; -import edu.harvard.i2b2.crc.datavo.db.QtQueryBreakdownType; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; -import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.FindByChildType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceRequestType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceResultResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.JobType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterResponseType; -import edu.harvard.i2b2.crc.delegate.RequestHandler; -import edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate; -import edu.harvard.i2b2.crc.ejb.QueryInfoBean; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - -/** - * GetQuartzJobHandler class implements execute method $Id: - * GetQuartzJobHandler.java,v - * - * - */ -public class SetJobHandlerMaybe extends RequestHandler { - private JobType setJobRequestType = null; - private SecurityType userRequestType = null; - /** - * Constuctor which accepts i2b2 request message xml - * - * @param requestXml - * @throws I2B2Exception - */ - public SetJobHandlerMaybe(String requestXml) throws I2B2Exception { - try { - setJobRequestType = (JobType) this - .getRequestType( - requestXml, - edu.harvard.i2b2.crc.datavo.setfinder.query.JobType.class); - this.setDataSourceLookup(requestXml); - - - - RequestMessageType requestMsg = getI2B2RequestMessageType( requestXml); - this.userRequestType = requestMsg.getMessageHeader() - .getSecurity(); - - } catch (JAXBUtilException jaxbUtilEx) { - throw new I2B2Exception("Error ", jaxbUtilEx); - } - } - - /** - * Perform operation for the given request using business class(ejb) and - * return response - * - * @see edu.harvard.i2b2.crc.delegate.GetQuartzJobHandler#execute() - */ - @Override - public BodyType execute() { - - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - String responseString = null; - BodyType bodyType = new BodyType(); - MasterResponseType masterResponseType = null; - try { - long initialTime = System.currentTimeMillis(); - // masterResponseType = queryInfoLocal.getQueryMasterListFromUserId(getDataSourceLookup(),userRequestType); - SchedulerInfoBean scheduler = new SchedulerInfoBean(); - masterResponseType = scheduler.setScheduler(SchedulerFactory.getDefaultScheduler(), getDataSourceLookup(),userRequestType, setJobRequestType); - long finalTime = System.currentTimeMillis(); - long diffTimeMill = finalTime - initialTime; - long diffTime = diffTimeMill / 1000; - log.debug(" EJB Diff mill =" + diffTimeMill + " diffTime =" + - diffTime); - masterResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.DONE_TYPE, "DONE")); - } catch (Exception e) { - log.debug(e.getMessage()); - masterResponseType = new MasterResponseType(); - masterResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.ERROR_TYPE, e.getMessage())); - } finally { - edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); - bodyType.getAny().add(of.createResponse(masterResponseType)); - } - - return bodyType; - - - // call ejb and pass input object - /* - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - ResponseMessageType responseMessageType = new ResponseMessageType(); - StatusType statusType = null; - String responseString = null; - InstanceResultResponseType instanceResultResponseType = null; - BodyType bodyType = new BodyType(); - try { - //TODO removed ejbs - // QueryInfoLocalHome queryInfoLocalHome = qpUtil - // .getQueryInfoLocalHome(); - // QueryInfoLocal queryInfoLocal = queryInfoLocalHome.create(); - //JobType job = setJobRequestType.getName(); //.getJob(); - - SchedulerInfoBean query = new SchedulerInfoBean(); - - query.setScheduler(dataSourceLookup, null, null); - // QuartzExec quartz = new QuartzExec(); - - // instanceResultResponseType = query.cancelQueryInstance( - // this.getDataSourceLookup(), instanceId); - // instanceResultResponseType.setStatus(this.buildCRCStausType( - // RequestHandlerDelegate.DONE_TYPE, "DONE")); - - } catch (Exception e) { - instanceResultResponseType = new InstanceResultResponseType(); - instanceResultResponseType.setStatus(this.buildCRCStausType( - RequestHandlerDelegate.ERROR_TYPE, e.getMessage())); - } finally { - edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); - bodyType.getAny() - .add(of.createResponse(instanceResultResponseType)); - - } - return bodyType; - */ - } - - // function to build StatusType for the given message - private StatusType buildStatusType(String statusTypeString, String message) { - StatusType statusType = new StatusType(); - statusType.setType(statusTypeString); - statusType.setValue(message); - - return statusType; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Mike Mendis + */ +package edu.harvard.i2b2.crc.delegate.quartz; + + +import java.sql.Connection; +import java.util.HashMap; +import java.util.Map; + +import org.quartz.Job; +import org.quartz.JobDetail; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; +import edu.harvard.i2b2.crc.dao.setfinder.IQueryBreakdownTypeDao; +import edu.harvard.i2b2.crc.dao.setfinder.SetFinderConnection; +import edu.harvard.i2b2.crc.datavo.db.QtQueryBreakdownType; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; +import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.FindByChildType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceRequestType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceResultResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.JobType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterResponseType; +import edu.harvard.i2b2.crc.delegate.RequestHandler; +import edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate; +import edu.harvard.i2b2.crc.ejb.QueryInfoBean; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + +/** + * GetQuartzJobHandler class implements execute method $Id: + * GetQuartzJobHandler.java,v + * + * + */ +public class SetJobHandlerMaybe extends RequestHandler { + private JobType setJobRequestType = null; + private SecurityType userRequestType = null; + /** + * Constuctor which accepts i2b2 request message xml + * + * @param requestXml + * @throws I2B2Exception + */ + public SetJobHandlerMaybe(String requestXml) throws I2B2Exception { + try { + setJobRequestType = (JobType) this + .getRequestType( + requestXml, + edu.harvard.i2b2.crc.datavo.setfinder.query.JobType.class); + this.setDataSourceLookup(requestXml); + + + + RequestMessageType requestMsg = getI2B2RequestMessageType( requestXml); + this.userRequestType = requestMsg.getMessageHeader() + .getSecurity(); + + } catch (JAXBUtilException jaxbUtilEx) { + throw new I2B2Exception("Error ", jaxbUtilEx); + } + } + + /** + * Perform operation for the given request using business class(ejb) and + * return response + * + * @see edu.harvard.i2b2.crc.delegate.GetQuartzJobHandler#execute() + */ + @Override + public BodyType execute() { + + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + String responseString = null; + BodyType bodyType = new BodyType(); + MasterResponseType masterResponseType = null; + try { + long initialTime = System.currentTimeMillis(); + // masterResponseType = queryInfoLocal.getQueryMasterListFromUserId(getDataSourceLookup(),userRequestType); + SchedulerInfoBean scheduler = new SchedulerInfoBean(); + masterResponseType = scheduler.setScheduler(SchedulerFactory.getDefaultScheduler(), getDataSourceLookup(),userRequestType, setJobRequestType); + long finalTime = System.currentTimeMillis(); + long diffTimeMill = finalTime - initialTime; + long diffTime = diffTimeMill / 1000; + log.debug(" EJB Diff mill =" + diffTimeMill + " diffTime =" + + diffTime); + masterResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.DONE_TYPE, "DONE")); + } catch (Exception e) { + log.debug(e.getMessage()); + masterResponseType = new MasterResponseType(); + masterResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.ERROR_TYPE, e.getMessage())); + } finally { + edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); + bodyType.getAny().add(of.createResponse(masterResponseType)); + } + + return bodyType; + + + // call ejb and pass input object + /* + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + ResponseMessageType responseMessageType = new ResponseMessageType(); + StatusType statusType = null; + String responseString = null; + InstanceResultResponseType instanceResultResponseType = null; + BodyType bodyType = new BodyType(); + try { + //TODO removed ejbs + // QueryInfoLocalHome queryInfoLocalHome = qpUtil + // .getQueryInfoLocalHome(); + // QueryInfoLocal queryInfoLocal = queryInfoLocalHome.create(); + //JobType job = setJobRequestType.getName(); //.getJob(); + + SchedulerInfoBean query = new SchedulerInfoBean(); + + query.setScheduler(dataSourceLookup, null, null); + // QuartzExec quartz = new QuartzExec(); + + // instanceResultResponseType = query.cancelQueryInstance( + // this.getDataSourceLookup(), instanceId); + // instanceResultResponseType.setStatus(this.buildCRCStausType( + // RequestHandlerDelegate.DONE_TYPE, "DONE")); + + } catch (Exception e) { + instanceResultResponseType = new InstanceResultResponseType(); + instanceResultResponseType.setStatus(this.buildCRCStausType( + RequestHandlerDelegate.ERROR_TYPE, e.getMessage())); + } finally { + edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); + bodyType.getAny() + .add(of.createResponse(instanceResultResponseType)); + + } + return bodyType; + */ + } + + // function to build StatusType for the given message + private StatusType buildStatusType(String statusTypeString, String message) { + StatusType statusType = new StatusType(); + statusType.setType(statusTypeString); + statusType.setValue(message); + + return statusType; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/CancelQueryInstanceHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/CancelQueryInstanceHandler.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/CancelQueryInstanceHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/CancelQueryInstanceHandler.java index 1d0acfb1..88a0f233 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/CancelQueryInstanceHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/CancelQueryInstanceHandler.java @@ -1,107 +1,107 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.delegate.setfinder; - - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceRequestType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceResultResponseType; -import edu.harvard.i2b2.crc.delegate.RequestHandler; -import edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate; -import edu.harvard.i2b2.crc.ejb.QueryInfoBean; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - -/** - * RenameQueryMasterHandler class implements execute method $Id: - * RenameQueryMasterHandler.java,v 1.8 2008/03/19 22:36:37 rk903 Exp $ - * - * @author rkuttan - */ -public class CancelQueryInstanceHandler extends RequestHandler { - private InstanceRequestType instanceRequestType = null; - - /** - * Constuctor which accepts i2b2 request message xml - * - * @param requestXml - * @throws I2B2Exception - */ - public CancelQueryInstanceHandler(String requestXml) throws I2B2Exception { - try { - instanceRequestType = (InstanceRequestType) this - .getRequestType( - requestXml, - edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceRequestType.class); - this.setDataSourceLookup(requestXml); - } catch (JAXBUtilException jaxbUtilEx) { - throw new I2B2Exception("Error ", jaxbUtilEx); - } - } - - /** - * Perform operation for the given request using business class(ejb) and - * return response - * - * @see edu.harvard.i2b2.crc.delegate.RequestHandler#execute() - */ - @Override - public BodyType execute() { - // call ejb and pass input object - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - ResponseMessageType responseMessageType = new ResponseMessageType(); - StatusType statusType = null; - String responseString = null; - InstanceResultResponseType instanceResultResponseType = null; - BodyType bodyType = new BodyType(); - try { - //TODO removed ejbs - // QueryInfoLocalHome queryInfoLocalHome = qpUtil - // .getQueryInfoLocalHome(); - // QueryInfoLocal queryInfoLocal = queryInfoLocalHome.create(); - String instanceId = instanceRequestType.getQueryInstanceId(); - - QueryInfoBean query = new QueryInfoBean(); - - instanceResultResponseType = query.cancelQueryInstance( - this.getDataSourceLookup(), instanceId); - instanceResultResponseType.setStatus(this.buildCRCStausType( - RequestHandlerDelegate.DONE_TYPE, "DONE")); - - } catch (Exception e) { - instanceResultResponseType = new InstanceResultResponseType(); - instanceResultResponseType.setStatus(this.buildCRCStausType( - RequestHandlerDelegate.ERROR_TYPE, e.getMessage())); - } finally { - edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); - bodyType.getAny() - .add(of.createResponse(instanceResultResponseType)); - - } - return bodyType; - } - - // function to build StatusType for the given message - private StatusType buildStatusType(String statusTypeString, String message) { - StatusType statusType = new StatusType(); - statusType.setType(statusTypeString); - statusType.setValue(message); - - return statusType; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.delegate.setfinder; + + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceRequestType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceResultResponseType; +import edu.harvard.i2b2.crc.delegate.RequestHandler; +import edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate; +import edu.harvard.i2b2.crc.ejb.QueryInfoBean; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + +/** + * RenameQueryMasterHandler class implements execute method $Id: + * RenameQueryMasterHandler.java,v 1.8 2008/03/19 22:36:37 rk903 Exp $ + * + * @author rkuttan + */ +public class CancelQueryInstanceHandler extends RequestHandler { + private InstanceRequestType instanceRequestType = null; + + /** + * Constuctor which accepts i2b2 request message xml + * + * @param requestXml + * @throws I2B2Exception + */ + public CancelQueryInstanceHandler(String requestXml) throws I2B2Exception { + try { + instanceRequestType = (InstanceRequestType) this + .getRequestType( + requestXml, + edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceRequestType.class); + this.setDataSourceLookup(requestXml); + } catch (JAXBUtilException jaxbUtilEx) { + throw new I2B2Exception("Error ", jaxbUtilEx); + } + } + + /** + * Perform operation for the given request using business class(ejb) and + * return response + * + * @see edu.harvard.i2b2.crc.delegate.RequestHandler#execute() + */ + @Override + public BodyType execute() { + // call ejb and pass input object + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + ResponseMessageType responseMessageType = new ResponseMessageType(); + StatusType statusType = null; + String responseString = null; + InstanceResultResponseType instanceResultResponseType = null; + BodyType bodyType = new BodyType(); + try { + //TODO removed ejbs + // QueryInfoLocalHome queryInfoLocalHome = qpUtil + // .getQueryInfoLocalHome(); + // QueryInfoLocal queryInfoLocal = queryInfoLocalHome.create(); + String instanceId = instanceRequestType.getQueryInstanceId(); + + QueryInfoBean query = new QueryInfoBean(); + + instanceResultResponseType = query.cancelQueryInstance( + this.getDataSourceLookup(), instanceId); + instanceResultResponseType.setStatus(this.buildCRCStausType( + RequestHandlerDelegate.DONE_TYPE, "DONE")); + + } catch (Exception e) { + instanceResultResponseType = new InstanceResultResponseType(); + instanceResultResponseType.setStatus(this.buildCRCStausType( + RequestHandlerDelegate.ERROR_TYPE, e.getMessage())); + } finally { + edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); + bodyType.getAny() + .add(of.createResponse(instanceResultResponseType)); + + } + return bodyType; + } + + // function to build StatusType for the given message + private StatusType buildStatusType(String statusTypeString, String message) { + StatusType statusType = new StatusType(); + statusType.setType(statusTypeString); + statusType.setValue(message); + + return statusType; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/DeleteQueryMasterHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/DeleteQueryMasterHandler.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/DeleteQueryMasterHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/DeleteQueryMasterHandler.java index 9a1db54d..f9d4aa9f --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/DeleteQueryMasterHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/DeleteQueryMasterHandler.java @@ -1,102 +1,102 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.delegate.setfinder; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterDeleteRequestType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterResponseType; -import edu.harvard.i2b2.crc.delegate.RequestHandler; -import edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate; -import edu.harvard.i2b2.crc.ejb.QueryInfoBean; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - - - -/** - * DeleteQueryMasterHandler class - * implements execute method - * $Id: DeleteQueryMasterHandler.java,v 1.7 2008/03/19 22:36:37 rk903 Exp $ - * @author rkuttan - */ -public class DeleteQueryMasterHandler extends RequestHandler { - private MasterDeleteRequestType masterDeleteRequestType = null; - - /** - * Constuctor which accepts i2b2 request message xml - * @param requestXml - * @throws I2B2Exception - */ - public DeleteQueryMasterHandler(String requestXml) - throws I2B2Exception { - try { - masterDeleteRequestType = (MasterDeleteRequestType) getRequestType(requestXml, - edu.harvard.i2b2.crc.datavo.setfinder.query.MasterDeleteRequestType.class); - this.setDataSourceLookup(requestXml); - } catch (JAXBUtilException jaxbUtilEx) { - throw new I2B2Exception("Error ", jaxbUtilEx); - } - } - - /** - * Perform operation for the given request - * using business class(ejb) and return response - */ - @Override - public BodyType execute() throws I2B2Exception { - // call ejb and pass input object - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - ResponseMessageType responseMessageType = new ResponseMessageType(); - StatusType statusType = null; - String responseStr = null; - BodyType bodyType = new BodyType(); - MasterResponseType masterResponseType = new MasterResponseType(); - try { - //TODO removed EJBS -// QueryInfoLocalHome queryInfoLocalHome = qpUtil.getQueryInfoLocalHome(); - // QueryInfoLocal queryInfoLocal = queryInfoLocalHome.create(); - String userId = masterDeleteRequestType.getUserId(); - String masterId = masterDeleteRequestType.getQueryMasterId(); - if (masterId==null) - throw new I2B2Exception("Null master id sent to DeleteQueryMasterHandler"); - QueryInfoBean query = new QueryInfoBean(); - masterResponseType = query.deleteQueryMaster(getDataSourceLookup(),userId,masterId); - - - masterResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.DONE_TYPE, "DONE")); - } catch (Exception ex) { - masterResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.ERROR_TYPE, ex.getMessage())); - ex.printStackTrace(); - } - finally { - edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); - bodyType.getAny().add(of.createResponse(masterResponseType)); - } - -// ResultStatusType resultStatusType = new ResultStatusType(); -// resultStatusType.setStatus(statusType); -// -// ResponseHeaderType responseHeader = new ResponseHeaderType(); -// responseHeader.setResultStatus(resultStatusType); -// responseMessageType.setResponseHeader(responseHeader); -// -// responseStr = getResponseString(responseMessageType); - - return bodyType; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.delegate.setfinder; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterDeleteRequestType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterResponseType; +import edu.harvard.i2b2.crc.delegate.RequestHandler; +import edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate; +import edu.harvard.i2b2.crc.ejb.QueryInfoBean; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + + + +/** + * DeleteQueryMasterHandler class + * implements execute method + * $Id: DeleteQueryMasterHandler.java,v 1.7 2008/03/19 22:36:37 rk903 Exp $ + * @author rkuttan + */ +public class DeleteQueryMasterHandler extends RequestHandler { + private MasterDeleteRequestType masterDeleteRequestType = null; + + /** + * Constuctor which accepts i2b2 request message xml + * @param requestXml + * @throws I2B2Exception + */ + public DeleteQueryMasterHandler(String requestXml) + throws I2B2Exception { + try { + masterDeleteRequestType = (MasterDeleteRequestType) getRequestType(requestXml, + edu.harvard.i2b2.crc.datavo.setfinder.query.MasterDeleteRequestType.class); + this.setDataSourceLookup(requestXml); + } catch (JAXBUtilException jaxbUtilEx) { + throw new I2B2Exception("Error ", jaxbUtilEx); + } + } + + /** + * Perform operation for the given request + * using business class(ejb) and return response + */ + @Override + public BodyType execute() throws I2B2Exception { + // call ejb and pass input object + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + ResponseMessageType responseMessageType = new ResponseMessageType(); + StatusType statusType = null; + String responseStr = null; + BodyType bodyType = new BodyType(); + MasterResponseType masterResponseType = new MasterResponseType(); + try { + //TODO removed EJBS +// QueryInfoLocalHome queryInfoLocalHome = qpUtil.getQueryInfoLocalHome(); + // QueryInfoLocal queryInfoLocal = queryInfoLocalHome.create(); + String userId = masterDeleteRequestType.getUserId(); + String masterId = masterDeleteRequestType.getQueryMasterId(); + if (masterId==null) + throw new I2B2Exception("Null master id sent to DeleteQueryMasterHandler"); + QueryInfoBean query = new QueryInfoBean(); + masterResponseType = query.deleteQueryMaster(getDataSourceLookup(),userId,masterId); + + + masterResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.DONE_TYPE, "DONE")); + } catch (Exception ex) { + masterResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.ERROR_TYPE, ex.getMessage())); + ex.printStackTrace(); + } + finally { + edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); + bodyType.getAny().add(of.createResponse(masterResponseType)); + } + +// ResultStatusType resultStatusType = new ResultStatusType(); +// resultStatusType.setStatus(statusType); +// +// ResponseHeaderType responseHeader = new ResponseHeaderType(); +// responseHeader.setResultStatus(resultStatusType); +// responseMessageType.setResponseHeader(responseHeader); +// +// responseStr = getResponseString(responseMessageType); + + return bodyType; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/GetAllQueryResultTypeHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/GetAllQueryResultTypeHandler.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/GetAllQueryResultTypeHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/GetAllQueryResultTypeHandler.java index b771c0b7..1162deca --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/GetAllQueryResultTypeHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/GetAllQueryResultTypeHandler.java @@ -1,101 +1,101 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.delegate.setfinder; - -import java.util.List; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.PsmQryHeaderType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultTypeRequestType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultTypeResponseType; -import edu.harvard.i2b2.crc.delegate.RequestHandler; -import edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate; -import edu.harvard.i2b2.crc.ejb.QueryInfoBean; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - - - -/** - * GetRequestXmlFromQueryMasterIdHandler class - * implements execute method - * $Id: GetAllQueryResultTypeHandler.java,v 1.1 2008/05/08 14:37:25 rk903 Exp $ - * @author rkuttan - */ -public class GetAllQueryResultTypeHandler extends RequestHandler { - ResultTypeRequestType resultTypeRequestType = null; - PsmQryHeaderType headerType = null; - String requestXml = null; - List roles = null; - - /** - * Constuctor which accepts i2b2 request message xml - * @param requestXml - * @param roles - * @throws I2B2Exception - */ - public GetAllQueryResultTypeHandler(String requestXml, List roles) - throws I2B2Exception { - this.requestXml = requestXml; - - try { - headerType = (PsmQryHeaderType) this.getRequestType(requestXml, - edu.harvard.i2b2.crc.datavo.setfinder.query.PsmQryHeaderType.class); - resultTypeRequestType = (ResultTypeRequestType) this.getRequestType(requestXml, - edu.harvard.i2b2.crc.datavo.setfinder.query.ResultTypeRequestType.class); - this.setDataSourceLookup(requestXml); - this.roles = roles; - } catch (JAXBUtilException jaxbUtilEx) { - throw new I2B2Exception("Error ", jaxbUtilEx); - } - } - - /** - * Perform operation for the given request - * using business class(ejb) and return response - * @throws I2B2Exception - * @see edu.harvard.i2b2.crc.delegate.RequestHandler#execute() - */ - @Override - public BodyType execute() throws I2B2Exception { - // call ejb and pass input object - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - String responseString = null; - BodyType bodyType = new BodyType(); - - ResultTypeResponseType resultTypeResponseType= new ResultTypeResponseType(); - try { - //TODO removed ejbs - // QueryInfoLocalHome queryInfoLocalHome = qpUtil.getQueryInfoLocalHome(); - // QueryInfoLocal queryInfoLocal = queryInfoLocalHome.create(); - - QueryInfoBean query = new QueryInfoBean(); - resultTypeResponseType = query.getAllResultType(dataSourceLookup, roles); - - - resultTypeResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.DONE_TYPE, "DONE")); - - } catch (Exception e) { - resultTypeResponseType = new ResultTypeResponseType(); - resultTypeResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.ERROR_TYPE, e.getMessage())); - } finally { - edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); - bodyType.getAny().add(of.createResponse(resultTypeResponseType)); - } - - return bodyType; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.delegate.setfinder; + +import java.util.List; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.PsmQryHeaderType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultTypeRequestType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultTypeResponseType; +import edu.harvard.i2b2.crc.delegate.RequestHandler; +import edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate; +import edu.harvard.i2b2.crc.ejb.QueryInfoBean; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + + + +/** + * GetRequestXmlFromQueryMasterIdHandler class + * implements execute method + * $Id: GetAllQueryResultTypeHandler.java,v 1.1 2008/05/08 14:37:25 rk903 Exp $ + * @author rkuttan + */ +public class GetAllQueryResultTypeHandler extends RequestHandler { + ResultTypeRequestType resultTypeRequestType = null; + PsmQryHeaderType headerType = null; + String requestXml = null; + List roles = null; + + /** + * Constuctor which accepts i2b2 request message xml + * @param requestXml + * @param roles + * @throws I2B2Exception + */ + public GetAllQueryResultTypeHandler(String requestXml, List roles) + throws I2B2Exception { + this.requestXml = requestXml; + + try { + headerType = (PsmQryHeaderType) this.getRequestType(requestXml, + edu.harvard.i2b2.crc.datavo.setfinder.query.PsmQryHeaderType.class); + resultTypeRequestType = (ResultTypeRequestType) this.getRequestType(requestXml, + edu.harvard.i2b2.crc.datavo.setfinder.query.ResultTypeRequestType.class); + this.setDataSourceLookup(requestXml); + this.roles = roles; + } catch (JAXBUtilException jaxbUtilEx) { + throw new I2B2Exception("Error ", jaxbUtilEx); + } + } + + /** + * Perform operation for the given request + * using business class(ejb) and return response + * @throws I2B2Exception + * @see edu.harvard.i2b2.crc.delegate.RequestHandler#execute() + */ + @Override + public BodyType execute() throws I2B2Exception { + // call ejb and pass input object + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + String responseString = null; + BodyType bodyType = new BodyType(); + + ResultTypeResponseType resultTypeResponseType= new ResultTypeResponseType(); + try { + //TODO removed ejbs + // QueryInfoLocalHome queryInfoLocalHome = qpUtil.getQueryInfoLocalHome(); + // QueryInfoLocal queryInfoLocal = queryInfoLocalHome.create(); + + QueryInfoBean query = new QueryInfoBean(); + resultTypeResponseType = query.getAllResultType(dataSourceLookup, roles); + + + resultTypeResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.DONE_TYPE, "DONE")); + + } catch (Exception e) { + resultTypeResponseType = new ResultTypeResponseType(); + resultTypeResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.ERROR_TYPE, e.getMessage())); + } finally { + edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); + bodyType.getAny().add(of.createResponse(resultTypeResponseType)); + } + + return bodyType; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/GetAnalysisPluginMetadataTypeHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/GetAnalysisPluginMetadataTypeHandler.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/GetAnalysisPluginMetadataTypeHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/GetAnalysisPluginMetadataTypeHandler.java index e5dbff12..536d59cb --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/GetAnalysisPluginMetadataTypeHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/GetAnalysisPluginMetadataTypeHandler.java @@ -1,100 +1,100 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * - */ -package edu.harvard.i2b2.crc.delegate.setfinder; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.AnalysisPluginMetadataRequestType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.AnalysisPluginMetadataResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.PsmQryHeaderType; -import edu.harvard.i2b2.crc.delegate.RequestHandler; -import edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate; -import edu.harvard.i2b2.crc.ejb.analysis.AnalysisPluginInfoLocal; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - -/** - * GetAnalysisPluginMetadataTypeHandler class. Returns plugin's metadata by - * plugin name and project - */ -public class GetAnalysisPluginMetadataTypeHandler extends RequestHandler { - AnalysisPluginMetadataRequestType apMetadataRequestType = null; - String projectId = ""; - PsmQryHeaderType headerType = null; - String requestXml = null; - - /** - * Constuctor which accepts i2b2 request message xml - * - * @param requestXml - * @throws I2B2Exception - */ - public GetAnalysisPluginMetadataTypeHandler(String requestXml) - throws I2B2Exception { - this.requestXml = requestXml; - - try { - headerType = (PsmQryHeaderType) this - .getRequestType( - requestXml, - edu.harvard.i2b2.crc.datavo.setfinder.query.PsmQryHeaderType.class); - apMetadataRequestType = (AnalysisPluginMetadataRequestType) this - .getRequestType( - requestXml, - edu.harvard.i2b2.crc.datavo.setfinder.query.AnalysisPluginMetadataRequestType.class); - this.setDataSourceLookup(requestXml); - projectId = this.getI2B2RequestMessageType(requestXml) - .getMessageHeader().getProjectId(); - } catch (JAXBUtilException jaxbUtilEx) { - throw new I2B2Exception("Error ", jaxbUtilEx); - } - } - - /** - * Perform operation for the given request using business class(ejb) and - * return response - * - * @throws I2B2Exception - * @see edu.harvard.i2b2.crc.delegate.RequestHandler#execute() - */ - @Override - public BodyType execute() throws I2B2Exception { - // call ejb and pass input object - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - String responseString = null; - BodyType bodyType = new BodyType(); - - AnalysisPluginMetadataResponseType resultTypeResponseType = new AnalysisPluginMetadataResponseType(); - try { - AnalysisPluginInfoLocal apInfoLocal = qpUtil - .getAnalysisPluginInfoLocal(); - - resultTypeResponseType = apInfoLocal.getAnalysisPluginMetadata( - dataSourceLookup, apMetadataRequestType, projectId); - - resultTypeResponseType.setStatus(this.buildCRCStausType( - RequestHandlerDelegate.DONE_TYPE, "DONE")); - - } catch (I2B2Exception e) { - resultTypeResponseType = new AnalysisPluginMetadataResponseType(); - resultTypeResponseType.setStatus(this.buildCRCStausType( - RequestHandlerDelegate.ERROR_TYPE, e.getMessage())); - } finally { - edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); - bodyType.getAny().add(of.createResponse(resultTypeResponseType)); - } - - return bodyType; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * + */ +package edu.harvard.i2b2.crc.delegate.setfinder; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.AnalysisPluginMetadataRequestType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.AnalysisPluginMetadataResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.PsmQryHeaderType; +import edu.harvard.i2b2.crc.delegate.RequestHandler; +import edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate; +import edu.harvard.i2b2.crc.ejb.analysis.AnalysisPluginInfoLocal; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + +/** + * GetAnalysisPluginMetadataTypeHandler class. Returns plugin's metadata by + * plugin name and project + */ +public class GetAnalysisPluginMetadataTypeHandler extends RequestHandler { + AnalysisPluginMetadataRequestType apMetadataRequestType = null; + String projectId = ""; + PsmQryHeaderType headerType = null; + String requestXml = null; + + /** + * Constuctor which accepts i2b2 request message xml + * + * @param requestXml + * @throws I2B2Exception + */ + public GetAnalysisPluginMetadataTypeHandler(String requestXml) + throws I2B2Exception { + this.requestXml = requestXml; + + try { + headerType = (PsmQryHeaderType) this + .getRequestType( + requestXml, + edu.harvard.i2b2.crc.datavo.setfinder.query.PsmQryHeaderType.class); + apMetadataRequestType = (AnalysisPluginMetadataRequestType) this + .getRequestType( + requestXml, + edu.harvard.i2b2.crc.datavo.setfinder.query.AnalysisPluginMetadataRequestType.class); + this.setDataSourceLookup(requestXml); + projectId = this.getI2B2RequestMessageType(requestXml) + .getMessageHeader().getProjectId(); + } catch (JAXBUtilException jaxbUtilEx) { + throw new I2B2Exception("Error ", jaxbUtilEx); + } + } + + /** + * Perform operation for the given request using business class(ejb) and + * return response + * + * @throws I2B2Exception + * @see edu.harvard.i2b2.crc.delegate.RequestHandler#execute() + */ + @Override + public BodyType execute() throws I2B2Exception { + // call ejb and pass input object + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + String responseString = null; + BodyType bodyType = new BodyType(); + + AnalysisPluginMetadataResponseType resultTypeResponseType = new AnalysisPluginMetadataResponseType(); + try { + AnalysisPluginInfoLocal apInfoLocal = qpUtil + .getAnalysisPluginInfoLocal(); + + resultTypeResponseType = apInfoLocal.getAnalysisPluginMetadata( + dataSourceLookup, apMetadataRequestType, projectId); + + resultTypeResponseType.setStatus(this.buildCRCStausType( + RequestHandlerDelegate.DONE_TYPE, "DONE")); + + } catch (I2B2Exception e) { + resultTypeResponseType = new AnalysisPluginMetadataResponseType(); + resultTypeResponseType.setStatus(this.buildCRCStausType( + RequestHandlerDelegate.ERROR_TYPE, e.getMessage())); + } finally { + edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); + bodyType.getAny().add(of.createResponse(resultTypeResponseType)); + } + + return bodyType; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/GetQueryInstanceListFromMasterIdHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/GetQueryInstanceListFromMasterIdHandler.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/GetQueryInstanceListFromMasterIdHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/GetQueryInstanceListFromMasterIdHandler.java index a4a832c2..db2aa210 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/GetQueryInstanceListFromMasterIdHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/GetQueryInstanceListFromMasterIdHandler.java @@ -1,94 +1,94 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.delegate.setfinder; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterRequestType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.PsmQryHeaderType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.UserType; -import edu.harvard.i2b2.crc.delegate.RequestHandler; -import edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate; -import edu.harvard.i2b2.crc.ejb.QueryRunBean; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - - -/** - * GetQueryInstanceListFromMasterIdHandler class - * implements execute method - * $Id: GetQueryInstanceListFromMasterIdHandler.java,v 1.6 2008/03/19 22:36:37 rk903 Exp $ - * @author rkuttan - */ -public class GetQueryInstanceListFromMasterIdHandler extends RequestHandler { - MasterRequestType masterRequestType = null; - PsmQryHeaderType headerType = null; - - /** - * Constuctor which accepts i2b2 request message xml - * @param requestXml - * @throws I2B2Exception - */ - public GetQueryInstanceListFromMasterIdHandler(String requestXml) - throws I2B2Exception { - try { - headerType = (PsmQryHeaderType) this.getRequestType(requestXml, - edu.harvard.i2b2.crc.datavo.setfinder.query.PsmQryHeaderType.class); - masterRequestType = (MasterRequestType) this.getRequestType(requestXml, - edu.harvard.i2b2.crc.datavo.setfinder.query.MasterRequestType.class); - this.setDataSourceLookup(requestXml); - - } catch (JAXBUtilException jaxbUtilEx) { - throw new I2B2Exception("Error ", jaxbUtilEx); - } - } - - /** - * Perform operation for the given request - * using business class(ejb) and return response - */ - @Override - public BodyType execute() throws I2B2Exception { - // call ejb and pass input object - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - - String responseString = null; - BodyType bodyType = new BodyType(); - InstanceResponseType instanceResponseType = null; - try { - //TODO removed ejbs - // QueryRunLocalHome queryRunLocalHome = qpUtil.getQueryRunLocalHome(); - // QueryRunLocal queryRunLocal = queryRunLocalHome.create(); - UserType userType = headerType.getUser(); - String userId = null; - - if (userType != null) { - userId = userType.getLogin(); - } - QueryRunBean query = new QueryRunBean(); - instanceResponseType = query.getQueryInstanceFromMasterId(getDataSourceLookup(),userId,masterRequestType); - instanceResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.DONE_TYPE, "DONE")); - } catch (Exception e) { - instanceResponseType = new InstanceResponseType(); - instanceResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.ERROR_TYPE, e.getMessage())); - } finally { - edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); - bodyType.getAny().add(of.createResponse(instanceResponseType)); - } - - return bodyType; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.delegate.setfinder; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterRequestType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.PsmQryHeaderType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.UserType; +import edu.harvard.i2b2.crc.delegate.RequestHandler; +import edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate; +import edu.harvard.i2b2.crc.ejb.QueryRunBean; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + + +/** + * GetQueryInstanceListFromMasterIdHandler class + * implements execute method + * $Id: GetQueryInstanceListFromMasterIdHandler.java,v 1.6 2008/03/19 22:36:37 rk903 Exp $ + * @author rkuttan + */ +public class GetQueryInstanceListFromMasterIdHandler extends RequestHandler { + MasterRequestType masterRequestType = null; + PsmQryHeaderType headerType = null; + + /** + * Constuctor which accepts i2b2 request message xml + * @param requestXml + * @throws I2B2Exception + */ + public GetQueryInstanceListFromMasterIdHandler(String requestXml) + throws I2B2Exception { + try { + headerType = (PsmQryHeaderType) this.getRequestType(requestXml, + edu.harvard.i2b2.crc.datavo.setfinder.query.PsmQryHeaderType.class); + masterRequestType = (MasterRequestType) this.getRequestType(requestXml, + edu.harvard.i2b2.crc.datavo.setfinder.query.MasterRequestType.class); + this.setDataSourceLookup(requestXml); + + } catch (JAXBUtilException jaxbUtilEx) { + throw new I2B2Exception("Error ", jaxbUtilEx); + } + } + + /** + * Perform operation for the given request + * using business class(ejb) and return response + */ + @Override + public BodyType execute() throws I2B2Exception { + // call ejb and pass input object + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + + String responseString = null; + BodyType bodyType = new BodyType(); + InstanceResponseType instanceResponseType = null; + try { + //TODO removed ejbs + // QueryRunLocalHome queryRunLocalHome = qpUtil.getQueryRunLocalHome(); + // QueryRunLocal queryRunLocal = queryRunLocalHome.create(); + UserType userType = headerType.getUser(); + String userId = null; + + if (userType != null) { + userId = userType.getLogin(); + } + QueryRunBean query = new QueryRunBean(); + instanceResponseType = query.getQueryInstanceFromMasterId(getDataSourceLookup(),userId,masterRequestType); + instanceResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.DONE_TYPE, "DONE")); + } catch (Exception e) { + instanceResponseType = new InstanceResponseType(); + instanceResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.ERROR_TYPE, e.getMessage())); + } finally { + edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); + bodyType.getAny().add(of.createResponse(instanceResponseType)); + } + + return bodyType; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/GetQueryMasterListFromGroupIdHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/GetQueryMasterListFromGroupIdHandler.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/GetQueryMasterListFromGroupIdHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/GetQueryMasterListFromGroupIdHandler.java index 6289604a..ae8a4d06 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/GetQueryMasterListFromGroupIdHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/GetQueryMasterListFromGroupIdHandler.java @@ -1,93 +1,93 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.delegate.setfinder; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.UserRequestType; -import edu.harvard.i2b2.crc.delegate.RequestHandler; -import edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate; -import edu.harvard.i2b2.crc.ejb.QueryInfoBean; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - - - -/** - * GetQueryMasterListFromGroupIdHandler class - * implements execute method - * $Id: GetQueryMasterListFromGroupIdHandler.java,v 1.4 2008/03/19 22:36:37 rk903 Exp $ - * @author rkuttan - */ -public class GetQueryMasterListFromGroupIdHandler extends RequestHandler { - private UserRequestType userRequestType = null; - - /** - * Constuctor which accepts i2b2 request message xml - * @param requestXml - * @throws I2B2Exception - */ - public GetQueryMasterListFromGroupIdHandler(String requestXml) - throws I2B2Exception { - try { - userRequestType = (UserRequestType) this.getRequestType(requestXml, - edu.harvard.i2b2.crc.datavo.setfinder.query.UserRequestType.class); - this.setDataSourceLookup(requestXml); - } catch (JAXBUtilException jaxbUtilEx) { - throw new I2B2Exception("Error ", jaxbUtilEx); - } - } - - /** - * Perform operation for the given request - * using business class(ejb) and return response - * @see edu.harvard.i2b2.crc.delegate.RequestHandler#execute() - */ - @Override - public BodyType execute() throws I2B2Exception { - // call ejb and pass input object - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - String responseString = null; - BodyType bodyType = new BodyType(); - MasterResponseType masterResponseType = null; - try { - //TODO removed ejbs - // QueryInfoLocalHome queryInfoLocalHome = qpUtil.getQueryInfoLocalHome(); - // QueryInfoLocal queryInfoLocal = queryInfoLocalHome.create(); - long initialTime = System.currentTimeMillis(); - // masterResponseType = queryInfoLocal.getQueryMasterListFromGroupId(this.getDataSourceLookup(),userRequestType); - QueryInfoBean query = new QueryInfoBean(); - masterResponseType = query.getQueryMasterListFromGroupId(getDataSourceLookup(),userRequestType); - - long finalTime = System.currentTimeMillis(); - long diffTimeMill = finalTime - initialTime; - long diffTime = diffTimeMill / 1000; - log.debug(" EJB Diff mill =" + diffTimeMill + " diffTime =" + - diffTime); - masterResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.DONE_TYPE, "DONE")); - log.debug("Size of list " + masterResponseType.getQueryMaster().size()); - } catch (Exception e) { - masterResponseType = new MasterResponseType(); - masterResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.ERROR_TYPE, e.getMessage())); - log.equals(e); - } finally { - edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); - bodyType.getAny().add(of.createResponse(masterResponseType)); - } - - return bodyType; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.delegate.setfinder; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.UserRequestType; +import edu.harvard.i2b2.crc.delegate.RequestHandler; +import edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate; +import edu.harvard.i2b2.crc.ejb.QueryInfoBean; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + + + +/** + * GetQueryMasterListFromGroupIdHandler class + * implements execute method + * $Id: GetQueryMasterListFromGroupIdHandler.java,v 1.4 2008/03/19 22:36:37 rk903 Exp $ + * @author rkuttan + */ +public class GetQueryMasterListFromGroupIdHandler extends RequestHandler { + private UserRequestType userRequestType = null; + + /** + * Constuctor which accepts i2b2 request message xml + * @param requestXml + * @throws I2B2Exception + */ + public GetQueryMasterListFromGroupIdHandler(String requestXml) + throws I2B2Exception { + try { + userRequestType = (UserRequestType) this.getRequestType(requestXml, + edu.harvard.i2b2.crc.datavo.setfinder.query.UserRequestType.class); + this.setDataSourceLookup(requestXml); + } catch (JAXBUtilException jaxbUtilEx) { + throw new I2B2Exception("Error ", jaxbUtilEx); + } + } + + /** + * Perform operation for the given request + * using business class(ejb) and return response + * @see edu.harvard.i2b2.crc.delegate.RequestHandler#execute() + */ + @Override + public BodyType execute() throws I2B2Exception { + // call ejb and pass input object + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + String responseString = null; + BodyType bodyType = new BodyType(); + MasterResponseType masterResponseType = null; + try { + //TODO removed ejbs + // QueryInfoLocalHome queryInfoLocalHome = qpUtil.getQueryInfoLocalHome(); + // QueryInfoLocal queryInfoLocal = queryInfoLocalHome.create(); + long initialTime = System.currentTimeMillis(); + // masterResponseType = queryInfoLocal.getQueryMasterListFromGroupId(this.getDataSourceLookup(),userRequestType); + QueryInfoBean query = new QueryInfoBean(); + masterResponseType = query.getQueryMasterListFromGroupId(getDataSourceLookup(),userRequestType); + + long finalTime = System.currentTimeMillis(); + long diffTimeMill = finalTime - initialTime; + long diffTime = diffTimeMill / 1000; + log.debug(" EJB Diff mill =" + diffTimeMill + " diffTime =" + + diffTime); + masterResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.DONE_TYPE, "DONE")); + log.debug("Size of list " + masterResponseType.getQueryMaster().size()); + } catch (Exception e) { + masterResponseType = new MasterResponseType(); + masterResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.ERROR_TYPE, e.getMessage())); + log.equals(e); + } finally { + edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); + bodyType.getAny().add(of.createResponse(masterResponseType)); + } + + return bodyType; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/GetQueryMasterListFromUserIdHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/GetQueryMasterListFromUserIdHandler.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/GetQueryMasterListFromUserIdHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/GetQueryMasterListFromUserIdHandler.java index 302256cb..ea77fd64 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/GetQueryMasterListFromUserIdHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/GetQueryMasterListFromUserIdHandler.java @@ -1,89 +1,89 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.delegate.setfinder; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.UserRequestType; -import edu.harvard.i2b2.crc.delegate.RequestHandler; -import edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate; -import edu.harvard.i2b2.crc.ejb.QueryInfoBean; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - - -/** - * GetQueryMasterListFromUserIdHandler class - * implements execute method - * $Id: GetQueryMasterListFromUserIdHandler.java,v 1.7 2008/03/19 22:36:37 rk903 Exp $ - * @author rkuttan - */ -public class GetQueryMasterListFromUserIdHandler extends RequestHandler { - private UserRequestType userRequestType = null; - - /** - * Constuctor which accepts i2b2 request message xml - * @param requestXml - * @throws I2B2Exception - */ - public GetQueryMasterListFromUserIdHandler(String requestXml) - throws I2B2Exception { - try { - userRequestType = (UserRequestType) this.getRequestType(requestXml, - edu.harvard.i2b2.crc.datavo.setfinder.query.UserRequestType.class); - setDataSourceLookup(requestXml); - } catch (JAXBUtilException jaxbUtilEx) { - throw new I2B2Exception("Error ", jaxbUtilEx); - } - } - - /** - * Perform operation for the given request - * using business class(ejb) and return response - * @see edu.harvard.i2b2.crc.delegate.RequestHandler#execute() - */ - @Override - public BodyType execute() throws I2B2Exception { - // call ejb and pass input object - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - String responseString = null; - BodyType bodyType = new BodyType(); - MasterResponseType masterResponseType = null; - try { - //TODO remove ejbs - // QueryInfoLocalHome queryInfoLocalHome = qpUtil.getQueryInfoLocalHome(); - // QueryInfoLocal queryInfoLocal = queryInfoLocalHome.create(); - long initialTime = System.currentTimeMillis(); - // masterResponseType = queryInfoLocal.getQueryMasterListFromUserId(getDataSourceLookup(),userRequestType); - QueryInfoBean query = new QueryInfoBean(); - masterResponseType = query.getQueryMasterListFromUserId(getDataSourceLookup(),userRequestType); - long finalTime = System.currentTimeMillis(); - long diffTimeMill = finalTime - initialTime; - long diffTime = diffTimeMill / 1000; - log.debug(" EJB Diff mill =" + diffTimeMill + " diffTime =" + - diffTime); - masterResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.DONE_TYPE, "DONE")); - } catch (Exception e) { - masterResponseType = new MasterResponseType(); - masterResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.ERROR_TYPE, e.getMessage())); - } finally { - edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); - bodyType.getAny().add(of.createResponse(masterResponseType)); - } - - return bodyType; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.delegate.setfinder; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.UserRequestType; +import edu.harvard.i2b2.crc.delegate.RequestHandler; +import edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate; +import edu.harvard.i2b2.crc.ejb.QueryInfoBean; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + + +/** + * GetQueryMasterListFromUserIdHandler class + * implements execute method + * $Id: GetQueryMasterListFromUserIdHandler.java,v 1.7 2008/03/19 22:36:37 rk903 Exp $ + * @author rkuttan + */ +public class GetQueryMasterListFromUserIdHandler extends RequestHandler { + private UserRequestType userRequestType = null; + + /** + * Constuctor which accepts i2b2 request message xml + * @param requestXml + * @throws I2B2Exception + */ + public GetQueryMasterListFromUserIdHandler(String requestXml) + throws I2B2Exception { + try { + userRequestType = (UserRequestType) this.getRequestType(requestXml, + edu.harvard.i2b2.crc.datavo.setfinder.query.UserRequestType.class); + setDataSourceLookup(requestXml); + } catch (JAXBUtilException jaxbUtilEx) { + throw new I2B2Exception("Error ", jaxbUtilEx); + } + } + + /** + * Perform operation for the given request + * using business class(ejb) and return response + * @see edu.harvard.i2b2.crc.delegate.RequestHandler#execute() + */ + @Override + public BodyType execute() throws I2B2Exception { + // call ejb and pass input object + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + String responseString = null; + BodyType bodyType = new BodyType(); + MasterResponseType masterResponseType = null; + try { + //TODO remove ejbs + // QueryInfoLocalHome queryInfoLocalHome = qpUtil.getQueryInfoLocalHome(); + // QueryInfoLocal queryInfoLocal = queryInfoLocalHome.create(); + long initialTime = System.currentTimeMillis(); + // masterResponseType = queryInfoLocal.getQueryMasterListFromUserId(getDataSourceLookup(),userRequestType); + QueryInfoBean query = new QueryInfoBean(); + masterResponseType = query.getQueryMasterListFromUserId(getDataSourceLookup(),userRequestType); + long finalTime = System.currentTimeMillis(); + long diffTimeMill = finalTime - initialTime; + long diffTime = diffTimeMill / 1000; + log.debug(" EJB Diff mill =" + diffTimeMill + " diffTime =" + + diffTime); + masterResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.DONE_TYPE, "DONE")); + } catch (Exception e) { + masterResponseType = new MasterResponseType(); + masterResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.ERROR_TYPE, e.getMessage())); + } finally { + edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); + bodyType.getAny().add(of.createResponse(masterResponseType)); + } + + return bodyType; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/GetQueryResultInstanceListFromQueryInstanceIdHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/GetQueryResultInstanceListFromQueryInstanceIdHandler.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/GetQueryResultInstanceListFromQueryInstanceIdHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/GetQueryResultInstanceListFromQueryInstanceIdHandler.java index e2e36b10..abc777d3 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/GetQueryResultInstanceListFromQueryInstanceIdHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/GetQueryResultInstanceListFromQueryInstanceIdHandler.java @@ -1,115 +1,115 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.delegate.setfinder; - -import java.util.List; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceRequestType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.PsmQryHeaderType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.UserType; -import edu.harvard.i2b2.crc.delegate.RequestHandler; -import edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate; -import edu.harvard.i2b2.crc.ejb.QueryResultBean; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - - -/** - * GetQueryResultInstanceListFromQueryInstanceIdHandler class - * implements execute method - * $Id: GetQueryResultInstanceListFromQueryInstanceIdHandler.java,v 1.7 2008/03/19 22:36:37 rk903 Exp $ - * @author rkuttan - */ -public class GetQueryResultInstanceListFromQueryInstanceIdHandler - extends RequestHandler { - String requestXml = null; - InstanceRequestType queryInstanceReqType = null; - PsmQryHeaderType headerType = null; - boolean nonObsUser = false; - - /** - * Constuctor which accepts i2b2 request message xml - * @param requestXml - * @param roles - * @throws I2B2Exception - */ - public GetQueryResultInstanceListFromQueryInstanceIdHandler( - String requestXml, List roles) throws I2B2Exception { - this.requestXml = requestXml; - - try { - headerType = (PsmQryHeaderType) this.getRequestType(requestXml, - edu.harvard.i2b2.crc.datavo.setfinder.query.PsmQryHeaderType.class); - queryInstanceReqType = (InstanceRequestType) this.getRequestType(requestXml, - edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceRequestType.class); - this.setDataSourceLookup(requestXml); - if (roles.contains("DATA_AGG")) - nonObsUser = true; - } catch (JAXBUtilException jaxbUtilEx) { - throw new I2B2Exception("Error ", jaxbUtilEx); - } - } - - /** - * Perform operation for the given request - * using business class(ejb) and return response - * @throws I2B2Exception - * @see edu.harvard.i2b2.crc.delegate.RequestHandler#execute() - */ - @Override - public BodyType execute() throws I2B2Exception { - // call ejb and pass input object - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - String responseString = null; - - BodyType bodyType = new BodyType(); - ResultResponseType resultResponseType = null; - try { - //TODO removed ejbs - // QueryResultLocalHome queryResultLocalHome = qpUtil.getQueryResultLocalHome(); - // QueryResultLocal queryResultLocal = queryResultLocalHome.create(); - - UserType userType = headerType.getUser(); - String userId = null; - - if (userType != null) { - userId = userType.getLogin(); - } - - if (queryInstanceReqType == null) { - //build response message with error information - resultResponseType = new ResultResponseType(); - } - - QueryResultBean query = new QueryResultBean(); - resultResponseType = query.getResultInstanceFromQueryInstanceId(this.getDataSourceLookup(),userId, - queryInstanceReqType.getQueryInstanceId(), nonObsUser); - - resultResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.DONE_TYPE, "DONE")); - } catch (Exception e) { - resultResponseType = new ResultResponseType(); - resultResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.ERROR_TYPE, e.getMessage())); - } finally { - edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); - bodyType.getAny().add(of.createResponse(resultResponseType)); - } - - - return bodyType; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.delegate.setfinder; + +import java.util.List; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceRequestType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.PsmQryHeaderType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.UserType; +import edu.harvard.i2b2.crc.delegate.RequestHandler; +import edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate; +import edu.harvard.i2b2.crc.ejb.QueryResultBean; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + + +/** + * GetQueryResultInstanceListFromQueryInstanceIdHandler class + * implements execute method + * $Id: GetQueryResultInstanceListFromQueryInstanceIdHandler.java,v 1.7 2008/03/19 22:36:37 rk903 Exp $ + * @author rkuttan + */ +public class GetQueryResultInstanceListFromQueryInstanceIdHandler + extends RequestHandler { + String requestXml = null; + InstanceRequestType queryInstanceReqType = null; + PsmQryHeaderType headerType = null; + boolean nonObsUser = false; + + /** + * Constuctor which accepts i2b2 request message xml + * @param requestXml + * @param roles + * @throws I2B2Exception + */ + public GetQueryResultInstanceListFromQueryInstanceIdHandler( + String requestXml, List roles) throws I2B2Exception { + this.requestXml = requestXml; + + try { + headerType = (PsmQryHeaderType) this.getRequestType(requestXml, + edu.harvard.i2b2.crc.datavo.setfinder.query.PsmQryHeaderType.class); + queryInstanceReqType = (InstanceRequestType) this.getRequestType(requestXml, + edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceRequestType.class); + this.setDataSourceLookup(requestXml); + if (roles.contains("DATA_AGG")) + nonObsUser = true; + } catch (JAXBUtilException jaxbUtilEx) { + throw new I2B2Exception("Error ", jaxbUtilEx); + } + } + + /** + * Perform operation for the given request + * using business class(ejb) and return response + * @throws I2B2Exception + * @see edu.harvard.i2b2.crc.delegate.RequestHandler#execute() + */ + @Override + public BodyType execute() throws I2B2Exception { + // call ejb and pass input object + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + String responseString = null; + + BodyType bodyType = new BodyType(); + ResultResponseType resultResponseType = null; + try { + //TODO removed ejbs + // QueryResultLocalHome queryResultLocalHome = qpUtil.getQueryResultLocalHome(); + // QueryResultLocal queryResultLocal = queryResultLocalHome.create(); + + UserType userType = headerType.getUser(); + String userId = null; + + if (userType != null) { + userId = userType.getLogin(); + } + + if (queryInstanceReqType == null) { + //build response message with error information + resultResponseType = new ResultResponseType(); + } + + QueryResultBean query = new QueryResultBean(); + resultResponseType = query.getResultInstanceFromQueryInstanceId(this.getDataSourceLookup(),userId, + queryInstanceReqType.getQueryInstanceId(), nonObsUser); + + resultResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.DONE_TYPE, "DONE")); + } catch (Exception e) { + resultResponseType = new ResultResponseType(); + resultResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.ERROR_TYPE, e.getMessage())); + } finally { + edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); + bodyType.getAny().add(of.createResponse(resultResponseType)); + } + + + return bodyType; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/GetRequestXmlFromQueryMasterIdHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/GetRequestXmlFromQueryMasterIdHandler.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/GetRequestXmlFromQueryMasterIdHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/GetRequestXmlFromQueryMasterIdHandler.java index 2c91fcfa..b464cf29 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/GetRequestXmlFromQueryMasterIdHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/GetRequestXmlFromQueryMasterIdHandler.java @@ -1,100 +1,100 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.delegate.setfinder; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterRequestType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.PsmQryHeaderType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.UserType; -import edu.harvard.i2b2.crc.delegate.RequestHandler; -import edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate; -import edu.harvard.i2b2.crc.ejb.QueryInfoBean; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - - -/** - * GetRequestXmlFromQueryMasterIdHandler class - * implements execute method - * $Id: GetRequestXmlFromQueryMasterIdHandler.java,v 1.6 2008/03/19 22:36:37 rk903 Exp $ - * @author rkuttan - */ -public class GetRequestXmlFromQueryMasterIdHandler extends RequestHandler { - MasterRequestType masterRequestType = null; - PsmQryHeaderType headerType = null; - String requestXml = null; - - /** - * Constuctor which accepts i2b2 request message xml - * @param requestXml - * @throws I2B2Exception - */ - public GetRequestXmlFromQueryMasterIdHandler(String requestXml) - throws I2B2Exception { - this.requestXml = requestXml; - - try { - headerType = (PsmQryHeaderType) this.getRequestType(requestXml, - edu.harvard.i2b2.crc.datavo.setfinder.query.PsmQryHeaderType.class); - masterRequestType = (MasterRequestType) this.getRequestType(requestXml, - edu.harvard.i2b2.crc.datavo.setfinder.query.MasterRequestType.class); - this.setDataSourceLookup(requestXml); - } catch (JAXBUtilException jaxbUtilEx) { - throw new I2B2Exception("Error ", jaxbUtilEx); - } - } - - /** - * Perform operation for the given request - * using business class(ejb) and return response - * @throws I2B2Exception - * @see edu.harvard.i2b2.crc.delegate.RequestHandler#execute() - */ - @Override - public BodyType execute() throws I2B2Exception { - // call ejb and pass input object - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - String responseString = null; - BodyType bodyType = new BodyType(); - MasterResponseType masterResponseType = null; - try { - //TODO removed ejbs - -// QueryInfoLocalHome queryInfoLocalHome = qpUtil.getQueryInfoLocalHome(); -// QueryInfoLocal queryInfoLocal = queryInfoLocalHome.create(); - UserType userType = headerType.getUser(); - String userId = null; - - if (userType != null) { - userId = userType.getLogin(); - } - - QueryInfoBean query = new QueryInfoBean(); - masterResponseType = query.getRequestXmlFromMasterId(this.getDataSourceLookup(),userId, - masterRequestType); - masterResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.DONE_TYPE, "DONE")); - } catch (Exception e) { - masterResponseType = new MasterResponseType(); - masterResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.ERROR_TYPE, e.getMessage())); - } finally { - edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); - bodyType.getAny().add(of.createResponse(masterResponseType)); - } - - return bodyType; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.delegate.setfinder; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterRequestType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.PsmQryHeaderType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.UserType; +import edu.harvard.i2b2.crc.delegate.RequestHandler; +import edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate; +import edu.harvard.i2b2.crc.ejb.QueryInfoBean; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + + +/** + * GetRequestXmlFromQueryMasterIdHandler class + * implements execute method + * $Id: GetRequestXmlFromQueryMasterIdHandler.java,v 1.6 2008/03/19 22:36:37 rk903 Exp $ + * @author rkuttan + */ +public class GetRequestXmlFromQueryMasterIdHandler extends RequestHandler { + MasterRequestType masterRequestType = null; + PsmQryHeaderType headerType = null; + String requestXml = null; + + /** + * Constuctor which accepts i2b2 request message xml + * @param requestXml + * @throws I2B2Exception + */ + public GetRequestXmlFromQueryMasterIdHandler(String requestXml) + throws I2B2Exception { + this.requestXml = requestXml; + + try { + headerType = (PsmQryHeaderType) this.getRequestType(requestXml, + edu.harvard.i2b2.crc.datavo.setfinder.query.PsmQryHeaderType.class); + masterRequestType = (MasterRequestType) this.getRequestType(requestXml, + edu.harvard.i2b2.crc.datavo.setfinder.query.MasterRequestType.class); + this.setDataSourceLookup(requestXml); + } catch (JAXBUtilException jaxbUtilEx) { + throw new I2B2Exception("Error ", jaxbUtilEx); + } + } + + /** + * Perform operation for the given request + * using business class(ejb) and return response + * @throws I2B2Exception + * @see edu.harvard.i2b2.crc.delegate.RequestHandler#execute() + */ + @Override + public BodyType execute() throws I2B2Exception { + // call ejb and pass input object + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + String responseString = null; + BodyType bodyType = new BodyType(); + MasterResponseType masterResponseType = null; + try { + //TODO removed ejbs + +// QueryInfoLocalHome queryInfoLocalHome = qpUtil.getQueryInfoLocalHome(); +// QueryInfoLocal queryInfoLocal = queryInfoLocalHome.create(); + UserType userType = headerType.getUser(); + String userId = null; + + if (userType != null) { + userId = userType.getLogin(); + } + + QueryInfoBean query = new QueryInfoBean(); + masterResponseType = query.getRequestXmlFromMasterId(this.getDataSourceLookup(),userId, + masterRequestType); + masterResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.DONE_TYPE, "DONE")); + } catch (Exception e) { + masterResponseType = new MasterResponseType(); + masterResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.ERROR_TYPE, e.getMessage())); + } finally { + edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); + bodyType.getAny().add(of.createResponse(masterResponseType)); + } + + return bodyType; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/GetXmlResultFromQueryResultIdHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/GetXmlResultFromQueryResultIdHandler.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/GetXmlResultFromQueryResultIdHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/GetXmlResultFromQueryResultIdHandler.java index 8ade3508..4842b822 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/GetXmlResultFromQueryResultIdHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/GetXmlResultFromQueryResultIdHandler.java @@ -1,101 +1,101 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.delegate.setfinder; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.CrcXmlResultResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.PsmQryHeaderType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultRequestType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.UserType; -import edu.harvard.i2b2.crc.delegate.RequestHandler; -import edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate; -import edu.harvard.i2b2.crc.ejb.QueryResultBean; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - - - -/** - * GetRequestXmlFromQueryMasterIdHandler class - * implements execute method - * $Id: GetXmlResultFromQueryResultIdHandler.java,v 1.1 2008/05/01 16:13:33 rk903 Exp $ - * @author rkuttan - */ -public class GetXmlResultFromQueryResultIdHandler extends RequestHandler { - ResultRequestType resultRequestType = null; - PsmQryHeaderType headerType = null; - String requestXml = null; - - /** - * Constuctor which accepts i2b2 request message xml - * @param requestXml - * @throws I2B2Exception - */ - public GetXmlResultFromQueryResultIdHandler(String requestXml) - throws I2B2Exception { - this.requestXml = requestXml; - - try { - headerType = (PsmQryHeaderType) this.getRequestType(requestXml, - edu.harvard.i2b2.crc.datavo.setfinder.query.PsmQryHeaderType.class); - resultRequestType = (ResultRequestType) this.getRequestType(requestXml, - edu.harvard.i2b2.crc.datavo.setfinder.query.ResultRequestType.class); - this.setDataSourceLookup(requestXml); - } catch (JAXBUtilException jaxbUtilEx) { - throw new I2B2Exception("Error ", jaxbUtilEx); - } - } - - /** - * Perform operation for the given request - * using business class(ejb) and return response - * @throws I2B2Exception - * @see edu.harvard.i2b2.crc.delegate.RequestHandler#execute() - */ - @Override - public BodyType execute() throws I2B2Exception { - // call ejb and pass input object - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - String responseString = null; - BodyType bodyType = new BodyType(); - CrcXmlResultResponseType xmlResultResponseType = new CrcXmlResultResponseType(); - try { - //TODO removed ejbs -// QueryResultLocalHome queryResultLocalHome = qpUtil.getQueryResultLocalHome(); - // QueryResultLocal queryResultLocal = queryResultLocalHome.create(); - UserType userType = headerType.getUser(); - String userId = null; - - if (userType != null) { - userId = userType.getLogin(); - } - - QueryResultBean query = new QueryResultBean(); - xmlResultResponseType = query.getXmlResultFromResultInstanceId(dataSourceLookup, resultRequestType.getQueryResultInstanceId()); - - - xmlResultResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.DONE_TYPE, "DONE")); - } catch (Exception e) { - xmlResultResponseType = new CrcXmlResultResponseType(); - xmlResultResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.ERROR_TYPE, e.getMessage())); - } finally { - edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); - bodyType.getAny().add(of.createResponse(xmlResultResponseType)); - } - - return bodyType; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.delegate.setfinder; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.CrcXmlResultResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.PsmQryHeaderType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultRequestType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.UserType; +import edu.harvard.i2b2.crc.delegate.RequestHandler; +import edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate; +import edu.harvard.i2b2.crc.ejb.QueryResultBean; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + + + +/** + * GetRequestXmlFromQueryMasterIdHandler class + * implements execute method + * $Id: GetXmlResultFromQueryResultIdHandler.java,v 1.1 2008/05/01 16:13:33 rk903 Exp $ + * @author rkuttan + */ +public class GetXmlResultFromQueryResultIdHandler extends RequestHandler { + ResultRequestType resultRequestType = null; + PsmQryHeaderType headerType = null; + String requestXml = null; + + /** + * Constuctor which accepts i2b2 request message xml + * @param requestXml + * @throws I2B2Exception + */ + public GetXmlResultFromQueryResultIdHandler(String requestXml) + throws I2B2Exception { + this.requestXml = requestXml; + + try { + headerType = (PsmQryHeaderType) this.getRequestType(requestXml, + edu.harvard.i2b2.crc.datavo.setfinder.query.PsmQryHeaderType.class); + resultRequestType = (ResultRequestType) this.getRequestType(requestXml, + edu.harvard.i2b2.crc.datavo.setfinder.query.ResultRequestType.class); + this.setDataSourceLookup(requestXml); + } catch (JAXBUtilException jaxbUtilEx) { + throw new I2B2Exception("Error ", jaxbUtilEx); + } + } + + /** + * Perform operation for the given request + * using business class(ejb) and return response + * @throws I2B2Exception + * @see edu.harvard.i2b2.crc.delegate.RequestHandler#execute() + */ + @Override + public BodyType execute() throws I2B2Exception { + // call ejb and pass input object + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + String responseString = null; + BodyType bodyType = new BodyType(); + CrcXmlResultResponseType xmlResultResponseType = new CrcXmlResultResponseType(); + try { + //TODO removed ejbs +// QueryResultLocalHome queryResultLocalHome = qpUtil.getQueryResultLocalHome(); + // QueryResultLocal queryResultLocal = queryResultLocalHome.create(); + UserType userType = headerType.getUser(); + String userId = null; + + if (userType != null) { + userId = userType.getLogin(); + } + + QueryResultBean query = new QueryResultBean(); + xmlResultResponseType = query.getXmlResultFromResultInstanceId(dataSourceLookup, resultRequestType.getQueryResultInstanceId()); + + + xmlResultResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.DONE_TYPE, "DONE")); + } catch (Exception e) { + xmlResultResponseType = new CrcXmlResultResponseType(); + xmlResultResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.ERROR_TYPE, e.getMessage())); + } finally { + edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); + bodyType.getAny().add(of.createResponse(xmlResultResponseType)); + } + + return bodyType; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/QueryRequestDelegate.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/QueryRequestDelegate.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/QueryRequestDelegate.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/QueryRequestDelegate.java index d757f3a3..a5cf81b0 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/QueryRequestDelegate.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/QueryRequestDelegate.java @@ -1,482 +1,482 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.delegate.setfinder; - -import java.util.Date; -import java.util.List; - -import jakarta.xml.bind.JAXBElement; - -import org.apache.axis2.AxisFault; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.exception.StackTraceUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.dao.setfinder.QueryMasterSpringDao; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.I2B2MessageResponseFactory; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; -import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; -import edu.harvard.i2b2.crc.datavo.pm.ParamType; -import edu.harvard.i2b2.crc.datavo.pm.ProjectType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.PsmQryHeaderType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.PsmRequestTypeType; -import edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate; -import edu.harvard.i2b2.crc.delegate.ejbpm.EJBPMUtil; -import edu.harvard.i2b2.crc.delegate.pm.PMServiceDriver; -import edu.harvard.i2b2.crc.delegate.quartz.GetQuartzJobHandler; -import edu.harvard.i2b2.crc.delegate.quartz.GetAllJobsHandler; -import edu.harvard.i2b2.crc.delegate.quartz.SetJobHandlerMaybe; -import edu.harvard.i2b2.crc.util.CacheUtil; -import edu.harvard.i2b2.crc.util.LogTimingUtil; -import edu.harvard.i2b2.crc.util.ParamUtil; - -/** - * Setfinder query request delegate class $Id: QueryRequestDelegate.java,v 1.17 - * 2008/05/08 15:13:45 rk903 Exp $ - * - * @author rkuttan - */ -public class QueryRequestDelegate extends RequestHandlerDelegate { - - /** log **/ - protected final Log log = LogFactory.getLog(getClass()); - - protected final Log logesapi = LogFactory.getLog(getClass()); - - /** - * @see edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate#handleRequest(java.lang.String) - */ - @Override - public String handleRequest(String requestXml) throws I2B2Exception { - PsmQryHeaderType headerType = null; - String response = null; - JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); - - try { - JAXBElement jaxbElement = jaxbUtil.unMashallFromString(requestXml); - - if (jaxbElement == null) { - throw new I2B2Exception("Request is null after unmashall" - + requestXml); - } - - RequestMessageType requestMessageType = (RequestMessageType) jaxbElement - .getValue(); - BodyType bodyType = requestMessageType.getMessageBody(); - - if (bodyType == null) { - log.error("null value in body type"); - throw new I2B2Exception("null value in body type"); - } - // Call PM cell to validate user - ProjectType projectType = null; - StatusType procStatus = null; - try { - SecurityType securityType = null; - String projectId = null; - if (requestMessageType.getMessageHeader() != null) { - if (requestMessageType.getMessageHeader().getSecurity() != null) { - securityType = requestMessageType.getMessageHeader() - .getSecurity(); - } - projectId = requestMessageType.getMessageHeader() - .getProjectId(); - } - if (securityType == null) { - procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus - .setValue("Request message missing user/password"); - response = I2B2MessageResponseFactory.buildResponseMessage( - requestXml, procStatus, bodyType); - return response; - } - - // String pmResponse = - // PMServiceDriver.checkValidUser(securityType); - PMServiceDriver pmServiceDriver = new PMServiceDriver(); - projectType = pmServiceDriver.checkValidUser(securityType, - projectId); - - if (projectType == null) { - procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus - .setValue("Invalid user/password for the given project[" - + projectId + "]"); - response = I2B2MessageResponseFactory.buildResponseMessage( - requestXml, procStatus, bodyType); - return response; - } - - log.debug("project name from PM " + projectType.getName()); - logesapi.debug("project id from PM " + projectType.getId()); - - - if (projectType.getRole() != null) { - log.debug("project role from PM " - + projectType.getRole().get(0)); - - this.putRoles(projectId, securityType.getUsername(), - securityType.getDomain(), projectType.getRole()); - - //TODO removed cache - // Node rootNode = CacheUtil.getCache().getRoot(); - //List roles = (List) rootNode - // .get(securityType.getDomain() + "/" + projectId - // + "/" + securityType.getUsername()); - List roles = (List) CacheUtil - .get(securityType.getDomain() + "/" + projectId - + "/" + securityType.getUsername()); - if (roles != null) { - log.debug("User Roles count " + roles.size()); - } - } else { - log.error("Project role not set for the user "); - - } - - //check if process_timing_flag is set - log.debug("check if process_timing_flag is set"); - LogTimingUtil.clearPocessTiming(projectId, securityType.getUsername(), securityType.getDomain()); - ParamUtil paramUtil = new ParamUtil(); - paramUtil.clearParam(projectId, securityType.getUsername(), securityType.getDomain(), ParamUtil.CRC_ENABLE_UNITCD_CONVERSION); - if (projectType.getParam() != null) { - for (ParamType param : projectType.getParam()) { - if (param.getName() != null && param.getName().trim().equalsIgnoreCase(LogTimingUtil.PM_ENABLE_PROCESS_TIMING)) { - //this.putPocessTiming(projectId, securityType.getUsername(), securityType.getDomain(), param); - LogTimingUtil.putPocessTiming(projectId, securityType.getUsername(), securityType.getDomain(), param); - String cacheValue = LogTimingUtil.getPocessTiming(projectId, securityType.getUsername(), securityType.getDomain()); - logesapi.debug("CRC param stored in the cache Project Id [" + projectId + "] user [" + securityType.getUsername() + "] domain [" + securityType.getDomain() + "] " + ParamUtil.PM_ENABLE_PROCESS_TIMING + "[" + cacheValue + "]" ); - - } else if (param.getName() != null && param.getName().trim().equalsIgnoreCase(ParamUtil.CRC_ENABLE_UNITCD_CONVERSION)) { - paramUtil.putParam(projectId, securityType.getUsername(), securityType.getDomain(),ParamUtil.CRC_ENABLE_UNITCD_CONVERSION,param); - String unitCdCache = paramUtil.getParam(projectId, securityType.getUsername(), securityType.getDomain(),ParamUtil.CRC_ENABLE_UNITCD_CONVERSION); - logesapi.debug("CRC param stored in the cache Project Id [" + projectId + "] user [" + securityType.getUsername() + "] domain [" + securityType.getDomain() + "] " + ParamUtil.CRC_ENABLE_UNITCD_CONVERSION + "[" + unitCdCache + "]" ); - } - } - } - - } catch (AxisFault e) { - procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus.setValue("Could not connect to server"); - response = I2B2MessageResponseFactory.buildResponseMessage( - requestXml, procStatus, bodyType); - return response; - } catch (I2B2Exception e) { - procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus - .setValue("Message error connecting Project Management cell"); - response = I2B2MessageResponseFactory.buildResponseMessage( - requestXml, procStatus, bodyType); - return response; - } catch (JAXBUtilException e) { - procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus - .setValue("Message error from Project Management cell"); - response = I2B2MessageResponseFactory.buildResponseMessage( - requestXml, procStatus, bodyType); - return response; - } - - // check if the role is DATA_AGG to proceed - log.debug("check if the role is DATA_AGG to proceed"); - boolean errorFlag = false; - JAXBUnWrapHelper unWrapHelper = new JAXBUnWrapHelper(); - headerType = (PsmQryHeaderType) unWrapHelper - .getObjectByClass( - bodyType.getAny(), - edu.harvard.i2b2.crc.datavo.setfinder.query.PsmQryHeaderType.class); - BodyType responseBodyType = null; - if (headerType - .getRequestType() - .equals( - PsmRequestTypeType.CRC_QRY_GET_QUERY_MASTER_LIST_FROM_USER_ID)) { - GetQueryMasterListFromUserIdHandler handler = new GetQueryMasterListFromUserIdHandler( - requestXml); - responseBodyType = handler.execute(); - } else if (headerType - .getRequestType() - .equals( - PsmRequestTypeType.CRC_QRY_GET_QUERY_MASTER_LIST_FROM_GROUP_ID)) { - // check if user have right permission to access this request - if (projectType != null && projectType.getRole().size() > 0) { - if ((!projectType.getRole().contains("MANAGER"))) { - // Not authorized - procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus - .setValue("Authorization failure, should have MANAGER role"); - response = I2B2MessageResponseFactory - .buildResponseMessage(requestXml, procStatus, - bodyType); - return response; - } - } else { - // Not authorized - procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus - .setValue("Authorization failure, should have MANAGER role"); - response = I2B2MessageResponseFactory.buildResponseMessage( - requestXml, procStatus, bodyType); - return response; - } - - GetQueryMasterListFromGroupIdHandler handler = new GetQueryMasterListFromGroupIdHandler( - requestXml); - responseBodyType = handler.execute(); - } else if (headerType - .getRequestType() - .equals( - PsmRequestTypeType.CRC_QRY_RUN_QUERY_INSTANCE_FROM_QUERY_DEFINITION)) { - log.debug("Running in " + PsmRequestTypeType.CRC_QRY_RUN_QUERY_INSTANCE_FROM_QUERY_DEFINITION); - ParamType lockedParamType = null; - List paramList = projectType.getParam(); - for (ParamType paramType : paramList) { - if (paramType.getName().equals(EJBPMUtil.LOCKEDOUT)) { - lockedParamType = paramType; - break; - } - } - log.debug("Check if user is locked out"); - if (lockedParamType != null) { - // Not authorized - procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus - .setValue("LOCKEDOUT error: The user account is lockedout at [" - + lockedParamType.getValue() + "]"); - bodyType = new BodyType(); - response = I2B2MessageResponseFactory.buildResponseMessage( - requestXml, procStatus, bodyType); - return response; - } else { - RunQueryInstanceFromQueryDefinitionHandler handler = new RunQueryInstanceFromQueryDefinitionHandler( - requestXml); - responseBodyType = handler.execute(); - - // check if the response body type has lockedout error - if (handler.getLockedoutFlag()) { - procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus - .setValue("LOCKEDOUT error: The user account is lockedout at [" - + new Date(System.currentTimeMillis()) - + "]"); - response = I2B2MessageResponseFactory - .buildResponseMessage(requestXml, procStatus, - responseBodyType); - return response; - } - - //if (handler.getErrorFlag()) { - // errorFlag = true; - //} - - } - } else if (headerType - .getRequestType() - .equals( - PsmRequestTypeType.CRC_QRY_RUN_QUERY_INSTANCE_FROM_QUERY_MASTER_ID)) { - RunQueryInstanceFromQueryMasterHandler handler = new RunQueryInstanceFromQueryMasterHandler( - requestXml); - responseBodyType = handler.execute(); - } else if (headerType - .getRequestType() - .equals( - PsmRequestTypeType.CRC_QRY_GET_QUERY_RESULT_INSTANCE_LIST_FROM_QUERY_INSTANCE_ID)) { - GetQueryResultInstanceListFromQueryInstanceIdHandler handler = new GetQueryResultInstanceListFromQueryInstanceIdHandler( - requestXml, projectType.getRole()); - responseBodyType = handler.execute(); - } else if (headerType - .getRequestType() - .equals( - PsmRequestTypeType.CRC_QRY_GET_QUERY_INSTANCE_LIST_FROM_QUERY_MASTER_ID)) { - GetQueryInstanceListFromMasterIdHandler handler = new GetQueryInstanceListFromMasterIdHandler( - requestXml); - responseBodyType = handler.execute(); - } else if (headerType - .getRequestType() - .equals( - PsmRequestTypeType.CRC_QRY_GET_REQUEST_XML_FROM_QUERY_MASTER_ID)) { - GetRequestXmlFromQueryMasterIdHandler handler = new GetRequestXmlFromQueryMasterIdHandler( - requestXml); - responseBodyType = handler.execute(); - } else if (headerType.getRequestType().equals( - PsmRequestTypeType.CRC_QRY_DELETE_QUERY_MASTER)) { - DeleteQueryMasterHandler handler = new DeleteQueryMasterHandler( - requestXml); - logesapi.info("DELETE QUERY MASTER: " + requestXml); - responseBodyType = handler.execute(); - } else if (headerType.getRequestType().equals( - PsmRequestTypeType.CRC_QRY_RENAME_QUERY_MASTER)) { - RenameQueryMasterHandler handler = new RenameQueryMasterHandler( - requestXml); - responseBodyType = handler.execute(); - } else if (headerType - .getRequestType() - .equals( - PsmRequestTypeType.CRC_QRY_UPDATE_RESULT_INSTANCE_DESCRIPTION)) { - UpdateQueryResultInstanceDescriptionHandler handler = new UpdateQueryResultInstanceDescriptionHandler( - requestXml); - responseBodyType = handler.execute(); - } else if (headerType - .getRequestType() - .equals( - PsmRequestTypeType.CRC_QRY_GET_RESULT_DOCUMENT_FROM_RESULT_INSTANCE_ID)) { - GetXmlResultFromQueryResultIdHandler handler = new GetXmlResultFromQueryResultIdHandler( - requestXml); - responseBodyType = handler.execute(); - } else if (headerType.getRequestType().equals( - PsmRequestTypeType.CRC_QRY_GET_RESULT_TYPE)) { - GetAllQueryResultTypeHandler handler = new GetAllQueryResultTypeHandler( - requestXml, projectType.getRole()); - responseBodyType = handler.execute(); - } else if (headerType - .getRequestType() - .equals( - PsmRequestTypeType.CRC_QRY_RUN_QUERY_INSTANCE_FROM_ANALYSIS_DEFINITION)) { - - RunQueryInstanceFromAnalysisDefinitionHandler handler = new RunQueryInstanceFromAnalysisDefinitionHandler( - requestXml); - responseBodyType = handler.execute(); - - } else if (headerType.getRequestType().equals( - PsmRequestTypeType.CRC_QRY_CANCEL_QUERY)) { - CancelQueryInstanceHandler handler = new CancelQueryInstanceHandler( - requestXml); - responseBodyType = handler.execute(); - } else if (headerType.getRequestType().equals( - PsmRequestTypeType.CRC_QRY_UPDATE_QUERY_INSTANCE_MESSAGE)) { - - boolean isManager = false; - if (projectType != null && projectType.getRole().size() > 0 && projectType.getRole().contains("MANAGER")) - isManager = true; - - UpdateQueryInstanceMessageHandler handler = new UpdateQueryInstanceMessageHandler( - requestXml, isManager, projectType.getUserName()); - responseBodyType = handler.execute(); - } else if (headerType.getRequestType().equals( - PsmRequestTypeType.CRC_QRY_RUN_EXPORT_FROM_QUERY_INSTANCE_ID)) { - - - RunExportFromQueryInstanceHandler handler = new RunExportFromQueryInstanceHandler( - requestXml); - responseBodyType = handler.execute(); - - - - } else if (headerType.getRequestType().equals( - PsmRequestTypeType.CRC_QRY_UPDATE_QUERY_INSTANCE_STATUS)) { - boolean isManager = false; - if (projectType != null && projectType.getRole().size() > 0 && projectType.getRole().contains("MANAGER")) - isManager = true; - - SetQueryInstanceStatusHandler handler = new SetQueryInstanceStatusHandler( - requestXml, isManager, projectType.getUserName()); - responseBodyType = handler.execute(); - } else if (headerType.getRequestType().equals( - PsmRequestTypeType.CRC_QRY_GET_ANALYSIS_PLUGIN_METADATA)) { - GetAnalysisPluginMetadataTypeHandler handler = new GetAnalysisPluginMetadataTypeHandler( - requestXml); - responseBodyType = handler.execute(); - - } else if (headerType.getRequestType().equals( - PsmRequestTypeType.CRC_QUARTZ_GET_JOB)) { - GetQuartzJobHandler handler = new GetQuartzJobHandler( - requestXml); - responseBodyType = handler.execute(); - } else if (headerType.getRequestType().equals( - PsmRequestTypeType.CRC_QUARTZ_SET_JOB)) { - SetJobHandlerMaybe handler = new SetJobHandlerMaybe( - requestXml); - responseBodyType = handler.execute(); - // } else if (headerType.getRequestType().equals( - // PsmRequestTypeType.CRC_QUARTZ_GET_ALL_JOB)) { - // GetAllJobsHandler handler = new GetAllJobsHandler( - // requestXml); - // responseBodyType = handler.execute(); - } else if (headerType.getRequestType().equals( - PsmRequestTypeType.CRC_QUARTZ_DELETE_JOB)) { - GetAnalysisPluginMetadataTypeHandler handler = new GetAnalysisPluginMetadataTypeHandler( - requestXml); - responseBodyType = handler.execute(); - } - - procStatus = new StatusType(); - if (errorFlag == false) { - procStatus.setType("DONE"); - procStatus.setValue("DONE"); - } else { - procStatus.setType("ERROR"); - procStatus.setValue("ERROR"); - } - - response = I2B2MessageResponseFactory.buildResponseMessage( - requestXml, procStatus, responseBodyType); - - } catch (JAXBUtilException e) { - log.error("JAXBUtilException", e); - StatusType procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus.setValue(requestXml + "\n\n" - + StackTraceUtil.getStackTrace(e)); - try { - response = I2B2MessageResponseFactory.buildResponseMessage( - null, procStatus, null); - } catch (JAXBUtilException e1) { - e1.printStackTrace(); - } - // throw new I2B2Exception("JAXBUtil exception",e); - } catch (I2B2Exception e) { - log.error("I2B2Exception", e); - StatusType procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus.setValue(StackTraceUtil.getStackTrace(e)); - try { - response = I2B2MessageResponseFactory.buildResponseMessage( - requestXml, procStatus, null); - } catch (JAXBUtilException e1) { - e1.printStackTrace(); - } - } catch (Throwable e) { - log.error("Throwable", e); - StatusType procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus.setValue(StackTraceUtil.getStackTrace(e)); - try { - response = I2B2MessageResponseFactory.buildResponseMessage( - requestXml, procStatus, null); - } catch (JAXBUtilException e1) { - e1.printStackTrace(); - } - } - - return response; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.delegate.setfinder; + +import java.util.Date; +import java.util.List; + +import jakarta.xml.bind.JAXBElement; + +import org.apache.axis2.AxisFault; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.exception.StackTraceUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.dao.setfinder.QueryMasterSpringDao; +import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; +import edu.harvard.i2b2.crc.datavo.I2B2MessageResponseFactory; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; +import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; +import edu.harvard.i2b2.crc.datavo.pm.ParamType; +import edu.harvard.i2b2.crc.datavo.pm.ProjectType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.PsmQryHeaderType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.PsmRequestTypeType; +import edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate; +import edu.harvard.i2b2.crc.delegate.ejbpm.EJBPMUtil; +import edu.harvard.i2b2.crc.delegate.pm.PMServiceDriver; +import edu.harvard.i2b2.crc.delegate.quartz.GetQuartzJobHandler; +import edu.harvard.i2b2.crc.delegate.quartz.GetAllJobsHandler; +import edu.harvard.i2b2.crc.delegate.quartz.SetJobHandlerMaybe; +import edu.harvard.i2b2.crc.util.CacheUtil; +import edu.harvard.i2b2.crc.util.LogTimingUtil; +import edu.harvard.i2b2.crc.util.ParamUtil; + +/** + * Setfinder query request delegate class $Id: QueryRequestDelegate.java,v 1.17 + * 2008/05/08 15:13:45 rk903 Exp $ + * + * @author rkuttan + */ +public class QueryRequestDelegate extends RequestHandlerDelegate { + + /** log **/ + protected final Log log = LogFactory.getLog(getClass()); + + protected final Log logesapi = LogFactory.getLog(getClass()); + + /** + * @see edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate#handleRequest(java.lang.String) + */ + @Override + public String handleRequest(String requestXml) throws I2B2Exception { + PsmQryHeaderType headerType = null; + String response = null; + JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); + + try { + JAXBElement jaxbElement = jaxbUtil.unMashallFromString(requestXml); + + if (jaxbElement == null) { + throw new I2B2Exception("Request is null after unmashall" + + requestXml); + } + + RequestMessageType requestMessageType = (RequestMessageType) jaxbElement + .getValue(); + BodyType bodyType = requestMessageType.getMessageBody(); + + if (bodyType == null) { + log.error("null value in body type"); + throw new I2B2Exception("null value in body type"); + } + // Call PM cell to validate user + ProjectType projectType = null; + StatusType procStatus = null; + try { + SecurityType securityType = null; + String projectId = null; + if (requestMessageType.getMessageHeader() != null) { + if (requestMessageType.getMessageHeader().getSecurity() != null) { + securityType = requestMessageType.getMessageHeader() + .getSecurity(); + } + projectId = requestMessageType.getMessageHeader() + .getProjectId(); + } + if (securityType == null) { + procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus + .setValue("Request message missing user/password"); + response = I2B2MessageResponseFactory.buildResponseMessage( + requestXml, procStatus, bodyType); + return response; + } + + // String pmResponse = + // PMServiceDriver.checkValidUser(securityType); + PMServiceDriver pmServiceDriver = new PMServiceDriver(); + projectType = pmServiceDriver.checkValidUser(securityType, + projectId); + + if (projectType == null) { + procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus + .setValue("Invalid user/password for the given project[" + + projectId + "]"); + response = I2B2MessageResponseFactory.buildResponseMessage( + requestXml, procStatus, bodyType); + return response; + } + + log.debug("project name from PM " + projectType.getName()); + logesapi.debug("project id from PM " + projectType.getId()); + + + if (projectType.getRole() != null) { + log.debug("project role from PM " + + projectType.getRole().get(0)); + + this.putRoles(projectId, securityType.getUsername(), + securityType.getDomain(), projectType.getRole()); + + //TODO removed cache + // Node rootNode = CacheUtil.getCache().getRoot(); + //List roles = (List) rootNode + // .get(securityType.getDomain() + "/" + projectId + // + "/" + securityType.getUsername()); + List roles = (List) CacheUtil + .get(securityType.getDomain() + "/" + projectId + + "/" + securityType.getUsername()); + if (roles != null) { + log.debug("User Roles count " + roles.size()); + } + } else { + log.error("Project role not set for the user "); + + } + + //check if process_timing_flag is set + log.debug("check if process_timing_flag is set"); + LogTimingUtil.clearPocessTiming(projectId, securityType.getUsername(), securityType.getDomain()); + ParamUtil paramUtil = new ParamUtil(); + paramUtil.clearParam(projectId, securityType.getUsername(), securityType.getDomain(), ParamUtil.CRC_ENABLE_UNITCD_CONVERSION); + if (projectType.getParam() != null) { + for (ParamType param : projectType.getParam()) { + if (param.getName() != null && param.getName().trim().equalsIgnoreCase(LogTimingUtil.PM_ENABLE_PROCESS_TIMING)) { + //this.putPocessTiming(projectId, securityType.getUsername(), securityType.getDomain(), param); + LogTimingUtil.putPocessTiming(projectId, securityType.getUsername(), securityType.getDomain(), param); + String cacheValue = LogTimingUtil.getPocessTiming(projectId, securityType.getUsername(), securityType.getDomain()); + logesapi.debug("CRC param stored in the cache Project Id [" + projectId + "] user [" + securityType.getUsername() + "] domain [" + securityType.getDomain() + "] " + ParamUtil.PM_ENABLE_PROCESS_TIMING + "[" + cacheValue + "]" ); + + } else if (param.getName() != null && param.getName().trim().equalsIgnoreCase(ParamUtil.CRC_ENABLE_UNITCD_CONVERSION)) { + paramUtil.putParam(projectId, securityType.getUsername(), securityType.getDomain(),ParamUtil.CRC_ENABLE_UNITCD_CONVERSION,param); + String unitCdCache = paramUtil.getParam(projectId, securityType.getUsername(), securityType.getDomain(),ParamUtil.CRC_ENABLE_UNITCD_CONVERSION); + logesapi.debug("CRC param stored in the cache Project Id [" + projectId + "] user [" + securityType.getUsername() + "] domain [" + securityType.getDomain() + "] " + ParamUtil.CRC_ENABLE_UNITCD_CONVERSION + "[" + unitCdCache + "]" ); + } + } + } + + } catch (AxisFault e) { + procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus.setValue("Could not connect to server"); + response = I2B2MessageResponseFactory.buildResponseMessage( + requestXml, procStatus, bodyType); + return response; + } catch (I2B2Exception e) { + procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus + .setValue("Message error connecting Project Management cell"); + response = I2B2MessageResponseFactory.buildResponseMessage( + requestXml, procStatus, bodyType); + return response; + } catch (JAXBUtilException e) { + procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus + .setValue("Message error from Project Management cell"); + response = I2B2MessageResponseFactory.buildResponseMessage( + requestXml, procStatus, bodyType); + return response; + } + + // check if the role is DATA_AGG to proceed + log.debug("check if the role is DATA_AGG to proceed"); + boolean errorFlag = false; + JAXBUnWrapHelper unWrapHelper = new JAXBUnWrapHelper(); + headerType = (PsmQryHeaderType) unWrapHelper + .getObjectByClass( + bodyType.getAny(), + edu.harvard.i2b2.crc.datavo.setfinder.query.PsmQryHeaderType.class); + BodyType responseBodyType = null; + if (headerType + .getRequestType() + .equals( + PsmRequestTypeType.CRC_QRY_GET_QUERY_MASTER_LIST_FROM_USER_ID)) { + GetQueryMasterListFromUserIdHandler handler = new GetQueryMasterListFromUserIdHandler( + requestXml); + responseBodyType = handler.execute(); + } else if (headerType + .getRequestType() + .equals( + PsmRequestTypeType.CRC_QRY_GET_QUERY_MASTER_LIST_FROM_GROUP_ID)) { + // check if user have right permission to access this request + if (projectType != null && projectType.getRole().size() > 0) { + if ((!projectType.getRole().contains("MANAGER"))) { + // Not authorized + procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus + .setValue("Authorization failure, should have MANAGER role"); + response = I2B2MessageResponseFactory + .buildResponseMessage(requestXml, procStatus, + bodyType); + return response; + } + } else { + // Not authorized + procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus + .setValue("Authorization failure, should have MANAGER role"); + response = I2B2MessageResponseFactory.buildResponseMessage( + requestXml, procStatus, bodyType); + return response; + } + + GetQueryMasterListFromGroupIdHandler handler = new GetQueryMasterListFromGroupIdHandler( + requestXml); + responseBodyType = handler.execute(); + } else if (headerType + .getRequestType() + .equals( + PsmRequestTypeType.CRC_QRY_RUN_QUERY_INSTANCE_FROM_QUERY_DEFINITION)) { + log.debug("Running in " + PsmRequestTypeType.CRC_QRY_RUN_QUERY_INSTANCE_FROM_QUERY_DEFINITION); + ParamType lockedParamType = null; + List paramList = projectType.getParam(); + for (ParamType paramType : paramList) { + if (paramType.getName().equals(EJBPMUtil.LOCKEDOUT)) { + lockedParamType = paramType; + break; + } + } + log.debug("Check if user is locked out"); + if (lockedParamType != null) { + // Not authorized + procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus + .setValue("LOCKEDOUT error: The user account is lockedout at [" + + lockedParamType.getValue() + "]"); + bodyType = new BodyType(); + response = I2B2MessageResponseFactory.buildResponseMessage( + requestXml, procStatus, bodyType); + return response; + } else { + RunQueryInstanceFromQueryDefinitionHandler handler = new RunQueryInstanceFromQueryDefinitionHandler( + requestXml); + responseBodyType = handler.execute(); + + // check if the response body type has lockedout error + if (handler.getLockedoutFlag()) { + procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus + .setValue("LOCKEDOUT error: The user account is lockedout at [" + + new Date(System.currentTimeMillis()) + + "]"); + response = I2B2MessageResponseFactory + .buildResponseMessage(requestXml, procStatus, + responseBodyType); + return response; + } + + //if (handler.getErrorFlag()) { + // errorFlag = true; + //} + + } + } else if (headerType + .getRequestType() + .equals( + PsmRequestTypeType.CRC_QRY_RUN_QUERY_INSTANCE_FROM_QUERY_MASTER_ID)) { + RunQueryInstanceFromQueryMasterHandler handler = new RunQueryInstanceFromQueryMasterHandler( + requestXml); + responseBodyType = handler.execute(); + } else if (headerType + .getRequestType() + .equals( + PsmRequestTypeType.CRC_QRY_GET_QUERY_RESULT_INSTANCE_LIST_FROM_QUERY_INSTANCE_ID)) { + GetQueryResultInstanceListFromQueryInstanceIdHandler handler = new GetQueryResultInstanceListFromQueryInstanceIdHandler( + requestXml, projectType.getRole()); + responseBodyType = handler.execute(); + } else if (headerType + .getRequestType() + .equals( + PsmRequestTypeType.CRC_QRY_GET_QUERY_INSTANCE_LIST_FROM_QUERY_MASTER_ID)) { + GetQueryInstanceListFromMasterIdHandler handler = new GetQueryInstanceListFromMasterIdHandler( + requestXml); + responseBodyType = handler.execute(); + } else if (headerType + .getRequestType() + .equals( + PsmRequestTypeType.CRC_QRY_GET_REQUEST_XML_FROM_QUERY_MASTER_ID)) { + GetRequestXmlFromQueryMasterIdHandler handler = new GetRequestXmlFromQueryMasterIdHandler( + requestXml); + responseBodyType = handler.execute(); + } else if (headerType.getRequestType().equals( + PsmRequestTypeType.CRC_QRY_DELETE_QUERY_MASTER)) { + DeleteQueryMasterHandler handler = new DeleteQueryMasterHandler( + requestXml); + logesapi.info("DELETE QUERY MASTER: " + requestXml); + responseBodyType = handler.execute(); + } else if (headerType.getRequestType().equals( + PsmRequestTypeType.CRC_QRY_RENAME_QUERY_MASTER)) { + RenameQueryMasterHandler handler = new RenameQueryMasterHandler( + requestXml); + responseBodyType = handler.execute(); + } else if (headerType + .getRequestType() + .equals( + PsmRequestTypeType.CRC_QRY_UPDATE_RESULT_INSTANCE_DESCRIPTION)) { + UpdateQueryResultInstanceDescriptionHandler handler = new UpdateQueryResultInstanceDescriptionHandler( + requestXml); + responseBodyType = handler.execute(); + } else if (headerType + .getRequestType() + .equals( + PsmRequestTypeType.CRC_QRY_GET_RESULT_DOCUMENT_FROM_RESULT_INSTANCE_ID)) { + GetXmlResultFromQueryResultIdHandler handler = new GetXmlResultFromQueryResultIdHandler( + requestXml); + responseBodyType = handler.execute(); + } else if (headerType.getRequestType().equals( + PsmRequestTypeType.CRC_QRY_GET_RESULT_TYPE)) { + GetAllQueryResultTypeHandler handler = new GetAllQueryResultTypeHandler( + requestXml, projectType.getRole()); + responseBodyType = handler.execute(); + } else if (headerType + .getRequestType() + .equals( + PsmRequestTypeType.CRC_QRY_RUN_QUERY_INSTANCE_FROM_ANALYSIS_DEFINITION)) { + + RunQueryInstanceFromAnalysisDefinitionHandler handler = new RunQueryInstanceFromAnalysisDefinitionHandler( + requestXml); + responseBodyType = handler.execute(); + + } else if (headerType.getRequestType().equals( + PsmRequestTypeType.CRC_QRY_CANCEL_QUERY)) { + CancelQueryInstanceHandler handler = new CancelQueryInstanceHandler( + requestXml); + responseBodyType = handler.execute(); + } else if (headerType.getRequestType().equals( + PsmRequestTypeType.CRC_QRY_UPDATE_QUERY_INSTANCE_MESSAGE)) { + + boolean isManager = false; + if (projectType != null && projectType.getRole().size() > 0 && projectType.getRole().contains("MANAGER")) + isManager = true; + + UpdateQueryInstanceMessageHandler handler = new UpdateQueryInstanceMessageHandler( + requestXml, isManager, projectType.getUserName()); + responseBodyType = handler.execute(); + } else if (headerType.getRequestType().equals( + PsmRequestTypeType.CRC_QRY_RUN_EXPORT_FROM_QUERY_INSTANCE_ID)) { + + + RunExportFromQueryInstanceHandler handler = new RunExportFromQueryInstanceHandler( + requestXml); + responseBodyType = handler.execute(); + + + + } else if (headerType.getRequestType().equals( + PsmRequestTypeType.CRC_QRY_UPDATE_QUERY_INSTANCE_STATUS)) { + boolean isManager = false; + if (projectType != null && projectType.getRole().size() > 0 && projectType.getRole().contains("MANAGER")) + isManager = true; + + SetQueryInstanceStatusHandler handler = new SetQueryInstanceStatusHandler( + requestXml, isManager, projectType.getUserName()); + responseBodyType = handler.execute(); + } else if (headerType.getRequestType().equals( + PsmRequestTypeType.CRC_QRY_GET_ANALYSIS_PLUGIN_METADATA)) { + GetAnalysisPluginMetadataTypeHandler handler = new GetAnalysisPluginMetadataTypeHandler( + requestXml); + responseBodyType = handler.execute(); + + } else if (headerType.getRequestType().equals( + PsmRequestTypeType.CRC_QUARTZ_GET_JOB)) { + GetQuartzJobHandler handler = new GetQuartzJobHandler( + requestXml); + responseBodyType = handler.execute(); + } else if (headerType.getRequestType().equals( + PsmRequestTypeType.CRC_QUARTZ_SET_JOB)) { + SetJobHandlerMaybe handler = new SetJobHandlerMaybe( + requestXml); + responseBodyType = handler.execute(); + // } else if (headerType.getRequestType().equals( + // PsmRequestTypeType.CRC_QUARTZ_GET_ALL_JOB)) { + // GetAllJobsHandler handler = new GetAllJobsHandler( + // requestXml); + // responseBodyType = handler.execute(); + } else if (headerType.getRequestType().equals( + PsmRequestTypeType.CRC_QUARTZ_DELETE_JOB)) { + GetAnalysisPluginMetadataTypeHandler handler = new GetAnalysisPluginMetadataTypeHandler( + requestXml); + responseBodyType = handler.execute(); + } + + procStatus = new StatusType(); + if (errorFlag == false) { + procStatus.setType("DONE"); + procStatus.setValue("DONE"); + } else { + procStatus.setType("ERROR"); + procStatus.setValue("ERROR"); + } + + response = I2B2MessageResponseFactory.buildResponseMessage( + requestXml, procStatus, responseBodyType); + + } catch (JAXBUtilException e) { + log.error("JAXBUtilException", e); + StatusType procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus.setValue(requestXml + "\n\n" + + StackTraceUtil.getStackTrace(e)); + try { + response = I2B2MessageResponseFactory.buildResponseMessage( + null, procStatus, null); + } catch (JAXBUtilException e1) { + e1.printStackTrace(); + } + // throw new I2B2Exception("JAXBUtil exception",e); + } catch (I2B2Exception e) { + log.error("I2B2Exception", e); + StatusType procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus.setValue(StackTraceUtil.getStackTrace(e)); + try { + response = I2B2MessageResponseFactory.buildResponseMessage( + requestXml, procStatus, null); + } catch (JAXBUtilException e1) { + e1.printStackTrace(); + } + } catch (Throwable e) { + log.error("Throwable", e); + StatusType procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus.setValue(StackTraceUtil.getStackTrace(e)); + try { + response = I2B2MessageResponseFactory.buildResponseMessage( + requestXml, procStatus, null); + } catch (JAXBUtilException e1) { + e1.printStackTrace(); + } + } + + return response; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/RenameQueryMasterHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/RenameQueryMasterHandler.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/RenameQueryMasterHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/RenameQueryMasterHandler.java index fb6d01f2..b617b1ff --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/RenameQueryMasterHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/RenameQueryMasterHandler.java @@ -1,102 +1,102 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.delegate.setfinder; - - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterRenameRequestType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterResponseType; -import edu.harvard.i2b2.crc.delegate.RequestHandler; -import edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate; -import edu.harvard.i2b2.crc.ejb.QueryInfoBean; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - - -/** - * RenameQueryMasterHandler class - * implements execute method - * $Id: RenameQueryMasterHandler.java,v 1.8 2008/03/19 22:36:37 rk903 Exp $ - * @author rkuttan - */ -public class RenameQueryMasterHandler extends RequestHandler { - private MasterRenameRequestType masterRenameRequestType = null; - - - /** - * Constuctor which accepts i2b2 request message xml - * @param requestXml - * @throws I2B2Exception - */ - public RenameQueryMasterHandler(String requestXml) - throws I2B2Exception { - try { - masterRenameRequestType = (MasterRenameRequestType) this.getRequestType(requestXml, - edu.harvard.i2b2.crc.datavo.setfinder.query.MasterRenameRequestType.class); - this.setDataSourceLookup(requestXml); - } catch (JAXBUtilException jaxbUtilEx) { - throw new I2B2Exception("Error ", jaxbUtilEx); - } - } - - /** - * Perform operation for the given request - * using business class(ejb) and return response - * @see edu.harvard.i2b2.crc.delegate.RequestHandler#execute() - */ - @Override - public BodyType execute() { - // call ejb and pass input object - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - ResponseMessageType responseMessageType = new ResponseMessageType(); - StatusType statusType = null; - String responseString = null; - BodyType bodyType = new BodyType(); - MasterResponseType masterResponseType = null; - try { - //TODO removed ejbs - // QueryInfoLocalHome queryInfoLocalHome = qpUtil.getQueryInfoLocalHome(); - // QueryInfoLocal queryInfoLocal = queryInfoLocalHome.create(); - String userId = masterRenameRequestType.getUserId(); - String masterId = masterRenameRequestType.getQueryMasterId(); - String newQueryName = masterRenameRequestType.getQueryName().replaceAll("\\<[^>]*>",""); - QueryInfoBean query = new QueryInfoBean(); - masterResponseType = query.renameQueryMaster(this.getDataSourceLookup(),userId, - masterId, newQueryName); - masterResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.DONE_TYPE, "DONE")); - - } catch (Exception e) { - masterResponseType = new MasterResponseType(); - masterResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.ERROR_TYPE, e.getMessage())); - } finally { - edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); - bodyType.getAny().add(of.createResponse(masterResponseType)); - - } - return bodyType; - } - - //function to build StatusType for the given message - private StatusType buildStatusType(String statusTypeString, String message) { - StatusType statusType = new StatusType(); - statusType.setType(statusTypeString); - statusType.setValue(message); - - return statusType; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.delegate.setfinder; + + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterRenameRequestType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterResponseType; +import edu.harvard.i2b2.crc.delegate.RequestHandler; +import edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate; +import edu.harvard.i2b2.crc.ejb.QueryInfoBean; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + + +/** + * RenameQueryMasterHandler class + * implements execute method + * $Id: RenameQueryMasterHandler.java,v 1.8 2008/03/19 22:36:37 rk903 Exp $ + * @author rkuttan + */ +public class RenameQueryMasterHandler extends RequestHandler { + private MasterRenameRequestType masterRenameRequestType = null; + + + /** + * Constuctor which accepts i2b2 request message xml + * @param requestXml + * @throws I2B2Exception + */ + public RenameQueryMasterHandler(String requestXml) + throws I2B2Exception { + try { + masterRenameRequestType = (MasterRenameRequestType) this.getRequestType(requestXml, + edu.harvard.i2b2.crc.datavo.setfinder.query.MasterRenameRequestType.class); + this.setDataSourceLookup(requestXml); + } catch (JAXBUtilException jaxbUtilEx) { + throw new I2B2Exception("Error ", jaxbUtilEx); + } + } + + /** + * Perform operation for the given request + * using business class(ejb) and return response + * @see edu.harvard.i2b2.crc.delegate.RequestHandler#execute() + */ + @Override + public BodyType execute() { + // call ejb and pass input object + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + ResponseMessageType responseMessageType = new ResponseMessageType(); + StatusType statusType = null; + String responseString = null; + BodyType bodyType = new BodyType(); + MasterResponseType masterResponseType = null; + try { + //TODO removed ejbs + // QueryInfoLocalHome queryInfoLocalHome = qpUtil.getQueryInfoLocalHome(); + // QueryInfoLocal queryInfoLocal = queryInfoLocalHome.create(); + String userId = masterRenameRequestType.getUserId(); + String masterId = masterRenameRequestType.getQueryMasterId(); + String newQueryName = masterRenameRequestType.getQueryName().replaceAll("\\<[^>]*>",""); + QueryInfoBean query = new QueryInfoBean(); + masterResponseType = query.renameQueryMaster(this.getDataSourceLookup(),userId, + masterId, newQueryName); + masterResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.DONE_TYPE, "DONE")); + + } catch (Exception e) { + masterResponseType = new MasterResponseType(); + masterResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.ERROR_TYPE, e.getMessage())); + } finally { + edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); + bodyType.getAny().add(of.createResponse(masterResponseType)); + + } + return bodyType; + } + + //function to build StatusType for the given message + private StatusType buildStatusType(String statusTypeString, String message) { + StatusType statusType = new StatusType(); + statusType.setType(statusTypeString); + statusType.setValue(message); + + return statusType; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/RunExportFromQueryInstanceHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/RunExportFromQueryInstanceHandler.java similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/RunExportFromQueryInstanceHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/RunExportFromQueryInstanceHandler.java index 591d8e6b..0d7f3a52 100644 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/RunExportFromQueryInstanceHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/RunExportFromQueryInstanceHandler.java @@ -1,130 +1,130 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.delegate.setfinder; - -import java.util.List; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.dao.IDAOFactory; -import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; -import edu.harvard.i2b2.crc.dao.setfinder.IQueryInstanceDao; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceMessageRequestType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceResultResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterInstanceResultResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.PsmQryHeaderType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionRequestType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryInstanceType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryResultInstanceType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryStatusTypeType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.StatusType; -import edu.harvard.i2b2.crc.delegate.RequestHandler; -import edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate; -import edu.harvard.i2b2.crc.ejb.QueryManagerBean; -import edu.harvard.i2b2.crc.ejb.QueryManagerBeanUtil; -import edu.harvard.i2b2.crc.ejb.role.PriviledgeLocal; -import edu.harvard.i2b2.crc.util.CacheUtil; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - -/** - * RunQueryInstanceFromQueryDefinitionHandler class implements execute method - * $Id: RunQueryInstanceFromQueryDefinitionHandler.java,v 1.6 2008/03/19 - * 22:36:37 rk903 Exp $ - * - * @author rkuttan - */ -public class RunExportFromQueryInstanceHandler extends RequestHandler { - private InstanceMessageRequestType instanceMessageRequestType = null; - private PsmQryHeaderType headerType = null; - - - String requestXml = null; - //boolean lockedoutFlag = false - boolean errorFlag = false; - protected final Log logesapi = LogFactory.getLog(getClass()); - - /** - * Constuctor which accepts i2b2 request message xml - * - * @param requestXml - * @throws I2B2Exception - */ - public RunExportFromQueryInstanceHandler(String requestXml) - throws I2B2Exception { - try { - instanceMessageRequestType = (InstanceMessageRequestType) this.getRequestType(requestXml, - edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceMessageRequestType.class); - headerType = (PsmQryHeaderType) this.getRequestType(requestXml, - edu.harvard.i2b2.crc.datavo.setfinder.query.PsmQryHeaderType.class); - this.requestXml = requestXml; - this.setDataSourceLookup(requestXml); - } catch (JAXBUtilException jaxbUtilEx) { - throw new I2B2Exception("Error ", jaxbUtilEx); - } - } - - /** - * Perform operation for the given request using business class(ejb) and - * return response - * - * @throws I2B2Exception - * @see edu.harvard.i2b2.crc.delegate.RequestHandler#execute() - */ - @Override public BodyType execute() throws I2B2Exception { - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - String response = null; - BodyType bodyType = new BodyType(); - InstanceResponseType masterResponseType = null; - try { - //get userId and timeout from request xml - RequestMessageType requestMessageType = getI2B2RequestMessageType(requestXml); - long timeout = requestMessageType.getRequestHeader() - .getResultWaittimeMs(); - String userId = headerType.getUser().getLogin(); - String instanceId = instanceMessageRequestType.getQueryInstanceId(); - - //TODO removed ejbs -// QueryManagerLocalHome queryManagerLocalHome = qpUtil.getQueryManagerLocalHome(); - // QueryManagerLocal queryManagerLocal = queryManagerLocalHome.create(); - QueryManagerBean query = new QueryManagerBean(); - query.runExportQueryInstance(this.getDataSourceLookup(),userId, - instanceId, requestXml); - masterResponseType = new InstanceResponseType(); - masterResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.DONE_TYPE, "DONE")); - } catch (Exception e) { - masterResponseType = new InstanceResponseType(); - masterResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.ERROR_TYPE, e.getMessage())); - } finally { - edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); - bodyType.getAny().add(of.createResponse(masterResponseType)); - - } - return bodyType; - } - - - - public boolean getErrorFlag() { - return errorFlag; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.delegate.setfinder; + +import java.util.List; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.dao.IDAOFactory; +import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; +import edu.harvard.i2b2.crc.dao.setfinder.IQueryInstanceDao; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceMessageRequestType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceResultResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterInstanceResultResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.PsmQryHeaderType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionRequestType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryInstanceType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryResultInstanceType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryStatusTypeType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.StatusType; +import edu.harvard.i2b2.crc.delegate.RequestHandler; +import edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate; +import edu.harvard.i2b2.crc.ejb.QueryManagerBean; +import edu.harvard.i2b2.crc.ejb.QueryManagerBeanUtil; +import edu.harvard.i2b2.crc.ejb.role.PriviledgeLocal; +import edu.harvard.i2b2.crc.util.CacheUtil; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + +/** + * RunQueryInstanceFromQueryDefinitionHandler class implements execute method + * $Id: RunQueryInstanceFromQueryDefinitionHandler.java,v 1.6 2008/03/19 + * 22:36:37 rk903 Exp $ + * + * @author rkuttan + */ +public class RunExportFromQueryInstanceHandler extends RequestHandler { + private InstanceMessageRequestType instanceMessageRequestType = null; + private PsmQryHeaderType headerType = null; + + + String requestXml = null; + //boolean lockedoutFlag = false + boolean errorFlag = false; + protected final Log logesapi = LogFactory.getLog(getClass()); + + /** + * Constuctor which accepts i2b2 request message xml + * + * @param requestXml + * @throws I2B2Exception + */ + public RunExportFromQueryInstanceHandler(String requestXml) + throws I2B2Exception { + try { + instanceMessageRequestType = (InstanceMessageRequestType) this.getRequestType(requestXml, + edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceMessageRequestType.class); + headerType = (PsmQryHeaderType) this.getRequestType(requestXml, + edu.harvard.i2b2.crc.datavo.setfinder.query.PsmQryHeaderType.class); + this.requestXml = requestXml; + this.setDataSourceLookup(requestXml); + } catch (JAXBUtilException jaxbUtilEx) { + throw new I2B2Exception("Error ", jaxbUtilEx); + } + } + + /** + * Perform operation for the given request using business class(ejb) and + * return response + * + * @throws I2B2Exception + * @see edu.harvard.i2b2.crc.delegate.RequestHandler#execute() + */ + @Override public BodyType execute() throws I2B2Exception { + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + String response = null; + BodyType bodyType = new BodyType(); + InstanceResponseType masterResponseType = null; + try { + //get userId and timeout from request xml + RequestMessageType requestMessageType = getI2B2RequestMessageType(requestXml); + long timeout = requestMessageType.getRequestHeader() + .getResultWaittimeMs(); + String userId = headerType.getUser().getLogin(); + String instanceId = instanceMessageRequestType.getQueryInstanceId(); + + //TODO removed ejbs +// QueryManagerLocalHome queryManagerLocalHome = qpUtil.getQueryManagerLocalHome(); + // QueryManagerLocal queryManagerLocal = queryManagerLocalHome.create(); + QueryManagerBean query = new QueryManagerBean(); + query.runExportQueryInstance(this.getDataSourceLookup(),userId, + instanceId, requestXml); + masterResponseType = new InstanceResponseType(); + masterResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.DONE_TYPE, "DONE")); + } catch (Exception e) { + masterResponseType = new InstanceResponseType(); + masterResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.ERROR_TYPE, e.getMessage())); + } finally { + edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); + bodyType.getAny().add(of.createResponse(masterResponseType)); + + } + return bodyType; + } + + + + public boolean getErrorFlag() { + return errorFlag; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/RunQueryInstanceFromAnalysisDefinitionHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/RunQueryInstanceFromAnalysisDefinitionHandler.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/RunQueryInstanceFromAnalysisDefinitionHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/RunQueryInstanceFromAnalysisDefinitionHandler.java index 4196c94e..1d6a72d8 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/RunQueryInstanceFromAnalysisDefinitionHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/RunQueryInstanceFromAnalysisDefinitionHandler.java @@ -1,106 +1,106 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.delegate.setfinder; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.dao.IDAOFactory; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.AnalysisDefinitionRequestType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterInstanceResultResponseType; -import edu.harvard.i2b2.crc.delegate.RequestHandler; -import edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate; -import edu.harvard.i2b2.crc.ejb.analysis.StartAnalysis; -import edu.harvard.i2b2.crc.ejb.analysis.StartAnalysisLocal; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - -/** - * RunQueryInstanceFromQueryDefinitionHandler class implements execute method - * $Id: RunQueryInstanceFromQueryDefinitionHandler.java,v 1.6 2008/03/19 - * 22:36:37 rk903 Exp $ - * - * @author rkuttan - */ -public class RunQueryInstanceFromAnalysisDefinitionHandler extends - RequestHandler { - AnalysisDefinitionRequestType analysisDefRequestType = null; - String requestXml = null; - - /** - * Constuctor which accepts i2b2 request message xml - * - * @param requestXml - * @throws I2B2Exception - */ - public RunQueryInstanceFromAnalysisDefinitionHandler(String requestXml) - throws I2B2Exception { - try { - analysisDefRequestType = (AnalysisDefinitionRequestType) getRequestType( - requestXml, - edu.harvard.i2b2.crc.datavo.setfinder.query.AnalysisDefinitionRequestType.class); - this.requestXml = requestXml; - this.setDataSourceLookup(requestXml); - } catch (JAXBUtilException jaxbUtilEx) { - throw new I2B2Exception("Error ", jaxbUtilEx); - } - } - - /** - * Perform operation for the given request using business class(ejb) and - * return response - * - * @throws I2B2Exception - * @see edu.harvard.i2b2.crc.delegate.RequestHandler#execute() - */ - @Override - public BodyType execute() throws I2B2Exception { - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - String response = null; - BodyType bodyType = new BodyType(); - MasterInstanceResultResponseType masterInstanceResponse = null; - try { - //StartAnalysisLocal startAnalysisLocal = qpUtil - // .getStartAnalysisLocal(); - - StartAnalysisLocal startAnalysisLocal = new StartAnalysis(); - - DAOFactoryHelper daoFactoryHelper = new DAOFactoryHelper(this - .getDataSourceLookup().getDomainId(), getDataSourceLookup() - .getProjectPath(), getDataSourceLookup().getOwnerId()); - IDAOFactory daoFactory = daoFactoryHelper.getDAOFactory(); - - // response = queryManagerLocal.processQuery(requestXml); - masterInstanceResponse = startAnalysisLocal.start(daoFactory, - requestXml); - // processQuery(this.getDataSourceLookup(), requestXml); - // masterInstanceResponse.setStatus(this.buildCRCStausType( - // RequestHandlerDelegate.DONE_TYPE, "DONE")); - - // response = this.buildResponseMessage(requestXml, bodyType); - } catch (I2B2Exception e) { - masterInstanceResponse = new MasterInstanceResultResponseType(); - masterInstanceResponse.setStatus(this.buildCRCStausType( - RequestHandlerDelegate.ERROR_TYPE, e.getMessage())); - - } finally { - edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory psmObjFactory = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); - bodyType.getAny().add( - psmObjFactory.createResponse(masterInstanceResponse)); - } - - return bodyType; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.delegate.setfinder; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.dao.IDAOFactory; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.AnalysisDefinitionRequestType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterInstanceResultResponseType; +import edu.harvard.i2b2.crc.delegate.RequestHandler; +import edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate; +import edu.harvard.i2b2.crc.ejb.analysis.StartAnalysis; +import edu.harvard.i2b2.crc.ejb.analysis.StartAnalysisLocal; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + +/** + * RunQueryInstanceFromQueryDefinitionHandler class implements execute method + * $Id: RunQueryInstanceFromQueryDefinitionHandler.java,v 1.6 2008/03/19 + * 22:36:37 rk903 Exp $ + * + * @author rkuttan + */ +public class RunQueryInstanceFromAnalysisDefinitionHandler extends + RequestHandler { + AnalysisDefinitionRequestType analysisDefRequestType = null; + String requestXml = null; + + /** + * Constuctor which accepts i2b2 request message xml + * + * @param requestXml + * @throws I2B2Exception + */ + public RunQueryInstanceFromAnalysisDefinitionHandler(String requestXml) + throws I2B2Exception { + try { + analysisDefRequestType = (AnalysisDefinitionRequestType) getRequestType( + requestXml, + edu.harvard.i2b2.crc.datavo.setfinder.query.AnalysisDefinitionRequestType.class); + this.requestXml = requestXml; + this.setDataSourceLookup(requestXml); + } catch (JAXBUtilException jaxbUtilEx) { + throw new I2B2Exception("Error ", jaxbUtilEx); + } + } + + /** + * Perform operation for the given request using business class(ejb) and + * return response + * + * @throws I2B2Exception + * @see edu.harvard.i2b2.crc.delegate.RequestHandler#execute() + */ + @Override + public BodyType execute() throws I2B2Exception { + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + String response = null; + BodyType bodyType = new BodyType(); + MasterInstanceResultResponseType masterInstanceResponse = null; + try { + //StartAnalysisLocal startAnalysisLocal = qpUtil + // .getStartAnalysisLocal(); + + StartAnalysisLocal startAnalysisLocal = new StartAnalysis(); + + DAOFactoryHelper daoFactoryHelper = new DAOFactoryHelper(this + .getDataSourceLookup().getDomainId(), getDataSourceLookup() + .getProjectPath(), getDataSourceLookup().getOwnerId()); + IDAOFactory daoFactory = daoFactoryHelper.getDAOFactory(); + + // response = queryManagerLocal.processQuery(requestXml); + masterInstanceResponse = startAnalysisLocal.start(daoFactory, + requestXml); + // processQuery(this.getDataSourceLookup(), requestXml); + // masterInstanceResponse.setStatus(this.buildCRCStausType( + // RequestHandlerDelegate.DONE_TYPE, "DONE")); + + // response = this.buildResponseMessage(requestXml, bodyType); + } catch (I2B2Exception e) { + masterInstanceResponse = new MasterInstanceResultResponseType(); + masterInstanceResponse.setStatus(this.buildCRCStausType( + RequestHandlerDelegate.ERROR_TYPE, e.getMessage())); + + } finally { + edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory psmObjFactory = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); + bodyType.getAny().add( + psmObjFactory.createResponse(masterInstanceResponse)); + } + + return bodyType; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/RunQueryInstanceFromQueryDefinitionHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/RunQueryInstanceFromQueryDefinitionHandler.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/RunQueryInstanceFromQueryDefinitionHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/RunQueryInstanceFromQueryDefinitionHandler.java index a1da33b8..e7b17701 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/RunQueryInstanceFromQueryDefinitionHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/RunQueryInstanceFromQueryDefinitionHandler.java @@ -1,262 +1,262 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.delegate.setfinder; - -import java.util.List; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.dao.IDAOFactory; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterInstanceResultResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionRequestType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryInstanceType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryResultInstanceType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryStatusTypeType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.StatusType; -import edu.harvard.i2b2.crc.delegate.RequestHandler; -import edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate; -import edu.harvard.i2b2.crc.ejb.QueryManagerBean; -import edu.harvard.i2b2.crc.ejb.QueryManagerBeanUtil; -import edu.harvard.i2b2.crc.ejb.role.PriviledgeLocal; -import edu.harvard.i2b2.crc.util.CacheUtil; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - -/** - * RunQueryInstanceFromQueryDefinitionHandler class implements execute method - * $Id: RunQueryInstanceFromQueryDefinitionHandler.java,v 1.6 2008/03/19 - * 22:36:37 rk903 Exp $ - * - * @author rkuttan - */ -public class RunQueryInstanceFromQueryDefinitionHandler extends RequestHandler { - QueryDefinitionRequestType queryDefRequestType = null; - String requestXml = null; - boolean lockedoutFlag = false,errorFlag = false; - protected final Log logesapi = LogFactory.getLog(getClass()); - - /** - * Constuctor which accepts i2b2 request message xml - * - * @param requestXml - * @throws I2B2Exception - */ - public RunQueryInstanceFromQueryDefinitionHandler(String requestXml) - throws I2B2Exception { - try { - queryDefRequestType = (QueryDefinitionRequestType) getRequestType( - requestXml, - edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionRequestType.class); - this.requestXml = requestXml; - this.setDataSourceLookup(requestXml); - } catch (JAXBUtilException jaxbUtilEx) { - throw new I2B2Exception("Error ", jaxbUtilEx); - } - } - - /** - * Perform operation for the given request using business class(ejb) and - * return response - * - * @throws I2B2Exception - * @see edu.harvard.i2b2.crc.delegate.RequestHandler#execute() - */ - @Override - public BodyType execute() throws I2B2Exception { - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - String response = null; - BodyType bodyType = new BodyType(); - MasterInstanceResultResponseType masterInstanceResponse = null; - try { - log.debug("Running Execute"); - - DAOFactoryHelper daoFactoryHelper = new DAOFactoryHelper(this - .getDataSourceLookup().getDomainId(), getDataSourceLookup() - .getProjectPath(), getDataSourceLookup().getOwnerId()); - - String rolePath = getDataSourceLookup().getDomainId() + "/" - + getDataSourceLookup().getProjectPath() + "/" - + getDataSourceLookup().getOwnerId(); - - //List roles = (List) cache.getRoot().get(rolePath); - logesapi.debug("Roles from get " + rolePath); - List roles = (List) CacheUtil.get(rolePath); - if (roles != null) { - log.debug("Roles from size " + roles.size()); - } else { - log.debug("Roles from get is null "); - } - - //TODO check previlieges - IDAOFactory daoFactory = daoFactoryHelper.getDAOFactory(); - PriviledgeLocal privilegeLocal = qpUtil.getPriviledgeLocal(); - - privilegeLocal.checkPriviledge(daoFactory, - "SETFINDER_QRY_WITH_DATAOBFSC", roles); - //TODO removed ejbs - // QueryManagerLocalHome queryManagerLocalHome = qpUtil - // .getQueryManagerLocalHome(); - - // QueryManagerLocal queryManagerLocal = queryManagerLocalHome - // .create(); - - log.debug("Calling QueryManager "); - QueryManagerBean queryManagerLocal = new QueryManagerBean(); - masterInstanceResponse = queryManagerLocal.processQuery(this - .getDataSourceLookup(), requestXml); - if (masterInstanceResponse.getStatus() != null) { - StatusType status = masterInstanceResponse.getStatus(); - if (status.getCondition().get(0) != null) { - if (status.getCondition().get(0).getValue() != null) { - if (status.getCondition().get(0).getValue().indexOf( - "LOCKEDOUT") > -1) { - lockedoutFlag = true; - } - } - } - } - log.debug("Calling QueryInstance "); - QueryInstanceType queryInstance = masterInstanceResponse.getQueryInstance(); - QueryStatusTypeType statusType = queryInstance.getQueryStatusType(); - log.debug("checking status type: " + statusType.getStatusTypeId()); - //masterInstanceResponse.getStatus().getCondition().get(0).g - if (statusType.getStatusTypeId() != null && statusType.getStatusTypeId().trim().equals("4")) { - log.debug("Changing status type to ERROR"); - StatusType status = new StatusType(); - StatusType.Condition condition = new StatusType.Condition(); - condition.setType("ERROR"); - condition.setValue("ERROR"); - status.getCondition().add(condition); - masterInstanceResponse.setStatus(status); - errorFlag = true; - } - - else if (statusType.getStatusTypeId() != null && statusType.getStatusTypeId().trim().equals("5")) { - //why is '5' (incomplete) == error ? - - QueryStatusTypeType newStatusType = new QueryStatusTypeType(); - newStatusType.setName("ERROR"); - newStatusType.setDescription("ERROR"); - newStatusType.setStatusTypeId("4"); - masterInstanceResponse.getQueryInstance().setQueryStatusType(newStatusType); - - masterInstanceResponse.setStatus(this.buildCRCStausType( - "ERROR", "ERROR")); - /* - } else if (statusType.getStatusTypeId() != null && statusType.getStatusTypeId().trim().equals("3")) { - masterInstanceResponse.setStatus(this.buildCRCStausType( - "DONE", "DONE")); - - } else if (statusType.getStatusTypeId() != null && !statusType.getStatusTypeId().trim().equals("6")) { - masterInstanceResponse.setStatus(this.buildCRCStausType( - "RUNNING", "RUNNING")); - */ - } else { - masterInstanceResponse.setStatus(this.buildCRCStausType( - RequestHandlerDelegate.DONE_TYPE, "DONE")); - } - - //Check to see if any queryinstance are stil processing - boolean isProcessing = false; - boolean isError = false; - for (QueryResultInstanceType queryIntance: masterInstanceResponse.getQueryResultInstance()) - { - - if (queryIntance.getQueryStatusType().getName().equals("QUEUED") - || queryIntance.getQueryStatusType().getName().equals("PROCESSING") - || queryIntance.getEndDate() == null) - isProcessing = true; - if (queryIntance.getQueryStatusType().getName().equals("ERROR") - || queryIntance.getQueryStatusType().getName().equals("TIMEDOUT")) - isError = true; - } - - //If Batchmode is equal to PROCESSING then set to finished - if (isProcessing || isError) - { - masterInstanceResponse.setStatus(this.buildCRCStausType( - RequestHandlerDelegate.DONE_TYPE, "DONE")); - - if (isProcessing) - { - - masterInstanceResponse.getStatus().getCondition().get(0).setType("RUNNING"); - masterInstanceResponse.getStatus().getCondition().get(0).setValue("RUNNING"); - - if (masterInstanceResponse.getQueryInstance().getBatchMode().equals("LARGE_QUEUE")) - { - masterInstanceResponse.getQueryInstance().setBatchMode("INCOMPLETE"); - } - else if (masterInstanceResponse.getQueryInstance().getBatchMode().equals("MEDIUM_QUEUE")) - { - QueryStatusTypeType newStatusType = new QueryStatusTypeType(); - newStatusType.setName("LARGE_QUEUE"); - newStatusType.setDescription("LARGE_QUEUE"); - newStatusType.setStatusTypeId("7"); - masterInstanceResponse.getQueryInstance().setQueryStatusType(newStatusType); - masterInstanceResponse.getQueryInstance().setEndDate(null); - - } else { - masterInstanceResponse.getQueryInstance().setBatchMode("MEDIUM_QUEUE"); - QueryStatusTypeType newStatusType = new QueryStatusTypeType(); - newStatusType.setName("MEDIUM_QUEUE"); - newStatusType.setDescription("MEDIUM_QUEUE"); - newStatusType.setStatusTypeId("7"); - masterInstanceResponse.getQueryInstance().setQueryStatusType(newStatusType); - masterInstanceResponse.getQueryInstance().setEndDate(null); - } - } else if (isError) - { - masterInstanceResponse.getStatus().getCondition().get(0).setType("ERROR"); - masterInstanceResponse.getStatus().getCondition().get(0).setValue("ERROR"); - masterInstanceResponse.getQueryInstance().setBatchMode("ERROR"); - QueryStatusTypeType newStatusType = new QueryStatusTypeType(); - newStatusType.setName("ERROR"); - newStatusType.setDescription("ERROR"); - newStatusType.setStatusTypeId("4"); - masterInstanceResponse.getQueryInstance().setQueryStatusType(newStatusType); - } - //else { - // masterInstanceResponse.getQueryInstance().setBatchMode(masterInstanceResponse.getQueryInstance().getQueryStatusType().getName()); - //} - } - response = this.buildResponseMessage(requestXml, bodyType); - } catch (Exception ee) { - log.debug("Ran into a error: " + ee.getMessage()); - masterInstanceResponse = new MasterInstanceResultResponseType(); - masterInstanceResponse.setStatus(this.buildCRCStausType( - RequestHandlerDelegate.ERROR_TYPE, ee.getMessage())); - } finally { - edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory psmObjFactory = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); - bodyType.getAny().add( - psmObjFactory.createResponse(masterInstanceResponse)); - } - - return bodyType; - } - - - public boolean getLockedoutFlag() { - return lockedoutFlag; - } - - public boolean getErrorFlag() { - return errorFlag; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.delegate.setfinder; + +import java.util.List; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.dao.IDAOFactory; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterInstanceResultResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionRequestType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryInstanceType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryResultInstanceType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryStatusTypeType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.StatusType; +import edu.harvard.i2b2.crc.delegate.RequestHandler; +import edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate; +import edu.harvard.i2b2.crc.ejb.QueryManagerBean; +import edu.harvard.i2b2.crc.ejb.QueryManagerBeanUtil; +import edu.harvard.i2b2.crc.ejb.role.PriviledgeLocal; +import edu.harvard.i2b2.crc.util.CacheUtil; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + +/** + * RunQueryInstanceFromQueryDefinitionHandler class implements execute method + * $Id: RunQueryInstanceFromQueryDefinitionHandler.java,v 1.6 2008/03/19 + * 22:36:37 rk903 Exp $ + * + * @author rkuttan + */ +public class RunQueryInstanceFromQueryDefinitionHandler extends RequestHandler { + QueryDefinitionRequestType queryDefRequestType = null; + String requestXml = null; + boolean lockedoutFlag = false,errorFlag = false; + protected final Log logesapi = LogFactory.getLog(getClass()); + + /** + * Constuctor which accepts i2b2 request message xml + * + * @param requestXml + * @throws I2B2Exception + */ + public RunQueryInstanceFromQueryDefinitionHandler(String requestXml) + throws I2B2Exception { + try { + queryDefRequestType = (QueryDefinitionRequestType) getRequestType( + requestXml, + edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionRequestType.class); + this.requestXml = requestXml; + this.setDataSourceLookup(requestXml); + } catch (JAXBUtilException jaxbUtilEx) { + throw new I2B2Exception("Error ", jaxbUtilEx); + } + } + + /** + * Perform operation for the given request using business class(ejb) and + * return response + * + * @throws I2B2Exception + * @see edu.harvard.i2b2.crc.delegate.RequestHandler#execute() + */ + @Override + public BodyType execute() throws I2B2Exception { + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + String response = null; + BodyType bodyType = new BodyType(); + MasterInstanceResultResponseType masterInstanceResponse = null; + try { + log.debug("Running Execute"); + + DAOFactoryHelper daoFactoryHelper = new DAOFactoryHelper(this + .getDataSourceLookup().getDomainId(), getDataSourceLookup() + .getProjectPath(), getDataSourceLookup().getOwnerId()); + + String rolePath = getDataSourceLookup().getDomainId() + "/" + + getDataSourceLookup().getProjectPath() + "/" + + getDataSourceLookup().getOwnerId(); + + //List roles = (List) cache.getRoot().get(rolePath); + logesapi.debug("Roles from get " + rolePath); + List roles = (List) CacheUtil.get(rolePath); + if (roles != null) { + log.debug("Roles from size " + roles.size()); + } else { + log.debug("Roles from get is null "); + } + + //TODO check previlieges + IDAOFactory daoFactory = daoFactoryHelper.getDAOFactory(); + PriviledgeLocal privilegeLocal = qpUtil.getPriviledgeLocal(); + + privilegeLocal.checkPriviledge(daoFactory, + "SETFINDER_QRY_WITH_DATAOBFSC", roles); + //TODO removed ejbs + // QueryManagerLocalHome queryManagerLocalHome = qpUtil + // .getQueryManagerLocalHome(); + + // QueryManagerLocal queryManagerLocal = queryManagerLocalHome + // .create(); + + log.debug("Calling QueryManager "); + QueryManagerBean queryManagerLocal = new QueryManagerBean(); + masterInstanceResponse = queryManagerLocal.processQuery(this + .getDataSourceLookup(), requestXml); + if (masterInstanceResponse.getStatus() != null) { + StatusType status = masterInstanceResponse.getStatus(); + if (status.getCondition().get(0) != null) { + if (status.getCondition().get(0).getValue() != null) { + if (status.getCondition().get(0).getValue().indexOf( + "LOCKEDOUT") > -1) { + lockedoutFlag = true; + } + } + } + } + log.debug("Calling QueryInstance "); + QueryInstanceType queryInstance = masterInstanceResponse.getQueryInstance(); + QueryStatusTypeType statusType = queryInstance.getQueryStatusType(); + log.debug("checking status type: " + statusType.getStatusTypeId()); + //masterInstanceResponse.getStatus().getCondition().get(0).g + if (statusType.getStatusTypeId() != null && statusType.getStatusTypeId().trim().equals("4")) { + log.debug("Changing status type to ERROR"); + StatusType status = new StatusType(); + StatusType.Condition condition = new StatusType.Condition(); + condition.setType("ERROR"); + condition.setValue("ERROR"); + status.getCondition().add(condition); + masterInstanceResponse.setStatus(status); + errorFlag = true; + } + + else if (statusType.getStatusTypeId() != null && statusType.getStatusTypeId().trim().equals("5")) { + //why is '5' (incomplete) == error ? + + QueryStatusTypeType newStatusType = new QueryStatusTypeType(); + newStatusType.setName("ERROR"); + newStatusType.setDescription("ERROR"); + newStatusType.setStatusTypeId("4"); + masterInstanceResponse.getQueryInstance().setQueryStatusType(newStatusType); + + masterInstanceResponse.setStatus(this.buildCRCStausType( + "ERROR", "ERROR")); + /* + } else if (statusType.getStatusTypeId() != null && statusType.getStatusTypeId().trim().equals("3")) { + masterInstanceResponse.setStatus(this.buildCRCStausType( + "DONE", "DONE")); + + } else if (statusType.getStatusTypeId() != null && !statusType.getStatusTypeId().trim().equals("6")) { + masterInstanceResponse.setStatus(this.buildCRCStausType( + "RUNNING", "RUNNING")); + */ + } else { + masterInstanceResponse.setStatus(this.buildCRCStausType( + RequestHandlerDelegate.DONE_TYPE, "DONE")); + } + + //Check to see if any queryinstance are stil processing + boolean isProcessing = false; + boolean isError = false; + for (QueryResultInstanceType queryIntance: masterInstanceResponse.getQueryResultInstance()) + { + + if (queryIntance.getQueryStatusType().getName().equals("QUEUED") + || queryIntance.getQueryStatusType().getName().equals("PROCESSING") + || queryIntance.getEndDate() == null) + isProcessing = true; + if (queryIntance.getQueryStatusType().getName().equals("ERROR") + || queryIntance.getQueryStatusType().getName().equals("TIMEDOUT")) + isError = true; + } + + //If Batchmode is equal to PROCESSING then set to finished + if (isProcessing || isError) + { + masterInstanceResponse.setStatus(this.buildCRCStausType( + RequestHandlerDelegate.DONE_TYPE, "DONE")); + + if (isProcessing) + { + + masterInstanceResponse.getStatus().getCondition().get(0).setType("RUNNING"); + masterInstanceResponse.getStatus().getCondition().get(0).setValue("RUNNING"); + + if (masterInstanceResponse.getQueryInstance().getBatchMode().equals("LARGE_QUEUE")) + { + masterInstanceResponse.getQueryInstance().setBatchMode("INCOMPLETE"); + } + else if (masterInstanceResponse.getQueryInstance().getBatchMode().equals("MEDIUM_QUEUE")) + { + QueryStatusTypeType newStatusType = new QueryStatusTypeType(); + newStatusType.setName("LARGE_QUEUE"); + newStatusType.setDescription("LARGE_QUEUE"); + newStatusType.setStatusTypeId("7"); + masterInstanceResponse.getQueryInstance().setQueryStatusType(newStatusType); + masterInstanceResponse.getQueryInstance().setEndDate(null); + + } else { + masterInstanceResponse.getQueryInstance().setBatchMode("MEDIUM_QUEUE"); + QueryStatusTypeType newStatusType = new QueryStatusTypeType(); + newStatusType.setName("MEDIUM_QUEUE"); + newStatusType.setDescription("MEDIUM_QUEUE"); + newStatusType.setStatusTypeId("7"); + masterInstanceResponse.getQueryInstance().setQueryStatusType(newStatusType); + masterInstanceResponse.getQueryInstance().setEndDate(null); + } + } else if (isError) + { + masterInstanceResponse.getStatus().getCondition().get(0).setType("ERROR"); + masterInstanceResponse.getStatus().getCondition().get(0).setValue("ERROR"); + masterInstanceResponse.getQueryInstance().setBatchMode("ERROR"); + QueryStatusTypeType newStatusType = new QueryStatusTypeType(); + newStatusType.setName("ERROR"); + newStatusType.setDescription("ERROR"); + newStatusType.setStatusTypeId("4"); + masterInstanceResponse.getQueryInstance().setQueryStatusType(newStatusType); + } + //else { + // masterInstanceResponse.getQueryInstance().setBatchMode(masterInstanceResponse.getQueryInstance().getQueryStatusType().getName()); + //} + } + response = this.buildResponseMessage(requestXml, bodyType); + } catch (Exception ee) { + log.debug("Ran into a error: " + ee.getMessage()); + masterInstanceResponse = new MasterInstanceResultResponseType(); + masterInstanceResponse.setStatus(this.buildCRCStausType( + RequestHandlerDelegate.ERROR_TYPE, ee.getMessage())); + } finally { + edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory psmObjFactory = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); + bodyType.getAny().add( + psmObjFactory.createResponse(masterInstanceResponse)); + } + + return bodyType; + } + + + public boolean getLockedoutFlag() { + return lockedoutFlag; + } + + public boolean getErrorFlag() { + return errorFlag; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/RunQueryInstanceFromQueryMasterHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/RunQueryInstanceFromQueryMasterHandler.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/RunQueryInstanceFromQueryMasterHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/RunQueryInstanceFromQueryMasterHandler.java index 9c107914..dea053c6 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/RunQueryInstanceFromQueryMasterHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/RunQueryInstanceFromQueryMasterHandler.java @@ -1,97 +1,97 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.delegate.setfinder; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceResultResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterRequestType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.PsmQryHeaderType; -import edu.harvard.i2b2.crc.delegate.RequestHandler; -import edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate; -import edu.harvard.i2b2.crc.ejb.QueryManagerBean; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - - -/** - * RunQueryInstanceFromQueryMasterHandler class - * implements execute method - * $Id: RunQueryInstanceFromQueryMasterHandler.java,v 1.7 2008/03/19 22:36:37 rk903 Exp $ - * @author rkuttan - */ -public class RunQueryInstanceFromQueryMasterHandler extends RequestHandler { - MasterRequestType masterRequestType = null; - String requestXml = null; - PsmQryHeaderType headerType = null; - - /** - * Constuctor which accepts i2b2 request message xml - * @param requestXml - * @throws I2B2Exception - */ - public RunQueryInstanceFromQueryMasterHandler(String requestXml) - throws I2B2Exception { - try { - masterRequestType = (MasterRequestType) getRequestType(requestXml, - edu.harvard.i2b2.crc.datavo.setfinder.query.MasterRequestType.class); - headerType = (PsmQryHeaderType) this.getRequestType(requestXml, - edu.harvard.i2b2.crc.datavo.setfinder.query.PsmQryHeaderType.class); - this.requestXml = requestXml; - this.setDataSourceLookup(requestXml); - } catch (JAXBUtilException jaxbUtilEx) { - throw new I2B2Exception("Error ", jaxbUtilEx); - } - } - - /** - * Perform operation for the given request - * using business class(ejb) and return response - * @see edu.harvard.i2b2.crc.delegate.RequestHandler#execute() - */ - @Override - public BodyType execute() throws I2B2Exception { - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - String response = null; - BodyType bodyType = new BodyType(); - InstanceResultResponseType instanceResult = null; - try { - //get userId and timeout from request xml - RequestMessageType requestMessageType = getI2B2RequestMessageType(requestXml); - long timeout = requestMessageType.getRequestHeader() - .getResultWaittimeMs(); - String userId = headerType.getUser().getLogin(); - String masterId = masterRequestType.getQueryMasterId(); - - //TODO removed ejbs -// QueryManagerLocalHome queryManagerLocalHome = qpUtil.getQueryManagerLocalHome(); - // QueryManagerLocal queryManagerLocal = queryManagerLocalHome.create(); - QueryManagerBean query = new QueryManagerBean(); - instanceResult = query.runQueryMaster(this.getDataSourceLookup(),userId, - masterId, timeout); - instanceResult.setStatus(this.buildCRCStausType(RequestHandlerDelegate.DONE_TYPE, "DONE")); - } catch (Exception e) { - instanceResult = new InstanceResultResponseType(); - instanceResult.setStatus(this.buildCRCStausType(RequestHandlerDelegate.ERROR_TYPE, e.getMessage())); - } finally { - edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); - bodyType.getAny().add(of.createResponse(instanceResult)); - - } - - return bodyType; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.delegate.setfinder; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceResultResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterRequestType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.PsmQryHeaderType; +import edu.harvard.i2b2.crc.delegate.RequestHandler; +import edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate; +import edu.harvard.i2b2.crc.ejb.QueryManagerBean; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + + +/** + * RunQueryInstanceFromQueryMasterHandler class + * implements execute method + * $Id: RunQueryInstanceFromQueryMasterHandler.java,v 1.7 2008/03/19 22:36:37 rk903 Exp $ + * @author rkuttan + */ +public class RunQueryInstanceFromQueryMasterHandler extends RequestHandler { + MasterRequestType masterRequestType = null; + String requestXml = null; + PsmQryHeaderType headerType = null; + + /** + * Constuctor which accepts i2b2 request message xml + * @param requestXml + * @throws I2B2Exception + */ + public RunQueryInstanceFromQueryMasterHandler(String requestXml) + throws I2B2Exception { + try { + masterRequestType = (MasterRequestType) getRequestType(requestXml, + edu.harvard.i2b2.crc.datavo.setfinder.query.MasterRequestType.class); + headerType = (PsmQryHeaderType) this.getRequestType(requestXml, + edu.harvard.i2b2.crc.datavo.setfinder.query.PsmQryHeaderType.class); + this.requestXml = requestXml; + this.setDataSourceLookup(requestXml); + } catch (JAXBUtilException jaxbUtilEx) { + throw new I2B2Exception("Error ", jaxbUtilEx); + } + } + + /** + * Perform operation for the given request + * using business class(ejb) and return response + * @see edu.harvard.i2b2.crc.delegate.RequestHandler#execute() + */ + @Override + public BodyType execute() throws I2B2Exception { + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + String response = null; + BodyType bodyType = new BodyType(); + InstanceResultResponseType instanceResult = null; + try { + //get userId and timeout from request xml + RequestMessageType requestMessageType = getI2B2RequestMessageType(requestXml); + long timeout = requestMessageType.getRequestHeader() + .getResultWaittimeMs(); + String userId = headerType.getUser().getLogin(); + String masterId = masterRequestType.getQueryMasterId(); + + //TODO removed ejbs +// QueryManagerLocalHome queryManagerLocalHome = qpUtil.getQueryManagerLocalHome(); + // QueryManagerLocal queryManagerLocal = queryManagerLocalHome.create(); + QueryManagerBean query = new QueryManagerBean(); + instanceResult = query.runQueryMaster(this.getDataSourceLookup(),userId, + masterId, timeout); + instanceResult.setStatus(this.buildCRCStausType(RequestHandlerDelegate.DONE_TYPE, "DONE")); + } catch (Exception e) { + instanceResult = new InstanceResultResponseType(); + instanceResult.setStatus(this.buildCRCStausType(RequestHandlerDelegate.ERROR_TYPE, e.getMessage())); + } finally { + edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); + bodyType.getAny().add(of.createResponse(instanceResult)); + + } + + return bodyType; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/SetQueryInstanceStatusHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/SetQueryInstanceStatusHandler.java similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/SetQueryInstanceStatusHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/SetQueryInstanceStatusHandler.java index bdc6aca4..8ca90a17 100644 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/SetQueryInstanceStatusHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/SetQueryInstanceStatusHandler.java @@ -1,104 +1,104 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Mike Mendis - */ -package edu.harvard.i2b2.crc.delegate.setfinder; - - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceStatusRequestType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterRenameRequestType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterResponseType; -import edu.harvard.i2b2.crc.delegate.RequestHandler; -import edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate; -import edu.harvard.i2b2.crc.ejb.QueryInfoBean; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - - -public class SetQueryInstanceStatusHandler extends RequestHandler { - private InstanceStatusRequestType instanceMessageRequestType = null; - - private boolean isManager = false; - private String userId = null; - - - /** - * Constuctor which accepts i2b2 request message xml - * @param requestXml - * @throws I2B2Exception - */ - public SetQueryInstanceStatusHandler(String requestXml, boolean isMgr, String username) - throws I2B2Exception { - isManager = isMgr; - userId = username; - try { - instanceMessageRequestType = (InstanceStatusRequestType) this.getRequestType(requestXml, - edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceStatusRequestType.class); - this.setDataSourceLookup(requestXml); - } catch (JAXBUtilException jaxbUtilEx) { - throw new I2B2Exception("Error ", jaxbUtilEx); - } - } - - /** - * Perform operation for the given request - * using business class(ejb) and return response - * @see edu.harvard.i2b2.crc.delegate.RequestHandler#execute() - */ - @Override - public BodyType execute() { - // call ejb and pass input object - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - ResponseMessageType responseMessageType = new ResponseMessageType(); - StatusType statusType = null; - String responseString = null; - BodyType bodyType = new BodyType(); - InstanceResponseType masterResponseType = null; - try { - //TODO removed ejbs - // QueryInfoLocalHome queryInfoLocalHome = qpUtil.getQueryInfoLocalHome(); - // QueryInfoLocal queryInfoLocal = queryInfoLocalHome.create(); - String userId = instanceMessageRequestType.getUserId(); - String instanceId = instanceMessageRequestType.getQueryInstanceId(); - String statusName = instanceMessageRequestType.getStatusName(); - QueryInfoBean query = new QueryInfoBean(); - query.setQueryInstanceStatus(this.getDataSourceLookup(), - instanceId, statusName, isManager, userId); - masterResponseType = new InstanceResponseType(); - masterResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.DONE_TYPE, "DONE")); - - } catch (Exception e) { - masterResponseType = new InstanceResponseType(); - masterResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.ERROR_TYPE, e.getMessage())); - } finally { - edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); - bodyType.getAny().add(of.createResponse(masterResponseType)); - - } - return bodyType; - } - - //function to build StatusType for the given message - private StatusType buildStatusType(String statusTypeString, String message) { - StatusType statusType = new StatusType(); - statusType.setType(statusTypeString); - statusType.setValue(message); - - return statusType; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Mike Mendis + */ +package edu.harvard.i2b2.crc.delegate.setfinder; + + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceStatusRequestType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterRenameRequestType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterResponseType; +import edu.harvard.i2b2.crc.delegate.RequestHandler; +import edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate; +import edu.harvard.i2b2.crc.ejb.QueryInfoBean; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + + +public class SetQueryInstanceStatusHandler extends RequestHandler { + private InstanceStatusRequestType instanceMessageRequestType = null; + + private boolean isManager = false; + private String userId = null; + + + /** + * Constuctor which accepts i2b2 request message xml + * @param requestXml + * @throws I2B2Exception + */ + public SetQueryInstanceStatusHandler(String requestXml, boolean isMgr, String username) + throws I2B2Exception { + isManager = isMgr; + userId = username; + try { + instanceMessageRequestType = (InstanceStatusRequestType) this.getRequestType(requestXml, + edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceStatusRequestType.class); + this.setDataSourceLookup(requestXml); + } catch (JAXBUtilException jaxbUtilEx) { + throw new I2B2Exception("Error ", jaxbUtilEx); + } + } + + /** + * Perform operation for the given request + * using business class(ejb) and return response + * @see edu.harvard.i2b2.crc.delegate.RequestHandler#execute() + */ + @Override + public BodyType execute() { + // call ejb and pass input object + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + ResponseMessageType responseMessageType = new ResponseMessageType(); + StatusType statusType = null; + String responseString = null; + BodyType bodyType = new BodyType(); + InstanceResponseType masterResponseType = null; + try { + //TODO removed ejbs + // QueryInfoLocalHome queryInfoLocalHome = qpUtil.getQueryInfoLocalHome(); + // QueryInfoLocal queryInfoLocal = queryInfoLocalHome.create(); + String userId = instanceMessageRequestType.getUserId(); + String instanceId = instanceMessageRequestType.getQueryInstanceId(); + String statusName = instanceMessageRequestType.getStatusName(); + QueryInfoBean query = new QueryInfoBean(); + query.setQueryInstanceStatus(this.getDataSourceLookup(), + instanceId, statusName, isManager, userId); + masterResponseType = new InstanceResponseType(); + masterResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.DONE_TYPE, "DONE")); + + } catch (Exception e) { + masterResponseType = new InstanceResponseType(); + masterResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.ERROR_TYPE, e.getMessage())); + } finally { + edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); + bodyType.getAny().add(of.createResponse(masterResponseType)); + + } + return bodyType; + } + + //function to build StatusType for the given message + private StatusType buildStatusType(String statusTypeString, String message) { + StatusType statusType = new StatusType(); + statusType.setType(statusTypeString); + statusType.setValue(message); + + return statusType; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/UpdateQueryInstanceMessageHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/UpdateQueryInstanceMessageHandler.java similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/UpdateQueryInstanceMessageHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/UpdateQueryInstanceMessageHandler.java index ff4870b8..8afe1758 100644 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/UpdateQueryInstanceMessageHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/UpdateQueryInstanceMessageHandler.java @@ -1,102 +1,102 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Mike Mendis - */ -package edu.harvard.i2b2.crc.delegate.setfinder; - - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceMessageRequestType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterRenameRequestType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterResponseType; -import edu.harvard.i2b2.crc.delegate.RequestHandler; -import edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate; -import edu.harvard.i2b2.crc.ejb.QueryInfoBean; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - - -public class UpdateQueryInstanceMessageHandler extends RequestHandler { - private InstanceMessageRequestType instanceMessageRequestType = null; - - private boolean isManager = false; - private String userId = null; - /** - * Constuctor which accepts i2b2 request message xml - * @param requestXml - * @throws I2B2Exception - */ - public UpdateQueryInstanceMessageHandler(String requestXml, boolean isMgr, String username) - throws I2B2Exception { - isManager = isMgr; - userId = username; - try { - instanceMessageRequestType = (InstanceMessageRequestType) this.getRequestType(requestXml, - edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceMessageRequestType.class); - this.setDataSourceLookup(requestXml); - } catch (JAXBUtilException jaxbUtilEx) { - throw new I2B2Exception("Error ", jaxbUtilEx); - } - } - - /** - * Perform operation for the given request - * using business class(ejb) and return response - * @see edu.harvard.i2b2.crc.delegate.RequestHandler#execute() - */ - @Override - public BodyType execute() { - // call ejb and pass input object - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - ResponseMessageType responseMessageType = new ResponseMessageType(); - StatusType statusType = null; - String responseString = null; - BodyType bodyType = new BodyType(); - InstanceResponseType masterResponseType = null; - try { - //TODO removed ejbs - // QueryInfoLocalHome queryInfoLocalHome = qpUtil.getQueryInfoLocalHome(); - // QueryInfoLocal queryInfoLocal = queryInfoLocalHome.create(); - //String userId = instanceMessageRequestType.getUserId(); - String instanceId = instanceMessageRequestType.getQueryInstanceId(); - String message = instanceMessageRequestType.getMessage().replaceAll("\\<[^>]*>",""); - QueryInfoBean query = new QueryInfoBean(); - query.setQueryInstanceMessage(this.getDataSourceLookup(), - instanceId, message, isManager, userId); - masterResponseType = new InstanceResponseType(); - masterResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.DONE_TYPE, "DONE")); - - } catch (Exception e) { - masterResponseType = new InstanceResponseType(); - masterResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.ERROR_TYPE, e.getMessage())); - } finally { - edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); - bodyType.getAny().add(of.createResponse(masterResponseType)); - - } - return bodyType; - } - - //function to build StatusType for the given message - private StatusType buildStatusType(String statusTypeString, String message) { - StatusType statusType = new StatusType(); - statusType.setType(statusTypeString); - statusType.setValue(message); - - return statusType; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Mike Mendis + */ +package edu.harvard.i2b2.crc.delegate.setfinder; + + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceMessageRequestType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterRenameRequestType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterResponseType; +import edu.harvard.i2b2.crc.delegate.RequestHandler; +import edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate; +import edu.harvard.i2b2.crc.ejb.QueryInfoBean; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + + +public class UpdateQueryInstanceMessageHandler extends RequestHandler { + private InstanceMessageRequestType instanceMessageRequestType = null; + + private boolean isManager = false; + private String userId = null; + /** + * Constuctor which accepts i2b2 request message xml + * @param requestXml + * @throws I2B2Exception + */ + public UpdateQueryInstanceMessageHandler(String requestXml, boolean isMgr, String username) + throws I2B2Exception { + isManager = isMgr; + userId = username; + try { + instanceMessageRequestType = (InstanceMessageRequestType) this.getRequestType(requestXml, + edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceMessageRequestType.class); + this.setDataSourceLookup(requestXml); + } catch (JAXBUtilException jaxbUtilEx) { + throw new I2B2Exception("Error ", jaxbUtilEx); + } + } + + /** + * Perform operation for the given request + * using business class(ejb) and return response + * @see edu.harvard.i2b2.crc.delegate.RequestHandler#execute() + */ + @Override + public BodyType execute() { + // call ejb and pass input object + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + ResponseMessageType responseMessageType = new ResponseMessageType(); + StatusType statusType = null; + String responseString = null; + BodyType bodyType = new BodyType(); + InstanceResponseType masterResponseType = null; + try { + //TODO removed ejbs + // QueryInfoLocalHome queryInfoLocalHome = qpUtil.getQueryInfoLocalHome(); + // QueryInfoLocal queryInfoLocal = queryInfoLocalHome.create(); + //String userId = instanceMessageRequestType.getUserId(); + String instanceId = instanceMessageRequestType.getQueryInstanceId(); + String message = instanceMessageRequestType.getMessage().replaceAll("\\<[^>]*>",""); + QueryInfoBean query = new QueryInfoBean(); + query.setQueryInstanceMessage(this.getDataSourceLookup(), + instanceId, message, isManager, userId); + masterResponseType = new InstanceResponseType(); + masterResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.DONE_TYPE, "DONE")); + + } catch (Exception e) { + masterResponseType = new InstanceResponseType(); + masterResponseType.setStatus(this.buildCRCStausType(RequestHandlerDelegate.ERROR_TYPE, e.getMessage())); + } finally { + edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); + bodyType.getAny().add(of.createResponse(masterResponseType)); + + } + return bodyType; + } + + //function to build StatusType for the given message + private StatusType buildStatusType(String statusTypeString, String message) { + StatusType statusType = new StatusType(); + statusType.setType(statusTypeString); + statusType.setValue(message); + + return statusType; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/UpdateQueryResultInstanceDescriptionHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/UpdateQueryResultInstanceDescriptionHandler.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/UpdateQueryResultInstanceDescriptionHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/UpdateQueryResultInstanceDescriptionHandler.java index eec4c64d..0373327b --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/delegate/setfinder/UpdateQueryResultInstanceDescriptionHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/delegate/setfinder/UpdateQueryResultInstanceDescriptionHandler.java @@ -1,110 +1,110 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.delegate.setfinder; - - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultRequestType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultResponseType; -import edu.harvard.i2b2.crc.delegate.RequestHandler; -import edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate; -import edu.harvard.i2b2.crc.ejb.QueryInfoBean; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - -/** - * RenameQueryMasterHandler class implements execute method $Id: - * RenameQueryMasterHandler.java,v 1.8 2008/03/19 22:36:37 rk903 Exp $ - * - * @author rkuttan - */ -public class UpdateQueryResultInstanceDescriptionHandler extends RequestHandler { - private ResultRequestType resultRequestType = null; - - /** - * Constuctor which accepts i2b2 request message xml - * - * @param requestXml - * @throws I2B2Exception - */ - public UpdateQueryResultInstanceDescriptionHandler(String requestXml) - throws I2B2Exception { - try { - resultRequestType = (ResultRequestType) this - .getRequestType( - requestXml, - edu.harvard.i2b2.crc.datavo.setfinder.query.ResultRequestType.class); - this.setDataSourceLookup(requestXml); - } catch (JAXBUtilException jaxbUtilEx) { - throw new I2B2Exception("Error ", jaxbUtilEx); - } - } - - /** - * Perform operation for the given request using business class(ejb) and - * return response - * - * @see edu.harvard.i2b2.crc.delegate.RequestHandler#execute() - */ - @Override - public BodyType execute() { - // call ejb and pass input object - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - ResponseMessageType responseMessageType = new ResponseMessageType(); - StatusType statusType = null; - String responseString = null; - ResultResponseType resultResponseType = null; - BodyType bodyType = new BodyType(); - try { - //TODO removed ejbs -// QueryInfoLocalHome queryInfoLocalHome = qpUtil -// .getQueryInfoLocalHome(); -// QueryInfoLocal queryInfoLocal = queryInfoLocalHome.create(); - String resultInstanceId = resultRequestType - .getQueryResultInstanceId(); - String description = resultRequestType.getDescription(); - QueryInfoBean query = new QueryInfoBean(); - - resultResponseType = query - .updateResultInstanceDescription( - this.getDataSourceLookup(), resultInstanceId, - description); - resultResponseType.setStatus(this.buildCRCStausType( - RequestHandlerDelegate.DONE_TYPE, "DONE")); - - } catch (Exception e) { - resultResponseType = new ResultResponseType(); - resultResponseType.setStatus(this.buildCRCStausType( - RequestHandlerDelegate.ERROR_TYPE, e.getMessage())); - } finally { - edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); - bodyType.getAny().add(of.createResponse(resultResponseType)); - - } - return bodyType; - } - - // function to build StatusType for the given message - private StatusType buildStatusType(String statusTypeString, String message) { - StatusType statusType = new StatusType(); - statusType.setType(statusTypeString); - statusType.setValue(message); - - return statusType; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.delegate.setfinder; + + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultRequestType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultResponseType; +import edu.harvard.i2b2.crc.delegate.RequestHandler; +import edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate; +import edu.harvard.i2b2.crc.ejb.QueryInfoBean; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + +/** + * RenameQueryMasterHandler class implements execute method $Id: + * RenameQueryMasterHandler.java,v 1.8 2008/03/19 22:36:37 rk903 Exp $ + * + * @author rkuttan + */ +public class UpdateQueryResultInstanceDescriptionHandler extends RequestHandler { + private ResultRequestType resultRequestType = null; + + /** + * Constuctor which accepts i2b2 request message xml + * + * @param requestXml + * @throws I2B2Exception + */ + public UpdateQueryResultInstanceDescriptionHandler(String requestXml) + throws I2B2Exception { + try { + resultRequestType = (ResultRequestType) this + .getRequestType( + requestXml, + edu.harvard.i2b2.crc.datavo.setfinder.query.ResultRequestType.class); + this.setDataSourceLookup(requestXml); + } catch (JAXBUtilException jaxbUtilEx) { + throw new I2B2Exception("Error ", jaxbUtilEx); + } + } + + /** + * Perform operation for the given request using business class(ejb) and + * return response + * + * @see edu.harvard.i2b2.crc.delegate.RequestHandler#execute() + */ + @Override + public BodyType execute() { + // call ejb and pass input object + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + ResponseMessageType responseMessageType = new ResponseMessageType(); + StatusType statusType = null; + String responseString = null; + ResultResponseType resultResponseType = null; + BodyType bodyType = new BodyType(); + try { + //TODO removed ejbs +// QueryInfoLocalHome queryInfoLocalHome = qpUtil +// .getQueryInfoLocalHome(); +// QueryInfoLocal queryInfoLocal = queryInfoLocalHome.create(); + String resultInstanceId = resultRequestType + .getQueryResultInstanceId(); + String description = resultRequestType.getDescription(); + QueryInfoBean query = new QueryInfoBean(); + + resultResponseType = query + .updateResultInstanceDescription( + this.getDataSourceLookup(), resultInstanceId, + description); + resultResponseType.setStatus(this.buildCRCStausType( + RequestHandlerDelegate.DONE_TYPE, "DONE")); + + } catch (Exception e) { + resultResponseType = new ResultResponseType(); + resultResponseType.setStatus(this.buildCRCStausType( + RequestHandlerDelegate.ERROR_TYPE, e.getMessage())); + } finally { + edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); + bodyType.getAny().add(of.createResponse(resultResponseType)); + + } + return bodyType; + } + + // function to build StatusType for the given message + private StatusType buildStatusType(String statusTypeString, String message) { + StatusType statusType = new StatusType(); + statusType.setType(statusTypeString); + statusType.setValue(message); + + return statusType; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/ExecRunnable.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/ExecRunnable.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/ExecRunnable.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/ExecRunnable.java index 402130f7..2bccdf5c --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/ExecRunnable.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/ExecRunnable.java @@ -1,501 +1,500 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.ejb; - -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import javax.sql.DataSource; - -import jakarta.xml.bind.JAXBElement; - -import org.apache.catalina.tribes.tipis.AbstractReplicatedMap.MapMessage; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.ServiceLocator; -import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.dao.IDAOFactory; -import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; -import edu.harvard.i2b2.crc.dao.setfinder.CRCTimeOutException; -import edu.harvard.i2b2.crc.dao.setfinder.CheckSkipTempTable; -import edu.harvard.i2b2.crc.dao.setfinder.IQueryInstanceDao; -import edu.harvard.i2b2.crc.dao.setfinder.IQueryMasterDao; -import edu.harvard.i2b2.crc.dao.setfinder.QueryExecutorDao; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.db.QtQueryInstance; -import edu.harvard.i2b2.crc.datavo.db.QtQueryMaster; -import edu.harvard.i2b2.crc.datavo.db.QtQueryStatusType; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.PsmQryHeaderType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionRequestType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryModeType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultOutputOptionListType; -import edu.harvard.i2b2.crc.delegate.ejbpm.EJBPMUtil; -import edu.harvard.i2b2.crc.role.AuthrizationHelper; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - -public class ExecRunnable implements Runnable{ - private static Log log = LogFactory.getLog(ExecRunnable.class); -// - protected static Log logesapi = LogFactory.getLog(ExecRunnable.class); - - String sqlString = ""; - String queryInstanceId = ""; - String patientSetId = ""; - String xmlRequest = ""; - String dsLookupDomainId= ""; - String dsLookupProjectId =""; - String dsLookupOwnerId = ""; - String pmXml = null; - int transactionTimeout; - - Map returnMap = new HashMap(); - - public ExecRunnable() { - } - - private Exception ex = null; - - private String callingMDBName = QueryManagerBeanUtil.RUNNING, sessionId = ""; - // default timeout three minutes -// int transactionTimeout = 0; - -// private volatile boolean running = true; - -// public void terminate() { -// running = false; -// } - - MapMessage message = null; - private boolean jobCompleteFlag = false; - private boolean jobErrorFlag = false; - - - public boolean isJobErrorFlag() { - return jobErrorFlag; - } - - public void setJobErrorFlag(boolean jobErrorFlag) { - this.jobErrorFlag = jobErrorFlag; - } - - public Exception getJobException() { - return ex; - } - - public boolean isJobCompleteFlag() { - return jobCompleteFlag; - } - - public void setJobCompleteFlag(boolean jobCompleteFlag) { - this.jobCompleteFlag = jobCompleteFlag; - } - - public void setJobException(Exception ex) { - this.ex = ex; - } - public Map getResult() { - - return returnMap; - } - - @Override - public void run() { - - try { - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - boolean allowLargeTextValueConstrainFlag = true; - List userRoles = null; - int queryResultInstanceId = 0; - - QtQueryInstance queryInstance = null; - IQueryInstanceDao queryInstanceDao = null; - try { - - - log.debug("domain id" + dsLookupDomainId + " " - + dsLookupProjectId + " " + dsLookupOwnerId - + " *********************"); - - DAOFactoryHelper daoFactoryHelper = new DAOFactoryHelper( - dsLookupDomainId, dsLookupProjectId, dsLookupOwnerId); - - IDAOFactory daoFactory = daoFactoryHelper.getDAOFactory(); - - SetFinderDAOFactory sfDAOFactory = daoFactory - .getSetFinderDAOFactory(); - DataSourceLookup dsLookup = sfDAOFactory.getDataSourceLookup(); - logesapi.debug("ORIG domain id" - + sfDAOFactory.getOriginalDataSourceLookup() - .getDomainId() - + " ORIG " - + sfDAOFactory.getOriginalDataSourceLookup() - .getProjectPath() - + " ORIG " - + sfDAOFactory.getOriginalDataSourceLookup() - .getOwnerId()); - - try { - AuthrizationHelper authHelper = new AuthrizationHelper(dsLookupDomainId, dsLookupProjectId, dsLookupOwnerId, daoFactory); - authHelper.checkRoleForProtectionLabel("SETFINDER_QRY_WITH_LGTEXT"); - } catch(I2B2Exception i2b2Ex) { - allowLargeTextValueConstrainFlag = false; - } - - try { - AuthrizationHelper authHelper = new AuthrizationHelper(dsLookupDomainId, dsLookupProjectId, dsLookupOwnerId, daoFactory); - userRoles = authHelper.getRolesFromCache(); - } catch(I2B2Exception i2b2Ex) { - //allowProtectedQueryFlag = false; - } - //try { - // check if the status is cancelled - queryInstanceDao = sfDAOFactory - .getQueryInstanceDAO(); - queryInstance = queryInstanceDao - .getQueryInstanceByInstanceId(queryInstanceId); - int queryStatusId = queryInstance.getQtQueryStatusType() - .getStatusTypeId(); - if (queryStatusId == 9) { - log - .info("Ignoring this query, query status was 'Cancelled'"); - //check end date, if not set set now - if (queryInstance.getEndDate() == null) - { - - - queryInstance.setEndDate(new Date(System - .currentTimeMillis())); - queryInstanceDao.update(queryInstance, false); - - } - } else { - // set the query instance batch mode to queue name - if (queryInstance.getBatchMode().equals(QueryManagerBeanUtil.MEDIUM_QUEUE)) - queryInstance.setBatchMode(QueryManagerBeanUtil.MEDIUM_QUEUE_RUNNING); - else if (queryInstance.getBatchMode().equals(QueryManagerBeanUtil.LARGE_QUEUE)) - queryInstance.setBatchMode(QueryManagerBeanUtil.LARGE_QUEUE_RUNNING); - else - queryInstance.setBatchMode(this.callingMDBName); - - queryInstanceDao.update(queryInstance, false); - - patientSetId = processQueryRequest( - transactionTimeout, dsLookup, sfDAOFactory, - xmlRequest, sqlString, sessionId, - queryInstanceId, patientSetId,allowLargeTextValueConstrainFlag, pmXml, userRoles); - - } - -// String masterType = queryInstance.getQtQueryMaster().getMasterTypeCd(); - - IQueryMasterDao queryMaster = sfDAOFactory.getQueryMasterDAO(); - QtQueryMaster queryDef = queryMaster.getQueryDefinition( queryInstance.getQtQueryMaster().getQueryMasterId()); - - String masterType= queryDef.getMasterTypeCd(); -// QueryMasterSpringDao masterType2 = new QueryMasterSpringDao(); - -// queryInstance.getQtQueryMaster().gt - // QtQueryMaster queryMaster = queryInstanceDao.ge queryMasterDao - // .getQueryDefinition(queryInstance.getQtQueryMaster().getQueryMasterId()); - // String masterType = queryInstanceDao.getQueryDefinition(queryInstance.getQtQueryMaster().getQueryMasterId()); - - // outputString = reqHandler.execute(); - setJobCompleteFlag(true); - log.info("Exec Finished Running Query"); - - if (masterType != null && masterType.equals("EXPORT")) - queryInstance.setBatchMode(QueryManagerBeanUtil.SUBMITTED); - else - queryInstance.setBatchMode(QueryManagerBeanUtil.FINISHED); - - // status and end time were missing -- added during transactionTimeout fix - QtQueryStatusType queryStatusType = queryInstance.getQtQueryStatusType(); - queryStatusType.setStatusTypeId(3); - queryStatusType.setName("DONE"); - queryStatusType.setDescription("DONE"); - queryInstance.setQtQueryStatusType(queryStatusType); - - queryInstance.setEndDate(new Date(System - .currentTimeMillis())); - - queryInstanceDao.update(queryInstance, true); - - returnMap.put(QueryManagerBeanUtil.QUERY_STATUS_PARAM, "DONE"); - returnMap.put(QueryManagerBeanUtil.QT_QUERY_RESULT_INSTANCE_ID_PARAM, queryResultInstanceId); - } - catch (CRCTimeOutException daoEx) { - log.info("Caught query time out"); - // catch this error and ignore. send general reply message. - setJobCompleteFlag(false); - // following commented out during transaction timeout fix - // setJobException(daoEx); - // setJobErrorFlag(true); - - try { - Thread.sleep(10000); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - return; - } - - } catch (Exception e) { - e.printStackTrace(); - if(e.getMessage() != null){ - log.error(e.getMessage()); - if(e.getMessage().contains("Interrupted")){ - log.info("Received interrupt"); - return; - } - } - setJobException(e); - setJobErrorFlag(true); - - if (queryInstance != null) - { - queryInstance.setBatchMode(QueryManagerBeanUtil.ERROR); - QtQueryStatusType queryStatusType = queryInstance.getQtQueryStatusType(); - queryStatusType.setStatusTypeId(4); - queryInstance.setQtQueryStatusType(queryStatusType); - queryInstance.setEndDate(new Date(System - .currentTimeMillis())); - try { - queryInstanceDao.update(queryInstance, false); - } catch (Exception e2) { - log.error("Problem updating query instance to ERROR " + e.getMessage()); - } - } - returnMap.put(QueryManagerBeanUtil.QUERY_STATUS_PARAM, "ERROR"); - returnMap.put(QueryManagerBeanUtil.QT_QUERY_RESULT_INSTANCE_ID_PARAM, queryResultInstanceId); - setJobCompleteFlag(true); - - log.error("Job Exception: " + getJobException().getMessage()); - - try { - Thread.sleep(10000); - } catch (InterruptedException e1) { - ; - } - - } - } catch (Exception e) { - log.error("Exception", e); - - } - - } - - /**/ - public ExecRunnable(int transactionTimeout, - String callingMDBName, MapMessage message, String sessionId) { - this.transactionTimeout = transactionTimeout; - this.callingMDBName = callingMDBName; - this.message = message; - this.sessionId = sessionId; - } - - public ExecRunnable(String sqlString, String queryInstanceId, String patientSetId , - String xmlRequest, String dsLookupDomainId, String dsLookupProjectId , - String dsLookupOwnerId, String pmXml, int transactionTimeout) throws Exception { - - this.sqlString = sqlString; - this.queryInstanceId = queryInstanceId; - this.patientSetId = patientSetId; - this.xmlRequest = xmlRequest; - this.dsLookupDomainId = dsLookupDomainId; - this.dsLookupProjectId = dsLookupProjectId; - this.dsLookupOwnerId = dsLookupOwnerId; - this.pmXml = pmXml; - - this.transactionTimeout = transactionTimeout; - - - } - - public void execute(String sqlString, String queryInstanceId, String patientSetId , - String xmlRequest, String dsLookupDomainId, String dsLookupProjectId , - String dsLookupOwnerId, long waitTimeMs ) throws Exception { - - this.sqlString = sqlString; - this.queryInstanceId = queryInstanceId; - this.patientSetId = patientSetId; - this.xmlRequest = xmlRequest; - this.dsLookupDomainId = dsLookupDomainId; - this.dsLookupProjectId = dsLookupProjectId; - this.dsLookupOwnerId = dsLookupOwnerId; - - this.transactionTimeout = (int) (waitTimeMs/1000); - } - - private String processQueryRequest( - int transactionTimeout, DataSourceLookup dsLookup, - SetFinderDAOFactory sfDAOFactory, String xmlRequest, - String sqlString, String sessionId, String queryInstanceId, - String patientSetId, boolean allowLargeTextValueConstrainFlag, String pmXml, List userRoles) throws I2B2DAOException, I2B2Exception, JAXBUtilException { - - QueryDefinitionRequestType qdRequestType = getQueryDefinitionRequestType(xmlRequest); - ResultOutputOptionListType resultOutputList = qdRequestType - .getResultOutputList(); - DataSource dataSource = ServiceLocator.getInstance() - .getAppServerDataSource(dsLookup.getDataSource()); - - QueryExecutorDao queryExDao = new QueryExecutorDao(dataSource, - dsLookup, sfDAOFactory.getOriginalDataSourceLookup()); - - //see if the query will be direct query(no temp table) - boolean queryWithoutTempTableFlag = false; - boolean queryCountMinSketchFlag = false; - - PsmQryHeaderType psmQryHeaderType = getSetfinderRequestHeaderType(xmlRequest); - if (psmQryHeaderType != null && psmQryHeaderType.getQueryMode() != null) { - String queryMode = psmQryHeaderType.getQueryMode().value(); - - if (queryMode.equals(QueryModeType.OPTIMIZE_WITHOUT_TEMP_TABLE.value())) { - log.debug("Setfinder query header has [optimize_without_temp_table]"); - CheckSkipTempTable checkSkipTempTable = new CheckSkipTempTable(); - queryWithoutTempTableFlag = checkSkipTempTable.getSkipTempTable(qdRequestType, resultOutputList); - log.debug("Sefinder query without temp table flag [" + queryWithoutTempTableFlag +"]"); - } else if (queryMode.equals(QueryModeType.COUNT_MIN_SKETCH.value())) { - queryCountMinSketchFlag = true; - } else { - log.debug("Setfinder query header doesnt have [optimize_without_temp_table]"); - } - } else { - log.debug("Setfinder query request header is null"); - } - queryExDao.setQueryCountMinSketchFlag(queryCountMinSketchFlag); - queryExDao.setQueryWithoutTempTableFlag(queryWithoutTempTableFlag); - - queryExDao.executeSQL( transactionTimeout, dsLookup, - sfDAOFactory, xmlRequest, sqlString, queryInstanceId, - patientSetId, resultOutputList,allowLargeTextValueConstrainFlag, pmXml, userRoles); - - return patientSetId; - } - - private QueryDefinitionRequestType getQueryDefinitionRequestType( - String xmlRequest) throws I2B2Exception { - String queryName = null; - QueryDefinitionType queryDef = null; - JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); - JAXBElement jaxbElement = null; - QueryDefinitionRequestType queryDefReqType = null; - try { - jaxbElement = jaxbUtil.unMashallFromString(xmlRequest); - - if (jaxbElement == null) { - throw new I2B2Exception( - "null value in after unmarshalling request string "); - } - - RequestMessageType requestMessageType = (RequestMessageType) jaxbElement - .getValue(); - requestMessageType.getMessageHeader().getSecurity(); - requestMessageType.getMessageHeader().getProjectId(); - - - BodyType bodyType = requestMessageType.getMessageBody(); - JAXBUnWrapHelper unWrapHelper = new JAXBUnWrapHelper(); - queryDefReqType = (QueryDefinitionRequestType) unWrapHelper - .getObjectByClass(bodyType.getAny(), - QueryDefinitionRequestType.class); - } catch (JAXBUtilException e) { - log.error(e.getMessage(), e); - throw new I2B2Exception(e.getMessage(), e); - } - return queryDefReqType; - - } - - private PsmQryHeaderType getSetfinderRequestHeaderType( - String xmlRequest) throws I2B2Exception { - String queryName = null; - QueryDefinitionType queryDef = null; - JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); - JAXBElement jaxbElement = null; - PsmQryHeaderType psmHeaderType = null; - try { - jaxbElement = jaxbUtil.unMashallFromString(xmlRequest); - - if (jaxbElement == null) { - throw new I2B2Exception( - "null value in after unmarshalling request string "); - } - - RequestMessageType requestMessageType = (RequestMessageType) jaxbElement - .getValue(); - BodyType bodyType = requestMessageType.getMessageBody(); - JAXBUnWrapHelper unWrapHelper = new JAXBUnWrapHelper(); - psmHeaderType = (PsmQryHeaderType) unWrapHelper - .getObjectByClass(bodyType.getAny(), - PsmQryHeaderType.class); - - } catch (JAXBUtilException e) { - log.error(e.getMessage(), e); - throw new I2B2Exception(e.getMessage(), e); - } - return psmHeaderType; - - } - - - private void setQueryInstanceStatus(SetFinderDAOFactory sfDAOFactory, - String queryInstanceId, int statusTypeId, String message) throws I2B2DAOException { - - IQueryInstanceDao queryInstanceDao = sfDAOFactory.getQueryInstanceDAO(); - QtQueryInstance queryInstance = queryInstanceDao - .getQueryInstanceByInstanceId(queryInstanceId); - - QtQueryStatusType queryStatusType = new QtQueryStatusType(); - queryStatusType.setStatusTypeId(statusTypeId); - queryInstance.setQtQueryStatusType(queryStatusType); - queryInstance.setEndDate(new Date(System.currentTimeMillis())); - queryInstance.setMessage(message); - queryInstance.setBatchMode(callingMDBName); - queryInstanceDao.update(queryInstance, true); - } - - /* - private int readTimeoutPropertyValue(String queueType) { - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - String timeoutStr = ""; - int timeoutVal = 0; - try { - if (queueType.equals(SMALL_QUEUE)) { - timeoutStr = qpUtil - .getCRCPropertyValue("edu.harvard.i2b2.crc.jms.small.timeoutsec"); - } else if (queueType.equals(MEDIUM_QUEUE)) { - timeoutStr = qpUtil - .getCRCPropertyValue("edu.harvard.i2b2.crc.jms.medium.timeoutsec"); - } else if (queueType.equals(LARGE_QUEUE)) { - timeoutStr = qpUtil - .getCRCPropertyValue("edu.harvard.i2b2.crc.jms.large.timeoutsec"); - } - timeoutVal = Integer.parseInt(timeoutStr); - - } catch (I2B2Exception ex) { - ex.printStackTrace(); - } - return timeoutVal; - - } - */ -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.ejb; + +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.sql.DataSource; + +import jakarta.xml.bind.JAXBElement; + +import org.apache.catalina.tribes.tipis.AbstractReplicatedMap.MapMessage; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.ServiceLocator; +import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.dao.IDAOFactory; +import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; +import edu.harvard.i2b2.crc.dao.setfinder.CRCTimeOutException; +import edu.harvard.i2b2.crc.dao.setfinder.CheckSkipTempTable; +import edu.harvard.i2b2.crc.dao.setfinder.IQueryInstanceDao; +import edu.harvard.i2b2.crc.dao.setfinder.IQueryMasterDao; +import edu.harvard.i2b2.crc.dao.setfinder.QueryExecutorDao; +import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.db.QtQueryInstance; +import edu.harvard.i2b2.crc.datavo.db.QtQueryMaster; +import edu.harvard.i2b2.crc.datavo.db.QtQueryStatusType; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.PsmQryHeaderType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionRequestType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryModeType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultOutputOptionListType; +import edu.harvard.i2b2.crc.delegate.ejbpm.EJBPMUtil; +import edu.harvard.i2b2.crc.role.AuthrizationHelper; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + +public class ExecRunnable implements Runnable{ + private static Log log = LogFactory.getLog(ExecRunnable.class); +// + protected static Log logesapi = LogFactory.getLog(ExecRunnable.class); + + String sqlString = ""; + String queryInstanceId = ""; + String patientSetId = ""; + String xmlRequest = ""; + String dsLookupDomainId= ""; + String dsLookupProjectId =""; + String dsLookupOwnerId = ""; + String pmXml = null; + int transactionTimeout; + + Map returnMap = new HashMap(); + + public ExecRunnable() { + } + + private Exception ex = null; + + private String callingMDBName = QueryManagerBeanUtil.RUNNING, sessionId = ""; + // default timeout three minutes +// int transactionTimeout = 0; + +// private volatile boolean running = true; + +// public void terminate() { +// running = false; +// } + + MapMessage message = null; + private boolean jobCompleteFlag = false; + private boolean jobErrorFlag = false; + + + public boolean isJobErrorFlag() { + return jobErrorFlag; + } + + public void setJobErrorFlag(boolean jobErrorFlag) { + this.jobErrorFlag = jobErrorFlag; + } + + public Exception getJobException() { + return ex; + } + + public boolean isJobCompleteFlag() { + return jobCompleteFlag; + } + + public void setJobCompleteFlag(boolean jobCompleteFlag) { + this.jobCompleteFlag = jobCompleteFlag; + } + + public void setJobException(Exception ex) { + this.ex = ex; + } + public Map getResult() { + + return returnMap; + } + + @Override + public void run() { + + try { + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + boolean allowLargeTextValueConstrainFlag = true; + List userRoles = null; + int queryResultInstanceId = 0; + + QtQueryInstance queryInstance = null; + IQueryInstanceDao queryInstanceDao = null; + try { + + + log.debug("domain id" + dsLookupDomainId + " " + + dsLookupProjectId + " " + dsLookupOwnerId + + " *********************"); + + DAOFactoryHelper daoFactoryHelper = new DAOFactoryHelper( + dsLookupDomainId, dsLookupProjectId, dsLookupOwnerId); + + IDAOFactory daoFactory = daoFactoryHelper.getDAOFactory(); + + SetFinderDAOFactory sfDAOFactory = daoFactory + .getSetFinderDAOFactory(); + DataSourceLookup dsLookup = sfDAOFactory.getDataSourceLookup(); + logesapi.debug("ORIG domain id" + + sfDAOFactory.getOriginalDataSourceLookup() + .getDomainId() + + " ORIG " + + sfDAOFactory.getOriginalDataSourceLookup() + .getProjectPath() + + " ORIG " + + sfDAOFactory.getOriginalDataSourceLookup() + .getOwnerId()); + + try { + AuthrizationHelper authHelper = new AuthrizationHelper(dsLookupDomainId, dsLookupProjectId, dsLookupOwnerId, daoFactory); + authHelper.checkRoleForProtectionLabel("SETFINDER_QRY_WITH_LGTEXT"); + } catch(I2B2Exception i2b2Ex) { + allowLargeTextValueConstrainFlag = false; + } + + try { + AuthrizationHelper authHelper = new AuthrizationHelper(dsLookupDomainId, dsLookupProjectId, dsLookupOwnerId, daoFactory); + userRoles = authHelper.getRolesFromCache(); + } catch(I2B2Exception i2b2Ex) { + //allowProtectedQueryFlag = false; + } + //try { + // check if the status is cancelled + queryInstanceDao = sfDAOFactory + .getQueryInstanceDAO(); + queryInstance = queryInstanceDao + .getQueryInstanceByInstanceId(queryInstanceId); + int queryStatusId = queryInstance.getQtQueryStatusType() + .getStatusTypeId(); + if (queryStatusId == 9) { + log + .info("Ignoring this query, query status was 'Cancelled'"); + //check end date, if not set set now + if (queryInstance.getEndDate() == null) + { + + + queryInstance.setEndDate(new Date(System + .currentTimeMillis())); + queryInstanceDao.update(queryInstance, false); + + } + } else { + // set the query instance batch mode to queue name + if (queryInstance.getBatchMode().equals(QueryManagerBeanUtil.MEDIUM_QUEUE)) + queryInstance.setBatchMode(QueryManagerBeanUtil.MEDIUM_QUEUE_RUNNING); + else if (queryInstance.getBatchMode().equals(QueryManagerBeanUtil.LARGE_QUEUE)) + queryInstance.setBatchMode(QueryManagerBeanUtil.LARGE_QUEUE_RUNNING); + else + queryInstance.setBatchMode(this.callingMDBName); + + queryInstanceDao.update(queryInstance, false); + + patientSetId = processQueryRequest( + transactionTimeout, dsLookup, sfDAOFactory, + xmlRequest, sqlString, sessionId, + queryInstanceId, patientSetId,allowLargeTextValueConstrainFlag, pmXml, userRoles); + + } + +// String masterType = queryInstance.getQtQueryMaster().getMasterTypeCd(); + + IQueryMasterDao queryMaster = sfDAOFactory.getQueryMasterDAO(); + QtQueryMaster queryDef = queryMaster.getQueryDefinition( queryInstance.getQtQueryMaster().getQueryMasterId()); + + String masterType= queryDef.getMasterTypeCd(); +// QueryMasterSpringDao masterType2 = new QueryMasterSpringDao(); + +// queryInstance.getQtQueryMaster().gt + // QtQueryMaster queryMaster = queryInstanceDao.ge queryMasterDao + // .getQueryDefinition(queryInstance.getQtQueryMaster().getQueryMasterId()); + // String masterType = queryInstanceDao.getQueryDefinition(queryInstance.getQtQueryMaster().getQueryMasterId()); + + // outputString = reqHandler.execute(); + setJobCompleteFlag(true); + log.info("Exec Finished Running Query"); + + if (masterType != null && masterType.equals("EXPORT")) + queryInstance.setBatchMode(QueryManagerBeanUtil.SUBMITTED); + else + queryInstance.setBatchMode(QueryManagerBeanUtil.FINISHED); + + // status and end time were missing -- added during transactionTimeout fix + QtQueryStatusType queryStatusType = queryInstance.getQtQueryStatusType(); + queryStatusType.setStatusTypeId(3); + queryStatusType.setName("DONE"); + queryStatusType.setDescription("DONE"); + queryInstance.setQtQueryStatusType(queryStatusType); + + queryInstance.setEndDate(new Date(System + .currentTimeMillis())); + + queryInstanceDao.update(queryInstance, true); + + returnMap.put(QueryManagerBeanUtil.QUERY_STATUS_PARAM, "DONE"); + returnMap.put(QueryManagerBeanUtil.QT_QUERY_RESULT_INSTANCE_ID_PARAM, queryResultInstanceId); + } + catch (CRCTimeOutException daoEx) { + log.info("Caught query time out"); + // catch this error and ignore. send general reply message. + setJobCompleteFlag(false); + // following commented out during transaction timeout fix + // setJobException(daoEx); + // setJobErrorFlag(true); + + try { + Thread.sleep(10000); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + return; + } + + } catch (Exception e) { + e.printStackTrace(); + if(e.getMessage() != null){ + log.error(e.getMessage()); + if(e.getMessage().contains("Interrupted")){ + log.info("Received interrupt"); + return; + } + } + setJobException(e); + setJobErrorFlag(true); + + if (queryInstance != null) + { + queryInstance.setBatchMode(QueryManagerBeanUtil.ERROR); + QtQueryStatusType queryStatusType = queryInstance.getQtQueryStatusType(); + queryStatusType.setStatusTypeId(4); + queryInstance.setQtQueryStatusType(queryStatusType); + queryInstance.setEndDate(new Date(System + .currentTimeMillis())); + try { + queryInstanceDao.update(queryInstance, false); + } catch (Exception e2) { + log.error("Problem updating query instance to ERROR " + e.getMessage()); + } + } + returnMap.put(QueryManagerBeanUtil.QUERY_STATUS_PARAM, "ERROR"); + returnMap.put(QueryManagerBeanUtil.QT_QUERY_RESULT_INSTANCE_ID_PARAM, queryResultInstanceId); + setJobCompleteFlag(true); + + log.error("Job Exception: " + getJobException().getMessage()); + + try { + Thread.sleep(10000); + } catch (InterruptedException e1) { + ; + } + + } + } catch (Exception e) { + log.error("Exception", e); + + } + + } + + /**/ + public ExecRunnable(int transactionTimeout, + String callingMDBName, MapMessage message, String sessionId) { + this.transactionTimeout = transactionTimeout; + this.callingMDBName = callingMDBName; + this.message = message; + this.sessionId = sessionId; + } + + public ExecRunnable(String sqlString, String queryInstanceId, String patientSetId , + String xmlRequest, String dsLookupDomainId, String dsLookupProjectId , + String dsLookupOwnerId, String pmXml, int transactionTimeout) throws Exception { + + this.sqlString = sqlString; + this.queryInstanceId = queryInstanceId; + this.patientSetId = patientSetId; + this.xmlRequest = xmlRequest; + this.dsLookupDomainId = dsLookupDomainId; + this.dsLookupProjectId = dsLookupProjectId; + this.dsLookupOwnerId = dsLookupOwnerId; + this.pmXml = pmXml; + + this.transactionTimeout = transactionTimeout; + + + } + + public void execute(String sqlString, String queryInstanceId, String patientSetId , + String xmlRequest, String dsLookupDomainId, String dsLookupProjectId , + String dsLookupOwnerId, long waitTimeMs ) throws Exception { + + this.sqlString = sqlString; + this.queryInstanceId = queryInstanceId; + this.patientSetId = patientSetId; + this.xmlRequest = xmlRequest; + this.dsLookupDomainId = dsLookupDomainId; + this.dsLookupProjectId = dsLookupProjectId; + this.dsLookupOwnerId = dsLookupOwnerId; + + this.transactionTimeout = (int) (waitTimeMs/1000); + } + + private String processQueryRequest( + int transactionTimeout, DataSourceLookup dsLookup, + SetFinderDAOFactory sfDAOFactory, String xmlRequest, + String sqlString, String sessionId, String queryInstanceId, + String patientSetId, boolean allowLargeTextValueConstrainFlag, String pmXml, List userRoles) throws I2B2DAOException, I2B2Exception, JAXBUtilException { + + QueryDefinitionRequestType qdRequestType = getQueryDefinitionRequestType(xmlRequest); + ResultOutputOptionListType resultOutputList = qdRequestType + .getResultOutputList(); + DataSource dataSource = ServiceLocator.getInstance() + .getAppServerDataSource(dsLookup.getDataSource()); + + QueryExecutorDao queryExDao = new QueryExecutorDao(dataSource, + dsLookup, sfDAOFactory.getOriginalDataSourceLookup()); + + //see if the query will be direct query(no temp table) + boolean queryWithoutTempTableFlag = false; + boolean queryCountMinSketchFlag = false; + + PsmQryHeaderType psmQryHeaderType = getSetfinderRequestHeaderType(xmlRequest); + if (psmQryHeaderType != null && psmQryHeaderType.getQueryMode() != null) { + String queryMode = psmQryHeaderType.getQueryMode().value(); + + if (queryMode.equals(QueryModeType.OPTIMIZE_WITHOUT_TEMP_TABLE.value())) { + log.debug("Setfinder query header has [optimize_without_temp_table]"); + CheckSkipTempTable checkSkipTempTable = new CheckSkipTempTable(); + queryWithoutTempTableFlag = checkSkipTempTable.getSkipTempTable(qdRequestType, resultOutputList); + log.debug("Sefinder query without temp table flag [" + queryWithoutTempTableFlag +"]"); + } else if (queryMode.equals(QueryModeType.COUNT_MIN_SKETCH.value())) { + queryCountMinSketchFlag = true; + } else { + log.debug("Setfinder query header doesnt have [optimize_without_temp_table]"); + } + } else { + log.debug("Setfinder query request header is null"); + } + queryExDao.setQueryCountMinSketchFlag(queryCountMinSketchFlag); + queryExDao.setQueryWithoutTempTableFlag(queryWithoutTempTableFlag); + + queryExDao.executeSQL( transactionTimeout, dsLookup, + sfDAOFactory, xmlRequest, sqlString, queryInstanceId, + patientSetId, resultOutputList,allowLargeTextValueConstrainFlag, pmXml, userRoles); + + return patientSetId; + } + + private QueryDefinitionRequestType getQueryDefinitionRequestType( + String xmlRequest) throws I2B2Exception { + String queryName = null; + QueryDefinitionType queryDef = null; + JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); + JAXBElement jaxbElement = null; + QueryDefinitionRequestType queryDefReqType = null; + try { + jaxbElement = jaxbUtil.unMashallFromString(xmlRequest); + + if (jaxbElement == null) { + throw new I2B2Exception( + "null value in after unmarshalling request string "); + } + + RequestMessageType requestMessageType = (RequestMessageType) jaxbElement + .getValue(); + requestMessageType.getMessageHeader().getSecurity(); + requestMessageType.getMessageHeader().getProjectId(); + + + BodyType bodyType = requestMessageType.getMessageBody(); + JAXBUnWrapHelper unWrapHelper = new JAXBUnWrapHelper(); + queryDefReqType = (QueryDefinitionRequestType) unWrapHelper + .getObjectByClass(bodyType.getAny(), + QueryDefinitionRequestType.class); + } catch (JAXBUtilException e) { + log.error(e.getMessage(), e); + throw new I2B2Exception(e.getMessage(), e); + } + return queryDefReqType; + + } + + private PsmQryHeaderType getSetfinderRequestHeaderType( + String xmlRequest) throws I2B2Exception { + String queryName = null; + QueryDefinitionType queryDef = null; + JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); + JAXBElement jaxbElement = null; + PsmQryHeaderType psmHeaderType = null; + try { + jaxbElement = jaxbUtil.unMashallFromString(xmlRequest); + + if (jaxbElement == null) { + throw new I2B2Exception( + "null value in after unmarshalling request string "); + } + + RequestMessageType requestMessageType = (RequestMessageType) jaxbElement + .getValue(); + BodyType bodyType = requestMessageType.getMessageBody(); + JAXBUnWrapHelper unWrapHelper = new JAXBUnWrapHelper(); + psmHeaderType = (PsmQryHeaderType) unWrapHelper + .getObjectByClass(bodyType.getAny(), + PsmQryHeaderType.class); + + } catch (JAXBUtilException e) { + log.error(e.getMessage(), e); + throw new I2B2Exception(e.getMessage(), e); + } + return psmHeaderType; + + } + + + private void setQueryInstanceStatus(SetFinderDAOFactory sfDAOFactory, + String queryInstanceId, int statusTypeId, String message) throws I2B2DAOException { + + IQueryInstanceDao queryInstanceDao = sfDAOFactory.getQueryInstanceDAO(); + QtQueryInstance queryInstance = queryInstanceDao + .getQueryInstanceByInstanceId(queryInstanceId); + + QtQueryStatusType queryStatusType = new QtQueryStatusType(); + queryStatusType.setStatusTypeId(statusTypeId); + queryInstance.setQtQueryStatusType(queryStatusType); + queryInstance.setEndDate(new Date(System.currentTimeMillis())); + queryInstance.setMessage(message); + queryInstance.setBatchMode(callingMDBName); + queryInstanceDao.update(queryInstance, true); + } + + /* + private int readTimeoutPropertyValue(String queueType) { + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + String timeoutStr = ""; + int timeoutVal = 0; + try { + if (queueType.equals(SMALL_QUEUE)) { + timeoutStr = qpUtil + .getCRCPropertyValue("edu.harvard.i2b2.crc.jms.small.timeoutsec"); + } else if (queueType.equals(MEDIUM_QUEUE)) { + timeoutStr = qpUtil + .getCRCPropertyValue("edu.harvard.i2b2.crc.jms.medium.timeoutsec"); + } else if (queueType.equals(LARGE_QUEUE)) { + timeoutStr = qpUtil + .getCRCPropertyValue("edu.harvard.i2b2.crc.jms.large.timeoutsec"); + } + timeoutVal = Integer.parseInt(timeoutStr); + + } catch (I2B2Exception ex) { + ex.printStackTrace(); + } + return timeoutVal; + + } + */ +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/PdoQueryBean.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/PdoQueryBean.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/PdoQueryBean.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/PdoQueryBean.java index 0f3315f4..c7e984b0 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/PdoQueryBean.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/PdoQueryBean.java @@ -1,664 +1,664 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.ejb; - -import java.io.StringWriter; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -//import javax.ejb.CreateException; -//import javax.ejb.EJBException; -//import javax.ejb.SessionBean; -//import javax.ejb.SessionContext; -import jakarta.xml.bind.JAXBElement; -import javax.xml.stream.XMLStreamException; - -import org.apache.axis2.AxisFault; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.exception.StackTraceUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.dao.IDAOFactory; -import edu.harvard.i2b2.crc.dao.PatientDataDAOFactory; -import edu.harvard.i2b2.crc.dao.pdo.IMetadataDao; -import edu.harvard.i2b2.crc.dao.pdo.IObservationFactDao; -import edu.harvard.i2b2.crc.dao.pdo.MetaDataTypeMapper; -import edu.harvard.i2b2.crc.dao.pdo.MetadataDao; -import edu.harvard.i2b2.crc.dao.pdo.MetadataDao.TableMetaData; -import edu.harvard.i2b2.crc.dao.pdo.PdoQueryHandler; -import edu.harvard.i2b2.crc.dao.pdo.input.IInputOptionListHandler; -import edu.harvard.i2b2.crc.dao.pdo.input.OutputOptionFactRelatedHelper; -import edu.harvard.i2b2.crc.dao.pdo.input.PDOFactory; -import edu.harvard.i2b2.crc.dao.pdo.input.PagingHandler; -import edu.harvard.i2b2.crc.dao.setfinder.IQueryPdoMasterDao; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.ItemMetaDataHandler; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.db.QtQueryMaster; -import edu.harvard.i2b2.crc.datavo.i2b2message.PasswordType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; -import edu.harvard.i2b2.crc.datavo.ontology.ConceptType; -import edu.harvard.i2b2.crc.datavo.ontology.ModifierType; -import edu.harvard.i2b2.crc.datavo.ontology.XmlValueType; -import edu.harvard.i2b2.crc.datavo.pdo.ParamType; -import edu.harvard.i2b2.crc.datavo.pdo.PatientDataType; -import edu.harvard.i2b2.crc.datavo.pdo.query.FilterListType; -import edu.harvard.i2b2.crc.datavo.pdo.query.GetObservationFactByPrimaryKeyRequestType; -import edu.harvard.i2b2.crc.datavo.pdo.query.GetPDOFromInputListRequestType; -import edu.harvard.i2b2.crc.datavo.pdo.query.InputOptionListType; -import edu.harvard.i2b2.crc.datavo.pdo.query.ItemType; -import edu.harvard.i2b2.crc.datavo.pdo.query.MetadataxmlValueType; -import edu.harvard.i2b2.crc.datavo.pdo.query.OutputOptionNameType; -import edu.harvard.i2b2.crc.datavo.pdo.query.PageByPatientType; -import edu.harvard.i2b2.crc.datavo.pdo.query.PageRangeType; -import edu.harvard.i2b2.crc.datavo.pdo.query.PageType; -import edu.harvard.i2b2.crc.datavo.pdo.query.PanelType; -import edu.harvard.i2b2.crc.datavo.pdo.query.PatientDataResponseType; -import edu.harvard.i2b2.crc.datavo.pdo.query.RangeType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionType; -import edu.harvard.i2b2.crc.delegate.ontology.CallOntologyUtil; -import edu.harvard.i2b2.crc.role.AuthrizationHelper; -import edu.harvard.i2b2.crc.util.I2B2RequestMessageHelper; -import edu.harvard.i2b2.crc.util.PMServiceAccountUtil; -import edu.harvard.i2b2.crc.util.ParamUtil; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - -/** - * This is the PDO Query ejb class. It passes pdo query request's to the - * appropriate dao classes to get response in pdo format. - * - * @ejb.bean description="Patient data Query bean" - * display-name="Patient data Query" - * jndi-name="ejb.querytool.PdoQuery" - * local-jndi-name="ejb.querytool.PdoQueryLocal" - * name="querytool.PdoQuery" type="Stateless" view-type="both" - * transaction-type="Container" - * - * @ejb.interface remote-class="edu.harvard.i2b2.crc.ejb.PdoQueryRemote" - * - * @author rkuttan - */ -public class PdoQueryBean { //implements SessionBean { - // RunQuery - /** log **/ - protected final Log log = LogFactory.getLog(getClass()); - - /** - * Function to get plain pdo from the given pdo request - * - * @ejb.interface-method view-type="both" - * @ejb.transaction type="Required" - */ - public PatientDataResponseType getPlainPatientData( - DataSourceLookup dataSourceLookup, - GetPDOFromInputListRequestType getPDOFromInputListReqType, - String requestXml) throws I2B2Exception { - PatientDataType patientDataType = null; - - DAOFactoryHelper helper = new DAOFactoryHelper(dataSourceLookup - .getDomainId(), dataSourceLookup.getProjectPath(), - dataSourceLookup.getOwnerId()); - IDAOFactory daoFactory = helper.getDAOFactory(); - - - IQueryPdoMasterDao queryPdoMasterDao = daoFactory - .getSetFinderDAOFactory().getQueryPdoMasterDAO(); - - savePdoQueryMaster(queryPdoMasterDao, requestXml); - - String version = getVersion(queryPdoMasterDao, requestXml); - // check if the user have the blob permission - boolean blobFlag = checkForBlob(getPDOFromInputListReqType); - //boolean hasProtectedStatus = false; - List userRoles = null; - String domainId = dataSourceLookup.getDomainId(); - String projectId = dataSourceLookup.getProjectPath(); - String userId = dataSourceLookup.getOwnerId(); - daoFactory = helper.getDAOFactory(); - AuthrizationHelper authHelper = new AuthrizationHelper(domainId, - projectId, userId, daoFactory); - try { - userRoles = authHelper.getRolesFromCache(); - } catch (Exception e) - {} - if (blobFlag) { - // - - authHelper.checkRoleForProtectionLabel("PDO_WITH_BLOB"); - } - - // get unit cd conversion project param from cache - ParamUtil paramUtil = new ParamUtil(); - DataSourceLookup origDataSourceLookup = daoFactory.getPatientDataDAOFactory().getOriginalDataSourceLookup(); - String unitCdConversionParam = paramUtil.getParam(origDataSourceLookup.getProjectPath(), origDataSourceLookup.getOwnerId(), - origDataSourceLookup.getDomainId(), ParamUtil.CRC_ENABLE_UNITCD_CONVERSION); - - Map projectParamMap = null; - if (unitCdConversionParam != null) { - projectParamMap = new HashMap(); - projectParamMap.put(ParamUtil.CRC_ENABLE_UNITCD_CONVERSION, unitCdConversionParam.trim()); - - } - - // call ontology cell to get the item's metadata to build the query sql - FilterListType filterList = getPDOFromInputListReqType.getFilterList(); - Map modifierMetadataXmlMap = new HashMap(); - if (filterList != null) { - try { - //CallOntologyUtil ontologyUtil = new CallOntologyUtil(requestXml); - - - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil() - .unMashallFromString(requestXml); - RequestMessageType request = (RequestMessageType) responseJaxb - .getValue(); - //String projectId = request.getMessageHeader().getProjectId(); - SecurityType tempSecurityType = request.getMessageHeader() - .getSecurity(); - SecurityType securityType = PMServiceAccountUtil - .getServiceSecurityType(tempSecurityType.getDomain()); - // if regular concepts - for (PanelType panel : filterList.getPanel()) { - for (ItemType item : panel.getItem()) { - //ConceptType conceptType = ontologyUtil.callOntology(item.getItemKey()); - ConceptType conceptType = CallOntologyUtil.callOntology(item.getItemKey(), securityType, projectId, QueryProcessorUtil.getInstance().getOntologyUrl()); - - log.debug("fetching the metadata information from ontology [" - + item.getItemKey() + "]"); - if (conceptType != null) { - item.setDimDimcode(conceptType.getDimcode()); - item.setDimColumnname(conceptType.getColumnname()); - item.setDimOperator(conceptType.getOperator()); - item.setDimTablename(conceptType.getTablename()); - item.setFacttablecolumn(conceptType - .getFacttablecolumn()); - item.setDimColumndatatype(conceptType - .getColumndatatype()); - if (conceptType.getProtectedAccess().equalsIgnoreCase("Y")) - { - Boolean protectedAccess = false; - String[] dataProt = {"DATA_PROT"}; - List ontologyProtection = Arrays.asList(conceptType.getOntologyProtection() == null || conceptType.getOntologyProtection().equals("")?dataProt:conceptType.getOntologyProtection().split(",")); - for (String s: userRoles) { - if (ontologyProtection.contains(s)) - protectedAccess = true; - - } - if (protectedAccess == false) - throw new I2B2Exception("Access Denies: Concept has protected access"); - } - if (conceptType.getMetadataxml() != null && conceptType.getMetadataxml().getAny().get(0) != null) { - MetadataxmlValueType metadataXmlType = new MetadataxmlValueType(); - metadataXmlType.getContent().add(conceptType.getMetadataxml().getAny().get(0)); - item.setMetadataxml(metadataXmlType); - } - - log.debug("metadata from ontology received for [" - + item.getItemKey() + "]" - + conceptType.getTablename()); - - //check for modifier constrain and get modifier metadata - ItemType.ConstrainByModifier modifierConstrain = item.getConstrainByModifier(); - if (modifierConstrain != null) { - ItemMetaDataHandler itemMetaDataHandler = new ItemMetaDataHandler(requestXml); - String modifierKey = modifierConstrain.getModifierKey(); - String modifierAppliedPath = modifierConstrain.getAppliedPath(); - ModifierType modifierType = itemMetaDataHandler.getModifierDataFromOntologyCell(modifierKey, modifierAppliedPath, helper.getDataSourceLookup().getServerType()); - copyModifierToItem(item,modifierType); - - //cache the modifier metadat in the map - if (projectParamMap != null) { - String unitConversionFlag = (String)projectParamMap.get(ParamUtil.CRC_ENABLE_UNITCD_CONVERSION); - if ( unitConversionFlag != null && unitConversionFlag.equals("ON")) { - if (modifierType.getMetadataxml() != null) { - log.debug("Adding modifier metadata xml to lookup map for modifier key" + modifierType.getKey() + modifierType.getAppliedPath() ); - modifierMetadataXmlMap.put(modifierType.getKey()+modifierType.getAppliedPath(), modifierType.getMetadataxml()); - } - } - } - } - - } else { - log - .debug("Unable to get item's metadata from ontology cell [" - + item.getItemKey() + "]"); - } - } - } - } catch (JAXBUtilException jaxEx) { - jaxEx.printStackTrace(); - throw new I2B2Exception( - "Error in getting item's metadata from the ontology : " - + jaxEx.getMessage(), jaxEx); - } catch (AxisFault e) { - e.printStackTrace(); - throw new I2B2Exception( - "Error in getting item's metadata from the ontology : " - + e.getMessage(), e); - } catch (XMLStreamException e) { - e.printStackTrace(); - throw new I2B2Exception( - "Error in getting item's metadata from the ontology : " - + e.getMessage(), e); - } - } - - PatientDataDAOFactory pdoDaoFactory = daoFactory - .getPatientDataDAOFactory(); - - PatientDataResponseType patientDataResponseType = new PatientDataResponseType(); - try { - OutputOptionNameType ot = getPDOFromInputListReqType - .getOutputOption().getNames(); - - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - String pageMethod = qpUtil.getPagingMethod(); - log.debug("PageMethod value [" + pageMethod + "]"); - - InputOptionListType origInputList = getPDOFromInputListReqType - .getInputList(); - InputOptionListType inputList = getPDOFromInputListReqType - .getInputList(); - IInputOptionListHandler inputListHandler = PDOFactory - .buildInputListHandler(inputList, helper - .getDataSourceLookup()); - - int requestedMinIndex = inputListHandler.getMinIndex(); - int requestedMaxIndex = inputListHandler.getMaxIndex(); - // if the request missing the max index, then default the maxindex - // to size of the input list - if (requestedMaxIndex < 1) { - requestedMaxIndex = inputListHandler.getInputSize(); - RangeType rangeType = PDOFactory.getRangeType(inputList); - rangeType.setMax(requestedMaxIndex); - } - - // before doing the paging, check if the output option list has - // observaion - OutputOptionFactRelatedHelper opFactRelatedHelper = new OutputOptionFactRelatedHelper( - getPDOFromInputListReqType.getOutputOption()); - boolean pagingNeeded = opFactRelatedHelper.isFactRelated(); - if (pagingNeeded) { - PagingHandler ph = new PagingHandler(helper, - getPDOFromInputListReqType.getInputList(), - getPDOFromInputListReqType.getFilterList(), pageMethod); - ph.setProjectParamMap(projectParamMap); - ph.setModifierMetadataXmlMap(modifierMetadataXmlMap); - HashMap calculatedValueMap = ph.calculateMaxPageInputList(); - - // do paging if required - if ((Boolean) calculatedValueMap - .get(PagingHandler.PAGING_REQUIRED_FLAG)) { - - long totalSize = (Long) calculatedValueMap - .get(PagingHandler.TOTAL_OBSERVATION); - int maxInputSize = (Integer) calculatedValueMap - .get(PagingHandler.MAX_INPUT_LIST); - long pageSize = ph.getPageSize(); - - // build page type - PageType pageType = buildPageType(requestedMinIndex, - requestedMaxIndex, maxInputSize, totalSize, - pageSize); - patientDataResponseType.setPage(pageType); - - RangeType rangeType = PDOFactory.getRangeType(inputList); - rangeType.setMax(requestedMinIndex + maxInputSize - 1); - - // inputList.getPatientList().setMax( - // requestedMinIndex + maxInputSize); - } - } - boolean tablePDO = false; - if (getPDOFromInputListReqType.getOutputOption().getNames() != null) { - if (getPDOFromInputListReqType.getOutputOption().getNames().name().equalsIgnoreCase(OutputOptionNameType.ASATTRIBUTES.name())) { - tablePDO = true; - } - } - log.debug("PDO reading metadat for patient_dimension table"); - //get patient dimension metadata - List patientMetaDataList = getPDOTemplate("patient_dimension", - dataSourceLookup, tablePDO); - //get visit dimension metadata - log.debug("PDO reading metadat for visit_dimension table"); - List visitMetaDataList = getPDOTemplate("visit_dimension", - dataSourceLookup, tablePDO); - - if ((ot != null) - && ot.name().equalsIgnoreCase( - OutputOptionNameType.ASATTRIBUTES.name())) { - PdoQueryHandler pdoQueryHandler = new PdoQueryHandler( - pdoDaoFactory, PdoQueryHandler.TABLE_PDO_TYPE, - origInputList, - inputList, // /getPDOFromInputListReqType.getInputList(), - getPDOFromInputListReqType.getFilterList(), - getPDOFromInputListReqType.getOutputOption()); - pdoQueryHandler.setProjectParamMap(projectParamMap); - pdoQueryHandler.setModifierMetadataXmlMap(modifierMetadataXmlMap); - pdoQueryHandler.setRequestVersion(version); - pdoQueryHandler.setDimensionMetaDataParamList(patientMetaDataList, visitMetaDataList); - pdoQueryHandler.processPDORequest(); - patientDataType = pdoQueryHandler.getTablePdo(); - } else { - PdoQueryHandler pdoQueryHandler = new PdoQueryHandler( - pdoDaoFactory, PdoQueryHandler.PLAIN_PDO_TYPE, - origInputList, - inputList, // getPDOFromInputListReqType.getInputList(), - getPDOFromInputListReqType.getFilterList(), - getPDOFromInputListReqType.getOutputOption()); - pdoQueryHandler.setProjectParamMap(projectParamMap); - pdoQueryHandler.setModifierMetadataXmlMap(modifierMetadataXmlMap); - pdoQueryHandler.setRequestVersion(version); - pdoQueryHandler.setDimensionMetaDataParamList(patientMetaDataList, visitMetaDataList); - pdoQueryHandler.processPDORequest(); - patientDataType = pdoQueryHandler.getPlainPdo(); - - } - } catch (Exception ex) { - ex.printStackTrace(); - log.error(ex.getMessage(), ex); - throw new I2B2Exception(ex.getMessage(), ex); - } - patientDataResponseType.setPatientData(patientDataType); - - return patientDataResponseType; - } - - /** - * Function to get plain pdo from the given pdo request - * - * @ejb.interface-method view-type="both" - * @ejb.transaction type="Required" - */ - public List getPDOTemplate(String dimensionTableName, - DataSourceLookup dataSourceLookup,boolean tablePDOFlag) throws I2B2Exception { - - List paramList = new ArrayList(); - - DAOFactoryHelper helper = new DAOFactoryHelper(dataSourceLookup - .getDomainId(), dataSourceLookup.getProjectPath(), - dataSourceLookup.getOwnerId()); - IDAOFactory daoFactory = helper.getDAOFactory(); - - // - MetaDataTypeMapper metaDataTypeMapper = new MetaDataTypeMapper(); - IMetadataDao metadataDao = daoFactory.getPatientDataDAOFactory().getMetadataDAO(); - try { - Map optionalFieldMap = metadataDao.getMetadataForOptionalField(dimensionTableName); - MetadataDao.TableMetaData[] tableMetaDataList = (TableMetaData[]) optionalFieldMap.values().toArray(new MetadataDao.TableMetaData[]{}); - metaDataTypeMapper.fillXmlDataType(tableMetaDataList,tablePDOFlag); - for (int i=0;i userRoles = null; + String domainId = dataSourceLookup.getDomainId(); + String projectId = dataSourceLookup.getProjectPath(); + String userId = dataSourceLookup.getOwnerId(); + daoFactory = helper.getDAOFactory(); + AuthrizationHelper authHelper = new AuthrizationHelper(domainId, + projectId, userId, daoFactory); + try { + userRoles = authHelper.getRolesFromCache(); + } catch (Exception e) + {} + if (blobFlag) { + // + + authHelper.checkRoleForProtectionLabel("PDO_WITH_BLOB"); + } + + // get unit cd conversion project param from cache + ParamUtil paramUtil = new ParamUtil(); + DataSourceLookup origDataSourceLookup = daoFactory.getPatientDataDAOFactory().getOriginalDataSourceLookup(); + String unitCdConversionParam = paramUtil.getParam(origDataSourceLookup.getProjectPath(), origDataSourceLookup.getOwnerId(), + origDataSourceLookup.getDomainId(), ParamUtil.CRC_ENABLE_UNITCD_CONVERSION); + + Map projectParamMap = null; + if (unitCdConversionParam != null) { + projectParamMap = new HashMap(); + projectParamMap.put(ParamUtil.CRC_ENABLE_UNITCD_CONVERSION, unitCdConversionParam.trim()); + + } + + // call ontology cell to get the item's metadata to build the query sql + FilterListType filterList = getPDOFromInputListReqType.getFilterList(); + Map modifierMetadataXmlMap = new HashMap(); + if (filterList != null) { + try { + //CallOntologyUtil ontologyUtil = new CallOntologyUtil(requestXml); + + + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil() + .unMashallFromString(requestXml); + RequestMessageType request = (RequestMessageType) responseJaxb + .getValue(); + //String projectId = request.getMessageHeader().getProjectId(); + SecurityType tempSecurityType = request.getMessageHeader() + .getSecurity(); + SecurityType securityType = PMServiceAccountUtil + .getServiceSecurityType(tempSecurityType.getDomain()); + // if regular concepts + for (PanelType panel : filterList.getPanel()) { + for (ItemType item : panel.getItem()) { + //ConceptType conceptType = ontologyUtil.callOntology(item.getItemKey()); + ConceptType conceptType = CallOntologyUtil.callOntology(item.getItemKey(), securityType, projectId, QueryProcessorUtil.getInstance().getOntologyUrl()); + + log.debug("fetching the metadata information from ontology [" + + item.getItemKey() + "]"); + if (conceptType != null) { + item.setDimDimcode(conceptType.getDimcode()); + item.setDimColumnname(conceptType.getColumnname()); + item.setDimOperator(conceptType.getOperator()); + item.setDimTablename(conceptType.getTablename()); + item.setFacttablecolumn(conceptType + .getFacttablecolumn()); + item.setDimColumndatatype(conceptType + .getColumndatatype()); + if (conceptType.getProtectedAccess().equalsIgnoreCase("Y")) + { + Boolean protectedAccess = false; + String[] dataProt = {"DATA_PROT"}; + List ontologyProtection = Arrays.asList(conceptType.getOntologyProtection() == null || conceptType.getOntologyProtection().equals("")?dataProt:conceptType.getOntologyProtection().split(",")); + for (String s: userRoles) { + if (ontologyProtection.contains(s)) + protectedAccess = true; + + } + if (protectedAccess == false) + throw new I2B2Exception("Access Denies: Concept has protected access"); + } + if (conceptType.getMetadataxml() != null && conceptType.getMetadataxml().getAny().get(0) != null) { + MetadataxmlValueType metadataXmlType = new MetadataxmlValueType(); + metadataXmlType.getContent().add(conceptType.getMetadataxml().getAny().get(0)); + item.setMetadataxml(metadataXmlType); + } + + log.debug("metadata from ontology received for [" + + item.getItemKey() + "]" + + conceptType.getTablename()); + + //check for modifier constrain and get modifier metadata + ItemType.ConstrainByModifier modifierConstrain = item.getConstrainByModifier(); + if (modifierConstrain != null) { + ItemMetaDataHandler itemMetaDataHandler = new ItemMetaDataHandler(requestXml); + String modifierKey = modifierConstrain.getModifierKey(); + String modifierAppliedPath = modifierConstrain.getAppliedPath(); + ModifierType modifierType = itemMetaDataHandler.getModifierDataFromOntologyCell(modifierKey, modifierAppliedPath, helper.getDataSourceLookup().getServerType()); + copyModifierToItem(item,modifierType); + + //cache the modifier metadat in the map + if (projectParamMap != null) { + String unitConversionFlag = (String)projectParamMap.get(ParamUtil.CRC_ENABLE_UNITCD_CONVERSION); + if ( unitConversionFlag != null && unitConversionFlag.equals("ON")) { + if (modifierType.getMetadataxml() != null) { + log.debug("Adding modifier metadata xml to lookup map for modifier key" + modifierType.getKey() + modifierType.getAppliedPath() ); + modifierMetadataXmlMap.put(modifierType.getKey()+modifierType.getAppliedPath(), modifierType.getMetadataxml()); + } + } + } + } + + } else { + log + .debug("Unable to get item's metadata from ontology cell [" + + item.getItemKey() + "]"); + } + } + } + } catch (JAXBUtilException jaxEx) { + jaxEx.printStackTrace(); + throw new I2B2Exception( + "Error in getting item's metadata from the ontology : " + + jaxEx.getMessage(), jaxEx); + } catch (AxisFault e) { + e.printStackTrace(); + throw new I2B2Exception( + "Error in getting item's metadata from the ontology : " + + e.getMessage(), e); + } catch (XMLStreamException e) { + e.printStackTrace(); + throw new I2B2Exception( + "Error in getting item's metadata from the ontology : " + + e.getMessage(), e); + } + } + + PatientDataDAOFactory pdoDaoFactory = daoFactory + .getPatientDataDAOFactory(); + + PatientDataResponseType patientDataResponseType = new PatientDataResponseType(); + try { + OutputOptionNameType ot = getPDOFromInputListReqType + .getOutputOption().getNames(); + + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + String pageMethod = qpUtil.getPagingMethod(); + log.debug("PageMethod value [" + pageMethod + "]"); + + InputOptionListType origInputList = getPDOFromInputListReqType + .getInputList(); + InputOptionListType inputList = getPDOFromInputListReqType + .getInputList(); + IInputOptionListHandler inputListHandler = PDOFactory + .buildInputListHandler(inputList, helper + .getDataSourceLookup()); + + int requestedMinIndex = inputListHandler.getMinIndex(); + int requestedMaxIndex = inputListHandler.getMaxIndex(); + // if the request missing the max index, then default the maxindex + // to size of the input list + if (requestedMaxIndex < 1) { + requestedMaxIndex = inputListHandler.getInputSize(); + RangeType rangeType = PDOFactory.getRangeType(inputList); + rangeType.setMax(requestedMaxIndex); + } + + // before doing the paging, check if the output option list has + // observaion + OutputOptionFactRelatedHelper opFactRelatedHelper = new OutputOptionFactRelatedHelper( + getPDOFromInputListReqType.getOutputOption()); + boolean pagingNeeded = opFactRelatedHelper.isFactRelated(); + if (pagingNeeded) { + PagingHandler ph = new PagingHandler(helper, + getPDOFromInputListReqType.getInputList(), + getPDOFromInputListReqType.getFilterList(), pageMethod); + ph.setProjectParamMap(projectParamMap); + ph.setModifierMetadataXmlMap(modifierMetadataXmlMap); + HashMap calculatedValueMap = ph.calculateMaxPageInputList(); + + // do paging if required + if ((Boolean) calculatedValueMap + .get(PagingHandler.PAGING_REQUIRED_FLAG)) { + + long totalSize = (Long) calculatedValueMap + .get(PagingHandler.TOTAL_OBSERVATION); + int maxInputSize = (Integer) calculatedValueMap + .get(PagingHandler.MAX_INPUT_LIST); + long pageSize = ph.getPageSize(); + + // build page type + PageType pageType = buildPageType(requestedMinIndex, + requestedMaxIndex, maxInputSize, totalSize, + pageSize); + patientDataResponseType.setPage(pageType); + + RangeType rangeType = PDOFactory.getRangeType(inputList); + rangeType.setMax(requestedMinIndex + maxInputSize - 1); + + // inputList.getPatientList().setMax( + // requestedMinIndex + maxInputSize); + } + } + boolean tablePDO = false; + if (getPDOFromInputListReqType.getOutputOption().getNames() != null) { + if (getPDOFromInputListReqType.getOutputOption().getNames().name().equalsIgnoreCase(OutputOptionNameType.ASATTRIBUTES.name())) { + tablePDO = true; + } + } + log.debug("PDO reading metadat for patient_dimension table"); + //get patient dimension metadata + List patientMetaDataList = getPDOTemplate("patient_dimension", + dataSourceLookup, tablePDO); + //get visit dimension metadata + log.debug("PDO reading metadat for visit_dimension table"); + List visitMetaDataList = getPDOTemplate("visit_dimension", + dataSourceLookup, tablePDO); + + if ((ot != null) + && ot.name().equalsIgnoreCase( + OutputOptionNameType.ASATTRIBUTES.name())) { + PdoQueryHandler pdoQueryHandler = new PdoQueryHandler( + pdoDaoFactory, PdoQueryHandler.TABLE_PDO_TYPE, + origInputList, + inputList, // /getPDOFromInputListReqType.getInputList(), + getPDOFromInputListReqType.getFilterList(), + getPDOFromInputListReqType.getOutputOption()); + pdoQueryHandler.setProjectParamMap(projectParamMap); + pdoQueryHandler.setModifierMetadataXmlMap(modifierMetadataXmlMap); + pdoQueryHandler.setRequestVersion(version); + pdoQueryHandler.setDimensionMetaDataParamList(patientMetaDataList, visitMetaDataList); + pdoQueryHandler.processPDORequest(); + patientDataType = pdoQueryHandler.getTablePdo(); + } else { + PdoQueryHandler pdoQueryHandler = new PdoQueryHandler( + pdoDaoFactory, PdoQueryHandler.PLAIN_PDO_TYPE, + origInputList, + inputList, // getPDOFromInputListReqType.getInputList(), + getPDOFromInputListReqType.getFilterList(), + getPDOFromInputListReqType.getOutputOption()); + pdoQueryHandler.setProjectParamMap(projectParamMap); + pdoQueryHandler.setModifierMetadataXmlMap(modifierMetadataXmlMap); + pdoQueryHandler.setRequestVersion(version); + pdoQueryHandler.setDimensionMetaDataParamList(patientMetaDataList, visitMetaDataList); + pdoQueryHandler.processPDORequest(); + patientDataType = pdoQueryHandler.getPlainPdo(); + + } + } catch (Exception ex) { + ex.printStackTrace(); + log.error(ex.getMessage(), ex); + throw new I2B2Exception(ex.getMessage(), ex); + } + patientDataResponseType.setPatientData(patientDataType); + + return patientDataResponseType; + } + + /** + * Function to get plain pdo from the given pdo request + * + * @ejb.interface-method view-type="both" + * @ejb.transaction type="Required" + */ + public List getPDOTemplate(String dimensionTableName, + DataSourceLookup dataSourceLookup,boolean tablePDOFlag) throws I2B2Exception { + + List paramList = new ArrayList(); + + DAOFactoryHelper helper = new DAOFactoryHelper(dataSourceLookup + .getDomainId(), dataSourceLookup.getProjectPath(), + dataSourceLookup.getOwnerId()); + IDAOFactory daoFactory = helper.getDAOFactory(); + + // + MetaDataTypeMapper metaDataTypeMapper = new MetaDataTypeMapper(); + IMetadataDao metadataDao = daoFactory.getPatientDataDAOFactory().getMetadataDAO(); + try { + Map optionalFieldMap = metadataDao.getMetadataForOptionalField(dimensionTableName); + MetadataDao.TableMetaData[] tableMetaDataList = (TableMetaData[]) optionalFieldMap.values().toArray(new MetadataDao.TableMetaData[]{}); + metaDataTypeMapper.fillXmlDataType(tableMetaDataList,tablePDOFlag); + for (int i=0;i dataSourceLookupList = null; - try { - dsLookupDao = DataSourceLookupDAOFactory.getDataSourceLookupDAO(); - dataSourceLookupList = dsLookupDao - .getDbLookupByHive("%"); - } catch (I2B2DAOException e1) { - // TODO Auto-generated catch block - log.error("Data source lookup failed: " + e1.getMessage()); - } - - - Connection conn = null; - PreparedStatement preparedStmt = null; - for (DataSourceLookup dslookup: dataSourceLookupList) - { - try { - DataSource ds = qpUtil.getDataSource( dslookup.getDataSource()); - conn = ds.getConnection(); - - String initializeSql = - "update " + dslookup.getFullSchema() + ".qt_query_instance " + - " set batch_mode = '" + queue + "'" + - " where batch_mode = '" + queue + "_RUNNING' and end_date is null"; - log.info("QUEUE START UP: " + initializeSql); - - preparedStmt = conn.prepareStatement(initializeSql); - preparedStmt.executeQuery(); - - } catch (I2B2Exception e) { - ; - } catch (SQLException e) { - ; - } finally { - try { - if(preparedStmt != null) - preparedStmt.close(); - } catch (SQLException e1) { - } - preparedStmt = null; - - try { - if(conn != null) - conn.close(); - } catch (SQLException e1) { - } - conn = null; - } - } -} - - @Override - public void run() { - initialize(); - - while(!Thread.interrupted()) - try { - runQueues(); - } - catch(Exception e) { - log.error("Failed in " + queue ); - e.printStackTrace(); - } - } - - public void runQueues() { - - // log.debug("In ProcessQueue"); - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - - int transactionTimeout = this - .readTimeoutPropertyValue(queue); - - - int count = 0; - try { - - // log.debug("My DBserver is: " + qpUtil.getCRCDBLookupServerType()); - // log.debug("My source is: " + qpUtil.getCRCDBLookupDataSource()); - // log.debug("My schemaName is: " + qpUtil.getCRCDBLookupSchemaName()); - - - DataSourceLookupDAO dsLookupDao = DataSourceLookupDAOFactory.getDataSourceLookupDAO(); - // log.debug("My dslookupis " + dsLookupDao); - // log.debug("My dslookupis ds conn info is " + dsLookupDao.getDataSource().getConnection().toString()); - List dataSourceLookupList = dsLookupDao - .getDbLookupByHive("%"); - - // log.debug("I found this number of datasources: " +dataSourceLookupList.size() ); - - - while (true) - { - - String finalSql = ""; - String message = ""; - int queryInstanceId = 0; - String ownerId = ""; - String sqlString = ""; - String projectId = ""; - String xmlRequest= ""; - String pmXml = ""; - Connection conn = null; - PreparedStatement preparedStmt = null; - ResultSet resultSet = null; - - for (DataSourceLookup dslookup: dataSourceLookupList) - { - try { - - log.debug("Connecting to: " + dslookup.getDataSource()); - DataSource ds = qpUtil.getDataSource( dslookup.getDataSource()); - conn = ds.getConnection(); - - finalSql = - "select qm.*, qi.query_instance_id, Row_number() " + - "over ( " + - " PARTITION BY qm.QUERY_MASTER_ID " + - " ORDER BY qm.QUERY_MASTER_ID desc) AS new_id " + - " from " +dslookup.getFullSchema() + ".QT_QUERY_MASTER qm, " + - dslookup.getFullSchema() + ".qt_query_instance qi " + - " where qm.QUERY_MASTER_ID = qi.QUERY_master_id " + - " and qi.batch_mode = '" + queue + "' " + - " and qi.end_date is null "; - if (dslookup.equals("SQLSERVER")) - finalSql += " and start_date < dateadd(minute, -3, getdate()) "; - - finalSql += " order by qi.start_date "; - - log.debug("Execut SQL [" + finalSql + "] for " + dslookup.getDataSource()); - preparedStmt = conn.prepareStatement(finalSql); - - //conn = dataSource.getConnection(); - queryInstanceId = 0; - resultSet = preparedStmt.executeQuery(); - if (resultSet.next()) { - queryInstanceId = resultSet.getInt("query_instance_id"); - ownerId = resultSet.getString("user_id"); - sqlString = resultSet.getString("generated_sql"); - projectId = resultSet.getString("group_id"); - xmlRequest = resultSet.getString("i2b2_request_xml"); - pmXml = resultSet.getString("pm_xml"); - // log.info("ProcessQueue found instance: " + queryInstanceId + " for " + dslookup.getDataSource()); - } - - - try { - if(resultSet != null) - resultSet.close(); - } catch (SQLException e1) { - } - resultSet = null; - - try { - if(preparedStmt != null) - preparedStmt.close(); - } catch (SQLException e1) { - } - preparedStmt = null; - - try { - if(conn != null) - conn.close(); - } catch (SQLException e1) { - } - conn = null; - - - if (queryInstanceId != 0 && readTimeoutPropertyValue(queue) > 1) { - - logesapi.debug("in ProcessQueue my pmXml is"+ pmXml); - ExecRunnable exec = new ExecRunnable(sqlString, Integer.toString(queryInstanceId), null, - xmlRequest, dslookup.getDomainId(), projectId, ownerId, pmXml, transactionTimeout); - logesapi.info("STARTING " + queue + " FOR " + queryInstanceId + " " + sqlString + " " + transactionTimeout); - - Thread t = new Thread(exec); - - - synchronized (t) { - t.start(); - - // add 10 sec to waitTime to allow query to finish/time - int waitTime = (readTimeoutPropertyValue(queue) + 10 )* 1000; - // int waitTime = (readTimeoutPropertyValue(queue))* 1000; - log.info("Waittime for " + queue+ " is " + waitTime); - - try { - - long startTime = System.currentTimeMillis(); - long deltaTime = -1; - while((exec.isJobCompleteFlag() == false)&& (exec.isJobErrorFlag() == false) && (deltaTime < waitTime)){ - - if (t.isAlive() == false) - log.debug("PQ32 - Job Exception: " + exec.getJobException().getMessage()); - if (t.isInterrupted() == true) - log.debug("PQ42 - Job Exception: " + exec.getJobException().getMessage()); - - if (exec.isJobErrorFlag() == true) - log.debug("PQ12 - Job Exception: " + exec.getJobException().getMessage()); - - if (exec.getJobException() != null) - log.debug("PQ22 - Job Exception: " + exec.getJobException().getMessage()); - if (waitTime > 0) { - // log.info("In ExecRunnable Thread QueryId: " + queryInstanceId + " Waiting: " + (waitTime - deltaTime)); - deltaTime = System.currentTimeMillis() - startTime; - } - } - log.debug("Timeout or finish of Thread of queryid " + queryInstanceId + " in" + queue); - - log.debug("Start queue waiting: " + startTime); - log.debug("End queue waiting: " + System.currentTimeMillis() ); - log.debug("Delta queue time: " + deltaTime); - - - if (exec.isJobCompleteFlag() == false) { - String timeOuterror = "Result waittime millisecond :" + - waitTime + - " elapsed, setting to next queue after " + queue; - log.info(timeOuterror); - - setToNextQueue( dslookup, projectId, ownerId, queryInstanceId); - - - } - } - catch (Exception e) { - - log.error("Error in thread ProcessQueue: " + queue + " " + e.getMessage()); - if (e.getMessage().startsWith("javax.naming.NameNotFoundException")) - break; - - setToNextQueue( dslookup, projectId, ownerId, queryInstanceId); - - //e.printStackTrace(); - - } finally { - // log.debug("Process Queue (runQueus-106-" + queue ); - log.debug("process queue finally queue : " + queue + " queryInstanceId = " + queryInstanceId); - if (t != null) { - - // log.info("Process Queue (runQueus-108-" + queue ); - - // t.interrupt(); - t = null; - // log.info("Thread successfully stopped."); - } - // log.info("Process Queue (runQueus-107-" + queue ); - - queryInstanceId = 0; - } - - - - } - } else if (queryInstanceId != 0) { - setToNextQueue( dslookup, projectId, ownerId, queryInstanceId); - } - Thread.sleep(10000); - } catch (Exception e) { - // log.debug("Process Queue (runQueus-105-" + queue ); - - try { - if (conn != null) - conn.close(); - } catch (SQLException e1) { - ; - } - - - } finally { - - // log.debug("Process Queue (runQueus-104-" + queue ); - - try { - if(resultSet != null) - resultSet.close(); - } catch (SQLException e1) { - } - resultSet = null; - - try { - if(preparedStmt != null) - preparedStmt.close(); - } catch (SQLException e1) { - } - preparedStmt = null; - - try { - if(conn != null) - conn.close(); - } catch (SQLException e1) { - } - conn = null; - - } - // log.info(queue + " - Current count: " + count); - count++; - - } - } - - - } catch (Exception e) { - - //e.printStackTrace(); - log.debug("Process Queue (runQueus-103-" + queue + " error: " + e.getMessage()); - - // isRunning = false; - //throw new I2B2DAOException( - // "Error while calculating query count by set size" - // + StackTraceUtil.getStackTrace(e)); - } - } - - private void setToNextQueue(DataSourceLookup dslookup, String projectId, String ownerId, int queryInstanceId) throws I2B2DAOException - { - // log.info("In set to next queue"); - - DAOFactoryHelper daoFactoryHelper = new DAOFactoryHelper( - dslookup.getDomainId(), projectId, ownerId); - - IDAOFactory daoFactory = daoFactoryHelper.getDAOFactory(); - - SetFinderDAOFactory sfDAOFactory = daoFactory - .getSetFinderDAOFactory(); - - // check if the status is cancelled - IQueryInstanceDao queryInstanceDao = sfDAOFactory - .getQueryInstanceDAO(); - QtQueryInstance queryInstance = queryInstanceDao - .getQueryInstanceByInstanceId(Integer.toString(queryInstanceId)); - if (queryInstance.getBatchMode().equals(QueryManagerBeanUtil.ERROR)) - { - return; - } - else if (queue.equals(QueryManagerBeanUtil.MEDIUM_QUEUE)) - { - queryInstance.setBatchMode(QueryManagerBeanUtil.LARGE_QUEUE); - log.debug("MEDIUM QUEUE timedout ... setting to LARGE_QUEUE"); - } - else if (queue.equals(QueryManagerBeanUtil.LARGE_QUEUE)) - { - log.debug("LARGE QUEUE timedout ... setting to NEVER_FINISHED"); - sfDAOFactory.getQueryResultTypeDao(); - queryInstance.setBatchMode("NEVER_FINISHED"); - QtQueryStatusType queryStatusType = queryInstance.getQtQueryStatusType(); - queryStatusType.setStatusTypeId(10); - - InstanceResultResponseType instanceResultResponseType = new InstanceResultResponseType(); - - IQueryResultInstanceDao queryResultInstanceDao = sfDAOFactory - .getPatientSetResultDAO(); - List resultInstanceList = queryResultInstanceDao - .getResultInstanceList(Integer.toString(queryInstanceId)); - - // update cancelled status to all the result instance - String resultInstanceId = ""; - int statusTypeId = 0; - for (QtQueryResultInstance resultInstance : resultInstanceList) { - resultInstanceId = resultInstance.getResultInstanceId(); - queryResultInstanceDao.updatePatientSet(resultInstanceId, 10, - resultInstance.getMessage(), 0, 0, resultInstance.getObfuscateMethod()); - - } - queryInstance.setQtQueryStatusType(queryStatusType); - - queryInstance.setEndDate(new Date(System - .currentTimeMillis())); - } - queryInstanceDao.update(queryInstance, false); - - } - - private int readTimeoutPropertyValue(String queueType) { - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - String timeoutStr = ""; - int timeoutVal = 0; - try { - if (queueType.equals(QueryManagerBeanUtil.SMALL_QUEUE)) { - timeoutStr = qpUtil - .getCRCPropertyValue("edu.harvard.i2b2.crc.jms.small.timeoutsec"); - } else if (queueType.equals(QueryManagerBeanUtil.MEDIUM_QUEUE)) { - timeoutStr = qpUtil - .getCRCPropertyValue("edu.harvard.i2b2.crc.jms.medium.timeoutsec"); - } else if (queueType.equals(QueryManagerBeanUtil.LARGE_QUEUE)) { - timeoutStr = qpUtil - .getCRCPropertyValue("edu.harvard.i2b2.crc.jms.large.timeoutsec"); - } - timeoutVal = Integer.parseInt(timeoutStr); - - } catch (I2B2Exception ex) { - ex.printStackTrace(); - } - return timeoutVal; - - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.ejb; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Date; +import java.util.List; +import javax.sql.DataSource; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.dao.DataSourceLookupDAO; +import edu.harvard.i2b2.crc.dao.DataSourceLookupDAOFactory; +import edu.harvard.i2b2.crc.dao.IDAOFactory; +import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; +import edu.harvard.i2b2.crc.dao.setfinder.IQueryInstanceDao; +import edu.harvard.i2b2.crc.dao.setfinder.IQueryResultInstanceDao; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.db.QtQueryInstance; +import edu.harvard.i2b2.crc.datavo.db.QtQueryResultInstance; +import edu.harvard.i2b2.crc.datavo.db.QtQueryStatusType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceResultResponseType; +import edu.harvard.i2b2.crc.loader.delegate.pm.PMServiceDriver; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + +public class ProcessQueue implements Runnable{ + private static Log log = LogFactory.getLog(ExecRunnable.class); + protected static Log logesapi = LogFactory.getLog(ExecRunnable.class); + + public ProcessQueue(String lQueue) { + +// isActive = true; + queue = lQueue; + + } + + private boolean jobCompleteFlag = false; + +// public boolean isActive() { +// return isActive; +// } + + private String queue; +// private boolean isActive = false; + // private boolean isRunning = false; + public boolean isJobCompleteFlag() { + return jobCompleteFlag; + } + + private void initialize(){ + + // initialize queue + // If queued queries from a previous jboss session are in running state reset to queue state. + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + DataSourceLookupDAO dsLookupDao = null; + List dataSourceLookupList = null; + try { + dsLookupDao = DataSourceLookupDAOFactory.getDataSourceLookupDAO(); + dataSourceLookupList = dsLookupDao + .getDbLookupByHive("%"); + } catch (I2B2DAOException e1) { + // TODO Auto-generated catch block + log.error("Data source lookup failed: " + e1.getMessage()); + } + + + Connection conn = null; + PreparedStatement preparedStmt = null; + for (DataSourceLookup dslookup: dataSourceLookupList) + { + try { + DataSource ds = qpUtil.getDataSource( dslookup.getDataSource()); + conn = ds.getConnection(); + + String initializeSql = + "update " + dslookup.getFullSchema() + ".qt_query_instance " + + " set batch_mode = '" + queue + "'" + + " where batch_mode = '" + queue + "_RUNNING' and end_date is null"; + log.info("QUEUE START UP: " + initializeSql); + + preparedStmt = conn.prepareStatement(initializeSql); + preparedStmt.executeQuery(); + + } catch (I2B2Exception e) { + ; + } catch (SQLException e) { + ; + } finally { + try { + if(preparedStmt != null) + preparedStmt.close(); + } catch (SQLException e1) { + } + preparedStmt = null; + + try { + if(conn != null) + conn.close(); + } catch (SQLException e1) { + } + conn = null; + } + } +} + + @Override + public void run() { + initialize(); + + while(!Thread.interrupted()) + try { + runQueues(); + } + catch(Exception e) { + log.error("Failed in " + queue ); + e.printStackTrace(); + } + } + + public void runQueues() { + + // log.debug("In ProcessQueue"); + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + + int transactionTimeout = this + .readTimeoutPropertyValue(queue); + + + int count = 0; + try { + + // log.debug("My DBserver is: " + qpUtil.getCRCDBLookupServerType()); + // log.debug("My source is: " + qpUtil.getCRCDBLookupDataSource()); + // log.debug("My schemaName is: " + qpUtil.getCRCDBLookupSchemaName()); + + + DataSourceLookupDAO dsLookupDao = DataSourceLookupDAOFactory.getDataSourceLookupDAO(); + // log.debug("My dslookupis " + dsLookupDao); + // log.debug("My dslookupis ds conn info is " + dsLookupDao.getDataSource().getConnection().toString()); + List dataSourceLookupList = dsLookupDao + .getDbLookupByHive("%"); + + // log.debug("I found this number of datasources: " +dataSourceLookupList.size() ); + + + while (true) + { + + String finalSql = ""; + String message = ""; + int queryInstanceId = 0; + String ownerId = ""; + String sqlString = ""; + String projectId = ""; + String xmlRequest= ""; + String pmXml = ""; + Connection conn = null; + PreparedStatement preparedStmt = null; + ResultSet resultSet = null; + + for (DataSourceLookup dslookup: dataSourceLookupList) + { + try { + + log.debug("Connecting to: " + dslookup.getDataSource()); + DataSource ds = qpUtil.getDataSource( dslookup.getDataSource()); + conn = ds.getConnection(); + + finalSql = + "select qm.*, qi.query_instance_id, Row_number() " + + "over ( " + + " PARTITION BY qm.QUERY_MASTER_ID " + + " ORDER BY qm.QUERY_MASTER_ID desc) AS new_id " + + " from " +dslookup.getFullSchema() + ".QT_QUERY_MASTER qm, " + + dslookup.getFullSchema() + ".qt_query_instance qi " + + " where qm.QUERY_MASTER_ID = qi.QUERY_master_id " + + " and qi.batch_mode = '" + queue + "' " + + " and qi.end_date is null "; + if (dslookup.equals("SQLSERVER")) + finalSql += " and start_date < dateadd(minute, -3, getdate()) "; + + finalSql += " order by qi.start_date "; + + log.debug("Execut SQL [" + finalSql + "] for " + dslookup.getDataSource()); + preparedStmt = conn.prepareStatement(finalSql); + + //conn = dataSource.getConnection(); + queryInstanceId = 0; + resultSet = preparedStmt.executeQuery(); + if (resultSet.next()) { + queryInstanceId = resultSet.getInt("query_instance_id"); + ownerId = resultSet.getString("user_id"); + sqlString = resultSet.getString("generated_sql"); + projectId = resultSet.getString("group_id"); + xmlRequest = resultSet.getString("i2b2_request_xml"); + pmXml = resultSet.getString("pm_xml"); + // log.info("ProcessQueue found instance: " + queryInstanceId + " for " + dslookup.getDataSource()); + } + + + try { + if(resultSet != null) + resultSet.close(); + } catch (SQLException e1) { + } + resultSet = null; + + try { + if(preparedStmt != null) + preparedStmt.close(); + } catch (SQLException e1) { + } + preparedStmt = null; + + try { + if(conn != null) + conn.close(); + } catch (SQLException e1) { + } + conn = null; + + + if (queryInstanceId != 0 && readTimeoutPropertyValue(queue) > 1) { + + logesapi.debug("in ProcessQueue my pmXml is"+ pmXml); + ExecRunnable exec = new ExecRunnable(sqlString, Integer.toString(queryInstanceId), null, + xmlRequest, dslookup.getDomainId(), projectId, ownerId, pmXml, transactionTimeout); + logesapi.info("STARTING " + queue + " FOR " + queryInstanceId + " " + sqlString + " " + transactionTimeout); + + Thread t = new Thread(exec); + + + synchronized (t) { + t.start(); + + // add 10 sec to waitTime to allow query to finish/time + int waitTime = (readTimeoutPropertyValue(queue) + 10 )* 1000; + // int waitTime = (readTimeoutPropertyValue(queue))* 1000; + log.info("Waittime for " + queue+ " is " + waitTime); + + try { + + long startTime = System.currentTimeMillis(); + long deltaTime = -1; + while((exec.isJobCompleteFlag() == false)&& (exec.isJobErrorFlag() == false) && (deltaTime < waitTime)){ + + if (t.isAlive() == false) + log.debug("PQ32 - Job Exception: " + exec.getJobException().getMessage()); + if (t.isInterrupted() == true) + log.debug("PQ42 - Job Exception: " + exec.getJobException().getMessage()); + + if (exec.isJobErrorFlag() == true) + log.debug("PQ12 - Job Exception: " + exec.getJobException().getMessage()); + + if (exec.getJobException() != null) + log.debug("PQ22 - Job Exception: " + exec.getJobException().getMessage()); + if (waitTime > 0) { + // log.info("In ExecRunnable Thread QueryId: " + queryInstanceId + " Waiting: " + (waitTime - deltaTime)); + deltaTime = System.currentTimeMillis() - startTime; + } + } + log.debug("Timeout or finish of Thread of queryid " + queryInstanceId + " in" + queue); + + log.debug("Start queue waiting: " + startTime); + log.debug("End queue waiting: " + System.currentTimeMillis() ); + log.debug("Delta queue time: " + deltaTime); + + + if (exec.isJobCompleteFlag() == false) { + String timeOuterror = "Result waittime millisecond :" + + waitTime + + " elapsed, setting to next queue after " + queue; + log.info(timeOuterror); + + setToNextQueue( dslookup, projectId, ownerId, queryInstanceId); + + + } + } + catch (Exception e) { + + log.error("Error in thread ProcessQueue: " + queue + " " + e.getMessage()); + if (e.getMessage().startsWith("javax.naming.NameNotFoundException")) + break; + + setToNextQueue( dslookup, projectId, ownerId, queryInstanceId); + + //e.printStackTrace(); + + } finally { + // log.debug("Process Queue (runQueus-106-" + queue ); + log.debug("process queue finally queue : " + queue + " queryInstanceId = " + queryInstanceId); + if (t != null) { + + // log.info("Process Queue (runQueus-108-" + queue ); + + // t.interrupt(); + t = null; + // log.info("Thread successfully stopped."); + } + // log.info("Process Queue (runQueus-107-" + queue ); + + queryInstanceId = 0; + } + + + + } + } else if (queryInstanceId != 0) { + setToNextQueue( dslookup, projectId, ownerId, queryInstanceId); + } + Thread.sleep(10000); + } catch (Exception e) { + // log.debug("Process Queue (runQueus-105-" + queue ); + + try { + if (conn != null) + conn.close(); + } catch (SQLException e1) { + ; + } + + + } finally { + + // log.debug("Process Queue (runQueus-104-" + queue ); + + try { + if(resultSet != null) + resultSet.close(); + } catch (SQLException e1) { + } + resultSet = null; + + try { + if(preparedStmt != null) + preparedStmt.close(); + } catch (SQLException e1) { + } + preparedStmt = null; + + try { + if(conn != null) + conn.close(); + } catch (SQLException e1) { + } + conn = null; + + } + // log.info(queue + " - Current count: " + count); + count++; + + } + } + + + } catch (Exception e) { + + //e.printStackTrace(); + log.debug("Process Queue (runQueus-103-" + queue + " error: " + e.getMessage()); + + // isRunning = false; + //throw new I2B2DAOException( + // "Error while calculating query count by set size" + // + StackTraceUtil.getStackTrace(e)); + } + } + + private void setToNextQueue(DataSourceLookup dslookup, String projectId, String ownerId, int queryInstanceId) throws I2B2DAOException + { + // log.info("In set to next queue"); + + DAOFactoryHelper daoFactoryHelper = new DAOFactoryHelper( + dslookup.getDomainId(), projectId, ownerId); + + IDAOFactory daoFactory = daoFactoryHelper.getDAOFactory(); + + SetFinderDAOFactory sfDAOFactory = daoFactory + .getSetFinderDAOFactory(); + + // check if the status is cancelled + IQueryInstanceDao queryInstanceDao = sfDAOFactory + .getQueryInstanceDAO(); + QtQueryInstance queryInstance = queryInstanceDao + .getQueryInstanceByInstanceId(Integer.toString(queryInstanceId)); + if (queryInstance.getBatchMode().equals(QueryManagerBeanUtil.ERROR)) + { + return; + } + else if (queue.equals(QueryManagerBeanUtil.MEDIUM_QUEUE)) + { + queryInstance.setBatchMode(QueryManagerBeanUtil.LARGE_QUEUE); + log.debug("MEDIUM QUEUE timedout ... setting to LARGE_QUEUE"); + } + else if (queue.equals(QueryManagerBeanUtil.LARGE_QUEUE)) + { + log.debug("LARGE QUEUE timedout ... setting to NEVER_FINISHED"); + sfDAOFactory.getQueryResultTypeDao(); + queryInstance.setBatchMode("NEVER_FINISHED"); + QtQueryStatusType queryStatusType = queryInstance.getQtQueryStatusType(); + queryStatusType.setStatusTypeId(10); + + InstanceResultResponseType instanceResultResponseType = new InstanceResultResponseType(); + + IQueryResultInstanceDao queryResultInstanceDao = sfDAOFactory + .getPatientSetResultDAO(); + List resultInstanceList = queryResultInstanceDao + .getResultInstanceList(Integer.toString(queryInstanceId)); + + // update cancelled status to all the result instance + String resultInstanceId = ""; + int statusTypeId = 0; + for (QtQueryResultInstance resultInstance : resultInstanceList) { + resultInstanceId = resultInstance.getResultInstanceId(); + queryResultInstanceDao.updatePatientSet(resultInstanceId, 10, + resultInstance.getMessage(), 0, 0, resultInstance.getObfuscateMethod()); + + } + queryInstance.setQtQueryStatusType(queryStatusType); + + queryInstance.setEndDate(new Date(System + .currentTimeMillis())); + } + queryInstanceDao.update(queryInstance, false); + + } + + private int readTimeoutPropertyValue(String queueType) { + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + String timeoutStr = ""; + int timeoutVal = 0; + try { + if (queueType.equals(QueryManagerBeanUtil.SMALL_QUEUE)) { + timeoutStr = qpUtil + .getCRCPropertyValue("edu.harvard.i2b2.crc.jms.small.timeoutsec"); + } else if (queueType.equals(QueryManagerBeanUtil.MEDIUM_QUEUE)) { + timeoutStr = qpUtil + .getCRCPropertyValue("edu.harvard.i2b2.crc.jms.medium.timeoutsec"); + } else if (queueType.equals(QueryManagerBeanUtil.LARGE_QUEUE)) { + timeoutStr = qpUtil + .getCRCPropertyValue("edu.harvard.i2b2.crc.jms.large.timeoutsec"); + } + timeoutVal = Integer.parseInt(timeoutStr); + + } catch (I2B2Exception ex) { + ex.printStackTrace(); + } + return timeoutVal; + + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/QueryInfoBean.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/QueryInfoBean.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/QueryInfoBean.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/QueryInfoBean.java index 590654eb..c5c28fe3 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/QueryInfoBean.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/QueryInfoBean.java @@ -1,695 +1,695 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.ejb; - -import java.sql.Connection; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.w3c.dom.Document; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.DTOFactory; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; -import edu.harvard.i2b2.crc.dao.setfinder.IQueryInstanceDao; -import edu.harvard.i2b2.crc.dao.setfinder.IQueryMasterDao; -import edu.harvard.i2b2.crc.dao.setfinder.IQueryResultInstanceDao; -import edu.harvard.i2b2.crc.dao.setfinder.IQueryResultTypeDao; -import edu.harvard.i2b2.crc.dao.setfinder.IResultGenerator; -import edu.harvard.i2b2.crc.dao.setfinder.QueryExecutorHelperDao; -import edu.harvard.i2b2.crc.dao.setfinder.QueryResultTypeSpringDao; -import edu.harvard.i2b2.crc.dao.setfinder.SetFinderConnection; -import edu.harvard.i2b2.crc.datavo.PSMFactory; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.db.QtQueryInstance; -import edu.harvard.i2b2.crc.datavo.db.QtQueryMaster; -import edu.harvard.i2b2.crc.datavo.db.QtQueryResultInstance; -import edu.harvard.i2b2.crc.datavo.db.QtQueryResultType; -import edu.harvard.i2b2.crc.datavo.db.QtQueryStatusType; -import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.CrcXmlResultResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.FindByChildType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceResultResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterRequestType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryInstanceType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryMasterType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryResultInstanceType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryResultTypeType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.RequestXmlType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultOutputOptionListType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultOutputOptionType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultTypeResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.UserRequestType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.XmlResultType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.XmlValueType; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - -/** - * Ejb manager class for query operation - * - * @author rkuttan - * - * @ejb.bean description="QueryTool Query Info" - * display-name="QueryTool Query Info" - * jndi-name="ejb.querytool.QueryInfo" - * local-jndi-name="ejb.querytool.QueryInfoLocal" - * name="querytool.QueryInfo" type="Stateless" view-type="both" - * transaction-type="Container" - * - * - * - * @ejb.interface remote-class="edu.harvard.i2b2.crc.ejb.QueryInfoRemote" - * - * - */ -public class QueryInfoBean { //implements SessionBean { - private static Log log = LogFactory.getLog(QueryInfoBean.class); - protected static Log logesapi = LogFactory.getLog(QueryInfoBean.class); - - /** - * Function to return master query list for the given user id - * - * @ejb.interface-method view-type="both" - * @ejb.transaction type="Required" - * - * @param userRequestType - * user_id - * - * @return String publish response XML - */ - public MasterResponseType getQueryMasterListFromUserId( - DataSourceLookup dataSourceLookup, UserRequestType userRequestType) - throws I2B2DAOException { - - String userId = userRequestType.getUserId(); - int fetchSize = userRequestType.getFetchSize(); - boolean includeQueryInstance = userRequestType.getIncludeQueryInstance(); - String masterTypeCd = userRequestType.getMasterTypeCd(); - - SetFinderDAOFactory sfDaoFactory = this.getSetFinderDaoFactory( - dataSourceLookup.getDomainId(), dataSourceLookup - .getProjectPath(), dataSourceLookup.getOwnerId()); - IQueryMasterDao queryMasterDao = sfDaoFactory.getQueryMasterDAO(); - List masterList = queryMasterDao.getQueryMasterByUserId( - userId, fetchSize, masterTypeCd, includeQueryInstance); - MasterResponseType masterResponseType = buildMasterResponseType(masterList); - return masterResponseType; - } - - - /** - * Function to return master query list for the give group id - * - * @ejb.interface-method view-type="both" - * @ejb.transaction type="Required" - * - * @param userRequestType - * group_id - * - * @return String publish response XML - * @throws I2B2Exception - */ - public MasterResponseType getQueryMasterListFromNameInfo( - DataSourceLookup dataSourceLookup, SecurityType userRequestType, FindByChildType findChildType) - throws I2B2Exception { - //String groupId = userRequestType.getGroupId(); - //int fetchSize = userRequestType.getFetchSize(); - SetFinderDAOFactory sfDaoFactory = this.getSetFinderDaoFactory( - dataSourceLookup.getDomainId(), dataSourceLookup - .getProjectPath(), dataSourceLookup.getOwnerId()); - IQueryMasterDao queryMasterDao = sfDaoFactory.getQueryMasterDAO(); - List masterList = queryMasterDao - .getQueryMasterByNameInfo(userRequestType, findChildType); - MasterResponseType masterResponseType = buildMasterResponseType(masterList); - return masterResponseType; - } - - - /** - * Function to return master query list for the give group id - * - * @ejb.interface-method view-type="both" - * @ejb.transaction type="Required" - * - * @param userRequestType - * group_id - * - * @return String publish response XML - * @throws I2B2DAOException - */ - public MasterResponseType getQueryMasterListFromGroupId( - DataSourceLookup dataSourceLookup, UserRequestType userRequestType) - throws I2B2DAOException { - String groupId = userRequestType.getGroupId(); - String masterTypeCd = userRequestType.getMasterTypeCd(); - boolean includeQueryInstance = userRequestType.getIncludeQueryInstance(); - - int fetchSize = userRequestType.getFetchSize(); - SetFinderDAOFactory sfDaoFactory = this.getSetFinderDaoFactory( - dataSourceLookup.getDomainId(), dataSourceLookup - .getProjectPath(), dataSourceLookup.getOwnerId()); - IQueryMasterDao queryMasterDao = sfDaoFactory.getQueryMasterDAO(); - List masterList = queryMasterDao - .getQueryMasterByGroupId(groupId, fetchSize, masterTypeCd, includeQueryInstance); - MasterResponseType masterResponseType = buildMasterResponseType(masterList); - return masterResponseType; - } - - /** - * Function to publish patients using publish message format. - * - * @ejb.interface-method view-type="both" - * @ejb.transaction type="Required" - * - * @param int session id publish request XML fileName - * - * @return String publish response XML - */ - public MasterResponseType getRequestXmlFromMasterId( - DataSourceLookup dataSourceLookup, String userId, - MasterRequestType masterRequestType) throws I2B2Exception { - String queryMasterId = masterRequestType.getQueryMasterId(); - SetFinderDAOFactory sfDaoFactory = this.getSetFinderDaoFactory( - dataSourceLookup.getDomainId(), dataSourceLookup - .getProjectPath(), dataSourceLookup.getOwnerId()); - IQueryMasterDao queryMasterDao = sfDaoFactory.getQueryMasterDAO(); - - QtQueryMaster qtQueryMaster = queryMasterDao - .getQueryDefinition(queryMasterId); - MasterResponseType masterResponseType = new MasterResponseType(); - if (qtQueryMaster != null) { - QueryMasterType queryMasterType = new QueryMasterType(); - queryMasterType.setQueryMasterId(qtQueryMaster.getQueryMasterId()); - queryMasterType.setName(qtQueryMaster.getName()); - queryMasterType.setUserId(qtQueryMaster.getUserId()); - String requestXml = qtQueryMaster.getRequestXml(); - - if (requestXml != null) { - Document doc = null; - RequestXmlType requestXmlType = new RequestXmlType(); - try { - /* - * //get jaxb object JAXBContext jc1 = - * JAXBContext.newInstance - * (edu.harvard.i2b2.crc.datavo.setfinder - * .query.ObjectFactory.class); Unmarshaller unMarshaller = - * jc1.createUnmarshaller(); JAXBElement jaxbElement = - * (JAXBElement)unMarshaller.unmarshal(new - * StringReader(requestXml)); QueryDefinitionType - * queryDefinition = - * (QueryDefinitionType)jaxbElement.getValue(); - * - * - * //marshall to dom JAXBContext jc = - * JAXBContext.newInstance - * (edu.harvard.i2b2.crc.datavo.setfinder - * .query.QueryDefinitionType.class); Marshaller m = - * jc.createMarshaller(); DocumentBuilderFactory f = - * DocumentBuilderFactory.newInstance(); DocumentBuilder - * builder = f.newDocumentBuilder(); doc = - * builder.newDocument(); m.marshal((new - * edu.harvard.i2b2.crc - * .datavo.setfinder.query.ObjectFactory( - * )).createQueryDefinition(queryDefinition), doc); - */ - - doc = edu.harvard.i2b2.common.util.xml.XMLUtil - .convertStringToDOM(requestXml); - logesapi.debug("query definition xml prefix " - + doc.getDocumentElement().getPrefix()); - requestXmlType.getContent().add(doc.getDocumentElement()); - } catch (Exception i2b2) { - i2b2.printStackTrace(); - throw new I2B2Exception( - "Error converting request xml to dom " - + i2b2.getMessage(), i2b2); - } - queryMasterType.setRequestXml(requestXmlType); - } - masterResponseType.getQueryMaster().add(queryMasterType); - } else { - throw new I2B2Exception("Could not find query for masterId: [" - + queryMasterId + "]"); - } - return masterResponseType; - } - - /** - * Function to delete master query - * - * @ejb.interface-method view-type="both" - * @ejb.transaction type="Required" - * - * @param string - * user id - * @param int master id - * - * @return String Master Query response XML - */ - public MasterResponseType deleteQueryMaster( - DataSourceLookup dataSourceLookup, String userId, String masterId) - throws I2B2Exception { - if (masterId==null){ - log.debug("Null master id sent to deleteQueryMaster method"); - return null; - } - else { - SetFinderDAOFactory sfDaoFactory = this.getSetFinderDaoFactory( - dataSourceLookup.getDomainId(), dataSourceLookup - .getProjectPath(), dataSourceLookup.getOwnerId()); - IQueryMasterDao queryMasterDao = sfDaoFactory.getQueryMasterDAO(); - - queryMasterDao.deleteQuery(masterId); - - MasterResponseType masterResponseType = new MasterResponseType(); - QueryMasterType queryMasterType = new QueryMasterType(); - queryMasterType.setQueryMasterId(masterId); - masterResponseType.getQueryMaster().add(queryMasterType); - return masterResponseType; - } - } - - /** - * Function to rename master query - * - * @ejb.interface-method view-type="both" - * @ejb.transaction type="Required" - * - * @param int session id publish request XML fileName - * - * @return Master Query response XML - */ - public MasterResponseType renameQueryMaster( - DataSourceLookup dataSourceLookup, String userId, String masterId, - String queryNewName) throws I2B2Exception { - SetFinderDAOFactory sfDaoFactory = this.getSetFinderDaoFactory( - dataSourceLookup.getDomainId(), dataSourceLookup - .getProjectPath(), dataSourceLookup.getOwnerId()); - IQueryMasterDao queryMasterDao = sfDaoFactory.getQueryMasterDAO(); - - queryMasterDao.renameQuery(masterId, queryNewName); - - MasterResponseType masterResponseType = new MasterResponseType(); - QueryMasterType queryMasterType = new QueryMasterType(); - queryMasterType.setQueryMasterId(masterId); - queryMasterType.setUserId(userId); - queryMasterType.setName(queryNewName); - masterResponseType.getQueryMaster().add(queryMasterType); - return masterResponseType; - } - - /** - * Function to update query result instance description - * - * @ejb.interface-method view-type="both" - * @ejb.transaction type="Required" - * - * @param String - * resultInstanceId - * @param Strign - * description - * - * @return Master Query response XML - */ - public ResultResponseType updateResultInstanceDescription( - DataSourceLookup dataSourceLookup, String resultInstanceId, - String newDescription) throws I2B2Exception { - SetFinderDAOFactory sfDaoFactory = this.getSetFinderDaoFactory( - dataSourceLookup.getDomainId(), dataSourceLookup - .getProjectPath(), dataSourceLookup.getOwnerId()); - IQueryResultInstanceDao queryResultInstanceDao = sfDaoFactory - .getPatientSetResultDAO(); - - queryResultInstanceDao.updateResultInstanceDescription( - resultInstanceId, newDescription); - QtQueryResultInstance updatedQueryResultInstance = queryResultInstanceDao - .getResultInstanceById(resultInstanceId); - - ResultResponseType resultResponseType = new ResultResponseType(); - QueryResultInstanceType resultInstanceType = PSMFactory - .buildQueryResultInstanceType(updatedQueryResultInstance); - resultResponseType.getQueryResultInstance().add(resultInstanceType); - return resultResponseType; - } - - /** - * Function to update query instance message - * @param userId - * @param isManager - * - * @ejb.interface-method view-type="both" - * @ejb.transaction type="Required" - * - * @param String - * resultInstanceId - * @param Strign - * description - * - * @return Master Query response XML - */ - public InstanceResponseType setQueryInstanceMessage( - DataSourceLookup dataSourceLookup, String instanceInstanceId, - String newMessage, boolean isManager, String userId) throws I2B2Exception { - SetFinderDAOFactory sfDaoFactory = this.getSetFinderDaoFactory( - dataSourceLookup.getDomainId(), dataSourceLookup - .getProjectPath(), dataSourceLookup.getOwnerId()); - IQueryInstanceDao queryResultInstanceDao = sfDaoFactory.getQueryInstanceDAO(); - - QtQueryInstance updatedQueryResultInstance = queryResultInstanceDao.getQueryInstanceByInstanceId(instanceInstanceId); - - if (isManager == false) { - if (!userId.equalsIgnoreCase(updatedQueryResultInstance.getUserId())) - throw new I2B2Exception("Access Denied"); - } - queryResultInstanceDao.updateMessage(instanceInstanceId, newMessage, false); - - - InstanceResponseType resultResponseType = new InstanceResponseType(); - QueryInstanceType resultInstanceType = PSMFactory - .buildQueryInstanceType(updatedQueryResultInstance); - resultResponseType.getQueryInstance().add(resultInstanceType); - return resultResponseType; - } - - - - public InstanceResponseType setQueryInstanceStatus(DataSourceLookup dataSourceLookup, String queryInstanceId, - String statusName, boolean isManager, String userId) throws I2B2Exception { - - SetFinderDAOFactory sfDaoFactory = this.getSetFinderDaoFactory( - dataSourceLookup.getDomainId(), dataSourceLookup - .getProjectPath(), dataSourceLookup.getOwnerId()); - IQueryInstanceDao queryResultInstanceDao = sfDaoFactory.getQueryInstanceDAO(); - - - QtQueryInstance queryInstance = queryResultInstanceDao - .getQueryInstanceByInstanceId(queryInstanceId); - if (isManager == false) { - if (!userId.equalsIgnoreCase(queryInstance.getUserId())) - throw new I2B2Exception("Access Denied"); - - } - - - queryInstance.setBatchMode(statusName); - - queryResultInstanceDao.update(queryInstance, false); - - QtQueryInstance updatedQueryResultInstance = queryResultInstanceDao.getQueryInstanceByInstanceId(queryInstanceId); - - InstanceResponseType resultResponseType = new InstanceResponseType(); - QueryInstanceType resultInstanceType = PSMFactory - .buildQueryInstanceType(updatedQueryResultInstance); - resultResponseType.getQueryInstance().add(resultInstanceType); - return resultResponseType; - - } - - /** - * Function to update query instance with cancel status - * - * @ejb.interface-method view-type="both" - * @ejb.transaction type="Required" - * - * @param String - * instanceId - * - * @return Instance Query response XML - */ - public InstanceResultResponseType cancelQueryInstance( - DataSourceLookup dataSourceLookup, String instanceId) - throws I2B2Exception { - InstanceResultResponseType instanceResultResponseType = new InstanceResultResponseType(); - SetFinderDAOFactory sfDaoFactory = this.getSetFinderDaoFactory( - dataSourceLookup.getDomainId(), dataSourceLookup - .getProjectPath(), dataSourceLookup.getOwnerId()); - // get query instance by id and change the status type to cancelled. - IQueryInstanceDao queryInstanceDao = sfDaoFactory.getQueryInstanceDAO(); - QtQueryInstance queryInstance = queryInstanceDao - .getQueryInstanceByInstanceId(instanceId); - QtQueryStatusType queryStatusType = queryInstance - .getQtQueryStatusType(); - int queryStatusTypeId = queryStatusType.getStatusTypeId(); - // check if the query is already completed - if ((queryStatusTypeId == 3 || queryStatusTypeId == 4 - || queryStatusTypeId == 6 || queryStatusTypeId == 10)) { - log.error("Query instance [" + instanceId - + "] is already finished"); - throw new I2B2Exception("Query instance [" + instanceId - + "] is already finished"); - } - // check if the query is already cancelled - if (queryStatusTypeId == 9) { - log.warn("Already the query [" + instanceId - + "] is in Cancelled state"); - } - queryStatusType.setStatusTypeId(9); - - queryInstance.setQtQueryStatusType(queryStatusType); - queryInstanceDao.update(queryInstance, false); - queryInstance = queryInstanceDao - .getQueryInstanceByInstanceId(instanceId); - - IQueryResultInstanceDao queryResultInstanceDao = sfDaoFactory - .getPatientSetResultDAO(); - List resultInstanceList = queryResultInstanceDao - .getResultInstanceList(instanceId); - QueryInstanceType queryInstanceResponse = PSMFactory - .buildQueryInstanceType(queryInstance); - instanceResultResponseType.setQueryInstance(queryInstanceResponse); - - // update cancelled status to all the result instance - String resultInstanceId = ""; - int statusTypeId = 0; - for (QtQueryResultInstance resultInstance : resultInstanceList) { - resultInstanceId = resultInstance.getResultInstanceId(); - queryResultInstanceDao.updatePatientSet(resultInstanceId, 9, 0); - resultInstance.getQtQueryStatusType().setStatusTypeId(9); - QueryResultInstanceType resultInstanceResponse = PSMFactory - .buildQueryResultInstanceType(resultInstance); - instanceResultResponseType.getQueryResultInstance().add( - resultInstanceResponse); - } - - return instanceResultResponseType; - } - - /** - * Function to return all query result type - * - * @ejb.interface-method view-type="both" - * @ejb.transaction type="Required" - * - */ - public ResultTypeResponseType getAllResultType( - DataSourceLookup dataSourceLookup, List roles) throws I2B2Exception { - SetFinderDAOFactory sfDaoFactory = this.getSetFinderDaoFactory( - dataSourceLookup.getDomainId(), dataSourceLookup - .getProjectPath(), dataSourceLookup.getOwnerId()); - IQueryResultTypeDao resultTypeDao = sfDaoFactory - .getQueryResultTypeDao(); - List queryResultTypeList = resultTypeDao - .getAllQueryResultType(roles); - - ResultTypeResponseType resultTypeResponseType = new ResultTypeResponseType(); - List returnQueryResultType = new ArrayList(); - for (QtQueryResultType queryResultType : queryResultTypeList) { - returnQueryResultType.add(PSMFactory - .buildQueryResultType(queryResultType)); - } - resultTypeResponseType.getQueryResultType().addAll( - returnQueryResultType); - return resultTypeResponseType; - } - - // ------------------------------------------------- - // private functions - // ------------------------------------------------- - private MasterResponseType buildMasterResponseType( - List masterList) { - MasterResponseType masterResponseType = new MasterResponseType(); - // masterResponseType - DTOFactory dtoFactory = new DTOFactory(); - for (QtQueryMaster queryMaster : masterList) { - QueryMasterType queryMasterType = new QueryMasterType(); - queryMasterType.setQueryMasterId(queryMaster.getQueryMasterId()); - java.util.Date createDate = queryMaster.getCreateDate(); - queryMasterType.setCreateDate(dtoFactory - .getXMLGregorianCalendar(createDate.getTime())); - java.util.Date deleteDate = queryMaster.getDeleteDate(); - if (deleteDate != null) { - queryMasterType.setDeleteDate(dtoFactory - .getXMLGregorianCalendar(deleteDate.getTime())); - } - queryMasterType.setName(queryMaster.getName()); - queryMasterType.setGroupId(queryMaster.getGroupId()); - queryMasterType.setUserId(queryMaster.getUserId()); - queryMasterType.setMasterTypeCd(queryMaster.getMasterTypeCd()); - QueryInstanceType queryInstance =new QueryInstanceType(); - Iterator it = queryMaster.getQtQueryInstances().iterator(); - while(it.hasNext()){ - QtQueryInstance a = it.next(); - queryInstance.setBatchMode(a.getBatchMode()); - if (a.getEndDate() != null) - queryInstance.setEndDate(dtoFactory - .getXMLGregorianCalendar(a.getEndDate().getTime())); - queryInstance.setStartDate(dtoFactory - .getXMLGregorianCalendar(a.getStartDate().getTime())); - queryInstance.setQueryInstanceId(a.getQueryInstanceId()); - - - - Iterator itResult = a.getQtQueryResultInstances().iterator(); - while(itResult.hasNext()){ - QueryResultInstanceType queryResultInstance =new QueryResultInstanceType(); - QtQueryResultInstance b = itResult.next(); - queryResultInstance.setSetSize(b.getSetSize()); - queryResultInstance.setDescription(b.getDescription()); - queryResultInstance.setStartDate(dtoFactory - .getXMLGregorianCalendar(b.getStartDate().getTime())); - queryResultInstance.setEndDate(dtoFactory - .getXMLGregorianCalendar(b.getEndDate().getTime())); - QueryResultTypeType queryResultType = new QueryResultTypeType(); - queryResultType.setVisualAttributeType(b.getQtQueryResultType().getVisualAttributeType()); - queryResultType.setName(b.getQtQueryResultType().getName()); - queryResultType.setDescription(b.getQtQueryResultType().getDescription()); - queryResultInstance.setQueryResultType(queryResultType); - queryResultInstance.setResultInstanceId(b.getResultInstanceId()); - queryInstance.getQueryResultInstanceType().add(queryResultInstance); - - } - //queryInstance.setQueryResultInstanceType(queryResultInstance); - } - - - - queryMasterType.setQueryInstanceType(queryInstance); - masterResponseType.getQueryMaster().add(queryMasterType); - } - return masterResponseType; - } - - private SetFinderDAOFactory getSetFinderDaoFactory(String domainId, - String projectPath, String ownerId) throws I2B2DAOException { - DAOFactoryHelper helper = new DAOFactoryHelper(domainId, projectPath, - ownerId); - SetFinderDAOFactory sfDaoFactory = helper.getDAOFactory() - .getSetFinderDAOFactory(); - return sfDaoFactory; - } - - - - public CrcXmlResultResponseType getQTBreakdownForAdmin(DataSourceLookup dataSourceLookup, SecurityType userRequestType, - ResultOutputOptionListType resultOutputList) throws I2B2DAOException, SQLException { - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - - CrcXmlResultResponseType response = new CrcXmlResultResponseType(); - // Map generatorMap = (Map) qpUtil.getSpringBeanFactory().getBean("setFinderResultGeneratorMap"); - - SetFinderDAOFactory sfDAOFactory = getSetFinderDaoFactory( - dataSourceLookup.getDomainId(), dataSourceLookup - .getProjectPath(), dataSourceLookup.getOwnerId()); - - Map param = new HashMap(); - log.debug("Creatiung hash map"); - Connection manualConnection = sfDAOFactory.getDataSource().getConnection(); - SetFinderConnection sfConn = new SetFinderConnection(manualConnection); - param.put("SetFinderConnection", sfConn); - param.put("SetFinderDAOFactory", sfDAOFactory); - //param.put("PatientSetId", patientSetId); - param.put("ServerType", dataSourceLookup.getServerType()); - // param.put("CallOntologyUtil", callOntologyUtil); - // param.put("projectId", projectId); - // param.put("ontologyGetChildrenUrl", ontologyGetChildrenUrl); - param.put("securityType", userRequestType); - param.put("TransactionTimeout", 180); - // param.put("ProcessTimingFlag", ""); - param.put("ObfuscatedRecordCount", 3); - param.put("RecordCount", 0); - param.put("ObfuscatedRoleFlag", true); - - XmlResultType xml = new XmlResultType(); - - for (ResultOutputOptionType resultOutputOption : resultOutputList - .getResultOutput()) { - String resultName = resultOutputOption.getName().toUpperCase(); - param.put("ResultOptionName", resultName); - if (!resultName.startsWith("ADMIN")) - throw new I2B2DAOException ("Only ADMIN breakdowns can be run."); - QueryResultTypeSpringDao resultTypeDao = new QueryResultTypeSpringDao( - sfDAOFactory.getDataSource(), sfDAOFactory.getDataSourceLookup()); - String generatorClassName = resultTypeDao.getQueryResultTypeClassname(resultName); - - //(String) generatorMap.get(resultName); - if (generatorClassName == null) { - throw new I2B2DAOException("Could not find result name [" - + resultName + "] in the config file"); - } - Class generatorClass; - IResultGenerator resultGenerator; - try { - generatorClass = Class.forName(generatorClassName, true, Thread - .currentThread().getContextClassLoader()); - if (generatorClass == null) { - throw new I2B2DAOException( - "Generator class not configured for result name[" - + resultName + "] "); - } - resultGenerator = (IResultGenerator) generatorClass.newInstance(); - log.debug("Running " + resultName + "'s class " - + generatorClassName); - resultGenerator.generateResult(param); - String results = resultGenerator.getResults(); - XmlValueType xmlValue = new XmlValueType(); - xmlValue.getContent().add(results); - xml.setXmlValue(xmlValue); - //results.get - } catch (ClassNotFoundException e) { - throw new I2B2DAOException( - "Class not found for the generator class[" - + generatorClassName + "] ", e); - } catch (InstantiationException e) { - throw new I2B2DAOException("Could not initialize generator class[" - + generatorClassName + "] ", e); - } catch (IllegalAccessException e) { - throw new I2B2DAOException( - "Illegal Access Exception for generator class[" - + generatorClassName + "] ", e); - } - } - - // TODO Auto-generated method stub - response.setCrcXmlResult(xml); - manualConnection.close(); - return response; - } - - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.ejb; + +import java.sql.Connection; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.w3c.dom.Document; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.DTOFactory; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; +import edu.harvard.i2b2.crc.dao.setfinder.IQueryInstanceDao; +import edu.harvard.i2b2.crc.dao.setfinder.IQueryMasterDao; +import edu.harvard.i2b2.crc.dao.setfinder.IQueryResultInstanceDao; +import edu.harvard.i2b2.crc.dao.setfinder.IQueryResultTypeDao; +import edu.harvard.i2b2.crc.dao.setfinder.IResultGenerator; +import edu.harvard.i2b2.crc.dao.setfinder.QueryExecutorHelperDao; +import edu.harvard.i2b2.crc.dao.setfinder.QueryResultTypeSpringDao; +import edu.harvard.i2b2.crc.dao.setfinder.SetFinderConnection; +import edu.harvard.i2b2.crc.datavo.PSMFactory; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.db.QtQueryInstance; +import edu.harvard.i2b2.crc.datavo.db.QtQueryMaster; +import edu.harvard.i2b2.crc.datavo.db.QtQueryResultInstance; +import edu.harvard.i2b2.crc.datavo.db.QtQueryResultType; +import edu.harvard.i2b2.crc.datavo.db.QtQueryStatusType; +import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.CrcXmlResultResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.FindByChildType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceResultResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterRequestType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryInstanceType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryMasterType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryResultInstanceType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryResultTypeType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.RequestXmlType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultOutputOptionListType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultOutputOptionType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultTypeResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.UserRequestType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.XmlResultType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.XmlValueType; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + +/** + * Ejb manager class for query operation + * + * @author rkuttan + * + * @ejb.bean description="QueryTool Query Info" + * display-name="QueryTool Query Info" + * jndi-name="ejb.querytool.QueryInfo" + * local-jndi-name="ejb.querytool.QueryInfoLocal" + * name="querytool.QueryInfo" type="Stateless" view-type="both" + * transaction-type="Container" + * + * + * + * @ejb.interface remote-class="edu.harvard.i2b2.crc.ejb.QueryInfoRemote" + * + * + */ +public class QueryInfoBean { //implements SessionBean { + private static Log log = LogFactory.getLog(QueryInfoBean.class); + protected static Log logesapi = LogFactory.getLog(QueryInfoBean.class); + + /** + * Function to return master query list for the given user id + * + * @ejb.interface-method view-type="both" + * @ejb.transaction type="Required" + * + * @param userRequestType + * user_id + * + * @return String publish response XML + */ + public MasterResponseType getQueryMasterListFromUserId( + DataSourceLookup dataSourceLookup, UserRequestType userRequestType) + throws I2B2DAOException { + + String userId = userRequestType.getUserId(); + int fetchSize = userRequestType.getFetchSize(); + boolean includeQueryInstance = userRequestType.getIncludeQueryInstance(); + String masterTypeCd = userRequestType.getMasterTypeCd(); + + SetFinderDAOFactory sfDaoFactory = this.getSetFinderDaoFactory( + dataSourceLookup.getDomainId(), dataSourceLookup + .getProjectPath(), dataSourceLookup.getOwnerId()); + IQueryMasterDao queryMasterDao = sfDaoFactory.getQueryMasterDAO(); + List masterList = queryMasterDao.getQueryMasterByUserId( + userId, fetchSize, masterTypeCd, includeQueryInstance); + MasterResponseType masterResponseType = buildMasterResponseType(masterList); + return masterResponseType; + } + + + /** + * Function to return master query list for the give group id + * + * @ejb.interface-method view-type="both" + * @ejb.transaction type="Required" + * + * @param userRequestType + * group_id + * + * @return String publish response XML + * @throws I2B2Exception + */ + public MasterResponseType getQueryMasterListFromNameInfo( + DataSourceLookup dataSourceLookup, SecurityType userRequestType, FindByChildType findChildType) + throws I2B2Exception { + //String groupId = userRequestType.getGroupId(); + //int fetchSize = userRequestType.getFetchSize(); + SetFinderDAOFactory sfDaoFactory = this.getSetFinderDaoFactory( + dataSourceLookup.getDomainId(), dataSourceLookup + .getProjectPath(), dataSourceLookup.getOwnerId()); + IQueryMasterDao queryMasterDao = sfDaoFactory.getQueryMasterDAO(); + List masterList = queryMasterDao + .getQueryMasterByNameInfo(userRequestType, findChildType); + MasterResponseType masterResponseType = buildMasterResponseType(masterList); + return masterResponseType; + } + + + /** + * Function to return master query list for the give group id + * + * @ejb.interface-method view-type="both" + * @ejb.transaction type="Required" + * + * @param userRequestType + * group_id + * + * @return String publish response XML + * @throws I2B2DAOException + */ + public MasterResponseType getQueryMasterListFromGroupId( + DataSourceLookup dataSourceLookup, UserRequestType userRequestType) + throws I2B2DAOException { + String groupId = userRequestType.getGroupId(); + String masterTypeCd = userRequestType.getMasterTypeCd(); + boolean includeQueryInstance = userRequestType.getIncludeQueryInstance(); + + int fetchSize = userRequestType.getFetchSize(); + SetFinderDAOFactory sfDaoFactory = this.getSetFinderDaoFactory( + dataSourceLookup.getDomainId(), dataSourceLookup + .getProjectPath(), dataSourceLookup.getOwnerId()); + IQueryMasterDao queryMasterDao = sfDaoFactory.getQueryMasterDAO(); + List masterList = queryMasterDao + .getQueryMasterByGroupId(groupId, fetchSize, masterTypeCd, includeQueryInstance); + MasterResponseType masterResponseType = buildMasterResponseType(masterList); + return masterResponseType; + } + + /** + * Function to publish patients using publish message format. + * + * @ejb.interface-method view-type="both" + * @ejb.transaction type="Required" + * + * @param int session id publish request XML fileName + * + * @return String publish response XML + */ + public MasterResponseType getRequestXmlFromMasterId( + DataSourceLookup dataSourceLookup, String userId, + MasterRequestType masterRequestType) throws I2B2Exception { + String queryMasterId = masterRequestType.getQueryMasterId(); + SetFinderDAOFactory sfDaoFactory = this.getSetFinderDaoFactory( + dataSourceLookup.getDomainId(), dataSourceLookup + .getProjectPath(), dataSourceLookup.getOwnerId()); + IQueryMasterDao queryMasterDao = sfDaoFactory.getQueryMasterDAO(); + + QtQueryMaster qtQueryMaster = queryMasterDao + .getQueryDefinition(queryMasterId); + MasterResponseType masterResponseType = new MasterResponseType(); + if (qtQueryMaster != null) { + QueryMasterType queryMasterType = new QueryMasterType(); + queryMasterType.setQueryMasterId(qtQueryMaster.getQueryMasterId()); + queryMasterType.setName(qtQueryMaster.getName()); + queryMasterType.setUserId(qtQueryMaster.getUserId()); + String requestXml = qtQueryMaster.getRequestXml(); + + if (requestXml != null) { + Document doc = null; + RequestXmlType requestXmlType = new RequestXmlType(); + try { + /* + * //get jaxb object JAXBContext jc1 = + * JAXBContext.newInstance + * (edu.harvard.i2b2.crc.datavo.setfinder + * .query.ObjectFactory.class); Unmarshaller unMarshaller = + * jc1.createUnmarshaller(); JAXBElement jaxbElement = + * (JAXBElement)unMarshaller.unmarshal(new + * StringReader(requestXml)); QueryDefinitionType + * queryDefinition = + * (QueryDefinitionType)jaxbElement.getValue(); + * + * + * //marshall to dom JAXBContext jc = + * JAXBContext.newInstance + * (edu.harvard.i2b2.crc.datavo.setfinder + * .query.QueryDefinitionType.class); Marshaller m = + * jc.createMarshaller(); DocumentBuilderFactory f = + * DocumentBuilderFactory.newInstance(); DocumentBuilder + * builder = f.newDocumentBuilder(); doc = + * builder.newDocument(); m.marshal((new + * edu.harvard.i2b2.crc + * .datavo.setfinder.query.ObjectFactory( + * )).createQueryDefinition(queryDefinition), doc); + */ + + doc = edu.harvard.i2b2.common.util.xml.XMLUtil + .convertStringToDOM(requestXml); + logesapi.debug("query definition xml prefix " + + doc.getDocumentElement().getPrefix()); + requestXmlType.getContent().add(doc.getDocumentElement()); + } catch (Exception i2b2) { + i2b2.printStackTrace(); + throw new I2B2Exception( + "Error converting request xml to dom " + + i2b2.getMessage(), i2b2); + } + queryMasterType.setRequestXml(requestXmlType); + } + masterResponseType.getQueryMaster().add(queryMasterType); + } else { + throw new I2B2Exception("Could not find query for masterId: [" + + queryMasterId + "]"); + } + return masterResponseType; + } + + /** + * Function to delete master query + * + * @ejb.interface-method view-type="both" + * @ejb.transaction type="Required" + * + * @param string + * user id + * @param int master id + * + * @return String Master Query response XML + */ + public MasterResponseType deleteQueryMaster( + DataSourceLookup dataSourceLookup, String userId, String masterId) + throws I2B2Exception { + if (masterId==null){ + log.debug("Null master id sent to deleteQueryMaster method"); + return null; + } + else { + SetFinderDAOFactory sfDaoFactory = this.getSetFinderDaoFactory( + dataSourceLookup.getDomainId(), dataSourceLookup + .getProjectPath(), dataSourceLookup.getOwnerId()); + IQueryMasterDao queryMasterDao = sfDaoFactory.getQueryMasterDAO(); + + queryMasterDao.deleteQuery(masterId); + + MasterResponseType masterResponseType = new MasterResponseType(); + QueryMasterType queryMasterType = new QueryMasterType(); + queryMasterType.setQueryMasterId(masterId); + masterResponseType.getQueryMaster().add(queryMasterType); + return masterResponseType; + } + } + + /** + * Function to rename master query + * + * @ejb.interface-method view-type="both" + * @ejb.transaction type="Required" + * + * @param int session id publish request XML fileName + * + * @return Master Query response XML + */ + public MasterResponseType renameQueryMaster( + DataSourceLookup dataSourceLookup, String userId, String masterId, + String queryNewName) throws I2B2Exception { + SetFinderDAOFactory sfDaoFactory = this.getSetFinderDaoFactory( + dataSourceLookup.getDomainId(), dataSourceLookup + .getProjectPath(), dataSourceLookup.getOwnerId()); + IQueryMasterDao queryMasterDao = sfDaoFactory.getQueryMasterDAO(); + + queryMasterDao.renameQuery(masterId, queryNewName); + + MasterResponseType masterResponseType = new MasterResponseType(); + QueryMasterType queryMasterType = new QueryMasterType(); + queryMasterType.setQueryMasterId(masterId); + queryMasterType.setUserId(userId); + queryMasterType.setName(queryNewName); + masterResponseType.getQueryMaster().add(queryMasterType); + return masterResponseType; + } + + /** + * Function to update query result instance description + * + * @ejb.interface-method view-type="both" + * @ejb.transaction type="Required" + * + * @param String + * resultInstanceId + * @param Strign + * description + * + * @return Master Query response XML + */ + public ResultResponseType updateResultInstanceDescription( + DataSourceLookup dataSourceLookup, String resultInstanceId, + String newDescription) throws I2B2Exception { + SetFinderDAOFactory sfDaoFactory = this.getSetFinderDaoFactory( + dataSourceLookup.getDomainId(), dataSourceLookup + .getProjectPath(), dataSourceLookup.getOwnerId()); + IQueryResultInstanceDao queryResultInstanceDao = sfDaoFactory + .getPatientSetResultDAO(); + + queryResultInstanceDao.updateResultInstanceDescription( + resultInstanceId, newDescription); + QtQueryResultInstance updatedQueryResultInstance = queryResultInstanceDao + .getResultInstanceById(resultInstanceId); + + ResultResponseType resultResponseType = new ResultResponseType(); + QueryResultInstanceType resultInstanceType = PSMFactory + .buildQueryResultInstanceType(updatedQueryResultInstance); + resultResponseType.getQueryResultInstance().add(resultInstanceType); + return resultResponseType; + } + + /** + * Function to update query instance message + * @param userId + * @param isManager + * + * @ejb.interface-method view-type="both" + * @ejb.transaction type="Required" + * + * @param String + * resultInstanceId + * @param Strign + * description + * + * @return Master Query response XML + */ + public InstanceResponseType setQueryInstanceMessage( + DataSourceLookup dataSourceLookup, String instanceInstanceId, + String newMessage, boolean isManager, String userId) throws I2B2Exception { + SetFinderDAOFactory sfDaoFactory = this.getSetFinderDaoFactory( + dataSourceLookup.getDomainId(), dataSourceLookup + .getProjectPath(), dataSourceLookup.getOwnerId()); + IQueryInstanceDao queryResultInstanceDao = sfDaoFactory.getQueryInstanceDAO(); + + QtQueryInstance updatedQueryResultInstance = queryResultInstanceDao.getQueryInstanceByInstanceId(instanceInstanceId); + + if (isManager == false) { + if (!userId.equalsIgnoreCase(updatedQueryResultInstance.getUserId())) + throw new I2B2Exception("Access Denied"); + } + queryResultInstanceDao.updateMessage(instanceInstanceId, newMessage, false); + + + InstanceResponseType resultResponseType = new InstanceResponseType(); + QueryInstanceType resultInstanceType = PSMFactory + .buildQueryInstanceType(updatedQueryResultInstance); + resultResponseType.getQueryInstance().add(resultInstanceType); + return resultResponseType; + } + + + + public InstanceResponseType setQueryInstanceStatus(DataSourceLookup dataSourceLookup, String queryInstanceId, + String statusName, boolean isManager, String userId) throws I2B2Exception { + + SetFinderDAOFactory sfDaoFactory = this.getSetFinderDaoFactory( + dataSourceLookup.getDomainId(), dataSourceLookup + .getProjectPath(), dataSourceLookup.getOwnerId()); + IQueryInstanceDao queryResultInstanceDao = sfDaoFactory.getQueryInstanceDAO(); + + + QtQueryInstance queryInstance = queryResultInstanceDao + .getQueryInstanceByInstanceId(queryInstanceId); + if (isManager == false) { + if (!userId.equalsIgnoreCase(queryInstance.getUserId())) + throw new I2B2Exception("Access Denied"); + + } + + + queryInstance.setBatchMode(statusName); + + queryResultInstanceDao.update(queryInstance, false); + + QtQueryInstance updatedQueryResultInstance = queryResultInstanceDao.getQueryInstanceByInstanceId(queryInstanceId); + + InstanceResponseType resultResponseType = new InstanceResponseType(); + QueryInstanceType resultInstanceType = PSMFactory + .buildQueryInstanceType(updatedQueryResultInstance); + resultResponseType.getQueryInstance().add(resultInstanceType); + return resultResponseType; + + } + + /** + * Function to update query instance with cancel status + * + * @ejb.interface-method view-type="both" + * @ejb.transaction type="Required" + * + * @param String + * instanceId + * + * @return Instance Query response XML + */ + public InstanceResultResponseType cancelQueryInstance( + DataSourceLookup dataSourceLookup, String instanceId) + throws I2B2Exception { + InstanceResultResponseType instanceResultResponseType = new InstanceResultResponseType(); + SetFinderDAOFactory sfDaoFactory = this.getSetFinderDaoFactory( + dataSourceLookup.getDomainId(), dataSourceLookup + .getProjectPath(), dataSourceLookup.getOwnerId()); + // get query instance by id and change the status type to cancelled. + IQueryInstanceDao queryInstanceDao = sfDaoFactory.getQueryInstanceDAO(); + QtQueryInstance queryInstance = queryInstanceDao + .getQueryInstanceByInstanceId(instanceId); + QtQueryStatusType queryStatusType = queryInstance + .getQtQueryStatusType(); + int queryStatusTypeId = queryStatusType.getStatusTypeId(); + // check if the query is already completed + if ((queryStatusTypeId == 3 || queryStatusTypeId == 4 + || queryStatusTypeId == 6 || queryStatusTypeId == 10)) { + log.error("Query instance [" + instanceId + + "] is already finished"); + throw new I2B2Exception("Query instance [" + instanceId + + "] is already finished"); + } + // check if the query is already cancelled + if (queryStatusTypeId == 9) { + log.warn("Already the query [" + instanceId + + "] is in Cancelled state"); + } + queryStatusType.setStatusTypeId(9); + + queryInstance.setQtQueryStatusType(queryStatusType); + queryInstanceDao.update(queryInstance, false); + queryInstance = queryInstanceDao + .getQueryInstanceByInstanceId(instanceId); + + IQueryResultInstanceDao queryResultInstanceDao = sfDaoFactory + .getPatientSetResultDAO(); + List resultInstanceList = queryResultInstanceDao + .getResultInstanceList(instanceId); + QueryInstanceType queryInstanceResponse = PSMFactory + .buildQueryInstanceType(queryInstance); + instanceResultResponseType.setQueryInstance(queryInstanceResponse); + + // update cancelled status to all the result instance + String resultInstanceId = ""; + int statusTypeId = 0; + for (QtQueryResultInstance resultInstance : resultInstanceList) { + resultInstanceId = resultInstance.getResultInstanceId(); + queryResultInstanceDao.updatePatientSet(resultInstanceId, 9, 0); + resultInstance.getQtQueryStatusType().setStatusTypeId(9); + QueryResultInstanceType resultInstanceResponse = PSMFactory + .buildQueryResultInstanceType(resultInstance); + instanceResultResponseType.getQueryResultInstance().add( + resultInstanceResponse); + } + + return instanceResultResponseType; + } + + /** + * Function to return all query result type + * + * @ejb.interface-method view-type="both" + * @ejb.transaction type="Required" + * + */ + public ResultTypeResponseType getAllResultType( + DataSourceLookup dataSourceLookup, List roles) throws I2B2Exception { + SetFinderDAOFactory sfDaoFactory = this.getSetFinderDaoFactory( + dataSourceLookup.getDomainId(), dataSourceLookup + .getProjectPath(), dataSourceLookup.getOwnerId()); + IQueryResultTypeDao resultTypeDao = sfDaoFactory + .getQueryResultTypeDao(); + List queryResultTypeList = resultTypeDao + .getAllQueryResultType(roles); + + ResultTypeResponseType resultTypeResponseType = new ResultTypeResponseType(); + List returnQueryResultType = new ArrayList(); + for (QtQueryResultType queryResultType : queryResultTypeList) { + returnQueryResultType.add(PSMFactory + .buildQueryResultType(queryResultType)); + } + resultTypeResponseType.getQueryResultType().addAll( + returnQueryResultType); + return resultTypeResponseType; + } + + // ------------------------------------------------- + // private functions + // ------------------------------------------------- + private MasterResponseType buildMasterResponseType( + List masterList) { + MasterResponseType masterResponseType = new MasterResponseType(); + // masterResponseType + DTOFactory dtoFactory = new DTOFactory(); + for (QtQueryMaster queryMaster : masterList) { + QueryMasterType queryMasterType = new QueryMasterType(); + queryMasterType.setQueryMasterId(queryMaster.getQueryMasterId()); + java.util.Date createDate = queryMaster.getCreateDate(); + queryMasterType.setCreateDate(dtoFactory + .getXMLGregorianCalendar(createDate.getTime())); + java.util.Date deleteDate = queryMaster.getDeleteDate(); + if (deleteDate != null) { + queryMasterType.setDeleteDate(dtoFactory + .getXMLGregorianCalendar(deleteDate.getTime())); + } + queryMasterType.setName(queryMaster.getName()); + queryMasterType.setGroupId(queryMaster.getGroupId()); + queryMasterType.setUserId(queryMaster.getUserId()); + queryMasterType.setMasterTypeCd(queryMaster.getMasterTypeCd()); + QueryInstanceType queryInstance =new QueryInstanceType(); + Iterator it = queryMaster.getQtQueryInstances().iterator(); + while(it.hasNext()){ + QtQueryInstance a = it.next(); + queryInstance.setBatchMode(a.getBatchMode()); + if (a.getEndDate() != null) + queryInstance.setEndDate(dtoFactory + .getXMLGregorianCalendar(a.getEndDate().getTime())); + queryInstance.setStartDate(dtoFactory + .getXMLGregorianCalendar(a.getStartDate().getTime())); + queryInstance.setQueryInstanceId(a.getQueryInstanceId()); + + + + Iterator itResult = a.getQtQueryResultInstances().iterator(); + while(itResult.hasNext()){ + QueryResultInstanceType queryResultInstance =new QueryResultInstanceType(); + QtQueryResultInstance b = itResult.next(); + queryResultInstance.setSetSize(b.getSetSize()); + queryResultInstance.setDescription(b.getDescription()); + queryResultInstance.setStartDate(dtoFactory + .getXMLGregorianCalendar(b.getStartDate().getTime())); + queryResultInstance.setEndDate(dtoFactory + .getXMLGregorianCalendar(b.getEndDate().getTime())); + QueryResultTypeType queryResultType = new QueryResultTypeType(); + queryResultType.setVisualAttributeType(b.getQtQueryResultType().getVisualAttributeType()); + queryResultType.setName(b.getQtQueryResultType().getName()); + queryResultType.setDescription(b.getQtQueryResultType().getDescription()); + queryResultInstance.setQueryResultType(queryResultType); + queryResultInstance.setResultInstanceId(b.getResultInstanceId()); + queryInstance.getQueryResultInstanceType().add(queryResultInstance); + + } + //queryInstance.setQueryResultInstanceType(queryResultInstance); + } + + + + queryMasterType.setQueryInstanceType(queryInstance); + masterResponseType.getQueryMaster().add(queryMasterType); + } + return masterResponseType; + } + + private SetFinderDAOFactory getSetFinderDaoFactory(String domainId, + String projectPath, String ownerId) throws I2B2DAOException { + DAOFactoryHelper helper = new DAOFactoryHelper(domainId, projectPath, + ownerId); + SetFinderDAOFactory sfDaoFactory = helper.getDAOFactory() + .getSetFinderDAOFactory(); + return sfDaoFactory; + } + + + + public CrcXmlResultResponseType getQTBreakdownForAdmin(DataSourceLookup dataSourceLookup, SecurityType userRequestType, + ResultOutputOptionListType resultOutputList) throws I2B2DAOException, SQLException { + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + + CrcXmlResultResponseType response = new CrcXmlResultResponseType(); + // Map generatorMap = (Map) qpUtil.getSpringBeanFactory().getBean("setFinderResultGeneratorMap"); + + SetFinderDAOFactory sfDAOFactory = getSetFinderDaoFactory( + dataSourceLookup.getDomainId(), dataSourceLookup + .getProjectPath(), dataSourceLookup.getOwnerId()); + + Map param = new HashMap(); + log.debug("Creatiung hash map"); + Connection manualConnection = sfDAOFactory.getDataSource().getConnection(); + SetFinderConnection sfConn = new SetFinderConnection(manualConnection); + param.put("SetFinderConnection", sfConn); + param.put("SetFinderDAOFactory", sfDAOFactory); + //param.put("PatientSetId", patientSetId); + param.put("ServerType", dataSourceLookup.getServerType()); + // param.put("CallOntologyUtil", callOntologyUtil); + // param.put("projectId", projectId); + // param.put("ontologyGetChildrenUrl", ontologyGetChildrenUrl); + param.put("securityType", userRequestType); + param.put("TransactionTimeout", 180); + // param.put("ProcessTimingFlag", ""); + param.put("ObfuscatedRecordCount", 3); + param.put("RecordCount", 0); + param.put("ObfuscatedRoleFlag", true); + + XmlResultType xml = new XmlResultType(); + + for (ResultOutputOptionType resultOutputOption : resultOutputList + .getResultOutput()) { + String resultName = resultOutputOption.getName().toUpperCase(); + param.put("ResultOptionName", resultName); + if (!resultName.startsWith("ADMIN")) + throw new I2B2DAOException ("Only ADMIN breakdowns can be run."); + QueryResultTypeSpringDao resultTypeDao = new QueryResultTypeSpringDao( + sfDAOFactory.getDataSource(), sfDAOFactory.getDataSourceLookup()); + String generatorClassName = resultTypeDao.getQueryResultTypeClassname(resultName); + + //(String) generatorMap.get(resultName); + if (generatorClassName == null) { + throw new I2B2DAOException("Could not find result name [" + + resultName + "] in the config file"); + } + Class generatorClass; + IResultGenerator resultGenerator; + try { + generatorClass = Class.forName(generatorClassName, true, Thread + .currentThread().getContextClassLoader()); + if (generatorClass == null) { + throw new I2B2DAOException( + "Generator class not configured for result name[" + + resultName + "] "); + } + resultGenerator = (IResultGenerator) generatorClass.newInstance(); + log.debug("Running " + resultName + "'s class " + + generatorClassName); + resultGenerator.generateResult(param); + String results = resultGenerator.getResults(); + XmlValueType xmlValue = new XmlValueType(); + xmlValue.getContent().add(results); + xml.setXmlValue(xmlValue); + //results.get + } catch (ClassNotFoundException e) { + throw new I2B2DAOException( + "Class not found for the generator class[" + + generatorClassName + "] ", e); + } catch (InstantiationException e) { + throw new I2B2DAOException("Could not initialize generator class[" + + generatorClassName + "] ", e); + } catch (IllegalAccessException e) { + throw new I2B2DAOException( + "Illegal Access Exception for generator class[" + + generatorClassName + "] ", e); + } + } + + // TODO Auto-generated method stub + response.setCrcXmlResult(xml); + manualConnection.close(); + return response; + } + + + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/QueryManagerBean.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/QueryManagerBean.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/QueryManagerBean.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/QueryManagerBean.java index 8c4be98e..faa9ab8b --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/QueryManagerBean.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/QueryManagerBean.java @@ -1,672 +1,672 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.ejb; - -import java.io.StringWriter; -import java.util.Date; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import jakarta.xml.bind.JAXBElement; -import javax.xml.datatype.XMLGregorianCalendar; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.dao.IDAOFactory; -import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; -import edu.harvard.i2b2.crc.dao.setfinder.IQueryInstanceDao; -import edu.harvard.i2b2.crc.dao.setfinder.IQueryMasterDao; -import edu.harvard.i2b2.crc.dao.setfinder.IQueryResultInstanceDao; -import edu.harvard.i2b2.crc.dao.setfinder.QueryInstanceSpringDao; -import edu.harvard.i2b2.crc.dao.setfinder.QueryResultInstanceSpringDao; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.PSMFactory; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.db.QtQueryInstance; -import edu.harvard.i2b2.crc.datavo.db.QtQueryMaster; -import edu.harvard.i2b2.crc.datavo.db.QtQueryResultInstance; -import edu.harvard.i2b2.crc.datavo.db.QtQueryStatusType; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2message.PasswordType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ConstrainDateTimeType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceResultResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterInstanceResultResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.PanelType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionRequestType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryInstanceType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryMasterType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryResultInstanceType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryStatusTypeType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultOutputOptionListType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultOutputOptionType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.StatusType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.StatusType.Condition; -import edu.harvard.i2b2.crc.datavo.setfinder.query.UserType; -import edu.harvard.i2b2.crc.delegate.pm.CallPMUtil; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - - -/** - * Ejb manager class for query operation - * - * @author rkuttan - * - * @ejb.bean description="QueryTool Query Manager" - * display-name="QueryTool Query Manager" - * jndi-name="ejb.querytool.QueryManager" - * local-jndi-name="ejb.querytool.QueryManagerLocal" - * name="querytool.QueryManager" type="Stateless" view-type="both" - * transaction-type="Bean" - * - * @ejb.transaction type="Required" - * - * - * @ejb.interface remote-class="edu.harvard.i2b2.crc.ejb.QueryManagerRemote" - * - * - */ -public class QueryManagerBean{ // implements SessionBean { - private static Log log = LogFactory.getLog(QueryManagerBean.class); - public static String RESPONSE_QUEUE_NAME = "queue/jms.querytool.QueryResponse"; - - protected static Log logesapi = LogFactory.getLog(QueryManagerBean.class); - - - // public static String UPLOADPROCESSOR_QUEUE_NAME = - // "queue/jms.querytool.QueryExecutor"; - - // SessionContext context; - - /** - * Function to publish patients using publish message format. - * - * @ejb.interface-method view-type="both" - * @ejb.transaction type="Required" - * - * @param String - * publish request XML fileName - * - * @return String publish response XML - * @throws Exception - */ - public MasterInstanceResultResponseType processQuery( - DataSourceLookup dataSourceLookup, String xmlRequest) - throws Exception { - String responseXML = null; - - MasterInstanceResultResponseType masterInstanceResultType = null; - - try { - String sessionId = String.valueOf(System.currentTimeMillis()); - QueryManagerBeanUtil qmBeanUtil = new QueryManagerBeanUtil(); - long timeout = qmBeanUtil.getTimeout(xmlRequest); - - DataSourceLookup dsLookupInput = qmBeanUtil - .getDataSourceLookupInput(xmlRequest); - SetFinderDAOFactory sfDAOFactory = null; - // tm.begin(); - // transaction.begin(); - if (dsLookupInput.getProjectPath() == null) { - throw new I2B2Exception("project id is missing in the request"); - } - DAOFactoryHelper daoFactoryHelper = new DAOFactoryHelper( - dsLookupInput.getDomainId(), - dsLookupInput.getProjectPath(), dsLookupInput.getOwnerId()); - IDAOFactory daoFactory = daoFactoryHelper.getDAOFactory(); - sfDAOFactory = daoFactory.getSetFinderDAOFactory(); - - String generatedSql = null; - RequestMessageType requestMsgType = this.getI2B2RequestType(xmlRequest); - String queryMasterId = saveQuery(sfDAOFactory, requestMsgType, - generatedSql); - - // create query instance - IQueryInstanceDao queryInstanceDao = sfDAOFactory - .getQueryInstanceDAO(); - - UserType userType = getUserTypeFromSetfinderHeader(requestMsgType); - String userId = userType.getLogin(); - String groupId = userType.getGroup(); - String queryInstanceId = queryInstanceDao.createQueryInstance( - queryMasterId, userId, groupId, - "QUEUED", 5); - // QueryExecutorMDB.SMALL_QUEUE, 5); - log.debug("New Query instance id " + queryInstanceId); - - IQueryResultInstanceDao patientSetResultDao = sfDAOFactory - .getPatientSetResultDAO(); - String patientSetId = null; - QueryDefinitionRequestType queryDefRequestType = getQueryDefinitionRequestType(requestMsgType); - ResultOutputOptionListType resultOptionList = queryDefRequestType - .getResultOutputList(); - - if (resultOptionList != null - && resultOptionList.getResultOutput() != null - && resultOptionList.getResultOutput().size() > 0) { - for (ResultOutputOptionType resultOption : resultOptionList - .getResultOutput()) { - - patientSetId = patientSetResultDao.createPatientSet( - queryInstanceId, resultOption.getName()); - logesapi.debug("Patient Set ID [" + patientSetId - + "] for query instance= " + queryInstanceId); - } - } else { - QueryProcessorUtil qp = QueryProcessorUtil.getInstance(); - //BeanFactory bf = qp.getSpringBeanFactory(); - String defaultResultType = "PATIENTSET"; - patientSetId = patientSetResultDao.createPatientSet( - queryInstanceId, defaultResultType); - logesapi.debug("Patient Set ID [" + patientSetId - + "] for query instance= " + queryInstanceId); - } - - // tm.commit(); - // transaction.commit(); - QtQueryInstance queryInstance = queryInstanceDao - .getQueryInstanceByInstanceId(queryInstanceId); - - - queryInstance.setBatchMode(QueryManagerBeanUtil.PROCESSING); - log.debug("getting responsetype"); - ResultResponseType responseType = executeSqlInQueue( - dsLookupInput.getDomainId(), - dsLookupInput.getProjectPath(), dsLookupInput.getOwnerId(), - userId, generatedSql, sessionId, queryInstanceId, - patientSetId, xmlRequest, timeout); - - // transaction.begin(); - // responseXML = qmBeanUtil.buildQueryRequestResponse(xmlRequest, - // status, - // sessionId,queryMasterId,queryInstanceId,responseType); - log.debug("after queue exectution"); - - /* - * query instance status is updated in the query executor class - * QtQueryInstance queryInstance = updateQueryInstanceStatus( - * sfDAOFactory, responseType, userId, queryInstanceId); - */ - - IQueryMasterDao queryMasterDao = sfDAOFactory.getQueryMasterDAO(); - QtQueryMaster queryMaster = queryMasterDao - .getQueryDefinition(queryMasterId); - masterInstanceResultType = new MasterInstanceResultResponseType(); - - QueryMasterType queryMasterType = PSMFactory - .buildQueryMasterType(queryMaster); - // set query master - masterInstanceResultType.setQueryMaster(queryMasterType); - - // fetch query instance by queryinstance id and build response - //QtQueryInstance queryInstance = queryInstanceDao - // .getQueryInstanceByInstanceId(queryInstanceId); - QueryInstanceType queryInstanceType = PSMFactory - .buildQueryInstanceType(queryInstance); - // set query instance - masterInstanceResultType.setQueryInstance(queryInstanceType); - // set status - masterInstanceResultType.setStatus(responseType.getStatus()); - - QueryResultBean queryResultBean = new QueryResultBean(); - ResultResponseType responseType1 = queryResultBean - .getResultInstanceFromQueryInstanceId(dataSourceLookup, - userId, queryInstanceId, false); - - log.debug("Size of result when called thru ejb " - + responseType1.getQueryResultInstance().size()); - - //If query result instanace -> query_status_type is processing that set QUEUE - //Determine if any resultinstance is type ERROR or PROCSSING - boolean processing = false; - boolean error = false; - if (responseType1.getQueryResultInstance() != null) - for (QueryResultInstanceType resultType :responseType1.getQueryResultInstance()) - { - if (resultType.getQueryStatusType().getStatusTypeId().equals("1")) - processing = true; - if (resultType.getQueryStatusType().getStatusTypeId().equals("2")) - processing = true; - if (resultType.getQueryStatusType().getStatusTypeId().equals("4")) - error = true; - if (resultType.getQueryStatusType().getStatusTypeId().equals("5")) - error = true; - - } - /* - if (responseType1.getQueryResultInstance() != null && processing== true) //responseType1.getQueryResultInstance().get(0).getQueryStatusType().getStatusTypeId().equals("2")) - { - responseType1.getQueryResultInstance().get(0).getQueryStatusType().setStatusTypeId("1"); - responseType1.getQueryResultInstance().get(0).getQueryStatusType().setName("QUEUED"); - responseType1.getQueryResultInstance().get(0).getQueryStatusType().setDescription("WAITING IN QUEUE TO START PROCESS"); - StatusType stype = new StatusType(); - Condition e = new Condition(); - e.setType("RUNNING"); - e.setValue("RUNNING"); - stype.getCondition().add(e); - responseType1.setStatus(stype); - } else - */ - if (responseType1.getQueryResultInstance() != null && error == false && processing == false) //responseType1.getQueryResultInstance().get(0).getQueryStatusType().getStatusTypeId().equals("3")) - { - // QueryStatusTypeType status = queryInstanceType.getQueryStatusType(); - // status.setStatusTypeId("3"); - // status.setDescription("FINISHED"); - // status.setName("FINISHED"); - // queryInstanceType.setQueryStatusType(status); - - QtQueryStatusType status1 = queryInstance.getQtQueryStatusType(); - status1.setStatusTypeId(3); - status1.setName("DONE"); - status1.setDescription("DONE"); - queryInstance.setQtQueryStatusType(status1); - //masterInstanceResultType.setQueryInstance(queryInstanceType); - - - if (queryMaster.getMasterTypeCd() != null && queryMaster.getMasterTypeCd().equals("EXPORT")) - queryInstance.setBatchMode(QueryManagerBeanUtil.SUBMITTED); - else - queryInstance.setBatchMode(QueryManagerBeanUtil.FINISHED); - //queryInstance.setQueryInstanceId("3"); - - queryInstance.setEndDate(new Date(System - .currentTimeMillis())); - queryInstanceDao.update(queryInstance, true); - } else if (responseType1.getQueryResultInstance() != null && error == true) //responseType1.getQueryResultInstance().get(0).getQueryStatusType().getStatusTypeId().equals("4")) - { - - // QueryStatusTypeType status = queryInstanceType.getQueryStatusType(); - // status.setStatusTypeId("4"); - // status.setDescription("ERROR"); - // status.setName("ERROR"); - // queryInstanceType.setQueryStatusType(status); - // QtQueryStatusType status1 = queryInstance.getQtQueryStatusType(); - // status1.setStatusTypeId(4); - // status1.setName("ERROR"); - // status1.setDescription("ERROR"); - // queryInstance.setQtQueryStatusType(status1); - - queryInstance.setBatchMode(QueryManagerBeanUtil.ERROR); - queryInstance.setEndDate(new Date(System - .currentTimeMillis())); - queryInstanceDao.update(queryInstance, false); - //SKIP this one and goto MEDIUM Queue - /* */ - - } else if (processing == true) //queryInstance.getBatchMode().equals("PROCESSING")) - { - QueryStatusTypeType status = queryInstanceType.getQueryStatusType(); - - status.setStatusTypeId("10"); - status.setDescription("TIMEDOUT"); - status.setName("TIMEDOUT"); - queryInstanceType.setQueryStatusType(status); - - QtQueryStatusType status1 = queryInstance.getQtQueryStatusType(); - status1.setStatusTypeId(10); - status1.setName("TIMEDOUT"); - status1.setDescription("TIMEDOUT"); - - queryInstance.setQtQueryStatusType(status1); - - queryInstance.setBatchMode("MEDIUM_QUEUE"); - queryInstance.setEndDate(null); - queryInstanceDao.update(queryInstance, false); - - responseType1.getQueryResultInstance().get(0).setQueryStatusType(status); - - } else if (responseType1.getQueryResultInstance() != null && error == true) //responseType1.getQueryResultInstance().get(0).getQueryStatusType().getStatusTypeId().equals("5")) - { - - // why does 5 (incomplete) become error? - queryInstance.setBatchMode(QueryManagerBeanUtil.ERROR); - - // QueryStatusTypeType status = queryInstanceType.getQueryStatusType(); - // status.setStatusTypeId("4"); - // status.setDescription("ERROR"); - // status.setName("ERROR"); - // queryInstanceType.setQueryStatusType(status); - - QtQueryStatusType status1 = queryInstance.getQtQueryStatusType(); - status1.setStatusTypeId(4); - status1.setName("ERROR"); - status1.setDescription("ERROR"); - queryInstance.setQtQueryStatusType(status1); - queryInstance.setEndDate(new Date(System - .currentTimeMillis())); - queryInstanceDao.update(queryInstance, false); - } - // set result instance - masterInstanceResultType.getQueryResultInstance().addAll( - responseType1.getQueryResultInstance()); - - //refresh the queryInstance to reflect the updates above - QueryInstanceType queryInstanceType2 = PSMFactory - .buildQueryInstanceType(queryInstance); - // set query instance - masterInstanceResultType.setQueryInstance(queryInstanceType2); - - - } catch (I2B2DAOException ex) { - log.debug("Got an error in QueryManagerBean, thropwing: " + ex.getMessage()); - ex.printStackTrace(); - - throw new I2B2Exception(ex.getMessage()); - } - - return masterInstanceResultType; - } - - /** - * Function to publish patients using publish message format. - * - * @ejb.interface-method view-type="both" - * @ejb.transaction type="Required" - * - * @param String - * userId - * @param int master id - * @param long timeout - * - * @return InstanceResultResponseType - */ - public InstanceResultResponseType runQueryMaster( - DataSourceLookup dataSourceLookup, String userId, String masterId, - long timeout) throws I2B2Exception { - return null; - - } - - /** - * Function to publish patients using publish message format. - * - * @ejb.interface-method view-type="both" - * @ejb.transaction type="Required" - * - * @param String - * userId - * @param int master id - * @param long timeout - * - * @return InstanceResultResponseType - */ - public InstanceResultResponseType runExportQueryInstance( - DataSourceLookup dataSourceLookup, String userId, String quertyInstanceId, - String xmlRequest) throws Exception { - - InstanceResultResponseType instanceResultResponse = new InstanceResultResponseType(); - - try { - String sessionId = String.valueOf(System.currentTimeMillis()); - QueryManagerBeanUtil qmBeanUtil = new QueryManagerBeanUtil(); - long timeout = qmBeanUtil.getTimeout(xmlRequest); - - DataSourceLookup dsLookupInput = qmBeanUtil - .getDataSourceLookupInput(xmlRequest); - SetFinderDAOFactory sfDAOFactory = null; - // tm.begin(); - // transaction.begin(); - if (dsLookupInput.getProjectPath() == null) { - throw new I2B2Exception("project id is missing in the request"); - } - DAOFactoryHelper daoFactoryHelper = new DAOFactoryHelper( - dsLookupInput.getDomainId(), - dsLookupInput.getProjectPath(), dsLookupInput.getOwnerId()); - IDAOFactory daoFactory = daoFactoryHelper.getDAOFactory(); - sfDAOFactory = daoFactory.getSetFinderDAOFactory(); - - - QueryInstanceSpringDao instanceSpringDao = new QueryInstanceSpringDao(sfDAOFactory.getDataSource(), sfDAOFactory.getDataSourceLookup()); - - - QueryResultInstanceSpringDao resultInstanceDao = new QueryResultInstanceSpringDao(sfDAOFactory.getDataSource(), sfDAOFactory.getDataSourceLookup()); - Set setResult = new HashSet<>(); - - //QueryInstanceType queryInstanceResponse = PSMFactory - // .buildQueryInstanceType(instanceSpringDao.getQueryInstanceByInstanceId(quertyInstanceId)); - //instanceResultResponse.setQueryInstance(queryInstanceResponse); - - for (QtQueryResultInstance r : resultInstanceDao.getResultInstanceList(quertyInstanceId)) - { - if (r.getQtQueryResultType().getClassname().equals("edu.harvard.i2b2.crc.dao.setfinder.QueryResultPatientDownload")) - r.getClass(); - } - - - - } catch (I2B2DAOException ex) { - log.debug("Got an error in QueryManagerBean, thropwing: " + ex.getMessage()); - ex.printStackTrace(); - - throw new I2B2Exception(ex.getMessage()); - } - - - return instanceResultResponse; - } - - private ResultResponseType executeSqlInQueue(String domainId, - String projectId, String ownerId, String userId, - String generatedSql, String sessionId, String queryInstanceId, - String patientSetId, String xmlRequest, long timeout) - throws Exception { - - QueryManagerBeanUtil qmBeanUtil = new QueryManagerBeanUtil(); - - // process interactive query - // log.debug("process query in queue"); - Map returnValues = qmBeanUtil.testSend(domainId, projectId, ownerId, - generatedSql, sessionId, queryInstanceId, patientSetId, - xmlRequest, timeout); - - // log.debug("My returnValue map is:" + returnValues); - // log.debug("My mapssize is: " + returnValues.size()); - // build response message, if query completed before given timeout - String status = (String) returnValues - .get(QueryManagerBeanUtil.QUERY_STATUS_PARAM); - int queryResultInstanceId = (Integer) returnValues - .get(QueryManagerBeanUtil.QT_QUERY_RESULT_INSTANCE_ID_PARAM); - log.debug("Query Result Instance id " + queryResultInstanceId); - - log.debug("Status coming from queue : " + status); - StatusType statusType = new StatusType(); - StatusType.Condition condition = new StatusType.Condition(); - condition.setValue(status); - if (status != null && status.indexOf("LOCKEDOUT") > -1) { - status = "ERROR"; - } - condition.setType(status); - statusType.getCondition().add(condition); - ResultResponseType responseType = new ResultResponseType(); - responseType.setStatus(statusType); - return responseType; - } - - private String saveQuery(SetFinderDAOFactory sfDAOFactory, - RequestMessageType i2b2RequestMsgType, String generatedSql) throws Exception { - IQueryMasterDao queryMasterDao = sfDAOFactory.getQueryMasterDAO(); - QtQueryMaster queryMaster = new QtQueryMaster(); - UserType userType = getUserTypeFromSetfinderHeader(i2b2RequestMsgType); - String userId = userType.getLogin(); - String groupId = userType.getGroup(); - QueryDefinitionType queryDefType = getQueryDefinition(i2b2RequestMsgType); - queryDefType.setQueryName(queryDefType.getQueryName().replaceAll("\\<[^>]*>","")); - edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); - - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - if (userId.equalsIgnoreCase(qpUtil - .getCRCPropertyValue("edu.harvard.i2b2.crc.pm.serviceaccount.user"))) - throw new Exception("Cannot run queries as servcice account: " + userId); - queryMaster.setUserId(userId); - - //If time not set than set to 12:00 - - for (PanelType panel: queryDefType.getPanel()) - { - if (panel.getPanelDateFrom() != null && panel.getPanelDateFrom().getValue() != null) { - ConstrainDateTimeType time = panel.getPanelDateFrom().getTime(); - if(time == null) - { - XMLGregorianCalendar fixTime = panel.getPanelDateFrom().getValue(); - fixTime.setSecond(0); - fixTime.setHour(12); - fixTime.setMinute(0); - fixTime.setMillisecond(0); - } - } - if (panel.getPanelDateTo() != null && panel.getPanelDateTo().getValue() != null) { - ConstrainDateTimeType time = panel.getPanelDateTo().getTime(); - if(time == null) - { - XMLGregorianCalendar fixTime2 = panel.getPanelDateTo().getValue(); - fixTime2.setSecond(0); - fixTime2.setHour(12); - fixTime2.setMinute(0); - fixTime2.setMillisecond(0); - - } - } - } - - - StringWriter queryDefWriter = new StringWriter(); - CRCJAXBUtil.getQueryDefJAXBUtil().marshaller( - of.createQueryDefinition(queryDefType), queryDefWriter); - - queryMaster.setRequestXml(queryDefWriter.toString()); - queryMaster.setGroupId(groupId); - queryMaster.setCreateDate(new Date(System.currentTimeMillis())); - queryMaster.setDeleteFlag(QtQueryMaster.DELETE_OFF_FLAG); - queryMaster.setGeneratedSql(generatedSql); - queryMaster.setName(queryDefType.getQueryName()); - - String pmXml = CallPMUtil.callUserResponse(i2b2RequestMsgType.getMessageHeader().getSecurity(), ""); - - //remove user password form the request - PasswordType passType = i2b2RequestMsgType.getMessageHeader().getSecurity().getPassword(); - passType.setValue("password not stored"); - passType.setIsToken(false); - - JAXBUtil util = CRCJAXBUtil.getJAXBUtil(); - StringWriter strWriter = new StringWriter(); - edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory i2b2ObjFactory = new edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory(); - util.marshaller(i2b2ObjFactory.createRequest(i2b2RequestMsgType), strWriter); - String queryMasterId = queryMasterDao.createQueryMaster(queryMaster, - strWriter.toString(), pmXml); - - return queryMasterId; - } - - private UserType getUserTypeFromSetfinderHeader(RequestMessageType requestMessageType) - throws Exception { - UserType userType = new UserType(); - userType.setLogin(requestMessageType.getMessageHeader().getSecurity() - .getUsername()); - userType.setGroup(requestMessageType.getMessageHeader().getProjectId()); - - return userType; - } - - private RequestMessageType getI2B2RequestType(String xmlRequest) - throws Exception { - - JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); - JAXBElement jaxbElement = jaxbUtil.unMashallFromString(xmlRequest); - - if (jaxbElement == null) { - throw new Exception( - "null value in after unmarshalling request string "); - } - - RequestMessageType requestMessageType = (RequestMessageType) jaxbElement - .getValue(); - - return requestMessageType; - } - - private QueryDefinitionRequestType getQueryDefinitionRequestType( - RequestMessageType requestMessageType) throws Exception { - String queryName = null; - QueryDefinitionType queryDef = null; - - BodyType bodyType = requestMessageType.getMessageBody(); - JAXBUnWrapHelper unWrapHelper = new JAXBUnWrapHelper(); - QueryDefinitionRequestType queryDefReqType = (QueryDefinitionRequestType) unWrapHelper - .getObjectByClass(bodyType.getAny(), - QueryDefinitionRequestType.class); - return queryDefReqType; - - } - - public QueryDefinitionType getQueryDefinition(RequestMessageType requestMessageType) - throws Exception { - QueryDefinitionRequestType queryDefReqType = getQueryDefinitionRequestType(requestMessageType); - QueryDefinitionType queryDef = null; - if (queryDefReqType != null) { - queryDef = queryDefReqType.getQueryDefinition(); - } - return queryDef; - } - - /** - * Function to publish patients using publish message format. - * - * @ejb.interface-method view-type="both" - * @ejb.transaction type="Required" - * - * @param int session id publish request XML fileName - * - * @return String publish response XML - */ - public String getResponseXML(String sessionId) { - QueryManagerBeanUtil qmBeanUtil = new QueryManagerBeanUtil(); - String status = qmBeanUtil.getStatus(sessionId); - String response = qmBeanUtil.buildGetQueryResultResponse(sessionId, - status); - - return response; - } - - /* - public void setSessionContext(SessionContext context) throws EJBException, - RemoteException { - this.context = context; - } - - public void ejbCreate() throws CreateException { - } - - public void ejbRemove() throws EJBException, RemoteException { - } - - public void ejbActivate() throws EJBException, RemoteException { - } - - public void ejbPassivate() throws EJBException, RemoteException { - } - */ -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.ejb; + +import java.io.StringWriter; +import java.util.Date; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import jakarta.xml.bind.JAXBElement; +import javax.xml.datatype.XMLGregorianCalendar; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.dao.IDAOFactory; +import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; +import edu.harvard.i2b2.crc.dao.setfinder.IQueryInstanceDao; +import edu.harvard.i2b2.crc.dao.setfinder.IQueryMasterDao; +import edu.harvard.i2b2.crc.dao.setfinder.IQueryResultInstanceDao; +import edu.harvard.i2b2.crc.dao.setfinder.QueryInstanceSpringDao; +import edu.harvard.i2b2.crc.dao.setfinder.QueryResultInstanceSpringDao; +import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; +import edu.harvard.i2b2.crc.datavo.PSMFactory; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.db.QtQueryInstance; +import edu.harvard.i2b2.crc.datavo.db.QtQueryMaster; +import edu.harvard.i2b2.crc.datavo.db.QtQueryResultInstance; +import edu.harvard.i2b2.crc.datavo.db.QtQueryStatusType; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2message.PasswordType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ConstrainDateTimeType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceResultResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterInstanceResultResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.PanelType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionRequestType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryInstanceType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryMasterType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryResultInstanceType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryStatusTypeType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultOutputOptionListType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultOutputOptionType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.StatusType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.StatusType.Condition; +import edu.harvard.i2b2.crc.datavo.setfinder.query.UserType; +import edu.harvard.i2b2.crc.delegate.pm.CallPMUtil; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + + +/** + * Ejb manager class for query operation + * + * @author rkuttan + * + * @ejb.bean description="QueryTool Query Manager" + * display-name="QueryTool Query Manager" + * jndi-name="ejb.querytool.QueryManager" + * local-jndi-name="ejb.querytool.QueryManagerLocal" + * name="querytool.QueryManager" type="Stateless" view-type="both" + * transaction-type="Bean" + * + * @ejb.transaction type="Required" + * + * + * @ejb.interface remote-class="edu.harvard.i2b2.crc.ejb.QueryManagerRemote" + * + * + */ +public class QueryManagerBean{ // implements SessionBean { + private static Log log = LogFactory.getLog(QueryManagerBean.class); + public static String RESPONSE_QUEUE_NAME = "queue/jms.querytool.QueryResponse"; + + protected static Log logesapi = LogFactory.getLog(QueryManagerBean.class); + + + // public static String UPLOADPROCESSOR_QUEUE_NAME = + // "queue/jms.querytool.QueryExecutor"; + + // SessionContext context; + + /** + * Function to publish patients using publish message format. + * + * @ejb.interface-method view-type="both" + * @ejb.transaction type="Required" + * + * @param String + * publish request XML fileName + * + * @return String publish response XML + * @throws Exception + */ + public MasterInstanceResultResponseType processQuery( + DataSourceLookup dataSourceLookup, String xmlRequest) + throws Exception { + String responseXML = null; + + MasterInstanceResultResponseType masterInstanceResultType = null; + + try { + String sessionId = String.valueOf(System.currentTimeMillis()); + QueryManagerBeanUtil qmBeanUtil = new QueryManagerBeanUtil(); + long timeout = qmBeanUtil.getTimeout(xmlRequest); + + DataSourceLookup dsLookupInput = qmBeanUtil + .getDataSourceLookupInput(xmlRequest); + SetFinderDAOFactory sfDAOFactory = null; + // tm.begin(); + // transaction.begin(); + if (dsLookupInput.getProjectPath() == null) { + throw new I2B2Exception("project id is missing in the request"); + } + DAOFactoryHelper daoFactoryHelper = new DAOFactoryHelper( + dsLookupInput.getDomainId(), + dsLookupInput.getProjectPath(), dsLookupInput.getOwnerId()); + IDAOFactory daoFactory = daoFactoryHelper.getDAOFactory(); + sfDAOFactory = daoFactory.getSetFinderDAOFactory(); + + String generatedSql = null; + RequestMessageType requestMsgType = this.getI2B2RequestType(xmlRequest); + String queryMasterId = saveQuery(sfDAOFactory, requestMsgType, + generatedSql); + + // create query instance + IQueryInstanceDao queryInstanceDao = sfDAOFactory + .getQueryInstanceDAO(); + + UserType userType = getUserTypeFromSetfinderHeader(requestMsgType); + String userId = userType.getLogin(); + String groupId = userType.getGroup(); + String queryInstanceId = queryInstanceDao.createQueryInstance( + queryMasterId, userId, groupId, + "QUEUED", 5); + // QueryExecutorMDB.SMALL_QUEUE, 5); + log.debug("New Query instance id " + queryInstanceId); + + IQueryResultInstanceDao patientSetResultDao = sfDAOFactory + .getPatientSetResultDAO(); + String patientSetId = null; + QueryDefinitionRequestType queryDefRequestType = getQueryDefinitionRequestType(requestMsgType); + ResultOutputOptionListType resultOptionList = queryDefRequestType + .getResultOutputList(); + + if (resultOptionList != null + && resultOptionList.getResultOutput() != null + && resultOptionList.getResultOutput().size() > 0) { + for (ResultOutputOptionType resultOption : resultOptionList + .getResultOutput()) { + + patientSetId = patientSetResultDao.createPatientSet( + queryInstanceId, resultOption.getName()); + logesapi.debug("Patient Set ID [" + patientSetId + + "] for query instance= " + queryInstanceId); + } + } else { + QueryProcessorUtil qp = QueryProcessorUtil.getInstance(); + //BeanFactory bf = qp.getSpringBeanFactory(); + String defaultResultType = "PATIENTSET"; + patientSetId = patientSetResultDao.createPatientSet( + queryInstanceId, defaultResultType); + logesapi.debug("Patient Set ID [" + patientSetId + + "] for query instance= " + queryInstanceId); + } + + // tm.commit(); + // transaction.commit(); + QtQueryInstance queryInstance = queryInstanceDao + .getQueryInstanceByInstanceId(queryInstanceId); + + + queryInstance.setBatchMode(QueryManagerBeanUtil.PROCESSING); + log.debug("getting responsetype"); + ResultResponseType responseType = executeSqlInQueue( + dsLookupInput.getDomainId(), + dsLookupInput.getProjectPath(), dsLookupInput.getOwnerId(), + userId, generatedSql, sessionId, queryInstanceId, + patientSetId, xmlRequest, timeout); + + // transaction.begin(); + // responseXML = qmBeanUtil.buildQueryRequestResponse(xmlRequest, + // status, + // sessionId,queryMasterId,queryInstanceId,responseType); + log.debug("after queue exectution"); + + /* + * query instance status is updated in the query executor class + * QtQueryInstance queryInstance = updateQueryInstanceStatus( + * sfDAOFactory, responseType, userId, queryInstanceId); + */ + + IQueryMasterDao queryMasterDao = sfDAOFactory.getQueryMasterDAO(); + QtQueryMaster queryMaster = queryMasterDao + .getQueryDefinition(queryMasterId); + masterInstanceResultType = new MasterInstanceResultResponseType(); + + QueryMasterType queryMasterType = PSMFactory + .buildQueryMasterType(queryMaster); + // set query master + masterInstanceResultType.setQueryMaster(queryMasterType); + + // fetch query instance by queryinstance id and build response + //QtQueryInstance queryInstance = queryInstanceDao + // .getQueryInstanceByInstanceId(queryInstanceId); + QueryInstanceType queryInstanceType = PSMFactory + .buildQueryInstanceType(queryInstance); + // set query instance + masterInstanceResultType.setQueryInstance(queryInstanceType); + // set status + masterInstanceResultType.setStatus(responseType.getStatus()); + + QueryResultBean queryResultBean = new QueryResultBean(); + ResultResponseType responseType1 = queryResultBean + .getResultInstanceFromQueryInstanceId(dataSourceLookup, + userId, queryInstanceId, false); + + log.debug("Size of result when called thru ejb " + + responseType1.getQueryResultInstance().size()); + + //If query result instanace -> query_status_type is processing that set QUEUE + //Determine if any resultinstance is type ERROR or PROCSSING + boolean processing = false; + boolean error = false; + if (responseType1.getQueryResultInstance() != null) + for (QueryResultInstanceType resultType :responseType1.getQueryResultInstance()) + { + if (resultType.getQueryStatusType().getStatusTypeId().equals("1")) + processing = true; + if (resultType.getQueryStatusType().getStatusTypeId().equals("2")) + processing = true; + if (resultType.getQueryStatusType().getStatusTypeId().equals("4")) + error = true; + if (resultType.getQueryStatusType().getStatusTypeId().equals("5")) + error = true; + + } + /* + if (responseType1.getQueryResultInstance() != null && processing== true) //responseType1.getQueryResultInstance().get(0).getQueryStatusType().getStatusTypeId().equals("2")) + { + responseType1.getQueryResultInstance().get(0).getQueryStatusType().setStatusTypeId("1"); + responseType1.getQueryResultInstance().get(0).getQueryStatusType().setName("QUEUED"); + responseType1.getQueryResultInstance().get(0).getQueryStatusType().setDescription("WAITING IN QUEUE TO START PROCESS"); + StatusType stype = new StatusType(); + Condition e = new Condition(); + e.setType("RUNNING"); + e.setValue("RUNNING"); + stype.getCondition().add(e); + responseType1.setStatus(stype); + } else + */ + if (responseType1.getQueryResultInstance() != null && error == false && processing == false) //responseType1.getQueryResultInstance().get(0).getQueryStatusType().getStatusTypeId().equals("3")) + { + // QueryStatusTypeType status = queryInstanceType.getQueryStatusType(); + // status.setStatusTypeId("3"); + // status.setDescription("FINISHED"); + // status.setName("FINISHED"); + // queryInstanceType.setQueryStatusType(status); + + QtQueryStatusType status1 = queryInstance.getQtQueryStatusType(); + status1.setStatusTypeId(3); + status1.setName("DONE"); + status1.setDescription("DONE"); + queryInstance.setQtQueryStatusType(status1); + //masterInstanceResultType.setQueryInstance(queryInstanceType); + + + if (queryMaster.getMasterTypeCd() != null && queryMaster.getMasterTypeCd().equals("EXPORT")) + queryInstance.setBatchMode(QueryManagerBeanUtil.SUBMITTED); + else + queryInstance.setBatchMode(QueryManagerBeanUtil.FINISHED); + //queryInstance.setQueryInstanceId("3"); + + queryInstance.setEndDate(new Date(System + .currentTimeMillis())); + queryInstanceDao.update(queryInstance, true); + } else if (responseType1.getQueryResultInstance() != null && error == true) //responseType1.getQueryResultInstance().get(0).getQueryStatusType().getStatusTypeId().equals("4")) + { + + // QueryStatusTypeType status = queryInstanceType.getQueryStatusType(); + // status.setStatusTypeId("4"); + // status.setDescription("ERROR"); + // status.setName("ERROR"); + // queryInstanceType.setQueryStatusType(status); + // QtQueryStatusType status1 = queryInstance.getQtQueryStatusType(); + // status1.setStatusTypeId(4); + // status1.setName("ERROR"); + // status1.setDescription("ERROR"); + // queryInstance.setQtQueryStatusType(status1); + + queryInstance.setBatchMode(QueryManagerBeanUtil.ERROR); + queryInstance.setEndDate(new Date(System + .currentTimeMillis())); + queryInstanceDao.update(queryInstance, false); + //SKIP this one and goto MEDIUM Queue + /* */ + + } else if (processing == true) //queryInstance.getBatchMode().equals("PROCESSING")) + { + QueryStatusTypeType status = queryInstanceType.getQueryStatusType(); + + status.setStatusTypeId("10"); + status.setDescription("TIMEDOUT"); + status.setName("TIMEDOUT"); + queryInstanceType.setQueryStatusType(status); + + QtQueryStatusType status1 = queryInstance.getQtQueryStatusType(); + status1.setStatusTypeId(10); + status1.setName("TIMEDOUT"); + status1.setDescription("TIMEDOUT"); + + queryInstance.setQtQueryStatusType(status1); + + queryInstance.setBatchMode("MEDIUM_QUEUE"); + queryInstance.setEndDate(null); + queryInstanceDao.update(queryInstance, false); + + responseType1.getQueryResultInstance().get(0).setQueryStatusType(status); + + } else if (responseType1.getQueryResultInstance() != null && error == true) //responseType1.getQueryResultInstance().get(0).getQueryStatusType().getStatusTypeId().equals("5")) + { + + // why does 5 (incomplete) become error? + queryInstance.setBatchMode(QueryManagerBeanUtil.ERROR); + + // QueryStatusTypeType status = queryInstanceType.getQueryStatusType(); + // status.setStatusTypeId("4"); + // status.setDescription("ERROR"); + // status.setName("ERROR"); + // queryInstanceType.setQueryStatusType(status); + + QtQueryStatusType status1 = queryInstance.getQtQueryStatusType(); + status1.setStatusTypeId(4); + status1.setName("ERROR"); + status1.setDescription("ERROR"); + queryInstance.setQtQueryStatusType(status1); + queryInstance.setEndDate(new Date(System + .currentTimeMillis())); + queryInstanceDao.update(queryInstance, false); + } + // set result instance + masterInstanceResultType.getQueryResultInstance().addAll( + responseType1.getQueryResultInstance()); + + //refresh the queryInstance to reflect the updates above + QueryInstanceType queryInstanceType2 = PSMFactory + .buildQueryInstanceType(queryInstance); + // set query instance + masterInstanceResultType.setQueryInstance(queryInstanceType2); + + + } catch (I2B2DAOException ex) { + log.debug("Got an error in QueryManagerBean, thropwing: " + ex.getMessage()); + ex.printStackTrace(); + + throw new I2B2Exception(ex.getMessage()); + } + + return masterInstanceResultType; + } + + /** + * Function to publish patients using publish message format. + * + * @ejb.interface-method view-type="both" + * @ejb.transaction type="Required" + * + * @param String + * userId + * @param int master id + * @param long timeout + * + * @return InstanceResultResponseType + */ + public InstanceResultResponseType runQueryMaster( + DataSourceLookup dataSourceLookup, String userId, String masterId, + long timeout) throws I2B2Exception { + return null; + + } + + /** + * Function to publish patients using publish message format. + * + * @ejb.interface-method view-type="both" + * @ejb.transaction type="Required" + * + * @param String + * userId + * @param int master id + * @param long timeout + * + * @return InstanceResultResponseType + */ + public InstanceResultResponseType runExportQueryInstance( + DataSourceLookup dataSourceLookup, String userId, String quertyInstanceId, + String xmlRequest) throws Exception { + + InstanceResultResponseType instanceResultResponse = new InstanceResultResponseType(); + + try { + String sessionId = String.valueOf(System.currentTimeMillis()); + QueryManagerBeanUtil qmBeanUtil = new QueryManagerBeanUtil(); + long timeout = qmBeanUtil.getTimeout(xmlRequest); + + DataSourceLookup dsLookupInput = qmBeanUtil + .getDataSourceLookupInput(xmlRequest); + SetFinderDAOFactory sfDAOFactory = null; + // tm.begin(); + // transaction.begin(); + if (dsLookupInput.getProjectPath() == null) { + throw new I2B2Exception("project id is missing in the request"); + } + DAOFactoryHelper daoFactoryHelper = new DAOFactoryHelper( + dsLookupInput.getDomainId(), + dsLookupInput.getProjectPath(), dsLookupInput.getOwnerId()); + IDAOFactory daoFactory = daoFactoryHelper.getDAOFactory(); + sfDAOFactory = daoFactory.getSetFinderDAOFactory(); + + + QueryInstanceSpringDao instanceSpringDao = new QueryInstanceSpringDao(sfDAOFactory.getDataSource(), sfDAOFactory.getDataSourceLookup()); + + + QueryResultInstanceSpringDao resultInstanceDao = new QueryResultInstanceSpringDao(sfDAOFactory.getDataSource(), sfDAOFactory.getDataSourceLookup()); + Set setResult = new HashSet<>(); + + //QueryInstanceType queryInstanceResponse = PSMFactory + // .buildQueryInstanceType(instanceSpringDao.getQueryInstanceByInstanceId(quertyInstanceId)); + //instanceResultResponse.setQueryInstance(queryInstanceResponse); + + for (QtQueryResultInstance r : resultInstanceDao.getResultInstanceList(quertyInstanceId)) + { + if (r.getQtQueryResultType().getClassname().equals("edu.harvard.i2b2.crc.dao.setfinder.QueryResultPatientDownload")) + r.getClass(); + } + + + + } catch (I2B2DAOException ex) { + log.debug("Got an error in QueryManagerBean, thropwing: " + ex.getMessage()); + ex.printStackTrace(); + + throw new I2B2Exception(ex.getMessage()); + } + + + return instanceResultResponse; + } + + private ResultResponseType executeSqlInQueue(String domainId, + String projectId, String ownerId, String userId, + String generatedSql, String sessionId, String queryInstanceId, + String patientSetId, String xmlRequest, long timeout) + throws Exception { + + QueryManagerBeanUtil qmBeanUtil = new QueryManagerBeanUtil(); + + // process interactive query + // log.debug("process query in queue"); + Map returnValues = qmBeanUtil.testSend(domainId, projectId, ownerId, + generatedSql, sessionId, queryInstanceId, patientSetId, + xmlRequest, timeout); + + // log.debug("My returnValue map is:" + returnValues); + // log.debug("My mapssize is: " + returnValues.size()); + // build response message, if query completed before given timeout + String status = (String) returnValues + .get(QueryManagerBeanUtil.QUERY_STATUS_PARAM); + int queryResultInstanceId = (Integer) returnValues + .get(QueryManagerBeanUtil.QT_QUERY_RESULT_INSTANCE_ID_PARAM); + log.debug("Query Result Instance id " + queryResultInstanceId); + + log.debug("Status coming from queue : " + status); + StatusType statusType = new StatusType(); + StatusType.Condition condition = new StatusType.Condition(); + condition.setValue(status); + if (status != null && status.indexOf("LOCKEDOUT") > -1) { + status = "ERROR"; + } + condition.setType(status); + statusType.getCondition().add(condition); + ResultResponseType responseType = new ResultResponseType(); + responseType.setStatus(statusType); + return responseType; + } + + private String saveQuery(SetFinderDAOFactory sfDAOFactory, + RequestMessageType i2b2RequestMsgType, String generatedSql) throws Exception { + IQueryMasterDao queryMasterDao = sfDAOFactory.getQueryMasterDAO(); + QtQueryMaster queryMaster = new QtQueryMaster(); + UserType userType = getUserTypeFromSetfinderHeader(i2b2RequestMsgType); + String userId = userType.getLogin(); + String groupId = userType.getGroup(); + QueryDefinitionType queryDefType = getQueryDefinition(i2b2RequestMsgType); + queryDefType.setQueryName(queryDefType.getQueryName().replaceAll("\\<[^>]*>","")); + edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); + + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + if (userId.equalsIgnoreCase(qpUtil + .getCRCPropertyValue("edu.harvard.i2b2.crc.pm.serviceaccount.user"))) + throw new Exception("Cannot run queries as servcice account: " + userId); + queryMaster.setUserId(userId); + + //If time not set than set to 12:00 + + for (PanelType panel: queryDefType.getPanel()) + { + if (panel.getPanelDateFrom() != null && panel.getPanelDateFrom().getValue() != null) { + ConstrainDateTimeType time = panel.getPanelDateFrom().getTime(); + if(time == null) + { + XMLGregorianCalendar fixTime = panel.getPanelDateFrom().getValue(); + fixTime.setSecond(0); + fixTime.setHour(12); + fixTime.setMinute(0); + fixTime.setMillisecond(0); + } + } + if (panel.getPanelDateTo() != null && panel.getPanelDateTo().getValue() != null) { + ConstrainDateTimeType time = panel.getPanelDateTo().getTime(); + if(time == null) + { + XMLGregorianCalendar fixTime2 = panel.getPanelDateTo().getValue(); + fixTime2.setSecond(0); + fixTime2.setHour(12); + fixTime2.setMinute(0); + fixTime2.setMillisecond(0); + + } + } + } + + + StringWriter queryDefWriter = new StringWriter(); + CRCJAXBUtil.getQueryDefJAXBUtil().marshaller( + of.createQueryDefinition(queryDefType), queryDefWriter); + + queryMaster.setRequestXml(queryDefWriter.toString()); + queryMaster.setGroupId(groupId); + queryMaster.setCreateDate(new Date(System.currentTimeMillis())); + queryMaster.setDeleteFlag(QtQueryMaster.DELETE_OFF_FLAG); + queryMaster.setGeneratedSql(generatedSql); + queryMaster.setName(queryDefType.getQueryName()); + + String pmXml = CallPMUtil.callUserResponse(i2b2RequestMsgType.getMessageHeader().getSecurity(), ""); + + //remove user password form the request + PasswordType passType = i2b2RequestMsgType.getMessageHeader().getSecurity().getPassword(); + passType.setValue("password not stored"); + passType.setIsToken(false); + + JAXBUtil util = CRCJAXBUtil.getJAXBUtil(); + StringWriter strWriter = new StringWriter(); + edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory i2b2ObjFactory = new edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory(); + util.marshaller(i2b2ObjFactory.createRequest(i2b2RequestMsgType), strWriter); + String queryMasterId = queryMasterDao.createQueryMaster(queryMaster, + strWriter.toString(), pmXml); + + return queryMasterId; + } + + private UserType getUserTypeFromSetfinderHeader(RequestMessageType requestMessageType) + throws Exception { + UserType userType = new UserType(); + userType.setLogin(requestMessageType.getMessageHeader().getSecurity() + .getUsername()); + userType.setGroup(requestMessageType.getMessageHeader().getProjectId()); + + return userType; + } + + private RequestMessageType getI2B2RequestType(String xmlRequest) + throws Exception { + + JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); + JAXBElement jaxbElement = jaxbUtil.unMashallFromString(xmlRequest); + + if (jaxbElement == null) { + throw new Exception( + "null value in after unmarshalling request string "); + } + + RequestMessageType requestMessageType = (RequestMessageType) jaxbElement + .getValue(); + + return requestMessageType; + } + + private QueryDefinitionRequestType getQueryDefinitionRequestType( + RequestMessageType requestMessageType) throws Exception { + String queryName = null; + QueryDefinitionType queryDef = null; + + BodyType bodyType = requestMessageType.getMessageBody(); + JAXBUnWrapHelper unWrapHelper = new JAXBUnWrapHelper(); + QueryDefinitionRequestType queryDefReqType = (QueryDefinitionRequestType) unWrapHelper + .getObjectByClass(bodyType.getAny(), + QueryDefinitionRequestType.class); + return queryDefReqType; + + } + + public QueryDefinitionType getQueryDefinition(RequestMessageType requestMessageType) + throws Exception { + QueryDefinitionRequestType queryDefReqType = getQueryDefinitionRequestType(requestMessageType); + QueryDefinitionType queryDef = null; + if (queryDefReqType != null) { + queryDef = queryDefReqType.getQueryDefinition(); + } + return queryDef; + } + + /** + * Function to publish patients using publish message format. + * + * @ejb.interface-method view-type="both" + * @ejb.transaction type="Required" + * + * @param int session id publish request XML fileName + * + * @return String publish response XML + */ + public String getResponseXML(String sessionId) { + QueryManagerBeanUtil qmBeanUtil = new QueryManagerBeanUtil(); + String status = qmBeanUtil.getStatus(sessionId); + String response = qmBeanUtil.buildGetQueryResultResponse(sessionId, + status); + + return response; + } + + /* + public void setSessionContext(SessionContext context) throws EJBException, + RemoteException { + this.context = context; + } + + public void ejbCreate() throws CreateException { + } + + public void ejbRemove() throws EJBException, RemoteException { + } + + public void ejbActivate() throws EJBException, RemoteException { + } + + public void ejbPassivate() throws EJBException, RemoteException { + } + */ +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/QueryManagerBeanUtil.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/QueryManagerBeanUtil.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/QueryManagerBeanUtil.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/QueryManagerBeanUtil.java index 8dc32217..56b3ff5e --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/QueryManagerBeanUtil.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/QueryManagerBeanUtil.java @@ -1,320 +1,320 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.ejb; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.io.StringWriter; -import java.util.HashMap; -import java.util.Map; - - -import jakarta.xml.bind.JAXBElement; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.ServiceLocator; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.dao.IDAOFactory; -import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; -import edu.harvard.i2b2.crc.dao.setfinder.IQueryInstanceDao; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.db.QtQueryInstance; -import edu.harvard.i2b2.crc.datavo.i2b2message.InfoType; -import edu.harvard.i2b2.crc.datavo.i2b2message.PollingUrlType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResultStatusType; -import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - -public class QueryManagerBeanUtil { - - /** log **/ - protected final Log log = LogFactory.getLog(getClass()); - - public final static String RESPONSE_QUEUE_NAME = "queue/jms.querytool.QueryResponse"; - // public final static String UPLOADPROCESSOR_QUEUE_NAME = - // "queue/jms.querytool.QueryExecutor"; - - public final static String SMALL_QUEUE_NAME = "queue/jms.querytool.QueryExecutorSmall"; - public final static String MEDIUM_QUEUE_NAME = "queue/jms.querytool.QueryExecutorMedium"; - public final static String LARGE_QUEUE_NAME = "queue/jms.querytool.QueryExecutorLarge"; - - public final static String QUEUE_CONN_FACTORY_NAME = "ConnectionFactory"; - - public final static String QUERY_MASTER_GENERATED_SQL_PARAM = "QUERY_MASTER_GENERATED_SQL_PARAM"; - public final static String QUERY_INSTANCE_ID_PARAM = "QUERY_INSTANCE_ID_PARAM"; - public final static String QUERY_PATIENT_SET_ID_PARAM = "QUERY_PATIENT_SET_ID_PARAM"; - public final static String XML_REQUEST_PARAM = "XML_REQUEST_PARAM"; - - public final static String DS_LOOKUP_DOMAIN_ID = "DS_LOOKUP_DOMAIN_ID"; - public final static String DS_LOOKUP_PROJECT_ID = "DS_LOOKUP_PROJECT_ID"; - public final static String DS_LOOKUP_OWNER_ID = "DS_LOOKUP_OWNER_ID"; - - public static final String QUEUED = "QUEUED"; - public static final String ERROR = "ERROR"; - public static final String FINISHED = "FINISHED"; - public static final String PROCESSING = "PROCESSING"; - public static final String SUBMITTED = "SUBMITTED"; - public static final String SMALL_QUEUE = "SMALL_QUEUE"; - public static final String MEDIUM_QUEUE = "MEDIUM_QUEUE"; - public static final String LARGE_QUEUE = "LARGE_QUEUE"; - public static final String MEDIUM_QUEUE_RUNNING = "MEDIUM_QUEUE_RUNNING"; - public static final String LARGE_QUEUE_RUNNING = "LARGE_QUEUE_RUNNING"; - public static final String RUNNING = "RUNNING"; - public final static String QUERY_STATUS_PARAM = "QUERY_STATUS_PARAM"; - public final static String QT_QUERY_RESULT_INSTANCE_ID_PARAM = "QT_QUERY_RESULT_INSTANCE_ID_PARAM"; - - - public QueryManagerBeanUtil() { - - } - - public Map testSend(String domainId, String projectId, String ownerId, - String generatedSql, String sessionId, String queryInstanceId, - String patientSetId, String xmlRequest, long timeout) - throws Exception { - String status = null; - int queryResultInstanceId = 0; - - log.debug("in testSend"); - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - ServiceLocator serviceLocator = ServiceLocator.getInstance(); - - - long waitTime = getTimeout(xmlRequest); - - ExecRunnable exec = new ExecRunnable(); - - exec.execute(generatedSql, queryInstanceId, patientSetId, xmlRequest, - domainId, projectId, ownerId, waitTime); - - - Thread t = new Thread(exec); - - - synchronized (t) { - t.start(); - - try { - //if (waitTime > 0) { - // t.wait(waitTime); - //} else { - // t.wait(); - //} - - // the exec is running for time = request timeout (waitTime) - // wait a little longer (+10 seconds) to give exec chance to finish before deciding about queue - // long waitTimePlus = waitTime + 10 ; - long startTime = System.currentTimeMillis(); - long deltaTime = -1; - while((exec.isJobCompleteFlag() == false)&& (deltaTime < waitTime)){ - if (waitTime > 0) { - t.wait(waitTime - deltaTime); - deltaTime = System.currentTimeMillis() - startTime; - } else { - t.wait(); - } - } - - if (exec.isJobCompleteFlag() == false) { - String timeOuterror = "Result waittime millisecond :" + - waitTime + - " elapsed, setting to next queue"; - log.debug(timeOuterror); - - DAOFactoryHelper daoFactoryHelper = new DAOFactoryHelper( - domainId, projectId, ownerId); - - IDAOFactory daoFactory = daoFactoryHelper.getDAOFactory(); - - SetFinderDAOFactory sfDAOFactory = daoFactory - .getSetFinderDAOFactory(); - //DataSourceLookup dsLookup = sfDAOFactory.getDataSourceLookup(); - - IQueryInstanceDao queryInstanceDao = sfDAOFactory - .getQueryInstanceDAO(); - QtQueryInstance queryInstance = queryInstanceDao - .getQueryInstanceByInstanceId(queryInstanceId); - - queryInstance.setBatchMode(MEDIUM_QUEUE); - //queryInstance.setEndDate(new Date(System - // .currentTimeMillis())); - queryInstanceDao.update(queryInstance, false); - - log.debug("QMgrBean: Set interactive query to MEDIUM Queue; status = running"); - Map returnMap = new HashMap(); - returnMap.put(QUERY_STATUS_PARAM, "RUNNING"); - int id = Integer.parseInt(queryInstanceId); - returnMap.put(QT_QUERY_RESULT_INSTANCE_ID_PARAM, id); - return returnMap; - //throw new Exception("Timed Out, setting to MEDIUM Queue"); - } - } - catch (InterruptedException e) { - log.error("Error in thread: " + e.getMessage()); - - e.printStackTrace(); - throw new I2B2Exception("Thread error while running CRC job " - , e); - } finally { - - // t.interrupt(); - //exec = null; - t = null; - } - } - - // closeAll(sender, null, conn, session); - // closeAll(null, rcvr, conn1, recvSession); - // closeAllTopic(rcvr,conn1,recvSession); - //MM - // Map returnMap = new HashMap(); - // returnMap.put(QUERY_STATUS_PARAM, status); - // returnMap.put(QT_QUERY_RESULT_INSTANCE_ID_PARAM, queryResultInstanceId); - // return returnMap; - return exec.getResult(); - } - - - - /* - * public String buildQueryRequestResponse(String requestXml, String - * status,String sessionId,String masterId, String - * queryInstanceId,ResultResponseType resultResponseType) throws Exception { - * return buildObject(requestXml, status, sessionId, - * masterId,queryInstanceId,resultResponseType ); } - */ - public void writerRepsonseFile(String sessionId, long recordCount) { - try { - BufferedWriter bw = new BufferedWriter(new FileWriter(sessionId)); - bw.write(String.valueOf(recordCount)); - bw.close(); - } catch (IOException ioE) { - ioE.printStackTrace(); - } - } - - public long getTimeout(String xmlRequest) throws Exception { - JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); - JAXBElement jaxbElement = jaxbUtil.unMashallFromString(xmlRequest); - RequestMessageType requestMessageType = (RequestMessageType) jaxbElement - .getValue(); - - RequestHeaderType requestHeader = requestMessageType.getRequestHeader(); - long timeOut = 1; - if (requestHeader != null && requestHeader.getResultWaittimeMs() > -1) { - timeOut = requestHeader.getResultWaittimeMs(); - } - return timeOut; - } - - public DataSourceLookup getDataSourceLookupInput(String xmlRequest) - throws Exception { - DataSourceLookup dsLookupInput = null; - JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); - JAXBElement jaxbElement = jaxbUtil.unMashallFromString(xmlRequest); - RequestMessageType requestMessageType = (RequestMessageType) jaxbElement - .getValue(); - String projectId = requestMessageType.getMessageHeader().getProjectId(); - String domainId = requestMessageType.getMessageHeader().getSecurity() - .getDomain(); - String ownerId = requestMessageType.getMessageHeader().getSecurity() - .getUsername(); - dsLookupInput = new DataSourceLookup(); - dsLookupInput.setProjectPath(projectId); - dsLookupInput.setDomainId(domainId); - dsLookupInput.setOwnerId(ownerId); - return dsLookupInput; - - } - - public String getStatus(String sessionId) { - String status = "UNKNOWN"; - // check directory - File file = new File(sessionId); - if (file.exists()) { - status = "DONE"; - } else { - //TODO removed JMS - // QueueConnection conn1 = null; - // Queue responseQueue = null; - // QueueSession recvSession = null; - // QueueReceiver rcvr = null; - try { - // check jms - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - ServiceLocator serviceLocator = ServiceLocator.getInstance(); - - } catch (Exception e) { - status = "ERROR"; - e.printStackTrace(); - } finally { - // closeAll(null, rcvr, conn1, recvSession); - } - - } - return status; - - } - - public String buildGetQueryResultResponse(String sessionId, String status) { - StringWriter strWriter = new StringWriter(); - // build infotype - InfoType infoType = new InfoType(); - infoType.setUrl(""); - infoType.setValue(""); - - ResultStatusType rsType = new ResultStatusType(); - StatusType st = new StatusType(); - st.setType(sessionId); - st.setValue(status); - rsType.setStatus(st); - - PollingUrlType pollUrlType = new PollingUrlType(); - pollUrlType - .setValue("http://localhost:9093/queryProcessor/checkStatus"); - rsType.setPollingUrl(pollUrlType); - - // MessageType messageType = dtoFactory.buildMessageType(infoType, - // rsType); - ResponseHeaderType responseHeader = new ResponseHeaderType(); - responseHeader.setInfo(infoType); - responseHeader.setResultStatus(rsType); - ResponseMessageType responseMessageType = new ResponseMessageType(); - responseMessageType.setResponseHeader(responseHeader); - - try { - JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); - edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory(); - jaxbUtil.marshaller(of.createResponse(responseMessageType), - strWriter); - log.debug("i2b2 Response XML " + strWriter.toString()); - } catch (Exception e) { - e.printStackTrace(); - } - return strWriter.toString(); - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.ejb; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.StringWriter; +import java.util.HashMap; +import java.util.Map; + + +import jakarta.xml.bind.JAXBElement; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.ServiceLocator; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.dao.IDAOFactory; +import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; +import edu.harvard.i2b2.crc.dao.setfinder.IQueryInstanceDao; +import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.db.QtQueryInstance; +import edu.harvard.i2b2.crc.datavo.i2b2message.InfoType; +import edu.harvard.i2b2.crc.datavo.i2b2message.PollingUrlType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResultStatusType; +import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + +public class QueryManagerBeanUtil { + + /** log **/ + protected final Log log = LogFactory.getLog(getClass()); + + public final static String RESPONSE_QUEUE_NAME = "queue/jms.querytool.QueryResponse"; + // public final static String UPLOADPROCESSOR_QUEUE_NAME = + // "queue/jms.querytool.QueryExecutor"; + + public final static String SMALL_QUEUE_NAME = "queue/jms.querytool.QueryExecutorSmall"; + public final static String MEDIUM_QUEUE_NAME = "queue/jms.querytool.QueryExecutorMedium"; + public final static String LARGE_QUEUE_NAME = "queue/jms.querytool.QueryExecutorLarge"; + + public final static String QUEUE_CONN_FACTORY_NAME = "ConnectionFactory"; + + public final static String QUERY_MASTER_GENERATED_SQL_PARAM = "QUERY_MASTER_GENERATED_SQL_PARAM"; + public final static String QUERY_INSTANCE_ID_PARAM = "QUERY_INSTANCE_ID_PARAM"; + public final static String QUERY_PATIENT_SET_ID_PARAM = "QUERY_PATIENT_SET_ID_PARAM"; + public final static String XML_REQUEST_PARAM = "XML_REQUEST_PARAM"; + + public final static String DS_LOOKUP_DOMAIN_ID = "DS_LOOKUP_DOMAIN_ID"; + public final static String DS_LOOKUP_PROJECT_ID = "DS_LOOKUP_PROJECT_ID"; + public final static String DS_LOOKUP_OWNER_ID = "DS_LOOKUP_OWNER_ID"; + + public static final String QUEUED = "QUEUED"; + public static final String ERROR = "ERROR"; + public static final String FINISHED = "FINISHED"; + public static final String PROCESSING = "PROCESSING"; + public static final String SUBMITTED = "SUBMITTED"; + public static final String SMALL_QUEUE = "SMALL_QUEUE"; + public static final String MEDIUM_QUEUE = "MEDIUM_QUEUE"; + public static final String LARGE_QUEUE = "LARGE_QUEUE"; + public static final String MEDIUM_QUEUE_RUNNING = "MEDIUM_QUEUE_RUNNING"; + public static final String LARGE_QUEUE_RUNNING = "LARGE_QUEUE_RUNNING"; + public static final String RUNNING = "RUNNING"; + public final static String QUERY_STATUS_PARAM = "QUERY_STATUS_PARAM"; + public final static String QT_QUERY_RESULT_INSTANCE_ID_PARAM = "QT_QUERY_RESULT_INSTANCE_ID_PARAM"; + + + public QueryManagerBeanUtil() { + + } + + public Map testSend(String domainId, String projectId, String ownerId, + String generatedSql, String sessionId, String queryInstanceId, + String patientSetId, String xmlRequest, long timeout) + throws Exception { + String status = null; + int queryResultInstanceId = 0; + + log.debug("in testSend"); + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + ServiceLocator serviceLocator = ServiceLocator.getInstance(); + + + long waitTime = getTimeout(xmlRequest); + + ExecRunnable exec = new ExecRunnable(); + + exec.execute(generatedSql, queryInstanceId, patientSetId, xmlRequest, + domainId, projectId, ownerId, waitTime); + + + Thread t = new Thread(exec); + + + synchronized (t) { + t.start(); + + try { + //if (waitTime > 0) { + // t.wait(waitTime); + //} else { + // t.wait(); + //} + + // the exec is running for time = request timeout (waitTime) + // wait a little longer (+10 seconds) to give exec chance to finish before deciding about queue + // long waitTimePlus = waitTime + 10 ; + long startTime = System.currentTimeMillis(); + long deltaTime = -1; + while((exec.isJobCompleteFlag() == false)&& (deltaTime < waitTime)){ + if (waitTime > 0) { + t.wait(waitTime - deltaTime); + deltaTime = System.currentTimeMillis() - startTime; + } else { + t.wait(); + } + } + + if (exec.isJobCompleteFlag() == false) { + String timeOuterror = "Result waittime millisecond :" + + waitTime + + " elapsed, setting to next queue"; + log.debug(timeOuterror); + + DAOFactoryHelper daoFactoryHelper = new DAOFactoryHelper( + domainId, projectId, ownerId); + + IDAOFactory daoFactory = daoFactoryHelper.getDAOFactory(); + + SetFinderDAOFactory sfDAOFactory = daoFactory + .getSetFinderDAOFactory(); + //DataSourceLookup dsLookup = sfDAOFactory.getDataSourceLookup(); + + IQueryInstanceDao queryInstanceDao = sfDAOFactory + .getQueryInstanceDAO(); + QtQueryInstance queryInstance = queryInstanceDao + .getQueryInstanceByInstanceId(queryInstanceId); + + queryInstance.setBatchMode(MEDIUM_QUEUE); + //queryInstance.setEndDate(new Date(System + // .currentTimeMillis())); + queryInstanceDao.update(queryInstance, false); + + log.debug("QMgrBean: Set interactive query to MEDIUM Queue; status = running"); + Map returnMap = new HashMap(); + returnMap.put(QUERY_STATUS_PARAM, "RUNNING"); + int id = Integer.parseInt(queryInstanceId); + returnMap.put(QT_QUERY_RESULT_INSTANCE_ID_PARAM, id); + return returnMap; + //throw new Exception("Timed Out, setting to MEDIUM Queue"); + } + } + catch (InterruptedException e) { + log.error("Error in thread: " + e.getMessage()); + + e.printStackTrace(); + throw new I2B2Exception("Thread error while running CRC job " + , e); + } finally { + + // t.interrupt(); + //exec = null; + t = null; + } + } + + // closeAll(sender, null, conn, session); + // closeAll(null, rcvr, conn1, recvSession); + // closeAllTopic(rcvr,conn1,recvSession); + //MM + // Map returnMap = new HashMap(); + // returnMap.put(QUERY_STATUS_PARAM, status); + // returnMap.put(QT_QUERY_RESULT_INSTANCE_ID_PARAM, queryResultInstanceId); + // return returnMap; + return exec.getResult(); + } + + + + /* + * public String buildQueryRequestResponse(String requestXml, String + * status,String sessionId,String masterId, String + * queryInstanceId,ResultResponseType resultResponseType) throws Exception { + * return buildObject(requestXml, status, sessionId, + * masterId,queryInstanceId,resultResponseType ); } + */ + public void writerRepsonseFile(String sessionId, long recordCount) { + try { + BufferedWriter bw = new BufferedWriter(new FileWriter(sessionId)); + bw.write(String.valueOf(recordCount)); + bw.close(); + } catch (IOException ioE) { + ioE.printStackTrace(); + } + } + + public long getTimeout(String xmlRequest) throws Exception { + JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); + JAXBElement jaxbElement = jaxbUtil.unMashallFromString(xmlRequest); + RequestMessageType requestMessageType = (RequestMessageType) jaxbElement + .getValue(); + + RequestHeaderType requestHeader = requestMessageType.getRequestHeader(); + long timeOut = 1; + if (requestHeader != null && requestHeader.getResultWaittimeMs() > -1) { + timeOut = requestHeader.getResultWaittimeMs(); + } + return timeOut; + } + + public DataSourceLookup getDataSourceLookupInput(String xmlRequest) + throws Exception { + DataSourceLookup dsLookupInput = null; + JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); + JAXBElement jaxbElement = jaxbUtil.unMashallFromString(xmlRequest); + RequestMessageType requestMessageType = (RequestMessageType) jaxbElement + .getValue(); + String projectId = requestMessageType.getMessageHeader().getProjectId(); + String domainId = requestMessageType.getMessageHeader().getSecurity() + .getDomain(); + String ownerId = requestMessageType.getMessageHeader().getSecurity() + .getUsername(); + dsLookupInput = new DataSourceLookup(); + dsLookupInput.setProjectPath(projectId); + dsLookupInput.setDomainId(domainId); + dsLookupInput.setOwnerId(ownerId); + return dsLookupInput; + + } + + public String getStatus(String sessionId) { + String status = "UNKNOWN"; + // check directory + File file = new File(sessionId); + if (file.exists()) { + status = "DONE"; + } else { + //TODO removed JMS + // QueueConnection conn1 = null; + // Queue responseQueue = null; + // QueueSession recvSession = null; + // QueueReceiver rcvr = null; + try { + // check jms + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + ServiceLocator serviceLocator = ServiceLocator.getInstance(); + + } catch (Exception e) { + status = "ERROR"; + e.printStackTrace(); + } finally { + // closeAll(null, rcvr, conn1, recvSession); + } + + } + return status; + + } + + public String buildGetQueryResultResponse(String sessionId, String status) { + StringWriter strWriter = new StringWriter(); + // build infotype + InfoType infoType = new InfoType(); + infoType.setUrl(""); + infoType.setValue(""); + + ResultStatusType rsType = new ResultStatusType(); + StatusType st = new StatusType(); + st.setType(sessionId); + st.setValue(status); + rsType.setStatus(st); + + PollingUrlType pollUrlType = new PollingUrlType(); + pollUrlType + .setValue("http://localhost:9093/queryProcessor/checkStatus"); + rsType.setPollingUrl(pollUrlType); + + // MessageType messageType = dtoFactory.buildMessageType(infoType, + // rsType); + ResponseHeaderType responseHeader = new ResponseHeaderType(); + responseHeader.setInfo(infoType); + responseHeader.setResultStatus(rsType); + ResponseMessageType responseMessageType = new ResponseMessageType(); + responseMessageType.setResponseHeader(responseHeader); + + try { + JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); + edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory(); + jaxbUtil.marshaller(of.createResponse(responseMessageType), + strWriter); + log.debug("i2b2 Response XML " + strWriter.toString()); + } catch (Exception e) { + e.printStackTrace(); + } + return strWriter.toString(); + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/QueryResultBean.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/QueryResultBean.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/QueryResultBean.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/QueryResultBean.java index be246f06..d7455532 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/QueryResultBean.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/QueryResultBean.java @@ -1,132 +1,132 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.ejb; - -import java.util.List; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.util.jaxb.DTOFactory; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; -import edu.harvard.i2b2.crc.dao.setfinder.IQueryResultInstanceDao; -import edu.harvard.i2b2.crc.dao.setfinder.IXmlResultDao; -import edu.harvard.i2b2.crc.datavo.PSMFactory; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.db.QtQueryResultInstance; -import edu.harvard.i2b2.crc.datavo.db.QtXmlResult; -import edu.harvard.i2b2.crc.datavo.setfinder.query.CrcXmlResultResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryResultInstanceType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.XmlResultType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.XmlValueType; - -/** - * Ejb manager class for query operation - * - * - * @ejb.bean description="QueryTool Query Result" - * display-name="QueryTool Query Result" - * jndi-name="ejb.querytool.QueryResult" - * local-jndi-name="ejb.querytool.QueryResultLocal" - * name="querytool.QueryResult" type="Stateless" view-type="both" - * transaction-type="Container" - * - * - * - * @ejb.interface remote-class="edu.harvard.i2b2.crc.ejb.QueryResultRemote" - * - * - */ -public class QueryResultBean { // implements SessionBean { - private static Log log = LogFactory.getLog(QueryResultBean.class); - - /** - * - * - * @param nonObsUser - * @throws I2B2DAOException - * @ejb.interface-method view-type="both" - * @ejb.transaction type="Required" - * - * - */ - public ResultResponseType getResultInstanceFromQueryInstanceId(DataSourceLookup dataSourceLookup,String userId, String queryInstanceId, boolean nonObsUser) throws I2B2DAOException { - SetFinderDAOFactory sfDaoFactory = this.getSetFinderDaoFactory(dataSourceLookup.getDomainId(), dataSourceLookup.getProjectPath(), dataSourceLookup.getOwnerId()); - IQueryResultInstanceDao patientSetResultDao = sfDaoFactory.getPatientSetResultDAO(); - log.debug("got resultinstancesdao" + patientSetResultDao.toString()); - List queryResultInstanceList = patientSetResultDao.getResultInstanceList( queryInstanceId); - log.debug("got QtQueryResultInstance" + queryResultInstanceList.size()); - ResultResponseType resultResponseType = new ResultResponseType(); - DTOFactory dtoFactory = new DTOFactory(); - for(QtQueryResultInstance resultInstance: queryResultInstanceList) { - if (nonObsUser) - resultInstance.setSetSize(resultInstance.getRealSetSize()); - QueryResultInstanceType queryResultInstanceType = PSMFactory.buildQueryResultInstanceType(resultInstance); - //System.out.println("RESULT INSTANCE " + resultInstance.getResultInstanceId() ); - resultResponseType.getQueryResultInstance().add(queryResultInstanceType); - } - //System.out.print("SIZE OF RESULT INSTANCE "+ resultResponseType.getQueryResultInstance().size()); - return resultResponseType; - } - - /** - * - * - * @throws I2B2DAOException - * @ejb.interface-method view-type="both" - * @ejb.transaction type="Required" - * - */ - public CrcXmlResultResponseType getXmlResultFromResultInstanceId(DataSourceLookup dataSourceLookup,String queryResultInstanceId) throws I2B2DAOException { - SetFinderDAOFactory sfDaoFactory = this.getSetFinderDaoFactory(dataSourceLookup.getDomainId(), dataSourceLookup.getProjectPath(), dataSourceLookup.getOwnerId()); - IXmlResultDao xmlResultDao = sfDaoFactory.getXmlResultDao(); - QtXmlResult xmlResult = xmlResultDao.getXmlResultByResultInstanceId(queryResultInstanceId); - CrcXmlResultResponseType resultResponseType = new CrcXmlResultResponseType(); - - IQueryResultInstanceDao queryResultInstanceDao = sfDaoFactory.getPatientSetResultDAO(); - QtQueryResultInstance resultInstance = queryResultInstanceDao.getResultInstanceById(queryResultInstanceId); - QueryResultInstanceType resultInstanceType = new QueryResultInstanceType(); - if (resultInstance != null) { - resultInstanceType = PSMFactory.buildQueryResultInstanceType(resultInstance); - } - resultResponseType.setQueryResultInstance(resultInstanceType); - if (xmlResult !=null) { - XmlResultType xmlResultType = new XmlResultType(); - xmlResultType.setXmlResultId(xmlResult.getXmlResultId()); - - String xmlValue = xmlResult.getXmlValue(); - if (xmlValue != null) { - XmlValueType xmlValueType = new XmlValueType(); - xmlValueType.getContent().add(xmlValue); - xmlResultType.setXmlValue(xmlValueType); - } - - xmlResultType.setResultInstanceId(xmlResult.getQtQueryResultInstance().getResultInstanceId()); - resultResponseType.setCrcXmlResult(xmlResultType); - } - return resultResponseType; - } - - private SetFinderDAOFactory getSetFinderDaoFactory(String domainId,String projectPath,String ownerId) throws I2B2DAOException { - DAOFactoryHelper helper = new DAOFactoryHelper(domainId,projectPath,ownerId); - SetFinderDAOFactory sfDaoFactory = helper.getDAOFactory().getSetFinderDAOFactory(); - return sfDaoFactory; - } - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.ejb; + +import java.util.List; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.util.jaxb.DTOFactory; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; +import edu.harvard.i2b2.crc.dao.setfinder.IQueryResultInstanceDao; +import edu.harvard.i2b2.crc.dao.setfinder.IXmlResultDao; +import edu.harvard.i2b2.crc.datavo.PSMFactory; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.db.QtQueryResultInstance; +import edu.harvard.i2b2.crc.datavo.db.QtXmlResult; +import edu.harvard.i2b2.crc.datavo.setfinder.query.CrcXmlResultResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryResultInstanceType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.XmlResultType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.XmlValueType; + +/** + * Ejb manager class for query operation + * + * + * @ejb.bean description="QueryTool Query Result" + * display-name="QueryTool Query Result" + * jndi-name="ejb.querytool.QueryResult" + * local-jndi-name="ejb.querytool.QueryResultLocal" + * name="querytool.QueryResult" type="Stateless" view-type="both" + * transaction-type="Container" + * + * + * + * @ejb.interface remote-class="edu.harvard.i2b2.crc.ejb.QueryResultRemote" + * + * + */ +public class QueryResultBean { // implements SessionBean { + private static Log log = LogFactory.getLog(QueryResultBean.class); + + /** + * + * + * @param nonObsUser + * @throws I2B2DAOException + * @ejb.interface-method view-type="both" + * @ejb.transaction type="Required" + * + * + */ + public ResultResponseType getResultInstanceFromQueryInstanceId(DataSourceLookup dataSourceLookup,String userId, String queryInstanceId, boolean nonObsUser) throws I2B2DAOException { + SetFinderDAOFactory sfDaoFactory = this.getSetFinderDaoFactory(dataSourceLookup.getDomainId(), dataSourceLookup.getProjectPath(), dataSourceLookup.getOwnerId()); + IQueryResultInstanceDao patientSetResultDao = sfDaoFactory.getPatientSetResultDAO(); + log.debug("got resultinstancesdao" + patientSetResultDao.toString()); + List queryResultInstanceList = patientSetResultDao.getResultInstanceList( queryInstanceId); + log.debug("got QtQueryResultInstance" + queryResultInstanceList.size()); + ResultResponseType resultResponseType = new ResultResponseType(); + DTOFactory dtoFactory = new DTOFactory(); + for(QtQueryResultInstance resultInstance: queryResultInstanceList) { + if (nonObsUser) + resultInstance.setSetSize(resultInstance.getRealSetSize()); + QueryResultInstanceType queryResultInstanceType = PSMFactory.buildQueryResultInstanceType(resultInstance); + //System.out.println("RESULT INSTANCE " + resultInstance.getResultInstanceId() ); + resultResponseType.getQueryResultInstance().add(queryResultInstanceType); + } + //System.out.print("SIZE OF RESULT INSTANCE "+ resultResponseType.getQueryResultInstance().size()); + return resultResponseType; + } + + /** + * + * + * @throws I2B2DAOException + * @ejb.interface-method view-type="both" + * @ejb.transaction type="Required" + * + */ + public CrcXmlResultResponseType getXmlResultFromResultInstanceId(DataSourceLookup dataSourceLookup,String queryResultInstanceId) throws I2B2DAOException { + SetFinderDAOFactory sfDaoFactory = this.getSetFinderDaoFactory(dataSourceLookup.getDomainId(), dataSourceLookup.getProjectPath(), dataSourceLookup.getOwnerId()); + IXmlResultDao xmlResultDao = sfDaoFactory.getXmlResultDao(); + QtXmlResult xmlResult = xmlResultDao.getXmlResultByResultInstanceId(queryResultInstanceId); + CrcXmlResultResponseType resultResponseType = new CrcXmlResultResponseType(); + + IQueryResultInstanceDao queryResultInstanceDao = sfDaoFactory.getPatientSetResultDAO(); + QtQueryResultInstance resultInstance = queryResultInstanceDao.getResultInstanceById(queryResultInstanceId); + QueryResultInstanceType resultInstanceType = new QueryResultInstanceType(); + if (resultInstance != null) { + resultInstanceType = PSMFactory.buildQueryResultInstanceType(resultInstance); + } + resultResponseType.setQueryResultInstance(resultInstanceType); + if (xmlResult !=null) { + XmlResultType xmlResultType = new XmlResultType(); + xmlResultType.setXmlResultId(xmlResult.getXmlResultId()); + + String xmlValue = xmlResult.getXmlValue(); + if (xmlValue != null) { + XmlValueType xmlValueType = new XmlValueType(); + xmlValueType.getContent().add(xmlValue); + xmlResultType.setXmlValue(xmlValueType); + } + + xmlResultType.setResultInstanceId(xmlResult.getQtQueryResultInstance().getResultInstanceId()); + resultResponseType.setCrcXmlResult(xmlResultType); + } + return resultResponseType; + } + + private SetFinderDAOFactory getSetFinderDaoFactory(String domainId,String projectPath,String ownerId) throws I2B2DAOException { + DAOFactoryHelper helper = new DAOFactoryHelper(domainId,projectPath,ownerId); + SetFinderDAOFactory sfDaoFactory = helper.getDAOFactory().getSetFinderDAOFactory(); + return sfDaoFactory; + } + + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/QueryRunBean.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/QueryRunBean.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/QueryRunBean.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/QueryRunBean.java index b5823c48..c63bb3be --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/QueryRunBean.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/QueryRunBean.java @@ -1,91 +1,91 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.ejb; - -import java.util.List; - - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; -import edu.harvard.i2b2.crc.dao.setfinder.IQueryInstanceDao; -import edu.harvard.i2b2.crc.datavo.PSMFactory; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.db.QtQueryInstance; -import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterRequestType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryInstanceType; - -/** - * Ejb manager class for query operation - * - * @author rkuttan - * - * @ejb.bean description="QueryTool Query Run" - * display-name="QueryTool Query Run" - * jndi-name="ejb.querytool.QueryRun" - * local-jndi-name="ejb.querytool.QueryRunLocal" - * name="querytool.QueryRun" type="Stateless" view-type="both" - * transaction-type="Container" - * - * - * - * @ejb.interface remote-class="edu.harvard.i2b2.crc.ejb.QueryRunRemote" - * - * - */ -public class QueryRunBean { //implements SessionBean { - // RunQuery - - /** - * - * - * @throws I2B2DAOException - * @ejb.interface-method view-type="both" - * @ejb.transaction type="Required" - * - * - */ - public InstanceResponseType getQueryInstanceFromMasterId( - DataSourceLookup dataSourceLookup, String userId, - MasterRequestType masterRequestType) throws I2B2DAOException { - String queryMasterId = masterRequestType.getQueryMasterId(); - SetFinderDAOFactory sfDaoFactory = this.getSetFinderDaoFactory( - dataSourceLookup.getDomainId(), dataSourceLookup - .getProjectPath(), dataSourceLookup.getOwnerId()); - - IQueryInstanceDao queryInstanceDao = sfDaoFactory.getQueryInstanceDAO(); - List queryInstanceList = queryInstanceDao - .getQueryInstanceByMasterId(queryMasterId); - InstanceResponseType instanceResponseType = new InstanceResponseType(); - - QueryInstanceType qiType = null; - for (QtQueryInstance queryInstance : queryInstanceList) { - qiType = PSMFactory.buildQueryInstanceType(queryInstance); - instanceResponseType.getQueryInstance().add(qiType); - } - return instanceResponseType; - } - - private SetFinderDAOFactory getSetFinderDaoFactory(String domainId, - String projectPath, String ownerId) throws I2B2DAOException { - DAOFactoryHelper helper = new DAOFactoryHelper(domainId, projectPath, - ownerId); - SetFinderDAOFactory sfDaoFactory = helper.getDAOFactory() - .getSetFinderDAOFactory(); - return sfDaoFactory; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.ejb; + +import java.util.List; + + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; +import edu.harvard.i2b2.crc.dao.setfinder.IQueryInstanceDao; +import edu.harvard.i2b2.crc.datavo.PSMFactory; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.db.QtQueryInstance; +import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterRequestType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryInstanceType; + +/** + * Ejb manager class for query operation + * + * @author rkuttan + * + * @ejb.bean description="QueryTool Query Run" + * display-name="QueryTool Query Run" + * jndi-name="ejb.querytool.QueryRun" + * local-jndi-name="ejb.querytool.QueryRunLocal" + * name="querytool.QueryRun" type="Stateless" view-type="both" + * transaction-type="Container" + * + * + * + * @ejb.interface remote-class="edu.harvard.i2b2.crc.ejb.QueryRunRemote" + * + * + */ +public class QueryRunBean { //implements SessionBean { + // RunQuery + + /** + * + * + * @throws I2B2DAOException + * @ejb.interface-method view-type="both" + * @ejb.transaction type="Required" + * + * + */ + public InstanceResponseType getQueryInstanceFromMasterId( + DataSourceLookup dataSourceLookup, String userId, + MasterRequestType masterRequestType) throws I2B2DAOException { + String queryMasterId = masterRequestType.getQueryMasterId(); + SetFinderDAOFactory sfDaoFactory = this.getSetFinderDaoFactory( + dataSourceLookup.getDomainId(), dataSourceLookup + .getProjectPath(), dataSourceLookup.getOwnerId()); + + IQueryInstanceDao queryInstanceDao = sfDaoFactory.getQueryInstanceDAO(); + List queryInstanceList = queryInstanceDao + .getQueryInstanceByMasterId(queryMasterId); + InstanceResponseType instanceResponseType = new InstanceResponseType(); + + QueryInstanceType qiType = null; + for (QtQueryInstance queryInstance : queryInstanceList) { + qiType = PSMFactory.buildQueryInstanceType(queryInstance); + instanceResponseType.getQueryInstance().add(qiType); + } + return instanceResponseType; + } + + private SetFinderDAOFactory getSetFinderDaoFactory(String domainId, + String projectPath, String ownerId) throws I2B2DAOException { + DAOFactoryHelper helper = new DAOFactoryHelper(domainId, projectPath, + ownerId); + SetFinderDAOFactory sfDaoFactory = helper.getDAOFactory() + .getSetFinderDAOFactory(); + return sfDaoFactory; + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/analysis/AnalysisPluginHelper.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/analysis/AnalysisPluginHelper.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/analysis/AnalysisPluginHelper.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/analysis/AnalysisPluginHelper.java index 93808431..2d4e03a5 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/analysis/AnalysisPluginHelper.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/analysis/AnalysisPluginHelper.java @@ -1,47 +1,47 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.ejb.analysis; - -import java.util.HashMap; -import java.util.Map; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; -import edu.harvard.i2b2.crc.dao.setfinder.IAnalysisPluginDao; -import edu.harvard.i2b2.crc.datavo.db.QtAnalysisPlugin; - -public class AnalysisPluginHelper { - - private SetFinderDAOFactory sfDAOFactory; - public static final String COMMAND_LINE = "COMMAND_LINE"; - public static final String WORKING_FOLDER = "WORKING_FOLDER"; - - public AnalysisPluginHelper(SetFinderDAOFactory sfDAOFactory) { - this.sfDAOFactory = sfDAOFactory; - } - - public Map getExecInfo(String analysisName, String version, String projectId) { - Map execInfoMap = new HashMap(); - // lookup by name and return - IAnalysisPluginDao analysisPluginDao = sfDAOFactory - .getAnalysisPluginDao(); - try { - QtAnalysisPlugin analysisPlugin = analysisPluginDao - .lookupAnalysisPluginByNameVersionProject(analysisName, - version, projectId); - execInfoMap.put(COMMAND_LINE, analysisPlugin.getCommandLine()); - execInfoMap.put(WORKING_FOLDER, analysisPlugin.getWorkingFolder()); - } catch (I2B2DAOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - // return command line and working directory - return execInfoMap; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.ejb.analysis; + +import java.util.HashMap; +import java.util.Map; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; +import edu.harvard.i2b2.crc.dao.setfinder.IAnalysisPluginDao; +import edu.harvard.i2b2.crc.datavo.db.QtAnalysisPlugin; + +public class AnalysisPluginHelper { + + private SetFinderDAOFactory sfDAOFactory; + public static final String COMMAND_LINE = "COMMAND_LINE"; + public static final String WORKING_FOLDER = "WORKING_FOLDER"; + + public AnalysisPluginHelper(SetFinderDAOFactory sfDAOFactory) { + this.sfDAOFactory = sfDAOFactory; + } + + public Map getExecInfo(String analysisName, String version, String projectId) { + Map execInfoMap = new HashMap(); + // lookup by name and return + IAnalysisPluginDao analysisPluginDao = sfDAOFactory + .getAnalysisPluginDao(); + try { + QtAnalysisPlugin analysisPlugin = analysisPluginDao + .lookupAnalysisPluginByNameVersionProject(analysisName, + version, projectId); + execInfoMap.put(COMMAND_LINE, analysisPlugin.getCommandLine()); + execInfoMap.put(WORKING_FOLDER, analysisPlugin.getWorkingFolder()); + } catch (I2B2DAOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + // return command line and working directory + return execInfoMap; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/analysis/AnalysisPluginInfo.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/analysis/AnalysisPluginInfo.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/analysis/AnalysisPluginInfo.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/analysis/AnalysisPluginInfo.java index 6567b22d..af6d3884 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/analysis/AnalysisPluginInfo.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/analysis/AnalysisPluginInfo.java @@ -1,103 +1,103 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.ejb.analysis; - -import java.util.List; - - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.DTOFactory; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; -import edu.harvard.i2b2.crc.dao.setfinder.IAnalysisPluginDao; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.db.QtAnalysisPlugin; -import edu.harvard.i2b2.crc.datavo.setfinder.query.AnalysisParameterXmlType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.AnalysisPluginMetadataRequestType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.AnalysisPluginMetadataResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.AnalysisPluginMetadataTypeType; - -/** - * Bean class to return analysis plugin metadata info - */ -//@Stateless -public class AnalysisPluginInfo implements AnalysisPluginInfoLocal { - - /** - * Return analysis plugin metadata by plugin name and project - */ - @Override - public AnalysisPluginMetadataResponseType getAnalysisPluginMetadata( - DataSourceLookup dataSourceLookup, - AnalysisPluginMetadataRequestType apMetadataRequestType, - String projectId) throws I2B2Exception { - SetFinderDAOFactory sfDaoFactory = getSetFinderDaoFactory( - dataSourceLookup.getDomainId(), dataSourceLookup - .getProjectPath(), dataSourceLookup.getOwnerId()); - IAnalysisPluginDao analysisPluginDao = sfDaoFactory - .getAnalysisPluginDao(); - String analysisName = apMetadataRequestType.getPluginName(); - - List analysisPluginList = analysisPluginDao - .getAnalysisPluginMetadata(analysisName, projectId); - - return buildAnalysisPluginMetadataResponse(analysisPluginList); - } - - // Function to build analysis plugin metadata response type - private AnalysisPluginMetadataResponseType buildAnalysisPluginMetadataResponse( - List analysisPluginList) { - DTOFactory dtoFactory = new DTOFactory(); - AnalysisPluginMetadataResponseType apMetadataResponseType = new AnalysisPluginMetadataResponseType(); - for (QtAnalysisPlugin analysisPlugin : analysisPluginList) { - AnalysisPluginMetadataTypeType apmType = new AnalysisPluginMetadataTypeType(); - apmType.setPluginId(analysisPlugin.getPluginId()); - apmType.setPluginName(analysisPlugin.getPluginName()); - apmType.setDescription(analysisPlugin.getDescription()); - apmType.setStatusCd(analysisPlugin.getStatusId()); - AnalysisParameterXmlType parameterXmlType = new AnalysisParameterXmlType(); - parameterXmlType.getContent() - .add(analysisPlugin.getParameterInfo()); - apmType.setParameterInfo(parameterXmlType); - AnalysisParameterXmlType parameterXsdType = new AnalysisParameterXmlType(); - parameterXmlType.getContent().add( - analysisPlugin.getParameterInfoXsd()); - apmType.setParameterInfoXsd(parameterXsdType); - if (analysisPlugin.getUpdateDate() != null) { - apmType.setUpdateDate(dtoFactory - .getXMLGregorianCalendar(analysisPlugin.getUpdateDate() - .getTime())); - } - - apmType.setVersionCd(analysisPlugin.getVersion()); - if (analysisPlugin.getCreateDate() != null) { - apmType.setCreateDate(dtoFactory - .getXMLGregorianCalendar(analysisPlugin.getCreateDate() - .getTime())); - } - apmType.setUserId(analysisPlugin.getUserId()); - apmType.setCommandoptionCd(analysisPlugin.getCommandOptionCd()); - apmType.setCommandLine(analysisPlugin.getCommandLine()); - apmType.setWorkingFolder(analysisPlugin.getWorkingFolder()); - apmType.setGroupId(analysisPlugin.getGroupId()); - apMetadataResponseType.getAnalysisPluginMetadataType().add(apmType); - } - return apMetadataResponseType; - } - - private SetFinderDAOFactory getSetFinderDaoFactory(String domainId, - String projectPath, String ownerId) throws I2B2DAOException { - DAOFactoryHelper helper = new DAOFactoryHelper(domainId, projectPath, - ownerId); - SetFinderDAOFactory sfDaoFactory = helper.getDAOFactory() - .getSetFinderDAOFactory(); - return sfDaoFactory; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.ejb.analysis; + +import java.util.List; + + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.DTOFactory; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; +import edu.harvard.i2b2.crc.dao.setfinder.IAnalysisPluginDao; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.db.QtAnalysisPlugin; +import edu.harvard.i2b2.crc.datavo.setfinder.query.AnalysisParameterXmlType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.AnalysisPluginMetadataRequestType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.AnalysisPluginMetadataResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.AnalysisPluginMetadataTypeType; + +/** + * Bean class to return analysis plugin metadata info + */ +//@Stateless +public class AnalysisPluginInfo implements AnalysisPluginInfoLocal { + + /** + * Return analysis plugin metadata by plugin name and project + */ + @Override + public AnalysisPluginMetadataResponseType getAnalysisPluginMetadata( + DataSourceLookup dataSourceLookup, + AnalysisPluginMetadataRequestType apMetadataRequestType, + String projectId) throws I2B2Exception { + SetFinderDAOFactory sfDaoFactory = getSetFinderDaoFactory( + dataSourceLookup.getDomainId(), dataSourceLookup + .getProjectPath(), dataSourceLookup.getOwnerId()); + IAnalysisPluginDao analysisPluginDao = sfDaoFactory + .getAnalysisPluginDao(); + String analysisName = apMetadataRequestType.getPluginName(); + + List analysisPluginList = analysisPluginDao + .getAnalysisPluginMetadata(analysisName, projectId); + + return buildAnalysisPluginMetadataResponse(analysisPluginList); + } + + // Function to build analysis plugin metadata response type + private AnalysisPluginMetadataResponseType buildAnalysisPluginMetadataResponse( + List analysisPluginList) { + DTOFactory dtoFactory = new DTOFactory(); + AnalysisPluginMetadataResponseType apMetadataResponseType = new AnalysisPluginMetadataResponseType(); + for (QtAnalysisPlugin analysisPlugin : analysisPluginList) { + AnalysisPluginMetadataTypeType apmType = new AnalysisPluginMetadataTypeType(); + apmType.setPluginId(analysisPlugin.getPluginId()); + apmType.setPluginName(analysisPlugin.getPluginName()); + apmType.setDescription(analysisPlugin.getDescription()); + apmType.setStatusCd(analysisPlugin.getStatusId()); + AnalysisParameterXmlType parameterXmlType = new AnalysisParameterXmlType(); + parameterXmlType.getContent() + .add(analysisPlugin.getParameterInfo()); + apmType.setParameterInfo(parameterXmlType); + AnalysisParameterXmlType parameterXsdType = new AnalysisParameterXmlType(); + parameterXmlType.getContent().add( + analysisPlugin.getParameterInfoXsd()); + apmType.setParameterInfoXsd(parameterXsdType); + if (analysisPlugin.getUpdateDate() != null) { + apmType.setUpdateDate(dtoFactory + .getXMLGregorianCalendar(analysisPlugin.getUpdateDate() + .getTime())); + } + + apmType.setVersionCd(analysisPlugin.getVersion()); + if (analysisPlugin.getCreateDate() != null) { + apmType.setCreateDate(dtoFactory + .getXMLGregorianCalendar(analysisPlugin.getCreateDate() + .getTime())); + } + apmType.setUserId(analysisPlugin.getUserId()); + apmType.setCommandoptionCd(analysisPlugin.getCommandOptionCd()); + apmType.setCommandLine(analysisPlugin.getCommandLine()); + apmType.setWorkingFolder(analysisPlugin.getWorkingFolder()); + apmType.setGroupId(analysisPlugin.getGroupId()); + apMetadataResponseType.getAnalysisPluginMetadataType().add(apmType); + } + return apMetadataResponseType; + } + + private SetFinderDAOFactory getSetFinderDaoFactory(String domainId, + String projectPath, String ownerId) throws I2B2DAOException { + DAOFactoryHelper helper = new DAOFactoryHelper(domainId, projectPath, + ownerId); + SetFinderDAOFactory sfDaoFactory = helper.getDAOFactory() + .getSetFinderDAOFactory(); + return sfDaoFactory; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/analysis/AnalysisPluginInfoLocal.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/analysis/AnalysisPluginInfoLocal.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/analysis/AnalysisPluginInfoLocal.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/analysis/AnalysisPluginInfoLocal.java index 30f7025e..f19fcb0b --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/analysis/AnalysisPluginInfoLocal.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/analysis/AnalysisPluginInfoLocal.java @@ -1,28 +1,28 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.ejb.analysis; - - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.setfinder.query.AnalysisPluginMetadataRequestType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.AnalysisPluginMetadataResponseType; - -//@Local -public interface AnalysisPluginInfoLocal { - - /** - * Return analysis plugin metadata by plugin name and project - */ - public AnalysisPluginMetadataResponseType getAnalysisPluginMetadata( - DataSourceLookup dataSourceLookup, - AnalysisPluginMetadataRequestType apMetadataRequestType, - String projectId) throws I2B2Exception; - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.ejb.analysis; + + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.setfinder.query.AnalysisPluginMetadataRequestType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.AnalysisPluginMetadataResponseType; + +//@Local +public interface AnalysisPluginInfoLocal { + + /** + * Return analysis plugin metadata by plugin name and project + */ + public AnalysisPluginMetadataResponseType getAnalysisPluginMetadata( + DataSourceLookup dataSourceLookup, + AnalysisPluginMetadataRequestType apMetadataRequestType, + String projectId) throws I2B2Exception; + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/analysis/AnalysisStatusType.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/analysis/AnalysisStatusType.java old mode 100755 new mode 100644 similarity index 98% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/analysis/AnalysisStatusType.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/analysis/AnalysisStatusType.java index c9159761..7cb580c1 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/analysis/AnalysisStatusType.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/analysis/AnalysisStatusType.java @@ -1,16 +1,16 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.ejb.analysis; - -public class AnalysisStatusType { - public final static String ERROR_STATUS = "ERROR"; - public final static String TIMEOUT_STATUS = "TIMEOUT"; - public final static String COMPLETED_STATUS = "COMPLETED"; - public final static String QUEUED_STATUS = "QUEUED"; -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.ejb.analysis; + +public class AnalysisStatusType { + public final static String ERROR_STATUS = "ERROR"; + public final static String TIMEOUT_STATUS = "TIMEOUT"; + public final static String COMPLETED_STATUS = "COMPLETED"; + public final static String QUEUED_STATUS = "QUEUED"; +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/analysis/CronEjbLocal.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/analysis/CronEjbLocal.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/analysis/CronEjbLocal.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/analysis/CronEjbLocal.java index 72a26525..0d9dffb1 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/analysis/CronEjbLocal.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/analysis/CronEjbLocal.java @@ -1,15 +1,15 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.ejb.analysis; - - -public interface CronEjbLocal { - public void start(); - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.ejb.analysis; + + +public interface CronEjbLocal { + public void start(); + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/analysis/HiveDAOFactory.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/analysis/HiveDAOFactory.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/analysis/HiveDAOFactory.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/analysis/HiveDAOFactory.java index ad3beb93..e56f8a8b --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/analysis/HiveDAOFactory.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/analysis/HiveDAOFactory.java @@ -1,13 +1,13 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.ejb.analysis; - -public class HiveDAOFactory { - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.ejb.analysis; + +public class HiveDAOFactory { + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/analysis/LargeCronEjbLocal.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/analysis/LargeCronEjbLocal.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/analysis/LargeCronEjbLocal.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/analysis/LargeCronEjbLocal.java index abdd42b8..1ccb043e --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/analysis/LargeCronEjbLocal.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/analysis/LargeCronEjbLocal.java @@ -1,14 +1,14 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.ejb.analysis; - -public interface LargeCronEjbLocal { - public void start(); - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.ejb.analysis; + +public interface LargeCronEjbLocal { + public void start(); + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/analysis/QueryExecutor.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/analysis/QueryExecutor.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/analysis/QueryExecutor.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/analysis/QueryExecutor.java index 6324bc72..be6b4306 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/analysis/QueryExecutor.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/analysis/QueryExecutor.java @@ -1,60 +1,60 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.ejb.analysis; - -import java.util.Map; - -import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; -import edu.harvard.i2b2.crc.datavo.setfinder.query.AnalysisDefinitionType; -import edu.harvard.i2b2.crc.exec.ExecException; -import edu.harvard.i2b2.crc.exec.ExecUtil; - -public class QueryExecutor { - - private String queryInstanceId = null; - private Map paramMap = null; - private SetFinderDAOFactory sfDAOFactory = null; - - public QueryExecutor(SetFinderDAOFactory sfDAOFactory, - String queryInstanceId) { - this.sfDAOFactory = sfDAOFactory; - this.queryInstanceId = queryInstanceId; - } - - public void execute(AnalysisDefinitionType analysisDefinition, - String projectId, long timeout) throws ExecException { - // from analysis definition type get the command line, type of program - // etc - // pass the command line , input parameter to exec util - AnalysisPluginHelper analysisPlugin = new AnalysisPluginHelper( - sfDAOFactory); - String analysisName = analysisDefinition.getAnalysisPluginName(); - String version = analysisDefinition.getVersion(); - - Map execInfoMap = analysisPlugin.getExecInfo(analysisName, version, - projectId); - - ExecUtil execUtil = new ExecUtil(); - - String line = (String) execInfoMap - .get(AnalysisPluginHelper.COMMAND_LINE); - String workingFolder = (String) execInfoMap - .get(AnalysisPluginHelper.WORKING_FOLDER); - - execUtil.execute(workingFolder, line, timeout); - - // get the exec result based on the output list - // update the result instance and query instance - } - - // public void getQueryInstanceStatus(); - - // public void getQueryResultInstanceStatus(); - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.ejb.analysis; + +import java.util.Map; + +import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; +import edu.harvard.i2b2.crc.datavo.setfinder.query.AnalysisDefinitionType; +import edu.harvard.i2b2.crc.exec.ExecException; +import edu.harvard.i2b2.crc.exec.ExecUtil; + +public class QueryExecutor { + + private String queryInstanceId = null; + private Map paramMap = null; + private SetFinderDAOFactory sfDAOFactory = null; + + public QueryExecutor(SetFinderDAOFactory sfDAOFactory, + String queryInstanceId) { + this.sfDAOFactory = sfDAOFactory; + this.queryInstanceId = queryInstanceId; + } + + public void execute(AnalysisDefinitionType analysisDefinition, + String projectId, long timeout) throws ExecException { + // from analysis definition type get the command line, type of program + // etc + // pass the command line , input parameter to exec util + AnalysisPluginHelper analysisPlugin = new AnalysisPluginHelper( + sfDAOFactory); + String analysisName = analysisDefinition.getAnalysisPluginName(); + String version = analysisDefinition.getVersion(); + + Map execInfoMap = analysisPlugin.getExecInfo(analysisName, version, + projectId); + + ExecUtil execUtil = new ExecUtil(); + + String line = (String) execInfoMap + .get(AnalysisPluginHelper.COMMAND_LINE); + String workingFolder = (String) execInfoMap + .get(AnalysisPluginHelper.WORKING_FOLDER); + + execUtil.execute(workingFolder, line, timeout); + + // get the exec result based on the output list + // update the result instance and query instance + } + + // public void getQueryInstanceStatus(); + + // public void getQueryResultInstanceStatus(); + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/analysis/QueryInstance.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/analysis/QueryInstance.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/analysis/QueryInstance.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/analysis/QueryInstance.java index 3b9fc3ca..724587e5 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/analysis/QueryInstance.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/analysis/QueryInstance.java @@ -1,132 +1,132 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.ejb.analysis; - -import java.util.Date; -import java.util.List; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; -import edu.harvard.i2b2.crc.dao.setfinder.IQueryInstanceDao; -import edu.harvard.i2b2.crc.dao.setfinder.IQueryResultInstanceDao; -import edu.harvard.i2b2.crc.datavo.db.QtQueryInstance; -import edu.harvard.i2b2.crc.datavo.db.QtQueryResultInstance; -import edu.harvard.i2b2.crc.datavo.db.QtQueryStatusType; -import edu.harvard.i2b2.crc.datavo.db.StatusEnum; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultOutputOptionListType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultOutputOptionType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.UserType; -import edu.harvard.i2b2.crc.ejb.QueryInfoBean; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - -public class QueryInstance { - - private static Log log = LogFactory.getLog(QueryInstance.class); - - protected static Log logesapi = LogFactory.getLog(QueryInstance.class); - - SetFinderDAOFactory sfDAOFactory = null; - - public QueryInstance(SetFinderDAOFactory sfDAOFactory) { - this.sfDAOFactory = sfDAOFactory; - } - - public String saveInstanceAndResultInstance(String queryMasterId, - UserType userType, String queueName, - ResultOutputOptionListType resultOptionList) - throws I2B2DAOException { - // create query instance - IQueryInstanceDao queryInstanceDao = sfDAOFactory.getQueryInstanceDAO(); - // UserType userType = getUserTypeFromSetfinderHeader(xmlRequest); - String userId = userType.getLogin(); - String groupId = userType.getGroup(); - String queryInstanceId = queryInstanceDao.createQueryInstance( - queryMasterId, userId, groupId, queueName, StatusEnum.QUEUED - .ordinal()); - log.debug("New Query instance id " + queryInstanceId); - - IQueryResultInstanceDao patientSetResultDao = sfDAOFactory - .getPatientSetResultDAO(); - String patientSetId = null; - if (resultOptionList != null - && resultOptionList.getResultOutput() != null - && resultOptionList.getResultOutput().size() > 0) { - - for (ResultOutputOptionType resultOption : resultOptionList - .getResultOutput()) { - log.debug("Patient result ID [" + resultOption.getName() - + "] for query instance= " + queryInstanceId); - patientSetId = patientSetResultDao.createPatientSet( - queryInstanceId, resultOption.getName()); - logesapi.debug("Patient Set ID [" + patientSetId - + "] for query instance= " + queryInstanceId); - } - } else { - QueryProcessorUtil qp = QueryProcessorUtil.getInstance(); - String defaultResultType = "PATIENTSET"; - patientSetId = patientSetResultDao.createPatientSet( - queryInstanceId, defaultResultType); - logesapi.debug("Patient Set ID [" + patientSetId - + "] for query instance= " + queryInstanceId); - } - return queryInstanceId; - } - - public void updateInstanceStatus(String queryInstanceId, String statusType, - String message) throws I2B2DAOException { - // get query instance - // update the status - IQueryInstanceDao queryInstanceDao = sfDAOFactory.getQueryInstanceDAO(); - QtQueryInstance qtQueryInstance = queryInstanceDao - .getQueryInstanceByInstanceId(queryInstanceId); - qtQueryInstance.setEndDate(new Date(System.currentTimeMillis())); - qtQueryInstance.setMessage(message); - QtQueryStatusType qtQueryStatusType = new QtQueryStatusType(); - qtQueryStatusType.setStatusTypeId(StatusEnum.valueOf(statusType) - .ordinal()); - qtQueryInstance.setQtQueryStatusType(qtQueryStatusType); - queryInstanceDao.update(qtQueryInstance, true); - - } - - public void updateResultInstanceStatusByInstanceId(String queryInstanceId, - String statusType, int setSize, String statusMsg) { - if (statusMsg == null) { - statusMsg = ""; - } - IQueryResultInstanceDao patientSetResultDao = sfDAOFactory - .getPatientSetResultDAO(); - List resultInstanceList = patientSetResultDao - .getResultInstanceList(queryInstanceId); - - // iterate the list and update the status - for (QtQueryResultInstance singleResultInstance : resultInstanceList) { - updateResultInstanceStatus(singleResultInstance - .getResultInstanceId(), StatusEnum.valueOf(statusType) - .ordinal(), statusMsg, setSize); - } - } - - public void updateResultInstanceStatus(String resultInstanceId, - int statusTypeId, String statusMsg, int setSize) { - // get query result instance - // update result instance status - IQueryResultInstanceDao patientSetResultDao = sfDAOFactory - .getPatientSetResultDAO(); - patientSetResultDao.updatePatientSet(resultInstanceId, statusTypeId, - statusMsg, setSize, 0, ""); - - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.ejb.analysis; + +import java.util.Date; +import java.util.List; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; +import edu.harvard.i2b2.crc.dao.setfinder.IQueryInstanceDao; +import edu.harvard.i2b2.crc.dao.setfinder.IQueryResultInstanceDao; +import edu.harvard.i2b2.crc.datavo.db.QtQueryInstance; +import edu.harvard.i2b2.crc.datavo.db.QtQueryResultInstance; +import edu.harvard.i2b2.crc.datavo.db.QtQueryStatusType; +import edu.harvard.i2b2.crc.datavo.db.StatusEnum; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultOutputOptionListType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultOutputOptionType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.UserType; +import edu.harvard.i2b2.crc.ejb.QueryInfoBean; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + +public class QueryInstance { + + private static Log log = LogFactory.getLog(QueryInstance.class); + + protected static Log logesapi = LogFactory.getLog(QueryInstance.class); + + SetFinderDAOFactory sfDAOFactory = null; + + public QueryInstance(SetFinderDAOFactory sfDAOFactory) { + this.sfDAOFactory = sfDAOFactory; + } + + public String saveInstanceAndResultInstance(String queryMasterId, + UserType userType, String queueName, + ResultOutputOptionListType resultOptionList) + throws I2B2DAOException { + // create query instance + IQueryInstanceDao queryInstanceDao = sfDAOFactory.getQueryInstanceDAO(); + // UserType userType = getUserTypeFromSetfinderHeader(xmlRequest); + String userId = userType.getLogin(); + String groupId = userType.getGroup(); + String queryInstanceId = queryInstanceDao.createQueryInstance( + queryMasterId, userId, groupId, queueName, StatusEnum.QUEUED + .ordinal()); + log.debug("New Query instance id " + queryInstanceId); + + IQueryResultInstanceDao patientSetResultDao = sfDAOFactory + .getPatientSetResultDAO(); + String patientSetId = null; + if (resultOptionList != null + && resultOptionList.getResultOutput() != null + && resultOptionList.getResultOutput().size() > 0) { + + for (ResultOutputOptionType resultOption : resultOptionList + .getResultOutput()) { + log.debug("Patient result ID [" + resultOption.getName() + + "] for query instance= " + queryInstanceId); + patientSetId = patientSetResultDao.createPatientSet( + queryInstanceId, resultOption.getName()); + logesapi.debug("Patient Set ID [" + patientSetId + + "] for query instance= " + queryInstanceId); + } + } else { + QueryProcessorUtil qp = QueryProcessorUtil.getInstance(); + String defaultResultType = "PATIENTSET"; + patientSetId = patientSetResultDao.createPatientSet( + queryInstanceId, defaultResultType); + logesapi.debug("Patient Set ID [" + patientSetId + + "] for query instance= " + queryInstanceId); + } + return queryInstanceId; + } + + public void updateInstanceStatus(String queryInstanceId, String statusType, + String message) throws I2B2DAOException { + // get query instance + // update the status + IQueryInstanceDao queryInstanceDao = sfDAOFactory.getQueryInstanceDAO(); + QtQueryInstance qtQueryInstance = queryInstanceDao + .getQueryInstanceByInstanceId(queryInstanceId); + qtQueryInstance.setEndDate(new Date(System.currentTimeMillis())); + qtQueryInstance.setMessage(message); + QtQueryStatusType qtQueryStatusType = new QtQueryStatusType(); + qtQueryStatusType.setStatusTypeId(StatusEnum.valueOf(statusType) + .ordinal()); + qtQueryInstance.setQtQueryStatusType(qtQueryStatusType); + queryInstanceDao.update(qtQueryInstance, true); + + } + + public void updateResultInstanceStatusByInstanceId(String queryInstanceId, + String statusType, int setSize, String statusMsg) { + if (statusMsg == null) { + statusMsg = ""; + } + IQueryResultInstanceDao patientSetResultDao = sfDAOFactory + .getPatientSetResultDAO(); + List resultInstanceList = patientSetResultDao + .getResultInstanceList(queryInstanceId); + + // iterate the list and update the status + for (QtQueryResultInstance singleResultInstance : resultInstanceList) { + updateResultInstanceStatus(singleResultInstance + .getResultInstanceId(), StatusEnum.valueOf(statusType) + .ordinal(), statusMsg, setSize); + } + } + + public void updateResultInstanceStatus(String resultInstanceId, + int statusTypeId, String statusMsg, int setSize) { + // get query result instance + // update result instance status + IQueryResultInstanceDao patientSetResultDao = sfDAOFactory + .getPatientSetResultDAO(); + patientSetResultDao.updatePatientSet(resultInstanceId, statusTypeId, + statusMsg, setSize, 0, ""); + + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/analysis/QueryMaster.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/analysis/QueryMaster.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/analysis/QueryMaster.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/analysis/QueryMaster.java index ef0ec4bd..84b4b737 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/analysis/QueryMaster.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/analysis/QueryMaster.java @@ -1,139 +1,139 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.ejb.analysis; - -import java.util.Date; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; -import edu.harvard.i2b2.crc.dao.setfinder.IAnalysisPluginDao; -import edu.harvard.i2b2.crc.dao.setfinder.IQueryMasterDao; -import edu.harvard.i2b2.crc.datavo.db.QtAnalysisPlugin; -import edu.harvard.i2b2.crc.datavo.db.QtQueryMaster; -import edu.harvard.i2b2.crc.datavo.setfinder.query.AnalysisDefinitionType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.UserType; -import edu.harvard.i2b2.crc.ejb.QueryManagerBean; -import edu.harvard.i2b2.crc.util.I2B2RequestMessageHelper; - -public class QueryMaster { - - private static Log log = LogFactory.getLog(QueryMaster.class); - protected static Log logesapi = LogFactory.getLog(QueryMaster.class); - - private SetFinderDAOFactory sfDAOFactory = null; - - public QueryMaster(SetFinderDAOFactory sfDAOFactory) { - this.sfDAOFactory = sfDAOFactory; - } - - public QtAnalysisPlugin lookupAnalysisPlugin(String analysisName, - String version, String projectId) throws I2B2Exception { - logesapi.debug("looking for: " + analysisName +":" + version + ":" + projectId); - IAnalysisPluginDao analysisPluginDao = sfDAOFactory - .getAnalysisPluginDao(); - log.debug("getting QtAnalysisPlugin"); - QtAnalysisPlugin analysisPlugin = analysisPluginDao - .lookupAnalysisPluginByNameVersionProject(analysisName, - version, projectId); - return analysisPlugin; - } - - public String saveQuery(String requestXml, String generatedSql, - QtAnalysisPlugin analysisPlugin) throws I2B2Exception { - IQueryMasterDao queryMasterDao = sfDAOFactory.getQueryMasterDAO(); - - QtQueryMaster queryMaster = new QtQueryMaster(); - I2B2RequestMessageHelper msgHelper = new I2B2RequestMessageHelper( - requestXml); - UserType userType = msgHelper.getUserType(); - String userId = userType.getLogin(); - String groupId = msgHelper.getProjectId(); - - queryMaster.setUserId(userId); - - AnalysisDefinitionType anaDefType; - String queryMasterId = null; - try { - anaDefType = msgHelper.getAnalysisDefinition(); - - String analysisDefinitionXml = I2B2RequestMessageHelper - .getAnalysisDefinitionXml(anaDefType); - queryMaster.setRequestXml(analysisDefinitionXml); - queryMaster.setGroupId(groupId); - queryMaster.setCreateDate(new Date(System.currentTimeMillis())); - queryMaster.setDeleteFlag(QtQueryMaster.DELETE_OFF_FLAG); - queryMaster.setGeneratedSql(null); - queryMaster.setName(anaDefType.getAnalysisPluginName()); - queryMaster.setPluginId(analysisPlugin.getPluginId()); - queryMaster.setMasterTypeCd(analysisPlugin.getPluginName()); - - queryMasterId = queryMasterDao.createQueryMaster(queryMaster, - requestXml, null); - } catch (JAXBUtilException e) { - - throw new I2B2Exception("Failed to save query definition: [" - + e.getMessage() + "]", e); - } - - return queryMasterId; - } - - public AnalysisDefinitionType getAnalysisDefinitionByMasterId( - String masterId) throws JAXBUtilException { - AnalysisDefinitionType analysisDefType = null; - IQueryMasterDao queryMasterDao = sfDAOFactory.getQueryMasterDAO(); - QtQueryMaster queryMaster = queryMasterDao.getQueryDefinition(masterId); - String definitionXml = queryMaster.getRequestXml(); - if (definitionXml == null) { - return analysisDefType; - } - analysisDefType = I2B2RequestMessageHelper - .getAnalysisDefinitionFromXml(definitionXml); - return analysisDefType; - } - - public QtQueryMaster getQueryMaster(String requestXml) throws Exception { - QtQueryMaster queryMaster = new QtQueryMaster(); - I2B2RequestMessageHelper msgHelper = new I2B2RequestMessageHelper( - requestXml); - UserType userType = msgHelper.getUserType(); - String userId = userType.getLogin(); - String groupId = userType.getGroup(); - - queryMaster.setUserId(userId); - - AnalysisDefinitionType anaDefType; - try { - anaDefType = msgHelper.getAnalysisDefinition(); - - String analysisDefinitionXml = I2B2RequestMessageHelper - .getAnalysisDefinitionXml(anaDefType); - queryMaster.setRequestXml(analysisDefinitionXml); - queryMaster.setGroupId(groupId); - queryMaster.setCreateDate(new Date(System.currentTimeMillis())); - queryMaster.setDeleteFlag(QtQueryMaster.DELETE_OFF_FLAG); - queryMaster.setGeneratedSql("generatedSql"); - queryMaster.setName(anaDefType.getAnalysisPluginName()); - queryMaster.setI2b2RequestXml(requestXml); - - } catch (JAXBUtilException e) { - - throw new I2B2Exception("Failed to save query definition: [" - + e.getMessage() + "]", e); - } - return queryMaster; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.ejb.analysis; + +import java.util.Date; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; +import edu.harvard.i2b2.crc.dao.setfinder.IAnalysisPluginDao; +import edu.harvard.i2b2.crc.dao.setfinder.IQueryMasterDao; +import edu.harvard.i2b2.crc.datavo.db.QtAnalysisPlugin; +import edu.harvard.i2b2.crc.datavo.db.QtQueryMaster; +import edu.harvard.i2b2.crc.datavo.setfinder.query.AnalysisDefinitionType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.UserType; +import edu.harvard.i2b2.crc.ejb.QueryManagerBean; +import edu.harvard.i2b2.crc.util.I2B2RequestMessageHelper; + +public class QueryMaster { + + private static Log log = LogFactory.getLog(QueryMaster.class); + protected static Log logesapi = LogFactory.getLog(QueryMaster.class); + + private SetFinderDAOFactory sfDAOFactory = null; + + public QueryMaster(SetFinderDAOFactory sfDAOFactory) { + this.sfDAOFactory = sfDAOFactory; + } + + public QtAnalysisPlugin lookupAnalysisPlugin(String analysisName, + String version, String projectId) throws I2B2Exception { + logesapi.debug("looking for: " + analysisName +":" + version + ":" + projectId); + IAnalysisPluginDao analysisPluginDao = sfDAOFactory + .getAnalysisPluginDao(); + log.debug("getting QtAnalysisPlugin"); + QtAnalysisPlugin analysisPlugin = analysisPluginDao + .lookupAnalysisPluginByNameVersionProject(analysisName, + version, projectId); + return analysisPlugin; + } + + public String saveQuery(String requestXml, String generatedSql, + QtAnalysisPlugin analysisPlugin) throws I2B2Exception { + IQueryMasterDao queryMasterDao = sfDAOFactory.getQueryMasterDAO(); + + QtQueryMaster queryMaster = new QtQueryMaster(); + I2B2RequestMessageHelper msgHelper = new I2B2RequestMessageHelper( + requestXml); + UserType userType = msgHelper.getUserType(); + String userId = userType.getLogin(); + String groupId = msgHelper.getProjectId(); + + queryMaster.setUserId(userId); + + AnalysisDefinitionType anaDefType; + String queryMasterId = null; + try { + anaDefType = msgHelper.getAnalysisDefinition(); + + String analysisDefinitionXml = I2B2RequestMessageHelper + .getAnalysisDefinitionXml(anaDefType); + queryMaster.setRequestXml(analysisDefinitionXml); + queryMaster.setGroupId(groupId); + queryMaster.setCreateDate(new Date(System.currentTimeMillis())); + queryMaster.setDeleteFlag(QtQueryMaster.DELETE_OFF_FLAG); + queryMaster.setGeneratedSql(null); + queryMaster.setName(anaDefType.getAnalysisPluginName()); + queryMaster.setPluginId(analysisPlugin.getPluginId()); + queryMaster.setMasterTypeCd(analysisPlugin.getPluginName()); + + queryMasterId = queryMasterDao.createQueryMaster(queryMaster, + requestXml, null); + } catch (JAXBUtilException e) { + + throw new I2B2Exception("Failed to save query definition: [" + + e.getMessage() + "]", e); + } + + return queryMasterId; + } + + public AnalysisDefinitionType getAnalysisDefinitionByMasterId( + String masterId) throws JAXBUtilException { + AnalysisDefinitionType analysisDefType = null; + IQueryMasterDao queryMasterDao = sfDAOFactory.getQueryMasterDAO(); + QtQueryMaster queryMaster = queryMasterDao.getQueryDefinition(masterId); + String definitionXml = queryMaster.getRequestXml(); + if (definitionXml == null) { + return analysisDefType; + } + analysisDefType = I2B2RequestMessageHelper + .getAnalysisDefinitionFromXml(definitionXml); + return analysisDefType; + } + + public QtQueryMaster getQueryMaster(String requestXml) throws Exception { + QtQueryMaster queryMaster = new QtQueryMaster(); + I2B2RequestMessageHelper msgHelper = new I2B2RequestMessageHelper( + requestXml); + UserType userType = msgHelper.getUserType(); + String userId = userType.getLogin(); + String groupId = userType.getGroup(); + + queryMaster.setUserId(userId); + + AnalysisDefinitionType anaDefType; + try { + anaDefType = msgHelper.getAnalysisDefinition(); + + String analysisDefinitionXml = I2B2RequestMessageHelper + .getAnalysisDefinitionXml(anaDefType); + queryMaster.setRequestXml(analysisDefinitionXml); + queryMaster.setGroupId(groupId); + queryMaster.setCreateDate(new Date(System.currentTimeMillis())); + queryMaster.setDeleteFlag(QtQueryMaster.DELETE_OFF_FLAG); + queryMaster.setGeneratedSql("generatedSql"); + queryMaster.setName(anaDefType.getAnalysisPluginName()); + queryMaster.setI2b2RequestXml(requestXml); + + } catch (JAXBUtilException e) { + + throw new I2B2Exception("Failed to save query definition: [" + + e.getMessage() + "]", e); + } + return queryMaster; + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/analysis/StartAnalysis.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/analysis/StartAnalysis.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/analysis/StartAnalysis.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/analysis/StartAnalysis.java index 165a4b43..404e57f1 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/analysis/StartAnalysis.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/analysis/StartAnalysis.java @@ -1,274 +1,274 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.ejb.analysis; - -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.quartz.SchedulerException; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.dao.IDAOFactory; -import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; -import edu.harvard.i2b2.crc.datavo.db.QtAnalysisPlugin; -import edu.harvard.i2b2.crc.datavo.db.StatusEnum; -import edu.harvard.i2b2.crc.datavo.setfinder.query.AnalysisDefinitionType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterInstanceResultResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultOutputOptionListType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.StatusType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.UserType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.StatusType.Condition; -import edu.harvard.i2b2.crc.exec.ExecException; -import edu.harvard.i2b2.crc.quartz.StartJobHandler; -import edu.harvard.i2b2.crc.role.AuthrizationHelper; -import edu.harvard.i2b2.crc.util.I2B2RequestMessageHelper; -import edu.harvard.i2b2.crc.util.I2B2ResponseMessageHelper; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - -public class StartAnalysis implements StartAnalysisLocal { -/* - Connection connection = null; - @Resource(mappedName = "ConnectionFactory") - private static ConnectionFactory connectionFactory; - @Resource(mappedName = "jms/edu.harvard.i2b2.crc.loader.loadrunner") - private static Queue queue; - @Resource(mappedName = "jms/edu.harvard.i2b2.crc.loader.loadresponse") - private static Queue responseQueue; - @Resource - private UserTransaction utx; - // public static ApplicationContext ac; -*/ - // log - private static Log log = LogFactory.getLog(StartAnalysis.class); - protected final Log logesapi = LogFactory.getLog(getClass()); - - @Override - public MasterInstanceResultResponseType start(IDAOFactory daoFactory, - String requestXml) throws I2B2Exception { - StatusType statusType = new StatusType(); - String statusName = null, statusMessage = null; - - log.debug("in StartAnalysis: getting getSetFinderDAOFactory"); - SetFinderDAOFactory sfDAOFactory = daoFactory.getSetFinderDAOFactory(); - - MasterInstanceResultResponseType masterInstanceResultResponseType = null; - - String queryMasterId = null, queryInstanceId = null; - UserType userType = null; - - log.debug("in StartAnalysis: getting queryMaster"); - - QueryMaster queryMaster = new QueryMaster(sfDAOFactory); - QueryInstance queryInstance = new QueryInstance(sfDAOFactory); - - try { - // store the request in master table - I2B2RequestMessageHelper msgHelper = new I2B2RequestMessageHelper( - requestXml); - AnalysisDefinitionType analysisDefType = msgHelper - .getAnalysisDefinition(); - userType = msgHelper.getUserType(); - - log.debug("in StartAnalysis: getting analysisPlugin in queryMaster:" + queryMaster); - - log.debug("analysisDefType is " + analysisDefType); - log.debug("plugin Name: " + analysisDefType.getAnalysisPluginName()); - log.debug("plugin version: " + analysisDefType - .getVersion()); - logesapi.debug("plugin projectid" + msgHelper.getProjectId()); - QtAnalysisPlugin analysisPlugin = queryMaster.lookupAnalysisPlugin( - analysisDefType.getAnalysisPluginName(), analysisDefType - .getVersion(), msgHelper.getProjectId()); - log.debug("in StartAnalysis: my plugin id is " + analysisPlugin.getPluginId()); - - String pluginId = analysisPlugin.getPluginId(); - String domainId = userType.getGroup(); - String projectId = msgHelper.getProjectId(); - String userId = userType.getLogin(); - // call privilege bean to check for permission - AuthrizationHelper authHelper = new AuthrizationHelper(domainId, - projectId, userId, daoFactory); - - authHelper.checkRoleForPluginId(pluginId); - log.debug("query master saved"); -// utx.begin(); - String generatedSql = null; - // save the analysis request - queryMasterId = queryMaster.saveQuery(requestXml, generatedSql, - analysisPlugin); - -// utx.commit(); - log.debug("query master saved [" + queryMasterId + "]"); - - // get run instance -// utx.begin(); - // save the analysis instance - - analysisDefType.getAnalysisPluginName(); - ResultOutputOptionListType resultOutputList = I2B2RequestMessageHelper - .buildResultOptionListFromAnalysisResultList(analysisDefType - .getCrcAnalysisResultList()); - - // userType.setGroup(msgHelper.getProjectId()); - - queryInstanceId = queryInstance.saveInstanceAndResultInstance( - queryMasterId, userType, "WITHOUT_QUEUE", resultOutputList); -// utx.commit(); - - // determine which queue it goes and put the jobs in that queue - /* - * QueryExecutor queryExecutor = new QueryExecutor(sfDAOFactory, - * queryInstanceId); long timeout = msgHelper.getTimeout(); - * queryExecutor.execute(analysisDefType, timeout); - */ - - long timeout = msgHelper.getTimeout(); - StartJobHandler startJobHandler = new StartJobHandler( - QueryProcessorUtil.getInstance().getQuartzScheduler()); - - startJobHandler.startNonQuartzJob(domainId, projectId, userId, - queryInstanceId, timeout); - - // Thread.sleep(timeout); - waitForProcess(timeout, queryInstanceId); - - } catch (ExecException execEx) { - if (execEx.getExitStatus().equals(ExecException.TIMEOUT_STATUS)) { - statusName = StatusEnum.QUEUED.toString(); - } else { - statusName = StatusEnum.ERROR.toString(); - } - statusMessage = edu.harvard.i2b2.common.exception.StackTraceUtil - .getStackTrace(execEx); - } catch (SecurityException e) { - statusName = StatusEnum.ERROR.toString(); - statusMessage = edu.harvard.i2b2.common.exception.StackTraceUtil - .getStackTrace(e); - } catch (IllegalStateException e) { - statusName = StatusEnum.ERROR.toString(); - statusMessage = edu.harvard.i2b2.common.exception.StackTraceUtil - .getStackTrace(e); - } catch (I2B2Exception e) { - statusName = StatusEnum.ERROR.toString(); - statusMessage = edu.harvard.i2b2.common.exception.StackTraceUtil - .getStackTrace(e); - } catch (JAXBUtilException e) { - statusName = StatusEnum.ERROR.toString(); - statusMessage = edu.harvard.i2b2.common.exception.StackTraceUtil - .getStackTrace(e); - } catch (SchedulerException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } finally { - // just update query instance status, result instance status will be - // updated by queryexecutor - // queryInstance.updateInstanceStatus(queryInstanceId, statusName, - // statusMessage); - // if error then rollback - // utx.setRollbackOnly(); - - } - - Condition condition = new Condition(); - condition.setType(statusName); - condition.setValue(statusMessage); - statusType.getCondition().add(condition); - // build masterInstanceResultResponse - I2B2ResponseMessageHelper responseMessageHelper = new I2B2ResponseMessageHelper( - sfDAOFactory); - try { - masterInstanceResultResponseType = responseMessageHelper - .buildResponse(queryMasterId, queryInstanceId, userType - .getLogin(), statusType); - } catch (I2B2DAOException e) { - throw new I2B2Exception("Error " + e.getMessage() + "] ", e); - } - return masterInstanceResultResponseType; - } - - private void waitForProcess(long timeout, String instanceId) { - /* - MessageConsumer receiver = null; - TextMessage message = null; - //TODO removed loaders - //LoadDataResponseType response = null; - Session session = null; - try { - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - String selector = "JMSCorrelationID='" + instanceId + "'"; - receiver = session.createConsumer(responseQueue, selector); - - connection.start(); - - TextMessage inMessage = (TextMessage) receiver.receive(timeout); - if (inMessage != null) { - log.info("Received text message from response queue" - + inMessage.getText()); - - } - } catch (JMSException jmsEx) { - jmsEx.printStackTrace(); - } finally { - if (session != null) { - try { - session.close(); - } catch (JMSException e) { - } - } - - } - */ - } - - public void queueProcess() { - // write the status to table - // if processs is small, run them by submitting to quartz right away - } - - public void cronJobProcess() { - // a)Cronjob for midium and long queue : - // a.1) Look for running job if the start time>30min, kill the job and - // change status to stop - // a.2) Start new job - } - - /** - * Creates the connection. - */ - @PostConstruct - public void makeConnection() { - try { - // connection = connectionFactory.createConnection(); - } catch (Throwable t) { - // JMSException could be thrown - log.error("DataMartLoaderAsync.makeConnection:" + "Exception: " - + t.toString()); - } - } - - /** - * Closes the connection. - */ - @PreDestroy - public void endConnection() throws RuntimeException { - // if (connection != null) { - // try { - // connection.close(); - // } catch (Exception e) { - // e.printStackTrace(); - // } - // } - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.ejb.analysis; + +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.quartz.SchedulerException; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.dao.IDAOFactory; +import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; +import edu.harvard.i2b2.crc.datavo.db.QtAnalysisPlugin; +import edu.harvard.i2b2.crc.datavo.db.StatusEnum; +import edu.harvard.i2b2.crc.datavo.setfinder.query.AnalysisDefinitionType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterInstanceResultResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultOutputOptionListType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.StatusType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.UserType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.StatusType.Condition; +import edu.harvard.i2b2.crc.exec.ExecException; +import edu.harvard.i2b2.crc.quartz.StartJobHandler; +import edu.harvard.i2b2.crc.role.AuthrizationHelper; +import edu.harvard.i2b2.crc.util.I2B2RequestMessageHelper; +import edu.harvard.i2b2.crc.util.I2B2ResponseMessageHelper; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + +public class StartAnalysis implements StartAnalysisLocal { +/* + Connection connection = null; + @Resource(mappedName = "ConnectionFactory") + private static ConnectionFactory connectionFactory; + @Resource(mappedName = "jms/edu.harvard.i2b2.crc.loader.loadrunner") + private static Queue queue; + @Resource(mappedName = "jms/edu.harvard.i2b2.crc.loader.loadresponse") + private static Queue responseQueue; + @Resource + private UserTransaction utx; + // public static ApplicationContext ac; +*/ + // log + private static Log log = LogFactory.getLog(StartAnalysis.class); + protected final Log logesapi = LogFactory.getLog(getClass()); + + @Override + public MasterInstanceResultResponseType start(IDAOFactory daoFactory, + String requestXml) throws I2B2Exception { + StatusType statusType = new StatusType(); + String statusName = null, statusMessage = null; + + log.debug("in StartAnalysis: getting getSetFinderDAOFactory"); + SetFinderDAOFactory sfDAOFactory = daoFactory.getSetFinderDAOFactory(); + + MasterInstanceResultResponseType masterInstanceResultResponseType = null; + + String queryMasterId = null, queryInstanceId = null; + UserType userType = null; + + log.debug("in StartAnalysis: getting queryMaster"); + + QueryMaster queryMaster = new QueryMaster(sfDAOFactory); + QueryInstance queryInstance = new QueryInstance(sfDAOFactory); + + try { + // store the request in master table + I2B2RequestMessageHelper msgHelper = new I2B2RequestMessageHelper( + requestXml); + AnalysisDefinitionType analysisDefType = msgHelper + .getAnalysisDefinition(); + userType = msgHelper.getUserType(); + + log.debug("in StartAnalysis: getting analysisPlugin in queryMaster:" + queryMaster); + + log.debug("analysisDefType is " + analysisDefType); + log.debug("plugin Name: " + analysisDefType.getAnalysisPluginName()); + log.debug("plugin version: " + analysisDefType + .getVersion()); + logesapi.debug("plugin projectid" + msgHelper.getProjectId()); + QtAnalysisPlugin analysisPlugin = queryMaster.lookupAnalysisPlugin( + analysisDefType.getAnalysisPluginName(), analysisDefType + .getVersion(), msgHelper.getProjectId()); + log.debug("in StartAnalysis: my plugin id is " + analysisPlugin.getPluginId()); + + String pluginId = analysisPlugin.getPluginId(); + String domainId = userType.getGroup(); + String projectId = msgHelper.getProjectId(); + String userId = userType.getLogin(); + // call privilege bean to check for permission + AuthrizationHelper authHelper = new AuthrizationHelper(domainId, + projectId, userId, daoFactory); + + authHelper.checkRoleForPluginId(pluginId); + log.debug("query master saved"); +// utx.begin(); + String generatedSql = null; + // save the analysis request + queryMasterId = queryMaster.saveQuery(requestXml, generatedSql, + analysisPlugin); + +// utx.commit(); + log.debug("query master saved [" + queryMasterId + "]"); + + // get run instance +// utx.begin(); + // save the analysis instance + + analysisDefType.getAnalysisPluginName(); + ResultOutputOptionListType resultOutputList = I2B2RequestMessageHelper + .buildResultOptionListFromAnalysisResultList(analysisDefType + .getCrcAnalysisResultList()); + + // userType.setGroup(msgHelper.getProjectId()); + + queryInstanceId = queryInstance.saveInstanceAndResultInstance( + queryMasterId, userType, "WITHOUT_QUEUE", resultOutputList); +// utx.commit(); + + // determine which queue it goes and put the jobs in that queue + /* + * QueryExecutor queryExecutor = new QueryExecutor(sfDAOFactory, + * queryInstanceId); long timeout = msgHelper.getTimeout(); + * queryExecutor.execute(analysisDefType, timeout); + */ + + long timeout = msgHelper.getTimeout(); + StartJobHandler startJobHandler = new StartJobHandler( + QueryProcessorUtil.getInstance().getQuartzScheduler()); + + startJobHandler.startNonQuartzJob(domainId, projectId, userId, + queryInstanceId, timeout); + + // Thread.sleep(timeout); + waitForProcess(timeout, queryInstanceId); + + } catch (ExecException execEx) { + if (execEx.getExitStatus().equals(ExecException.TIMEOUT_STATUS)) { + statusName = StatusEnum.QUEUED.toString(); + } else { + statusName = StatusEnum.ERROR.toString(); + } + statusMessage = edu.harvard.i2b2.common.exception.StackTraceUtil + .getStackTrace(execEx); + } catch (SecurityException e) { + statusName = StatusEnum.ERROR.toString(); + statusMessage = edu.harvard.i2b2.common.exception.StackTraceUtil + .getStackTrace(e); + } catch (IllegalStateException e) { + statusName = StatusEnum.ERROR.toString(); + statusMessage = edu.harvard.i2b2.common.exception.StackTraceUtil + .getStackTrace(e); + } catch (I2B2Exception e) { + statusName = StatusEnum.ERROR.toString(); + statusMessage = edu.harvard.i2b2.common.exception.StackTraceUtil + .getStackTrace(e); + } catch (JAXBUtilException e) { + statusName = StatusEnum.ERROR.toString(); + statusMessage = edu.harvard.i2b2.common.exception.StackTraceUtil + .getStackTrace(e); + } catch (SchedulerException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } finally { + // just update query instance status, result instance status will be + // updated by queryexecutor + // queryInstance.updateInstanceStatus(queryInstanceId, statusName, + // statusMessage); + // if error then rollback + // utx.setRollbackOnly(); + + } + + Condition condition = new Condition(); + condition.setType(statusName); + condition.setValue(statusMessage); + statusType.getCondition().add(condition); + // build masterInstanceResultResponse + I2B2ResponseMessageHelper responseMessageHelper = new I2B2ResponseMessageHelper( + sfDAOFactory); + try { + masterInstanceResultResponseType = responseMessageHelper + .buildResponse(queryMasterId, queryInstanceId, userType + .getLogin(), statusType); + } catch (I2B2DAOException e) { + throw new I2B2Exception("Error " + e.getMessage() + "] ", e); + } + return masterInstanceResultResponseType; + } + + private void waitForProcess(long timeout, String instanceId) { + /* + MessageConsumer receiver = null; + TextMessage message = null; + //TODO removed loaders + //LoadDataResponseType response = null; + Session session = null; + try { + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + String selector = "JMSCorrelationID='" + instanceId + "'"; + receiver = session.createConsumer(responseQueue, selector); + + connection.start(); + + TextMessage inMessage = (TextMessage) receiver.receive(timeout); + if (inMessage != null) { + log.info("Received text message from response queue" + + inMessage.getText()); + + } + } catch (JMSException jmsEx) { + jmsEx.printStackTrace(); + } finally { + if (session != null) { + try { + session.close(); + } catch (JMSException e) { + } + } + + } + */ + } + + public void queueProcess() { + // write the status to table + // if processs is small, run them by submitting to quartz right away + } + + public void cronJobProcess() { + // a)Cronjob for midium and long queue : + // a.1) Look for running job if the start time>30min, kill the job and + // change status to stop + // a.2) Start new job + } + + /** + * Creates the connection. + */ + @PostConstruct + public void makeConnection() { + try { + // connection = connectionFactory.createConnection(); + } catch (Throwable t) { + // JMSException could be thrown + log.error("DataMartLoaderAsync.makeConnection:" + "Exception: " + + t.toString()); + } + } + + /** + * Closes the connection. + */ + @PreDestroy + public void endConnection() throws RuntimeException { + // if (connection != null) { + // try { + // connection.close(); + // } catch (Exception e) { + // e.printStackTrace(); + // } + // } + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/analysis/StartAnalysisLocal.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/analysis/StartAnalysisLocal.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/analysis/StartAnalysisLocal.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/analysis/StartAnalysisLocal.java index 5418cbcb..f2346b67 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/analysis/StartAnalysisLocal.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/analysis/StartAnalysisLocal.java @@ -1,21 +1,21 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.ejb.analysis; - - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.crc.dao.IDAOFactory; -import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterInstanceResultResponseType; - -public interface StartAnalysisLocal { - - public MasterInstanceResultResponseType start(IDAOFactory daoFactory, - String requestXml) throws I2B2Exception; - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.ejb.analysis; + + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.crc.dao.IDAOFactory; +import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterInstanceResultResponseType; + +public interface StartAnalysisLocal { + + public MasterInstanceResultResponseType start(IDAOFactory daoFactory, + String requestXml) throws I2B2Exception; + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/role/MissingRoleException.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/role/MissingRoleException.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/role/MissingRoleException.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/role/MissingRoleException.java index a3333f0a..0ff8b514 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/role/MissingRoleException.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/role/MissingRoleException.java @@ -1,41 +1,41 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.ejb.role; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; - -public class MissingRoleException extends I2B2DAOException { - - /** - * - */ - private static final long serialVersionUID = 1L; - - - public MissingRoleException() { - } - - /** - * Constructor that takes message and the exception as inputs. - * @param message - * @param e - */ - public MissingRoleException(String message, Exception e) { - super(message, e); - } - - /** - * Constructor that takes message as input. - * @param message - */ - public MissingRoleException(String message) { - super(message); - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.ejb.role; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; + +public class MissingRoleException extends I2B2DAOException { + + /** + * + */ + private static final long serialVersionUID = 1L; + + + public MissingRoleException() { + } + + /** + * Constructor that takes message and the exception as inputs. + * @param message + * @param e + */ + public MissingRoleException(String message, Exception e) { + super(message, e); + } + + /** + * Constructor that takes message as input. + * @param message + */ + public MissingRoleException(String message) { + super(message); + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/role/PriviledgeBean.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/role/PriviledgeBean.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/role/PriviledgeBean.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/role/PriviledgeBean.java index 0998d60c..79ddb6ec --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/role/PriviledgeBean.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/role/PriviledgeBean.java @@ -1,96 +1,96 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.ejb.role; - -import java.util.List; - - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.crc.dao.IDAOFactory; -import edu.harvard.i2b2.crc.dao.role.IPriviledgeDao; -import edu.harvard.i2b2.crc.datavo.db.QtPriviledge; - -public class PriviledgeBean implements PriviledgeLocal { - - // public static ApplicationContext ac; - // log - private static Log log = LogFactory.getLog(PriviledgeBean.class); - - @Override - public QtPriviledge checkPriviledge(IDAOFactory daoFactory, - String protectionLabel, List roles) - throws MissingRoleException, I2B2Exception { - IPriviledgeDao priviledgeDao = daoFactory.getSetFinderDAOFactory() - .getPriviledgeDao(); - QtPriviledge priviledge = priviledgeDao - .getPriviledgeByProtectionLabel(protectionLabel); - String dataTrck = priviledge.getDataProtCd(); - String mgmtTrck = priviledge.getHivemgmtCd(); - // check if dataTrck in roles - boolean dataTrckPassFlag = roles.contains(dataTrck); - // check for mgmtTrck in roles - boolean mgmtTrckPassFlag = roles.contains(mgmtTrck); - if (dataTrckPassFlag && mgmtTrckPassFlag) { - return priviledge; - } else { - String errorMsg = "This operation required privilege : "; - - String andMsg = " "; - if (dataTrckPassFlag == false) { - errorMsg += dataTrck; - andMsg = " and "; - } - if (mgmtTrckPassFlag == false) { - errorMsg += andMsg + mgmtTrck; - } - - throw new MissingRoleException(errorMsg); - } - } - - @Override - public QtPriviledge checkPluginPrivilege(IDAOFactory daoFactory, - String pluginId, List roles) throws MissingRoleException, - I2B2Exception { - QtPriviledge privilege = null; - IPriviledgeDao priviledgeDao = daoFactory.getSetFinderDAOFactory() - .getPriviledgeDao(); - List priviledgeList = priviledgeDao - .getPriviledgeByPluginId(pluginId); - if (priviledgeList.size() < 1) { - return privilege; - } - privilege = priviledgeList.get(0); - String dataTrck = privilege.getDataProtCd(); - String mgmtTrck = privilege.getHivemgmtCd(); - // check if dataTrck in roles - boolean dataTrckPassFlag = roles.contains(dataTrck); - // check for mgmtTrck in roles - boolean mgmtTrckPassFlag = roles.contains(mgmtTrck); - if (dataTrckPassFlag && mgmtTrckPassFlag) { - return privilege; - } else { - String errorMsg = "This operation required privilege : "; - - String andMsg = " "; - if (dataTrckPassFlag == false) { - errorMsg += dataTrck; - andMsg = " and "; - } - if (mgmtTrckPassFlag == false) { - errorMsg += andMsg + mgmtTrck; - } - - throw new MissingRoleException(errorMsg); - } - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.ejb.role; + +import java.util.List; + + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.crc.dao.IDAOFactory; +import edu.harvard.i2b2.crc.dao.role.IPriviledgeDao; +import edu.harvard.i2b2.crc.datavo.db.QtPriviledge; + +public class PriviledgeBean implements PriviledgeLocal { + + // public static ApplicationContext ac; + // log + private static Log log = LogFactory.getLog(PriviledgeBean.class); + + @Override + public QtPriviledge checkPriviledge(IDAOFactory daoFactory, + String protectionLabel, List roles) + throws MissingRoleException, I2B2Exception { + IPriviledgeDao priviledgeDao = daoFactory.getSetFinderDAOFactory() + .getPriviledgeDao(); + QtPriviledge priviledge = priviledgeDao + .getPriviledgeByProtectionLabel(protectionLabel); + String dataTrck = priviledge.getDataProtCd(); + String mgmtTrck = priviledge.getHivemgmtCd(); + // check if dataTrck in roles + boolean dataTrckPassFlag = roles.contains(dataTrck); + // check for mgmtTrck in roles + boolean mgmtTrckPassFlag = roles.contains(mgmtTrck); + if (dataTrckPassFlag && mgmtTrckPassFlag) { + return priviledge; + } else { + String errorMsg = "This operation required privilege : "; + + String andMsg = " "; + if (dataTrckPassFlag == false) { + errorMsg += dataTrck; + andMsg = " and "; + } + if (mgmtTrckPassFlag == false) { + errorMsg += andMsg + mgmtTrck; + } + + throw new MissingRoleException(errorMsg); + } + } + + @Override + public QtPriviledge checkPluginPrivilege(IDAOFactory daoFactory, + String pluginId, List roles) throws MissingRoleException, + I2B2Exception { + QtPriviledge privilege = null; + IPriviledgeDao priviledgeDao = daoFactory.getSetFinderDAOFactory() + .getPriviledgeDao(); + List priviledgeList = priviledgeDao + .getPriviledgeByPluginId(pluginId); + if (priviledgeList.size() < 1) { + return privilege; + } + privilege = priviledgeList.get(0); + String dataTrck = privilege.getDataProtCd(); + String mgmtTrck = privilege.getHivemgmtCd(); + // check if dataTrck in roles + boolean dataTrckPassFlag = roles.contains(dataTrck); + // check for mgmtTrck in roles + boolean mgmtTrckPassFlag = roles.contains(mgmtTrck); + if (dataTrckPassFlag && mgmtTrckPassFlag) { + return privilege; + } else { + String errorMsg = "This operation required privilege : "; + + String andMsg = " "; + if (dataTrckPassFlag == false) { + errorMsg += dataTrck; + andMsg = " and "; + } + if (mgmtTrckPassFlag == false) { + errorMsg += andMsg + mgmtTrck; + } + + throw new MissingRoleException(errorMsg); + } + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/role/PriviledgeLocal.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/role/PriviledgeLocal.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/role/PriviledgeLocal.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/role/PriviledgeLocal.java index 4e7f4b11..6496fd67 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/ejb/role/PriviledgeLocal.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/ejb/role/PriviledgeLocal.java @@ -1,28 +1,28 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.ejb.role; - -import java.util.List; - - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.crc.dao.IDAOFactory; -import edu.harvard.i2b2.crc.datavo.db.QtPriviledge; - -public interface PriviledgeLocal { - - public QtPriviledge checkPriviledge(IDAOFactory daoFactory, - String protectionLabel, List roles) - throws MissingRoleException, I2B2Exception; - - public QtPriviledge checkPluginPrivilege(IDAOFactory daoFactory, - String pluginId, List roles) throws MissingRoleException, - I2B2Exception; - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.ejb.role; + +import java.util.List; + + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.crc.dao.IDAOFactory; +import edu.harvard.i2b2.crc.datavo.db.QtPriviledge; + +public interface PriviledgeLocal { + + public QtPriviledge checkPriviledge(IDAOFactory daoFactory, + String protectionLabel, List roles) + throws MissingRoleException, I2B2Exception; + + public QtPriviledge checkPluginPrivilege(IDAOFactory daoFactory, + String pluginId, List roles) throws MissingRoleException, + I2B2Exception; + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/exec/CalulatePatientCountMain.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/exec/CalulatePatientCountMain.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/exec/CalulatePatientCountMain.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/exec/CalulatePatientCountMain.java index e74b9fb3..7457a4e8 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/exec/CalulatePatientCountMain.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/exec/CalulatePatientCountMain.java @@ -1,162 +1,162 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.exec; - -import java.io.StringWriter; -import java.util.List; - -import javax.sql.DataSource; - -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.dao.DataSourceLookupHelper; -import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; -import edu.harvard.i2b2.crc.dao.setfinder.IQueryInstanceDao; -import edu.harvard.i2b2.crc.dao.setfinder.IXmlResultDao; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.db.QtQueryInstance; -import edu.harvard.i2b2.crc.datavo.db.QtQueryResultInstance; -import edu.harvard.i2b2.crc.datavo.i2b2result.DataType; -import edu.harvard.i2b2.crc.datavo.i2b2result.ResultEnvelopeType; -import edu.harvard.i2b2.crc.datavo.i2b2result.ResultType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.AnalysisDefinitionType; -import edu.harvard.i2b2.crc.ejb.analysis.QueryMaster; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - -/** - * - * Sample analysis plugin. - * - * Shows how to fetch datasource and uses existing DAOs for following - * operations. - * - * - * a)using instance id to fetch analysis requests xml from the master table - * - * b)write generated result xml to the QT_XML_RESULT table - * - */ -public class CalulatePatientCountMain { - - private static final String RESULT_NAME = "CALCULATE_PATIENTCOUNT_BY_PATIENTSET_ID"; - - public static void main(String args[]) throws Exception { - CalulatePatientCountMain main1 = new CalulatePatientCountMain(); - - // read command line params[domain, project, user and analysis - // instance id - String arg = "", domainId = "", projectId = "", userId = "", patientSetId = "", instanceId = ""; - int i = 0; - while (i < args.length) { - arg = args[i++]; - if (arg.startsWith("-domain_id")) { - domainId = arg.substring(arg.indexOf('=') + 1); - } else if (arg.startsWith("-project_id")) { - projectId = arg.substring(arg.indexOf('=') + 1); - } else if (arg.startsWith("-user_id")) { - userId = arg.substring(arg.indexOf('=') + 1); - } else if (arg.startsWith("-instance_id")) { - instanceId = arg.substring(arg.indexOf('=') + 1); - } - } - - // call the calculation function - main1.calculateAndWriteResultXml(projectId, userId, domainId, - patientSetId, instanceId); - } - - public void calculateAndWriteResultXml(String projectId, String userId, - String domainId, String patientSetId, String instanceId) - throws Exception { - try { - - // find out datasource for the matching domain,project and user id - DataSourceLookupHelper dataSourceLookupHelper = new DataSourceLookupHelper(); - DataSourceLookup dataSourceLookup = dataSourceLookupHelper - .matchDataSource(domainId, projectId, userId); - - // inside analysis plugin always instanciate datasource using - // spring, the - // jboss container datasource will not work - DataSource dataSource = QueryProcessorUtil.getInstance() - .getDataSource(dataSourceLookup.getDataSource()); - DAOFactoryHelper daoHelper = new DAOFactoryHelper(dataSourceLookup, - dataSource); - - // from the dao helper, get the setfinder dao factory - SetFinderDAOFactory setfinderDaoFactory = daoHelper.getDAOFactory() - .getSetFinderDAOFactory(); - - // read the analysis definition from the master to perform the - // calculation - // //step 1:get master id from the instance id - IQueryInstanceDao queryInstanceDao = setfinderDaoFactory - .getQueryInstanceDAO(); - QtQueryInstance queryInstance = queryInstanceDao - .getQueryInstanceByInstanceId(instanceId); - String masterId = queryInstance.getQtQueryMaster() - .getQueryMasterId(); - // //step2:get analysis definition from the master id - QueryMaster queryMasterHelper = new QueryMaster(setfinderDaoFactory); - AnalysisDefinitionType analysisDefinition = queryMasterHelper - .getAnalysisDefinitionByMasterId(masterId); - - // just generating random number, not calculating patitient set size - // using analysis definition info - java.util.Random r = new java.util.Random(); - int setSize = r.nextInt(); - - // build result xml - String resultXml = buildXmlResult(RESULT_NAME, setSize); - - // to write the result xml get the result instance id by instance id - List resultInstanceList = setfinderDaoFactory - .getPatientSetResultDAO().getResultInstanceList(instanceId); - - String resultInstanceId = resultInstanceList.get(0) - .getResultInstanceId(); - - // writing back the result xml in the result table - IXmlResultDao xmlResultDao = setfinderDaoFactory.getXmlResultDao(); - xmlResultDao.createQueryXmlResult(resultInstanceId, resultXml); - } catch (Exception e) { - // write exception stack trace to the output file - e.printStackTrace(); - throw e; - } - - } - - private String buildXmlResult(String resultName, int setSize) - throws JAXBUtilException { - DataType dataType = new DataType(); - dataType.setValue(String.valueOf(setSize)); - dataType.setColumn("count"); - dataType.setType("int"); - - ResultType resultType = new ResultType(); - resultType.setName(resultName); - resultType.getData().add(dataType); - edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory(); - - edu.harvard.i2b2.crc.datavo.i2b2result.BodyType bodyType = new edu.harvard.i2b2.crc.datavo.i2b2result.BodyType(); - bodyType.getAny().add(of.createResult(resultType)); - ResultEnvelopeType resultEnvelopeType = new ResultEnvelopeType(); - resultEnvelopeType.setBody(bodyType); - - StringWriter strWriter = new StringWriter(); - JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); - jaxbUtil.marshaller(of.createI2B2ResultEnvelope(resultEnvelopeType), - strWriter); - - return strWriter.toString(); - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.exec; + +import java.io.StringWriter; +import java.util.List; + +import javax.sql.DataSource; + +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.dao.DataSourceLookupHelper; +import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; +import edu.harvard.i2b2.crc.dao.setfinder.IQueryInstanceDao; +import edu.harvard.i2b2.crc.dao.setfinder.IXmlResultDao; +import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.db.QtQueryInstance; +import edu.harvard.i2b2.crc.datavo.db.QtQueryResultInstance; +import edu.harvard.i2b2.crc.datavo.i2b2result.DataType; +import edu.harvard.i2b2.crc.datavo.i2b2result.ResultEnvelopeType; +import edu.harvard.i2b2.crc.datavo.i2b2result.ResultType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.AnalysisDefinitionType; +import edu.harvard.i2b2.crc.ejb.analysis.QueryMaster; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + +/** + * + * Sample analysis plugin. + * + * Shows how to fetch datasource and uses existing DAOs for following + * operations. + * + * + * a)using instance id to fetch analysis requests xml from the master table + * + * b)write generated result xml to the QT_XML_RESULT table + * + */ +public class CalulatePatientCountMain { + + private static final String RESULT_NAME = "CALCULATE_PATIENTCOUNT_BY_PATIENTSET_ID"; + + public static void main(String args[]) throws Exception { + CalulatePatientCountMain main1 = new CalulatePatientCountMain(); + + // read command line params[domain, project, user and analysis + // instance id + String arg = "", domainId = "", projectId = "", userId = "", patientSetId = "", instanceId = ""; + int i = 0; + while (i < args.length) { + arg = args[i++]; + if (arg.startsWith("-domain_id")) { + domainId = arg.substring(arg.indexOf('=') + 1); + } else if (arg.startsWith("-project_id")) { + projectId = arg.substring(arg.indexOf('=') + 1); + } else if (arg.startsWith("-user_id")) { + userId = arg.substring(arg.indexOf('=') + 1); + } else if (arg.startsWith("-instance_id")) { + instanceId = arg.substring(arg.indexOf('=') + 1); + } + } + + // call the calculation function + main1.calculateAndWriteResultXml(projectId, userId, domainId, + patientSetId, instanceId); + } + + public void calculateAndWriteResultXml(String projectId, String userId, + String domainId, String patientSetId, String instanceId) + throws Exception { + try { + + // find out datasource for the matching domain,project and user id + DataSourceLookupHelper dataSourceLookupHelper = new DataSourceLookupHelper(); + DataSourceLookup dataSourceLookup = dataSourceLookupHelper + .matchDataSource(domainId, projectId, userId); + + // inside analysis plugin always instanciate datasource using + // spring, the + // jboss container datasource will not work + DataSource dataSource = QueryProcessorUtil.getInstance() + .getDataSource(dataSourceLookup.getDataSource()); + DAOFactoryHelper daoHelper = new DAOFactoryHelper(dataSourceLookup, + dataSource); + + // from the dao helper, get the setfinder dao factory + SetFinderDAOFactory setfinderDaoFactory = daoHelper.getDAOFactory() + .getSetFinderDAOFactory(); + + // read the analysis definition from the master to perform the + // calculation + // //step 1:get master id from the instance id + IQueryInstanceDao queryInstanceDao = setfinderDaoFactory + .getQueryInstanceDAO(); + QtQueryInstance queryInstance = queryInstanceDao + .getQueryInstanceByInstanceId(instanceId); + String masterId = queryInstance.getQtQueryMaster() + .getQueryMasterId(); + // //step2:get analysis definition from the master id + QueryMaster queryMasterHelper = new QueryMaster(setfinderDaoFactory); + AnalysisDefinitionType analysisDefinition = queryMasterHelper + .getAnalysisDefinitionByMasterId(masterId); + + // just generating random number, not calculating patitient set size + // using analysis definition info + java.util.Random r = new java.util.Random(); + int setSize = r.nextInt(); + + // build result xml + String resultXml = buildXmlResult(RESULT_NAME, setSize); + + // to write the result xml get the result instance id by instance id + List resultInstanceList = setfinderDaoFactory + .getPatientSetResultDAO().getResultInstanceList(instanceId); + + String resultInstanceId = resultInstanceList.get(0) + .getResultInstanceId(); + + // writing back the result xml in the result table + IXmlResultDao xmlResultDao = setfinderDaoFactory.getXmlResultDao(); + xmlResultDao.createQueryXmlResult(resultInstanceId, resultXml); + } catch (Exception e) { + // write exception stack trace to the output file + e.printStackTrace(); + throw e; + } + + } + + private String buildXmlResult(String resultName, int setSize) + throws JAXBUtilException { + DataType dataType = new DataType(); + dataType.setValue(String.valueOf(setSize)); + dataType.setColumn("count"); + dataType.setType("int"); + + ResultType resultType = new ResultType(); + resultType.setName(resultName); + resultType.getData().add(dataType); + edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory(); + + edu.harvard.i2b2.crc.datavo.i2b2result.BodyType bodyType = new edu.harvard.i2b2.crc.datavo.i2b2result.BodyType(); + bodyType.getAny().add(of.createResult(resultType)); + ResultEnvelopeType resultEnvelopeType = new ResultEnvelopeType(); + resultEnvelopeType.setBody(bodyType); + + StringWriter strWriter = new StringWriter(); + JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); + jaxbUtil.marshaller(of.createI2B2ResultEnvelope(resultEnvelopeType), + strWriter); + + return strWriter.toString(); + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/exec/CalulatePatientCountMainFromItemKey.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/exec/CalulatePatientCountMainFromItemKey.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/exec/CalulatePatientCountMainFromItemKey.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/exec/CalulatePatientCountMainFromItemKey.java index 406eb93a..26d649e1 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/exec/CalulatePatientCountMainFromItemKey.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/exec/CalulatePatientCountMainFromItemKey.java @@ -1,298 +1,298 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.exec; - -import java.io.StringWriter; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.List; - -import javax.sql.DataSource; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.crc.dao.CRCDAO; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.dao.DataSourceLookupHelper; -import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; -import edu.harvard.i2b2.crc.dao.setfinder.IQueryInstanceDao; -import edu.harvard.i2b2.crc.dao.setfinder.IQueryMasterDao; -import edu.harvard.i2b2.crc.dao.setfinder.IQueryResultInstanceDao; -import edu.harvard.i2b2.crc.dao.setfinder.IXmlResultDao; -import edu.harvard.i2b2.crc.dao.setfinder.QueryStatusTypeId; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.db.QtQueryInstance; -import edu.harvard.i2b2.crc.datavo.db.QtQueryMaster; -import edu.harvard.i2b2.crc.datavo.db.QtQueryResultInstance; -import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; -import edu.harvard.i2b2.crc.datavo.i2b2result.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2result.DataType; -import edu.harvard.i2b2.crc.datavo.i2b2result.ResultEnvelopeType; -import edu.harvard.i2b2.crc.datavo.i2b2result.ResultType; -import edu.harvard.i2b2.crc.datavo.ontology.ConceptType; -import edu.harvard.i2b2.crc.datavo.ontology.ConceptsType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.AnalysisDefinitionType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.AnalysisParamType; -import edu.harvard.i2b2.crc.delegate.ontology.CallOntologyUtil; -import edu.harvard.i2b2.crc.ejb.analysis.QueryMaster; -import edu.harvard.i2b2.crc.util.I2B2RequestMessageHelper; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - -/** - * - * Sample analysis plugin. - * - * Shows how to fetch datasource and uses existing DAOs for following - * operations. - * - * - * a)using instance id to fetch analysis requests xml from the master table - * - * b)write generated result xml to the QT_XML_RESULT table - * - */ -public class CalulatePatientCountMainFromItemKey extends CRCDAO { - - private static final String RESULT_NAME = "CALCULATE_PATIENTCOUNT_FROM_CONCEPTPATH"; - - public static void main(String args[]) throws Exception { - CalulatePatientCountMainFromItemKey main1 = new CalulatePatientCountMainFromItemKey(); - - // read command line params[domain, project, user and analysis - // instance id - String arg = "", domainId = "", projectId = "", userId = "", patientSetId = "", instanceId = "", conceptPath = ""; - int i = 0; - while (i < args.length) { - arg = args[i++]; - if (arg.startsWith("-domain_id")) { - domainId = arg.substring(arg.indexOf('=') + 1); - } else if (arg.startsWith("-project_id")) { - projectId = arg.substring(arg.indexOf('=') + 1); - } else if (arg.startsWith("-user_id")) { - userId = arg.substring(arg.indexOf('=') + 1); - } else if (arg.startsWith("-instance_id")) { - instanceId = arg.substring(arg.indexOf('=') + 1); - } - } - - // call the calculation function - main1.calculateAndWriteResultXml(projectId, userId, domainId, - patientSetId, instanceId, conceptPath); - } - - public void calculateAndWriteResultXml(String projectId, String userId, - String domainId, String patientSetId, String instanceId, - String conceptPath) throws Exception { - boolean errorFlag = false; - String resultInstanceId = ""; - SetFinderDAOFactory setfinderDaoFactory = null; - Throwable throwable = null; - try { - - // find out datasource for the matching domain,project and user id - DataSourceLookupHelper dataSourceLookupHelper = new DataSourceLookupHelper(); - DataSourceLookup dataSourceLookup = dataSourceLookupHelper - .matchDataSource(domainId, projectId, userId); - - // inside analysis plugin always instanciate datasource using - // spring, the - // jboss container datasource will not work - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - DataSource dataSource = qpUtil.getDataSource(dataSourceLookup - .getDataSource()); - DAOFactoryHelper daoHelper = new DAOFactoryHelper(dataSourceLookup, - dataSource); - - // from the dao helper, get the setfinder dao factory - setfinderDaoFactory = daoHelper.getDAOFactory() - .getSetFinderDAOFactory(); - - // read the analysis definition from the master to perform the - // calculation - // //step 1:get master id from the instance id - IQueryInstanceDao queryInstanceDao = setfinderDaoFactory - .getQueryInstanceDAO(); - QtQueryInstance queryInstance = queryInstanceDao - .getQueryInstanceByInstanceId(instanceId); - String masterId = queryInstance.getQtQueryMaster() - .getQueryMasterId(); - - // //step2:get analysis definition from the master id to read the - // parameters like concept_path,.. - IQueryMasterDao queryMasterDao = setfinderDaoFactory - .getQueryMasterDAO(); - QtQueryMaster qtQueryMaster = queryMasterDao - .getQueryDefinition(masterId); - String requestXml = qtQueryMaster.getRequestXml(); - - String i2b2RequestXml = qtQueryMaster.getI2b2RequestXml(); - I2B2RequestMessageHelper analysisRequestHelper = new I2B2RequestMessageHelper( - i2b2RequestXml); - SecurityType securityType = analysisRequestHelper.getSecurityType(); - - QueryMaster queryMasterHelper = new QueryMaster(setfinderDaoFactory); - AnalysisDefinitionType analysisDefinition = queryMasterHelper - .getAnalysisDefinitionByMasterId(masterId); - AnalysisParamType conceptPathParam = analysisDefinition - .getCrcAnalysisInputParam().getParam().get(0); - conceptPath = conceptPathParam.getValue(); - - // call ontology to get children - // CallOntologyUtil callOntologyUtil = buildOntologyUtil(requestXml, - // projectId, securityType); - - // ConceptsType conceptsType = callOntologyUtil - // .callGetChildrenWithHttpClient(conceptPath); - - - ConceptsType conceptsType = CallOntologyUtil.callGetChildrenWithHttpClient(conceptPath, securityType, projectId); - - // build result xml - String resultXml = buildXmlResult(dataSource, conceptsType, - setfinderDaoFactory); - - // to write the result xml get the result instance id by instance id - List resultInstanceList = setfinderDaoFactory - .getPatientSetResultDAO().getResultInstanceList(instanceId); - - resultInstanceId = resultInstanceList.get(0).getResultInstanceId(); - - // writing back the result xml in the result table - IXmlResultDao xmlResultDao = setfinderDaoFactory.getXmlResultDao(); - xmlResultDao.createQueryXmlResult(resultInstanceId, resultXml); - } catch (Exception e) { - e.printStackTrace(); - errorFlag = true; - // write exception stack trace to the output file - throwable = e.getCause(); - throw e; - } finally { - - IQueryResultInstanceDao resultInstanceDao = setfinderDaoFactory - .getPatientSetResultDAO(); - - if (errorFlag) { - resultInstanceDao.updatePatientSet(resultInstanceId, - QueryStatusTypeId.STATUSTYPE_ID_ERROR, throwable - .getMessage(), 0, 0, ""); - } else { - resultInstanceDao.updatePatientSet(resultInstanceId, - QueryStatusTypeId.STATUSTYPE_ID_FINISHED, 0); - } - } - - } - - public String buildXmlResult(DataSource dataSource, - ConceptsType conceptsType, SetFinderDAOFactory sfDAOFactory) - throws I2B2DAOException { - this - .setDbSchemaName(sfDAOFactory.getDataSourceLookup() - .getFullSchema()); - - String tempTableName = ""; - PreparedStatement stmt = null; - boolean errorFlag = false; - String itemKey = ""; - Connection conn = null; - try { - - String itemCountSql = " select count(distinct PATIENT_NUM) as item_count from " - + this.getDbSchemaName() - + "observation_fact obs_fact " - + " where obs_fact.patient_num in (select patient_num from " - + this.getDbSchemaName() - + "patient_dimension" - + " ) " - + " and obs_fact.concept_cd in (select concept_cd from " - + this.getDbSchemaName() - + "concept_dimension where concept_path like ?)"; - ResultType resultType = new ResultType(); - resultType.setName(RESULT_NAME); - conn = dataSource.getConnection(); - stmt = conn.prepareStatement(itemCountSql); - for (ConceptType conceptType : conceptsType.getConcept()) { - - // build results - stmt.setString(1, conceptType.getDimcode() + "%"); - System.out - .println("Executing count sql [" + itemCountSql + "]"); - ResultSet resultSet = stmt.executeQuery(); - resultSet.next(); - String demoCount = resultSet.getString("item_count"); - DataType mdataType = new DataType(); - mdataType.setValue(demoCount); - mdataType.setColumn(conceptType.getName()); - mdataType.setType("int"); - resultType.getData().add(mdataType); - } - - edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory(); - BodyType bodyType = new BodyType(); - bodyType.getAny().add(of.createResult(resultType)); - ResultEnvelopeType resultEnvelop = new ResultEnvelopeType(); - resultEnvelop.setBody(bodyType); - - JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); - - StringWriter strWriter = new StringWriter(); - - jaxbUtil.marshaller(of.createI2B2ResultEnvelope(resultEnvelop), - strWriter); - - return strWriter.toString(); - - } catch (Exception sqlEx) { - log.error("CalulatePatientCountMainFromItemKey.buildXmlResult:" - + sqlEx.getMessage(), sqlEx); - throw new I2B2DAOException( - "CalulatePatientCountMainFromItemKey.buildXmlResult:" - + sqlEx.getMessage(), sqlEx); - } finally { - try { - stmt.close(); - conn.close(); - } catch (SQLException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - } - - /* - private CallOntologyUtil buildOntologyUtils(String requestXml, - String projectId, SecurityType securityType) { - //CallOntologyUtil callOntologyUtil = null; - try { - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - String ontologyUrl = qpUtil - .getCRCPropertyValue("edu.harvard.i2b2.crc.delegate.ontology.url"); - String getChildrenOperationName = qpUtil - .getCRCPropertyValue("edu.harvard.i2b2.crc.delegate.ontology.operation.getchildren"); - String ontologyGetChildrenUrl = ontologyUrl - + getChildrenOperationName; - log.debug("Ontology getChildren url from property file [" - + ontologyGetChildrenUrl + "]"); - - SecurityType serviceSecurityType = PMServiceAccountUtil - .getServiceSecurityType(securityType.getDomain()); - // callOntologyUtil = new CallOntologyUtil(ontologyUrl, requestXml); - callOntologyUtil = new CallOntologyUtil(ontologyGetChildrenUrl, - serviceSecurityType, projectId); - } catch (I2B2Exception e) { - e.printStackTrace(); - } - return callOntologyUtil; - } - */ -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.exec; + +import java.io.StringWriter; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.List; + +import javax.sql.DataSource; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.crc.dao.CRCDAO; +import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; +import edu.harvard.i2b2.crc.dao.DataSourceLookupHelper; +import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; +import edu.harvard.i2b2.crc.dao.setfinder.IQueryInstanceDao; +import edu.harvard.i2b2.crc.dao.setfinder.IQueryMasterDao; +import edu.harvard.i2b2.crc.dao.setfinder.IQueryResultInstanceDao; +import edu.harvard.i2b2.crc.dao.setfinder.IXmlResultDao; +import edu.harvard.i2b2.crc.dao.setfinder.QueryStatusTypeId; +import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.db.QtQueryInstance; +import edu.harvard.i2b2.crc.datavo.db.QtQueryMaster; +import edu.harvard.i2b2.crc.datavo.db.QtQueryResultInstance; +import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; +import edu.harvard.i2b2.crc.datavo.i2b2result.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2result.DataType; +import edu.harvard.i2b2.crc.datavo.i2b2result.ResultEnvelopeType; +import edu.harvard.i2b2.crc.datavo.i2b2result.ResultType; +import edu.harvard.i2b2.crc.datavo.ontology.ConceptType; +import edu.harvard.i2b2.crc.datavo.ontology.ConceptsType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.AnalysisDefinitionType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.AnalysisParamType; +import edu.harvard.i2b2.crc.delegate.ontology.CallOntologyUtil; +import edu.harvard.i2b2.crc.ejb.analysis.QueryMaster; +import edu.harvard.i2b2.crc.util.I2B2RequestMessageHelper; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + +/** + * + * Sample analysis plugin. + * + * Shows how to fetch datasource and uses existing DAOs for following + * operations. + * + * + * a)using instance id to fetch analysis requests xml from the master table + * + * b)write generated result xml to the QT_XML_RESULT table + * + */ +public class CalulatePatientCountMainFromItemKey extends CRCDAO { + + private static final String RESULT_NAME = "CALCULATE_PATIENTCOUNT_FROM_CONCEPTPATH"; + + public static void main(String args[]) throws Exception { + CalulatePatientCountMainFromItemKey main1 = new CalulatePatientCountMainFromItemKey(); + + // read command line params[domain, project, user and analysis + // instance id + String arg = "", domainId = "", projectId = "", userId = "", patientSetId = "", instanceId = "", conceptPath = ""; + int i = 0; + while (i < args.length) { + arg = args[i++]; + if (arg.startsWith("-domain_id")) { + domainId = arg.substring(arg.indexOf('=') + 1); + } else if (arg.startsWith("-project_id")) { + projectId = arg.substring(arg.indexOf('=') + 1); + } else if (arg.startsWith("-user_id")) { + userId = arg.substring(arg.indexOf('=') + 1); + } else if (arg.startsWith("-instance_id")) { + instanceId = arg.substring(arg.indexOf('=') + 1); + } + } + + // call the calculation function + main1.calculateAndWriteResultXml(projectId, userId, domainId, + patientSetId, instanceId, conceptPath); + } + + public void calculateAndWriteResultXml(String projectId, String userId, + String domainId, String patientSetId, String instanceId, + String conceptPath) throws Exception { + boolean errorFlag = false; + String resultInstanceId = ""; + SetFinderDAOFactory setfinderDaoFactory = null; + Throwable throwable = null; + try { + + // find out datasource for the matching domain,project and user id + DataSourceLookupHelper dataSourceLookupHelper = new DataSourceLookupHelper(); + DataSourceLookup dataSourceLookup = dataSourceLookupHelper + .matchDataSource(domainId, projectId, userId); + + // inside analysis plugin always instanciate datasource using + // spring, the + // jboss container datasource will not work + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + DataSource dataSource = qpUtil.getDataSource(dataSourceLookup + .getDataSource()); + DAOFactoryHelper daoHelper = new DAOFactoryHelper(dataSourceLookup, + dataSource); + + // from the dao helper, get the setfinder dao factory + setfinderDaoFactory = daoHelper.getDAOFactory() + .getSetFinderDAOFactory(); + + // read the analysis definition from the master to perform the + // calculation + // //step 1:get master id from the instance id + IQueryInstanceDao queryInstanceDao = setfinderDaoFactory + .getQueryInstanceDAO(); + QtQueryInstance queryInstance = queryInstanceDao + .getQueryInstanceByInstanceId(instanceId); + String masterId = queryInstance.getQtQueryMaster() + .getQueryMasterId(); + + // //step2:get analysis definition from the master id to read the + // parameters like concept_path,.. + IQueryMasterDao queryMasterDao = setfinderDaoFactory + .getQueryMasterDAO(); + QtQueryMaster qtQueryMaster = queryMasterDao + .getQueryDefinition(masterId); + String requestXml = qtQueryMaster.getRequestXml(); + + String i2b2RequestXml = qtQueryMaster.getI2b2RequestXml(); + I2B2RequestMessageHelper analysisRequestHelper = new I2B2RequestMessageHelper( + i2b2RequestXml); + SecurityType securityType = analysisRequestHelper.getSecurityType(); + + QueryMaster queryMasterHelper = new QueryMaster(setfinderDaoFactory); + AnalysisDefinitionType analysisDefinition = queryMasterHelper + .getAnalysisDefinitionByMasterId(masterId); + AnalysisParamType conceptPathParam = analysisDefinition + .getCrcAnalysisInputParam().getParam().get(0); + conceptPath = conceptPathParam.getValue(); + + // call ontology to get children + // CallOntologyUtil callOntologyUtil = buildOntologyUtil(requestXml, + // projectId, securityType); + + // ConceptsType conceptsType = callOntologyUtil + // .callGetChildrenWithHttpClient(conceptPath); + + + ConceptsType conceptsType = CallOntologyUtil.callGetChildrenWithHttpClient(conceptPath, securityType, projectId); + + // build result xml + String resultXml = buildXmlResult(dataSource, conceptsType, + setfinderDaoFactory); + + // to write the result xml get the result instance id by instance id + List resultInstanceList = setfinderDaoFactory + .getPatientSetResultDAO().getResultInstanceList(instanceId); + + resultInstanceId = resultInstanceList.get(0).getResultInstanceId(); + + // writing back the result xml in the result table + IXmlResultDao xmlResultDao = setfinderDaoFactory.getXmlResultDao(); + xmlResultDao.createQueryXmlResult(resultInstanceId, resultXml); + } catch (Exception e) { + e.printStackTrace(); + errorFlag = true; + // write exception stack trace to the output file + throwable = e.getCause(); + throw e; + } finally { + + IQueryResultInstanceDao resultInstanceDao = setfinderDaoFactory + .getPatientSetResultDAO(); + + if (errorFlag) { + resultInstanceDao.updatePatientSet(resultInstanceId, + QueryStatusTypeId.STATUSTYPE_ID_ERROR, throwable + .getMessage(), 0, 0, ""); + } else { + resultInstanceDao.updatePatientSet(resultInstanceId, + QueryStatusTypeId.STATUSTYPE_ID_FINISHED, 0); + } + } + + } + + public String buildXmlResult(DataSource dataSource, + ConceptsType conceptsType, SetFinderDAOFactory sfDAOFactory) + throws I2B2DAOException { + this + .setDbSchemaName(sfDAOFactory.getDataSourceLookup() + .getFullSchema()); + + String tempTableName = ""; + PreparedStatement stmt = null; + boolean errorFlag = false; + String itemKey = ""; + Connection conn = null; + try { + + String itemCountSql = " select count(distinct PATIENT_NUM) as item_count from " + + this.getDbSchemaName() + + "observation_fact obs_fact " + + " where obs_fact.patient_num in (select patient_num from " + + this.getDbSchemaName() + + "patient_dimension" + + " ) " + + " and obs_fact.concept_cd in (select concept_cd from " + + this.getDbSchemaName() + + "concept_dimension where concept_path like ?)"; + ResultType resultType = new ResultType(); + resultType.setName(RESULT_NAME); + conn = dataSource.getConnection(); + stmt = conn.prepareStatement(itemCountSql); + for (ConceptType conceptType : conceptsType.getConcept()) { + + // build results + stmt.setString(1, conceptType.getDimcode() + "%"); + System.out + .println("Executing count sql [" + itemCountSql + "]"); + ResultSet resultSet = stmt.executeQuery(); + resultSet.next(); + String demoCount = resultSet.getString("item_count"); + DataType mdataType = new DataType(); + mdataType.setValue(demoCount); + mdataType.setColumn(conceptType.getName()); + mdataType.setType("int"); + resultType.getData().add(mdataType); + } + + edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory(); + BodyType bodyType = new BodyType(); + bodyType.getAny().add(of.createResult(resultType)); + ResultEnvelopeType resultEnvelop = new ResultEnvelopeType(); + resultEnvelop.setBody(bodyType); + + JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); + + StringWriter strWriter = new StringWriter(); + + jaxbUtil.marshaller(of.createI2B2ResultEnvelope(resultEnvelop), + strWriter); + + return strWriter.toString(); + + } catch (Exception sqlEx) { + log.error("CalulatePatientCountMainFromItemKey.buildXmlResult:" + + sqlEx.getMessage(), sqlEx); + throw new I2B2DAOException( + "CalulatePatientCountMainFromItemKey.buildXmlResult:" + + sqlEx.getMessage(), sqlEx); + } finally { + try { + stmt.close(); + conn.close(); + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + } + + /* + private CallOntologyUtil buildOntologyUtils(String requestXml, + String projectId, SecurityType securityType) { + //CallOntologyUtil callOntologyUtil = null; + try { + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + String ontologyUrl = qpUtil + .getCRCPropertyValue("edu.harvard.i2b2.crc.delegate.ontology.url"); + String getChildrenOperationName = qpUtil + .getCRCPropertyValue("edu.harvard.i2b2.crc.delegate.ontology.operation.getchildren"); + String ontologyGetChildrenUrl = ontologyUrl + + getChildrenOperationName; + log.debug("Ontology getChildren url from property file [" + + ontologyGetChildrenUrl + "]"); + + SecurityType serviceSecurityType = PMServiceAccountUtil + .getServiceSecurityType(securityType.getDomain()); + // callOntologyUtil = new CallOntologyUtil(ontologyUrl, requestXml); + callOntologyUtil = new CallOntologyUtil(ontologyGetChildrenUrl, + serviceSecurityType, projectId); + } catch (I2B2Exception e) { + e.printStackTrace(); + } + return callOntologyUtil; + } + */ +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/exec/ExecException.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/exec/ExecException.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/exec/ExecException.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/exec/ExecException.java index bee6361e..5bc6863a --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/exec/ExecException.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/exec/ExecException.java @@ -1,45 +1,45 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.exec; - -import edu.harvard.i2b2.common.exception.I2B2Exception; - -public class ExecException extends I2B2Exception { - - private String exitStatus = null; - private String message = null; - - public final static String TIMEOUT_STATUS = "TIMEOUT_STATUS"; - public final static String ERROR_STATUS = "ERROR_STATUS"; - - public ExecException(int exitValue, String message) { - - if (exitValue == 143) { - exitStatus = TIMEOUT_STATUS; - this.message = "Process Timeout Error : " + message; - } else { - exitStatus = ERROR_STATUS; - this.message = message; - } - } - - public ExecException(String message) { - super(message); - } - - public String getExitStatus() { - return exitStatus; - } - - @Override - public String getMessage() { - return message; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.exec; + +import edu.harvard.i2b2.common.exception.I2B2Exception; + +public class ExecException extends I2B2Exception { + + private String exitStatus = null; + private String message = null; + + public final static String TIMEOUT_STATUS = "TIMEOUT_STATUS"; + public final static String ERROR_STATUS = "ERROR_STATUS"; + + public ExecException(int exitValue, String message) { + + if (exitValue == 143) { + exitStatus = TIMEOUT_STATUS; + this.message = "Process Timeout Error : " + message; + } else { + exitStatus = ERROR_STATUS; + this.message = message; + } + } + + public ExecException(String message) { + super(message); + } + + public String getExitStatus() { + return exitStatus; + } + + @Override + public String getMessage() { + return message; + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/exec/ExecUtil.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/exec/ExecUtil.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/exec/ExecUtil.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/exec/ExecUtil.java index f95d1b51..a2fe92a8 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/exec/ExecUtil.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/exec/ExecUtil.java @@ -1,69 +1,69 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.exec; - -import java.io.File; -import java.io.IOException; - -import org.apache.commons.exec.CommandLine; -import org.apache.commons.exec.DefaultExecutor; -import org.apache.commons.exec.ExecuteWatchdog; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.StackTraceUtil; - -public class ExecUtil { - - private static Log log = LogFactory.getLog(ExecUtil.class); - - public void execute(String workingFolder, String commandLineStr, - long timeOut) throws ExecException { - log.info("Working folder :[" + workingFolder + "]"); - log.info("Command line :[ " + commandLineStr + "]"); - CommandLine commandLine = CommandLine.parse(commandLineStr); - ExecuteWatchdog watchdog = new ExecuteWatchdog(timeOut); - DefaultExecutor executor = new DefaultExecutor(); - executor.setWorkingDirectory(new File(workingFolder)); - executor.setWatchdog(watchdog); - int errCode = -1; - try { - - - MySecurityManager secManager = new MySecurityManager(); - System.setSecurityManager(secManager); - - log.info("Executing command line [" + commandLine + "]"); - // executor.setExitValue(0); - long startTime = System.currentTimeMillis(); - - // ProcessBuilder pb = new ProcessBuilder(commandLineStr); - // System.out.println("Run echo command"); - // Process process = pb.start(); - // errCode = process.waitFor(); - - - int exitValue = executor.execute(commandLine); - long endTime = System.currentTimeMillis(); - long diffTime = endTime - startTime; - log.debug(commandLine + " ran for " + diffTime + " mills"); - } catch (SecurityException e) { - throw new ExecException(errCode, StackTraceUtil - .getStackTrace(e)); - } catch (IOException e) { - e.printStackTrace(); - throw new ExecException(0, StackTraceUtil.getStackTrace(e)); - // } catch (InterruptedException e) { - // TODO Auto-generated catch block -// e.printStackTrace(); - } - - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.exec; + +import java.io.File; +import java.io.IOException; + +import org.apache.commons.exec.CommandLine; +import org.apache.commons.exec.DefaultExecutor; +import org.apache.commons.exec.ExecuteWatchdog; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.StackTraceUtil; + +public class ExecUtil { + + private static Log log = LogFactory.getLog(ExecUtil.class); + + public void execute(String workingFolder, String commandLineStr, + long timeOut) throws ExecException { + log.info("Working folder :[" + workingFolder + "]"); + log.info("Command line :[ " + commandLineStr + "]"); + CommandLine commandLine = CommandLine.parse(commandLineStr); + ExecuteWatchdog watchdog = new ExecuteWatchdog(timeOut); + DefaultExecutor executor = new DefaultExecutor(); + executor.setWorkingDirectory(new File(workingFolder)); + executor.setWatchdog(watchdog); + int errCode = -1; + try { + + + MySecurityManager secManager = new MySecurityManager(); + System.setSecurityManager(secManager); + + log.info("Executing command line [" + commandLine + "]"); + // executor.setExitValue(0); + long startTime = System.currentTimeMillis(); + + // ProcessBuilder pb = new ProcessBuilder(commandLineStr); + // System.out.println("Run echo command"); + // Process process = pb.start(); + // errCode = process.waitFor(); + + + int exitValue = executor.execute(commandLine); + long endTime = System.currentTimeMillis(); + long diffTime = endTime - startTime; + log.debug(commandLine + " ran for " + diffTime + " mills"); + } catch (SecurityException e) { + throw new ExecException(errCode, StackTraceUtil + .getStackTrace(e)); + } catch (IOException e) { + e.printStackTrace(); + throw new ExecException(0, StackTraceUtil.getStackTrace(e)); + // } catch (InterruptedException e) { + // TODO Auto-generated catch block +// e.printStackTrace(); + } + + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/exec/LargeMain.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/exec/LargeMain.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/exec/LargeMain.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/exec/LargeMain.java index e341beac..286f68b5 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/exec/LargeMain.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/exec/LargeMain.java @@ -1,18 +1,18 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.exec; - -public class LargeMain { - - public static void main(String args[]) throws InterruptedException { - for (long i = 0; i < 10000000; i++) { - Thread.sleep(500); - } - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.exec; + +public class LargeMain { + + public static void main(String args[]) throws InterruptedException { + for (long i = 0; i < 10000000; i++) { + Thread.sleep(500); + } + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/exec/Main.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/exec/Main.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/exec/Main.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/exec/Main.java index 0461a315..e52b48da --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/exec/Main.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/exec/Main.java @@ -1,18 +1,18 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.exec; - -public class Main { - - public static void main(String args[]) throws InterruptedException { - for (long i = 0; i < 100; i++) { - Thread.sleep(500); - } - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.exec; + +public class Main { + + public static void main(String args[]) throws InterruptedException { + for (long i = 0; i < 100; i++) { + Thread.sleep(500); + } + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/exec/MediumMain.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/exec/MediumMain.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/exec/MediumMain.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/exec/MediumMain.java index 8bc5a609..a7fbd827 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/exec/MediumMain.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/exec/MediumMain.java @@ -1,18 +1,18 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.exec; - -public class MediumMain { - - public static void main(String args[]) throws InterruptedException { - for (long i = 0; i < 100000; i++) { - Thread.sleep(500); - } - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.exec; + +public class MediumMain { + + public static void main(String args[]) throws InterruptedException { + for (long i = 0; i < 100000; i++) { + Thread.sleep(500); + } + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/exec/MySecurityManager.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/exec/MySecurityManager.java similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/exec/MySecurityManager.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/exec/MySecurityManager.java index 08408f10..6b3f8b85 100644 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/exec/MySecurityManager.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/exec/MySecurityManager.java @@ -1,13 +1,13 @@ -package edu.harvard.i2b2.crc.exec; - -import java.security.Permission; - -public class MySecurityManager extends SecurityManager { - @Override public void checkExit(int status) { - throw new SecurityException(); - } - - @Override public void checkPermission(Permission perm) { - // Allow other activities by default - } +package edu.harvard.i2b2.crc.exec; + +import java.security.Permission; + +public class MySecurityManager extends SecurityManager { + @Override public void checkExit(int status) { + throw new SecurityException(); + } + + @Override public void checkPermission(Permission perm) { + // Allow other activities by default + } } \ No newline at end of file diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/CRCLoaderDAO.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/CRCLoaderDAO.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/CRCLoaderDAO.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/CRCLoaderDAO.java index 41517a44..cc5a9732 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/CRCLoaderDAO.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/CRCLoaderDAO.java @@ -1,94 +1,94 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.loader.dao; - -import java.sql.CallableStatement; -import java.sql.Connection; -import java.sql.SQLException; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.sql.DataSource; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.crc.datavo.pdo.ParamType; - -/** - * DAO abstract class to provide common dao functions $Id: CRCLoaderDAO.java,v - * 1.3 2008/06/03 21:09:03 rk903 Exp $ - * - * @author rkuttan - * @see Connection - * @see Session - */ -public class CRCLoaderDAO { - /** log **/ - protected final Log log = LogFactory.getLog(getClass()); - protected DataSource dataSource = null; - - protected String dbSchemaName = null; - - public final static String DATASOUCE_JNDI_NAME = "java:QueryToolDS"; - - public DataSource getDataSource() { - return dataSource; - } - - public void setDataSource(DataSource dataSource) { - this.dataSource = dataSource; - } - - public String getDbSchemaName() { - return this.dbSchemaName; - } - - public void setDbSchemaName(String dbSchemaName) { - if (dbSchemaName != null && dbSchemaName.endsWith(".")) { - this.dbSchemaName = dbSchemaName.trim(); - } else if (dbSchemaName != null) { - this.dbSchemaName = dbSchemaName.trim() + "."; - } - - } - - public Map buildNVParam(List paramTypeList) { - Map paramMap = new HashMap(); - for (ParamType paramType : paramTypeList) { - if (paramType.getColumn() != null) { - paramMap.put(paramType.getColumn(), paramType); - } - } - return paramMap; - } - - public void getSQLServerProcedureError(String serverType, - CallableStatement callStmt, int outParamIndex) throws SQLException, - I2B2Exception { - - if (serverType.equalsIgnoreCase(DataSourceLookupDAOFactory.SQLSERVER)) { - String errorMsg = callStmt.getString(outParamIndex); - if (errorMsg != null) { - log.debug("error codde" + errorMsg); - throw new I2B2Exception("Error from stored procedure [" - + errorMsg + "]"); - } - } - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.loader.dao; + +import java.sql.CallableStatement; +import java.sql.Connection; +import java.sql.SQLException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.sql.DataSource; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.crc.datavo.pdo.ParamType; + +/** + * DAO abstract class to provide common dao functions $Id: CRCLoaderDAO.java,v + * 1.3 2008/06/03 21:09:03 rk903 Exp $ + * + * @author rkuttan + * @see Connection + * @see Session + */ +public class CRCLoaderDAO { + /** log **/ + protected final Log log = LogFactory.getLog(getClass()); + protected DataSource dataSource = null; + + protected String dbSchemaName = null; + + public final static String DATASOUCE_JNDI_NAME = "java:QueryToolDS"; + + public DataSource getDataSource() { + return dataSource; + } + + public void setDataSource(DataSource dataSource) { + this.dataSource = dataSource; + } + + public String getDbSchemaName() { + return this.dbSchemaName; + } + + public void setDbSchemaName(String dbSchemaName) { + if (dbSchemaName != null && dbSchemaName.endsWith(".")) { + this.dbSchemaName = dbSchemaName.trim(); + } else if (dbSchemaName != null) { + this.dbSchemaName = dbSchemaName.trim() + "."; + } + + } + + public Map buildNVParam(List paramTypeList) { + Map paramMap = new HashMap(); + for (ParamType paramType : paramTypeList) { + if (paramType.getColumn() != null) { + paramMap.put(paramType.getColumn(), paramType); + } + } + return paramMap; + } + + public void getSQLServerProcedureError(String serverType, + CallableStatement callStmt, int outParamIndex) throws SQLException, + I2B2Exception { + + if (serverType.equalsIgnoreCase(DataSourceLookupDAOFactory.SQLSERVER)) { + String errorMsg = callStmt.getString(outParamIndex); + if (errorMsg != null) { + log.debug("error codde" + errorMsg); + throw new I2B2Exception("Error from stored procedure [" + + errorMsg + "]"); + } + } + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/ConceptDAO.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/ConceptDAO.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/ConceptDAO.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/ConceptDAO.java index 07a0d77f..e63ea202 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/ConceptDAO.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/ConceptDAO.java @@ -1,245 +1,245 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.dao; - -import java.sql.CallableStatement; -import java.sql.Connection; -import java.sql.SQLException; -import java.sql.Types; - -import javax.sql.DataSource; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.SqlParameter; -import org.springframework.jdbc.object.BatchSqlUpdate; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.crc.loader.datavo.loader.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.pdo.ConceptType; - -/** - * Patient Dimension data access object. - * - * @author rk903 - */ -public class ConceptDAO extends CRCLoaderDAO implements IConceptDAO { - - private int DB_BATCH_INSERT_SIZE = 1; - private DataSourceLookup dataSourceLookup = null; - - private static Log log = LogFactory.getLog(ConceptDAO.class); - - public ConceptDAO(DataSourceLookup dataSourceLookup, DataSource dataSource) { - setDataSource(dataSource); - setDbSchemaName(dataSourceLookup.getFullSchema()); - this.dataSourceLookup = dataSourceLookup; - - } - - /** - * Function to create temp visit dimension table using stored proc. - * - * @param tempTableName - * @throws Exception - */ - @Override - public void createTempTable(String tempPatientMappingTableName) - throws I2B2Exception { - Connection conn = null; - try { - conn = getDataSource().getConnection(); - CallableStatement callStmt = conn.prepareCall("{call " - + this.getDbSchemaName() - + "CREATE_TEMP_CONCEPT_TABLE(?,?)}"); - callStmt.setString(1, tempPatientMappingTableName); - callStmt.registerOutParameter(2, java.sql.Types.VARCHAR); - callStmt.execute(); - this.getSQLServerProcedureError(dataSourceLookup.getServerType(), - callStmt, 2); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - throw new I2B2Exception( - "SQLException occured" + sqlEx.getMessage(), sqlEx); - } catch (Exception ex) { - ex.printStackTrace(); - throw new I2B2Exception("Exception occured" + ex.getMessage(), ex); - } finally { - if (conn != null) { - try { - conn.close(); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - log.error("Error while closing connection", sqlEx); - } - } - } - } - - /** - * Create batch insert handle for temp observation fact table. - * - * @param tempTableName - * @return - */ - @Override - public TempConceptInsertHandler createTempConceptInsert(String tempTableName) { - TempConceptInsert tempConceptInsert = new TempConceptInsert( - getDataSource(), tempTableName, getDbSchemaName()); - tempConceptInsert.setBatchSize(DB_BATCH_INSERT_SIZE); - return new TempConceptInsertHandler(tempConceptInsert); - } - - /** - * Function to create new encounter/visit from temp_visit_dimension table - * using stored proc. - * - * @param tempTableName - * @throws Exception - */ - @Override - public void createConceptFromTempTable(String tempMapTableName, int uploadId) - throws I2B2Exception { - Connection conn = null; - try { - conn = getDataSource().getConnection(); - CallableStatement callStmt = conn.prepareCall("{call " - + this.getDbSchemaName() - + "INSERT_CONCEPT_FROMTEMP(?,?,?)}"); - callStmt.setString(1, tempMapTableName); - callStmt.setInt(2, uploadId); - callStmt.registerOutParameter(3, java.sql.Types.VARCHAR); - callStmt.execute(); - this.getSQLServerProcedureError(dataSourceLookup.getServerType(), - callStmt, 3); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - throw new I2B2Exception( - "SQLException occured" + sqlEx.getMessage(), sqlEx); - } catch (Exception ex) { - ex.printStackTrace(); - throw new I2B2Exception("Exception occured" + ex.getMessage(), ex); - } finally { - if (conn != null) { - try { - conn.close(); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - log.error("Error while closing connection", sqlEx); - } - } - } - } - - @Override - public int getRecordCountByUploadId(int uploadId) { - JdbcTemplate jdbcTemplate = new JdbcTemplate(getDataSource()); - int insertCount = jdbcTemplate.queryForObject("select count(1) from " - + this.getDbSchemaName() - + "concept_dimension where upload_id =?", Integer.class, - new Object[] { uploadId }); - return insertCount; - } - - /** - * Function to backup and clear concept dimension table using stored proc. - * - * @param tempTableName - * @throws Exception - */ - @Override - public void backupAndSyncConceptDimensionTable(String tempConceptTableName, - String backupConceptDimensionTableName, int uploadId) - throws I2B2Exception { - Connection conn = null; - try { - conn = getDataSource().getConnection(); - CallableStatement callStmt = conn.prepareCall("{call " - + this.getDbSchemaName() - + "SYNC_CLEAR_CONCEPT_TABLE(?,?,?,?)}"); - callStmt.setString(1, tempConceptTableName); - callStmt.setString(2, backupConceptDimensionTableName); - callStmt.setInt(3, uploadId); - callStmt.registerOutParameter(4, java.sql.Types.VARCHAR); - callStmt.execute(); - this.getSQLServerProcedureError(dataSourceLookup.getServerType(), - callStmt, 4); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - throw new I2B2Exception( - "SQLException occured" + sqlEx.getMessage(), sqlEx); - } catch (Exception ex) { - ex.printStackTrace(); - throw new I2B2Exception("Exception occured" + ex.getMessage(), ex); - } finally { - if (conn != null) { - try { - conn.close(); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - log.error("Error while closing connection", sqlEx); - } - } - } - } - - /** - * Patient_Mapping insert code. - */ - protected class TempConceptInsert extends BatchSqlUpdate { - - /** - * Create a new instance of Patient_MappingInsert. - * - * @param ds - * the DataSource to use for the insert - */ - protected TempConceptInsert(DataSource ds, String tempTableName, - String dbSchemaName) { - - super(ds, "INSERT INTO " + dbSchemaName + tempTableName + " (" - + "CONCEPT_CD," + "CONCEPT_PATH," + "NAME_CHAR," - + "CONCEPT_BLOB," + "UPDATE_DATE," + "DOWNLOAD_DATE," - + "IMPORT_DATE," + "SOURCESYSTEM_CD" + ")" - + " VALUES(?,?,?,?,?,?,?,?)"); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.TIMESTAMP)); - declareParameter(new SqlParameter(Types.TIMESTAMP)); - declareParameter(new SqlParameter(Types.TIMESTAMP)); - declareParameter(new SqlParameter(Types.VARCHAR)); - compile(); - } - - protected void insert(ConceptType concept) { - - // do self insert - Object[] objs = new Object[] { - concept.getConceptCd(), - concept.getConceptPath(), - concept.getNameChar(), - (concept.getConceptBlob() != null) ? concept - .getConceptBlob().getContent().get(0) : null, - (concept.getUpdateDate() != null) ? concept.getUpdateDate() - .toGregorianCalendar().getTime() : null, - (concept.getDownloadDate() != null) ? concept - .getDownloadDate().toGregorianCalendar().getTime() - : null, - (concept.getImportDate() != null) ? concept.getImportDate() - .toGregorianCalendar().getTime() : null, - concept.getSourcesystemCd() }; - super.update(objs); - } - - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.dao; + +import java.sql.CallableStatement; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.Types; + +import javax.sql.DataSource; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.SqlParameter; +import org.springframework.jdbc.object.BatchSqlUpdate; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.crc.loader.datavo.loader.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.pdo.ConceptType; + +/** + * Patient Dimension data access object. + * + * @author rk903 + */ +public class ConceptDAO extends CRCLoaderDAO implements IConceptDAO { + + private int DB_BATCH_INSERT_SIZE = 1; + private DataSourceLookup dataSourceLookup = null; + + private static Log log = LogFactory.getLog(ConceptDAO.class); + + public ConceptDAO(DataSourceLookup dataSourceLookup, DataSource dataSource) { + setDataSource(dataSource); + setDbSchemaName(dataSourceLookup.getFullSchema()); + this.dataSourceLookup = dataSourceLookup; + + } + + /** + * Function to create temp visit dimension table using stored proc. + * + * @param tempTableName + * @throws Exception + */ + @Override + public void createTempTable(String tempPatientMappingTableName) + throws I2B2Exception { + Connection conn = null; + try { + conn = getDataSource().getConnection(); + CallableStatement callStmt = conn.prepareCall("{call " + + this.getDbSchemaName() + + "CREATE_TEMP_CONCEPT_TABLE(?,?)}"); + callStmt.setString(1, tempPatientMappingTableName); + callStmt.registerOutParameter(2, java.sql.Types.VARCHAR); + callStmt.execute(); + this.getSQLServerProcedureError(dataSourceLookup.getServerType(), + callStmt, 2); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + throw new I2B2Exception( + "SQLException occured" + sqlEx.getMessage(), sqlEx); + } catch (Exception ex) { + ex.printStackTrace(); + throw new I2B2Exception("Exception occured" + ex.getMessage(), ex); + } finally { + if (conn != null) { + try { + conn.close(); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + log.error("Error while closing connection", sqlEx); + } + } + } + } + + /** + * Create batch insert handle for temp observation fact table. + * + * @param tempTableName + * @return + */ + @Override + public TempConceptInsertHandler createTempConceptInsert(String tempTableName) { + TempConceptInsert tempConceptInsert = new TempConceptInsert( + getDataSource(), tempTableName, getDbSchemaName()); + tempConceptInsert.setBatchSize(DB_BATCH_INSERT_SIZE); + return new TempConceptInsertHandler(tempConceptInsert); + } + + /** + * Function to create new encounter/visit from temp_visit_dimension table + * using stored proc. + * + * @param tempTableName + * @throws Exception + */ + @Override + public void createConceptFromTempTable(String tempMapTableName, int uploadId) + throws I2B2Exception { + Connection conn = null; + try { + conn = getDataSource().getConnection(); + CallableStatement callStmt = conn.prepareCall("{call " + + this.getDbSchemaName() + + "INSERT_CONCEPT_FROMTEMP(?,?,?)}"); + callStmt.setString(1, tempMapTableName); + callStmt.setInt(2, uploadId); + callStmt.registerOutParameter(3, java.sql.Types.VARCHAR); + callStmt.execute(); + this.getSQLServerProcedureError(dataSourceLookup.getServerType(), + callStmt, 3); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + throw new I2B2Exception( + "SQLException occured" + sqlEx.getMessage(), sqlEx); + } catch (Exception ex) { + ex.printStackTrace(); + throw new I2B2Exception("Exception occured" + ex.getMessage(), ex); + } finally { + if (conn != null) { + try { + conn.close(); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + log.error("Error while closing connection", sqlEx); + } + } + } + } + + @Override + public int getRecordCountByUploadId(int uploadId) { + JdbcTemplate jdbcTemplate = new JdbcTemplate(getDataSource()); + int insertCount = jdbcTemplate.queryForObject("select count(1) from " + + this.getDbSchemaName() + + "concept_dimension where upload_id =?", Integer.class, + new Object[] { uploadId }); + return insertCount; + } + + /** + * Function to backup and clear concept dimension table using stored proc. + * + * @param tempTableName + * @throws Exception + */ + @Override + public void backupAndSyncConceptDimensionTable(String tempConceptTableName, + String backupConceptDimensionTableName, int uploadId) + throws I2B2Exception { + Connection conn = null; + try { + conn = getDataSource().getConnection(); + CallableStatement callStmt = conn.prepareCall("{call " + + this.getDbSchemaName() + + "SYNC_CLEAR_CONCEPT_TABLE(?,?,?,?)}"); + callStmt.setString(1, tempConceptTableName); + callStmt.setString(2, backupConceptDimensionTableName); + callStmt.setInt(3, uploadId); + callStmt.registerOutParameter(4, java.sql.Types.VARCHAR); + callStmt.execute(); + this.getSQLServerProcedureError(dataSourceLookup.getServerType(), + callStmt, 4); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + throw new I2B2Exception( + "SQLException occured" + sqlEx.getMessage(), sqlEx); + } catch (Exception ex) { + ex.printStackTrace(); + throw new I2B2Exception("Exception occured" + ex.getMessage(), ex); + } finally { + if (conn != null) { + try { + conn.close(); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + log.error("Error while closing connection", sqlEx); + } + } + } + } + + /** + * Patient_Mapping insert code. + */ + protected class TempConceptInsert extends BatchSqlUpdate { + + /** + * Create a new instance of Patient_MappingInsert. + * + * @param ds + * the DataSource to use for the insert + */ + protected TempConceptInsert(DataSource ds, String tempTableName, + String dbSchemaName) { + + super(ds, "INSERT INTO " + dbSchemaName + tempTableName + " (" + + "CONCEPT_CD," + "CONCEPT_PATH," + "NAME_CHAR," + + "CONCEPT_BLOB," + "UPDATE_DATE," + "DOWNLOAD_DATE," + + "IMPORT_DATE," + "SOURCESYSTEM_CD" + ")" + + " VALUES(?,?,?,?,?,?,?,?)"); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.TIMESTAMP)); + declareParameter(new SqlParameter(Types.TIMESTAMP)); + declareParameter(new SqlParameter(Types.TIMESTAMP)); + declareParameter(new SqlParameter(Types.VARCHAR)); + compile(); + } + + protected void insert(ConceptType concept) { + + // do self insert + Object[] objs = new Object[] { + concept.getConceptCd(), + concept.getConceptPath(), + concept.getNameChar(), + (concept.getConceptBlob() != null) ? concept + .getConceptBlob().getContent().get(0) : null, + (concept.getUpdateDate() != null) ? concept.getUpdateDate() + .toGregorianCalendar().getTime() : null, + (concept.getDownloadDate() != null) ? concept + .getDownloadDate().toGregorianCalendar().getTime() + : null, + (concept.getImportDate() != null) ? concept.getImportDate() + .toGregorianCalendar().getTime() : null, + concept.getSourcesystemCd() }; + super.update(objs); + } + + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/DataSourceLookupDAO.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/DataSourceLookupDAO.java old mode 100755 new mode 100644 similarity index 98% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/DataSourceLookupDAO.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/DataSourceLookupDAO.java index 7b963aba..0e0a5143 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/DataSourceLookupDAO.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/DataSourceLookupDAO.java @@ -1,23 +1,23 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.dao; - -import java.util.List; - -import org.springframework.jdbc.core.JdbcTemplate; - -import edu.harvard.i2b2.crc.loader.datavo.loader.DataSourceLookup; - -public abstract class DataSourceLookupDAO extends JdbcTemplate { - public abstract List getDbLookupByHiveOwner(String hiveId,String ownerId); - //public abstract DataSourceLookup getDataSourceByHiveProjectOwner(String hive,String projectId, String owner); - public abstract List getDbLookupByHiveProjectOwner(String hiveId, String projectId, - String ownerId); - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.dao; + +import java.util.List; + +import org.springframework.jdbc.core.JdbcTemplate; + +import edu.harvard.i2b2.crc.loader.datavo.loader.DataSourceLookup; + +public abstract class DataSourceLookupDAO extends JdbcTemplate { + public abstract List getDbLookupByHiveOwner(String hiveId,String ownerId); + //public abstract DataSourceLookup getDataSourceByHiveProjectOwner(String hive,String projectId, String owner); + public abstract List getDbLookupByHiveProjectOwner(String hiveId, String projectId, + String ownerId); + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/DataSourceLookupDAOFactory.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/DataSourceLookupDAOFactory.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/DataSourceLookupDAOFactory.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/DataSourceLookupDAOFactory.java index 5448cf47..392b4e43 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/DataSourceLookupDAOFactory.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/DataSourceLookupDAOFactory.java @@ -1,104 +1,104 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.dao; - -import java.sql.Connection; -import java.sql.SQLException; - -import javax.sql.DataSource; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.ServiceLocator; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - -public class DataSourceLookupDAOFactory { - - /** log **/ - protected final static Log log = LogFactory.getLog(DataSourceLookupDAOFactory.class); - - public static final String ORACLE = "ORACLE"; - public static final String SQLSERVER = "MICROSOFT SQL SERVER"; - public static final String POSTGRESQL = "POSTGRESQL"; - - //private static String dataSourceName = null; - private static String serverType = null; - private static String schemaName = null; - private static DataSource lookupDataSource = null; - private static ServiceLocator serviceLocator = ServiceLocator.getInstance(); - //private static CRCLoaderUtil crcUtil = CRCLoaderUtil.getInstance(); - - public static DataSourceLookupDAO getDataSourceLookupDAO() - throws I2B2DAOException { - if (serverType == null) { - getLookupDataSourceFromPropertyFile(); - } - if (serverType.equalsIgnoreCase(ORACLE)) { - return new OracleDataSourceLookupDAO(lookupDataSource, schemaName); - } else if (serverType.equalsIgnoreCase(SQLSERVER)) { - return new OracleDataSourceLookupDAO(lookupDataSource, - schemaName); - } else if (serverType.equalsIgnoreCase(POSTGRESQL)) { - return new OracleDataSourceLookupDAO(lookupDataSource, - schemaName); - } else { - throw new I2B2DAOException("DataSourceLookupDAOFactory.getDataSourceLookupDAO: serverType=" + serverType + " not valid"); - } - } - - - private static void getLookupDataSourceFromPropertyFile() - throws I2B2DAOException { - QueryProcessorUtil crcUtil = QueryProcessorUtil.getInstance(); - try { - //dataSourceName = crcUtil.getCRCDBLookupDataSource(); - //serverType = crcUtil.getCRCDBLookupServerType(); - //schemaName = crcUtil.getCRCDBLookupSchemaName(); - lookupDataSource = crcUtil - .getDataSource("java:/CRCBootStrapDS"); - Connection conn = lookupDataSource.getConnection(); - - serverType = conn.getMetaData().getDatabaseProductName().toUpperCase(); - schemaName = conn.getSchema(); - conn.close(); - } catch (I2B2Exception i2b2Ex) { - log.error( - "DataSourceLookupDAOFactory.getLookupDataSourceFromPropertyFile" - + i2b2Ex.getMessage(), i2b2Ex); - throw new I2B2DAOException( - "DataSourceLookupDAOFactory.getLookupDataSourceFromPropertyFile" - + i2b2Ex.getMessage(), i2b2Ex); - } catch (SQLException e) { - // TODO Auto-generated catch block - throw new I2B2DAOException( - "DataSourceLookupDAOFactory.getLookupDataSourceFromPropertyFile SQL Error" - + e.getMessage(), e); - } - } - /* - private static void getLookupDataSourceFromPropertyFile() throws I2B2DAOException { - CRCLoaderUtil crcUtil = CRCLoaderUtil.getInstance(); - try { - dataSourceName = crcUtil.getCRCDBLookupDataSource(); - serverType = crcUtil.getCRCDBLookupServerType(); - schemaName = crcUtil.getCRCDBLookupSchemaName(); - lookupDataSource = (DataSource) crcUtil.getSpringDataSource(dataSourceName); - } catch (I2B2Exception i2b2Ex) { - log.error( - "DataSourceLookupDAOFactory.getLookupDataSourceFromPropertyFile" - + i2b2Ex.getMessage(), i2b2Ex); - throw new I2B2DAOException("DataSourceLookupDAOFactory.getLookupDataSourceFromPropertyFile" - + i2b2Ex.getMessage(), i2b2Ex); - } - } - */ -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.dao; + +import java.sql.Connection; +import java.sql.SQLException; + +import javax.sql.DataSource; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.ServiceLocator; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + +public class DataSourceLookupDAOFactory { + + /** log **/ + protected final static Log log = LogFactory.getLog(DataSourceLookupDAOFactory.class); + + public static final String ORACLE = "ORACLE"; + public static final String SQLSERVER = "MICROSOFT SQL SERVER"; + public static final String POSTGRESQL = "POSTGRESQL"; + + //private static String dataSourceName = null; + private static String serverType = null; + private static String schemaName = null; + private static DataSource lookupDataSource = null; + private static ServiceLocator serviceLocator = ServiceLocator.getInstance(); + //private static CRCLoaderUtil crcUtil = CRCLoaderUtil.getInstance(); + + public static DataSourceLookupDAO getDataSourceLookupDAO() + throws I2B2DAOException { + if (serverType == null) { + getLookupDataSourceFromPropertyFile(); + } + if (serverType.equalsIgnoreCase(ORACLE)) { + return new OracleDataSourceLookupDAO(lookupDataSource, schemaName); + } else if (serverType.equalsIgnoreCase(SQLSERVER)) { + return new OracleDataSourceLookupDAO(lookupDataSource, + schemaName); + } else if (serverType.equalsIgnoreCase(POSTGRESQL)) { + return new OracleDataSourceLookupDAO(lookupDataSource, + schemaName); + } else { + throw new I2B2DAOException("DataSourceLookupDAOFactory.getDataSourceLookupDAO: serverType=" + serverType + " not valid"); + } + } + + + private static void getLookupDataSourceFromPropertyFile() + throws I2B2DAOException { + QueryProcessorUtil crcUtil = QueryProcessorUtil.getInstance(); + try { + //dataSourceName = crcUtil.getCRCDBLookupDataSource(); + //serverType = crcUtil.getCRCDBLookupServerType(); + //schemaName = crcUtil.getCRCDBLookupSchemaName(); + lookupDataSource = crcUtil + .getDataSource("java:/CRCBootStrapDS"); + Connection conn = lookupDataSource.getConnection(); + + serverType = conn.getMetaData().getDatabaseProductName().toUpperCase(); + schemaName = conn.getSchema(); + conn.close(); + } catch (I2B2Exception i2b2Ex) { + log.error( + "DataSourceLookupDAOFactory.getLookupDataSourceFromPropertyFile" + + i2b2Ex.getMessage(), i2b2Ex); + throw new I2B2DAOException( + "DataSourceLookupDAOFactory.getLookupDataSourceFromPropertyFile" + + i2b2Ex.getMessage(), i2b2Ex); + } catch (SQLException e) { + // TODO Auto-generated catch block + throw new I2B2DAOException( + "DataSourceLookupDAOFactory.getLookupDataSourceFromPropertyFile SQL Error" + + e.getMessage(), e); + } + } + /* + private static void getLookupDataSourceFromPropertyFile() throws I2B2DAOException { + CRCLoaderUtil crcUtil = CRCLoaderUtil.getInstance(); + try { + dataSourceName = crcUtil.getCRCDBLookupDataSource(); + serverType = crcUtil.getCRCDBLookupServerType(); + schemaName = crcUtil.getCRCDBLookupSchemaName(); + lookupDataSource = (DataSource) crcUtil.getSpringDataSource(dataSourceName); + } catch (I2B2Exception i2b2Ex) { + log.error( + "DataSourceLookupDAOFactory.getLookupDataSourceFromPropertyFile" + + i2b2Ex.getMessage(), i2b2Ex); + throw new I2B2DAOException("DataSourceLookupDAOFactory.getLookupDataSourceFromPropertyFile" + + i2b2Ex.getMessage(), i2b2Ex); + } + } + */ +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/DataSourceLookupHelper.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/DataSourceLookupHelper.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/DataSourceLookupHelper.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/DataSourceLookupHelper.java index 39627f3b..a3cfae63 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/DataSourceLookupHelper.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/DataSourceLookupHelper.java @@ -1,165 +1,165 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.dao; - -import java.util.List; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.crc.loader.datavo.loader.DataSourceLookup; -import edu.harvard.i2b2.crc.loader.delegate.pm.PMResponseMessage; - - -public class DataSourceLookupHelper { - - /** log **/ - protected final static Log log = LogFactory.getLog(DataSourceLookupHelper.class); - protected static Log logesapi = LogFactory.getLog(DataSourceLookupHelper.class); - - private DataSourceLookupDAO dsLookupDao = null; - - public DataSourceLookupHelper() throws I2B2Exception { - - dsLookupDao = DataSourceLookupDAOFactory.getDataSourceLookupDAO(); - } - - public DataSourceLookup matchDataSource(String hiveId, String projectId, - String ownerId) throws I2B2Exception { - DataSourceLookup matchedDataSourceLookup = null; - List dataSourceLookupList = null; - if (projectId == null) { - throw new I2B2Exception(" Project id is null, could not perform datasource lookup for given domain["+hiveId+"] and owner[" + ownerId+"]"); - } - - if (projectId.equals("@")) { - matchedDataSourceLookup = matchHiveOwner(hiveId,ownerId); - return matchedDataSourceLookup; - } - - //check if project id contains subprojects, if so then query by first level subproject - if (projectId.endsWith("/") == false) { - projectId += "/"; - } - if (projectId.startsWith("/") == false) { - projectId = "/" + projectId; - } - String[] projectSplit = projectId.split("/"); - String filterProjectId = ""; - if (projectSplit.length>2) { - filterProjectId = "/" + projectSplit[1] + "/" + projectSplit[2] + "/"; - } - else { - filterProjectId = "/" + projectSplit[1] + "/"; - } - dataSourceLookupList = dsLookupDao.getDbLookupByHiveProjectOwner(hiveId, filterProjectId, ownerId); - //if the project path with two level fails then try with one level - if (dataSourceLookupList.size()<1) { - filterProjectId = "/" + projectSplit[1] + "/"; - dataSourceLookupList = dsLookupDao.getDbLookupByHiveProjectOwner(hiveId, filterProjectId, ownerId); - } - if (dataSourceLookupList.size()>0) { - DataSourceLookup matchedDataSource = null; - int projectLevel = projectId.length(); - boolean matchedFlag = false; - String parentProjectId=null; - while ((projectLevel=projectId.lastIndexOf('/', projectLevel))>0) { - parentProjectId = projectId.substring(0, projectLevel+1); - logesapi.debug("Trying with project id :" + parentProjectId); - matchedDataSource = match(parentProjectId,ownerId,dataSourceLookupList); - if (matchedDataSource != null) { - matchedFlag = true; - break; - } - - projectLevel = projectId.lastIndexOf('/', projectLevel-1); - } - if (matchedFlag) { - if (ownerId.equalsIgnoreCase(matchedDataSource.getOwnerId())) { - logesapi.info("Located DataSource for hiveId=[" + hiveId + - "] projectId=[" + parentProjectId + "] and ownerId =[" + - ownerId + "]"); - } else { - logesapi.info("Located DataSource for hiveId=[" + hiveId + - "] projectId=[" + parentProjectId + "]"); - - } - return matchedDataSource; - - } - else { - logesapi.info("Could not match Project id=[" + projectId+"] Trying with hive =" + hiveId); - matchedDataSourceLookup = matchHiveOwner(hiveId,ownerId); - return matchedDataSourceLookup; - } - - } else { - logesapi.info("Could not match Project id=[" + projectId+"] Trying with hive =" + hiveId); - matchedDataSourceLookup = matchHiveOwner(hiveId,ownerId); - return matchedDataSourceLookup; - } - - - - } - - private DataSourceLookup matchHiveOwner(String hiveId,String ownerId) throws I2B2Exception { - DataSourceLookup matchedDataSourceLookup = null; - //check for hive and owner (userid or @) - List dataSourceLookupList = dsLookupDao.getDbLookupByHiveOwner(hiveId, ownerId); - if (dataSourceLookupList.size() == 0 ) { - throw new I2B2Exception("Could not locate hive= " + hiveId); - } - else if (dataSourceLookupList.size() >0) { - boolean matchedFlag = false; - - for (DataSourceLookup dsLookup : dataSourceLookupList) { - if(dsLookup.getOwnerId() != null && dsLookup.getOwnerId().equalsIgnoreCase(ownerId)) { - matchedDataSourceLookup = dsLookup; - matchedFlag = true; - break; - } - else if (dsLookup.getOwnerId() !=null && dsLookup.getOwnerId().equals("@")) { - matchedDataSourceLookup = dsLookup; - } - } - if (matchedFlag) { - logesapi.info("Located Datasource matching hive=[" + hiveId + "] and owner=[" + ownerId + "]"); - } else if (matchedDataSourceLookup != null) { - logesapi.info("Located Datasource matching hive=[" + hiveId + " and owner =[@]"); - } else { - throw new I2B2Exception("Could not locate Datasource matching hive=[" + hiveId + "] and owner=["+ ownerId + " or @]"); - } - } - return matchedDataSourceLookup; - } - - private DataSourceLookup match(String searchProjectId,String owner, List dataSourceLookupList) { - DataSourceLookup matchedDataSource = null; - - for (DataSourceLookup dataSourceLookup : dataSourceLookupList) { - String lookupProjectId = dataSourceLookup.getProjectPath(); - String lookupOwnerId = dataSourceLookup.getOwnerId(); - if (searchProjectId.equalsIgnoreCase(lookupProjectId)) { - matchedDataSource = dataSourceLookup; - if (owner.equalsIgnoreCase(lookupOwnerId)) { - break; - } - - - } - } - return matchedDataSource; - } - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.dao; + +import java.util.List; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.crc.loader.datavo.loader.DataSourceLookup; +import edu.harvard.i2b2.crc.loader.delegate.pm.PMResponseMessage; + + +public class DataSourceLookupHelper { + + /** log **/ + protected final static Log log = LogFactory.getLog(DataSourceLookupHelper.class); + protected static Log logesapi = LogFactory.getLog(DataSourceLookupHelper.class); + + private DataSourceLookupDAO dsLookupDao = null; + + public DataSourceLookupHelper() throws I2B2Exception { + + dsLookupDao = DataSourceLookupDAOFactory.getDataSourceLookupDAO(); + } + + public DataSourceLookup matchDataSource(String hiveId, String projectId, + String ownerId) throws I2B2Exception { + DataSourceLookup matchedDataSourceLookup = null; + List dataSourceLookupList = null; + if (projectId == null) { + throw new I2B2Exception(" Project id is null, could not perform datasource lookup for given domain["+hiveId+"] and owner[" + ownerId+"]"); + } + + if (projectId.equals("@")) { + matchedDataSourceLookup = matchHiveOwner(hiveId,ownerId); + return matchedDataSourceLookup; + } + + //check if project id contains subprojects, if so then query by first level subproject + if (projectId.endsWith("/") == false) { + projectId += "/"; + } + if (projectId.startsWith("/") == false) { + projectId = "/" + projectId; + } + String[] projectSplit = projectId.split("/"); + String filterProjectId = ""; + if (projectSplit.length>2) { + filterProjectId = "/" + projectSplit[1] + "/" + projectSplit[2] + "/"; + } + else { + filterProjectId = "/" + projectSplit[1] + "/"; + } + dataSourceLookupList = dsLookupDao.getDbLookupByHiveProjectOwner(hiveId, filterProjectId, ownerId); + //if the project path with two level fails then try with one level + if (dataSourceLookupList.size()<1) { + filterProjectId = "/" + projectSplit[1] + "/"; + dataSourceLookupList = dsLookupDao.getDbLookupByHiveProjectOwner(hiveId, filterProjectId, ownerId); + } + if (dataSourceLookupList.size()>0) { + DataSourceLookup matchedDataSource = null; + int projectLevel = projectId.length(); + boolean matchedFlag = false; + String parentProjectId=null; + while ((projectLevel=projectId.lastIndexOf('/', projectLevel))>0) { + parentProjectId = projectId.substring(0, projectLevel+1); + logesapi.debug("Trying with project id :" + parentProjectId); + matchedDataSource = match(parentProjectId,ownerId,dataSourceLookupList); + if (matchedDataSource != null) { + matchedFlag = true; + break; + } + + projectLevel = projectId.lastIndexOf('/', projectLevel-1); + } + if (matchedFlag) { + if (ownerId.equalsIgnoreCase(matchedDataSource.getOwnerId())) { + logesapi.info("Located DataSource for hiveId=[" + hiveId + + "] projectId=[" + parentProjectId + "] and ownerId =[" + + ownerId + "]"); + } else { + logesapi.info("Located DataSource for hiveId=[" + hiveId + + "] projectId=[" + parentProjectId + "]"); + + } + return matchedDataSource; + + } + else { + logesapi.info("Could not match Project id=[" + projectId+"] Trying with hive =" + hiveId); + matchedDataSourceLookup = matchHiveOwner(hiveId,ownerId); + return matchedDataSourceLookup; + } + + } else { + logesapi.info("Could not match Project id=[" + projectId+"] Trying with hive =" + hiveId); + matchedDataSourceLookup = matchHiveOwner(hiveId,ownerId); + return matchedDataSourceLookup; + } + + + + } + + private DataSourceLookup matchHiveOwner(String hiveId,String ownerId) throws I2B2Exception { + DataSourceLookup matchedDataSourceLookup = null; + //check for hive and owner (userid or @) + List dataSourceLookupList = dsLookupDao.getDbLookupByHiveOwner(hiveId, ownerId); + if (dataSourceLookupList.size() == 0 ) { + throw new I2B2Exception("Could not locate hive= " + hiveId); + } + else if (dataSourceLookupList.size() >0) { + boolean matchedFlag = false; + + for (DataSourceLookup dsLookup : dataSourceLookupList) { + if(dsLookup.getOwnerId() != null && dsLookup.getOwnerId().equalsIgnoreCase(ownerId)) { + matchedDataSourceLookup = dsLookup; + matchedFlag = true; + break; + } + else if (dsLookup.getOwnerId() !=null && dsLookup.getOwnerId().equals("@")) { + matchedDataSourceLookup = dsLookup; + } + } + if (matchedFlag) { + logesapi.info("Located Datasource matching hive=[" + hiveId + "] and owner=[" + ownerId + "]"); + } else if (matchedDataSourceLookup != null) { + logesapi.info("Located Datasource matching hive=[" + hiveId + " and owner =[@]"); + } else { + throw new I2B2Exception("Could not locate Datasource matching hive=[" + hiveId + "] and owner=["+ ownerId + " or @]"); + } + } + return matchedDataSourceLookup; + } + + private DataSourceLookup match(String searchProjectId,String owner, List dataSourceLookupList) { + DataSourceLookup matchedDataSource = null; + + for (DataSourceLookup dataSourceLookup : dataSourceLookupList) { + String lookupProjectId = dataSourceLookup.getProjectPath(); + String lookupOwnerId = dataSourceLookup.getOwnerId(); + if (searchProjectId.equalsIgnoreCase(lookupProjectId)) { + matchedDataSource = dataSourceLookup; + if (owner.equalsIgnoreCase(lookupOwnerId)) { + break; + } + + + } + } + return matchedDataSource; + } + + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/EidDAO.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/EidDAO.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/EidDAO.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/EidDAO.java index 08b86fce..974dec79 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/EidDAO.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/EidDAO.java @@ -1,235 +1,235 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.dao; - -import java.sql.CallableStatement; -import java.sql.Connection; -import java.sql.SQLException; -import java.sql.Types; -import java.util.List; - -import javax.sql.DataSource; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.SqlParameter; -import org.springframework.jdbc.object.BatchSqlUpdate; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.crc.loader.datavo.loader.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.pdo.EidType; -import edu.harvard.i2b2.crc.datavo.pdo.EidType.EventMapId; - -/** - * Patient Dimension data access object. - * - * @author rk903 - */ -public class EidDAO extends CRCLoaderDAO implements IEidDAO { - - private int DB_BATCH_INSERT_SIZE = 1; - - private static Log log = LogFactory.getLog(EidDAO.class); - private DataSourceLookup dataSourceLookup = null; - - public EidDAO(DataSourceLookup dataSourceLookup, DataSource ds) { - setDataSource(ds); - setDbSchemaName(dataSourceLookup.getFullSchema()); - this.dataSourceLookup = dataSourceLookup; - } - - @Override - public int getRecordCountByUploadId(int uploadId) { - JdbcTemplate jdbcTemplate = new JdbcTemplate(getDataSource()); - int insertCount = jdbcTemplate.queryForObject("select count(1) from " - + getDbSchemaName() + " encounter_mapping where upload_id =?", Integer.class, - new Object[] { uploadId }); - return insertCount; - } - - /** - * Function to create temp visit dimension table using stored proc. - * - * @param tempTableName - * @throws Exception - */ - @Override - public void createTempTable(String tempEncounterMappingTableName) - throws I2B2Exception { - Connection conn = null; - try { - conn = getDataSource().getConnection(); - CallableStatement callStmt = conn.prepareCall("{call " - + getDbSchemaName() + "CREATE_TEMP_EID_TABLE(?,?)}"); - callStmt.setString(1, tempEncounterMappingTableName); - callStmt.registerOutParameter(2, java.sql.Types.VARCHAR); - callStmt.execute(); - this.getSQLServerProcedureError(dataSourceLookup.getServerType(), - callStmt, 2); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - throw new I2B2Exception( - "SQLException occured" + sqlEx.getMessage(), sqlEx); - } catch (Exception ex) { - ex.printStackTrace(); - throw new I2B2Exception("Exception occured" + ex.getMessage(), ex); - } finally { - if (conn != null) { - try { - conn.close(); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - log.error("Error while closing connection", sqlEx); - } - } - } - } - - /** - * Create batch insert handle for temp observation fact table. - * - * @param tempTableName - * @return - */ - @Override - public TempEidInsertHandler createTempEidInsert(String tempTableName) { - TempEidInsert tempEidInsert = new TempEidInsert(getDataSource(), - tempTableName, this.getDbSchemaName()); - tempEidInsert.setBatchSize(DB_BATCH_INSERT_SIZE); - return new TempEidInsertHandler(tempEidInsert); - } - - /** - * Function to create new encounter/visit from temp_visit_dimension table - * using stored proc. - * - * @param tempTableName - * @throws Exception - */ - @Override - public void createEidFromTempTable(String tempMapTableName, int uploadId) - throws I2B2Exception { - Connection conn = null; - try { - conn = getDataSource().getConnection(); - CallableStatement callStmt = conn.prepareCall("{call " - + this.getDbSchemaName() - + "INSERT_EID_MAP_FROMTEMP(?,?,?)}"); - callStmt.setString(1, tempMapTableName); - callStmt.setInt(2, uploadId); - callStmt.registerOutParameter(3, java.sql.Types.VARCHAR); - callStmt.execute(); - this.getSQLServerProcedureError(dataSourceLookup.getServerType(), - callStmt, 3); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - throw new I2B2Exception( - "SQLException occured" + sqlEx.getMessage(), sqlEx); - } catch (Exception ex) { - ex.printStackTrace(); - throw new I2B2Exception("Exception occured" + ex.getMessage(), ex); - } finally { - if (conn != null) { - try { - conn.close(); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - log.error("Error while closing connection", sqlEx); - } - } - } - } - - /** - * Patient_Mapping insert code. - */ - protected class TempEidInsert extends BatchSqlUpdate { - - /** - * Create a new instance of Patient_MappingInsert. - * - * @param ds - * the DataSource to use for the insert - */ - protected TempEidInsert(DataSource ds, String tempTableName, - String schemaName) { - - super( - ds, - "INSERT INTO " - + schemaName - + tempTableName - + " (" - + "encounter_map_id, encounter_map_id_source, patient_map_id," - + "patient_map_id_source, encounter_id, " - + "encounter_id_source, " - + "ENCOUNTER_MAP_ID_STATUS ," + " UPDATE_DATE, " - + "DOWNLOAD_DATE," + " SOURCESYSTEM_CD )" - + " VALUES(?,?,?,?,?,?,?,?,?,?)"); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.TIMESTAMP)); - declareParameter(new SqlParameter(Types.TIMESTAMP)); - declareParameter(new SqlParameter(Types.VARCHAR)); - compile(); - } - - protected void insert(EidType eid) { - List mapIdList = eid.getEventMapId(); - String encounterId = eid.getEventId().getValue(); - String encounterIdSource = eid.getEventId().getSource(); - String encounterPatientId = eid.getEventId().getPatientId(); - String encounterPatientIdSource = eid.getEventId() - .getPatientIdSource(); - - for (EventMapId mapId : mapIdList) { - - Object[] objs = new Object[] { - mapId.getValue(), - mapId.getSource(), - mapId.getPatientId(), - mapId.getPatientIdSource(), - encounterId, - encounterIdSource, - mapId.getStatus(), - (mapId.getUpdateDate() != null) ? mapId.getUpdateDate() - .toGregorianCalendar().getTime() : null, - (mapId.getDownloadDate() != null) ? mapId - .getDownloadDate().toGregorianCalendar() - .getTime() : null, mapId.getSourcesystemCd() }; - super.update(objs); - } - // do self insert - Object[] objs = new Object[] { - encounterId, - encounterIdSource, - encounterPatientId, - encounterPatientIdSource, - encounterId, - encounterIdSource, - eid.getEventId().getStatus(), - (eid.getEventId().getUpdateDate() != null) ? eid - .getEventId().getUpdateDate().toGregorianCalendar() - .getTime() : null, - (eid.getEventId().getDownloadDate() != null) ? eid - .getEventId().getDownloadDate() - .toGregorianCalendar().getTime() : null, - eid.getEventId().getSourcesystemCd() }; - super.update(objs); - } - - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.dao; + +import java.sql.CallableStatement; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.Types; +import java.util.List; + +import javax.sql.DataSource; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.SqlParameter; +import org.springframework.jdbc.object.BatchSqlUpdate; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.crc.loader.datavo.loader.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.pdo.EidType; +import edu.harvard.i2b2.crc.datavo.pdo.EidType.EventMapId; + +/** + * Patient Dimension data access object. + * + * @author rk903 + */ +public class EidDAO extends CRCLoaderDAO implements IEidDAO { + + private int DB_BATCH_INSERT_SIZE = 1; + + private static Log log = LogFactory.getLog(EidDAO.class); + private DataSourceLookup dataSourceLookup = null; + + public EidDAO(DataSourceLookup dataSourceLookup, DataSource ds) { + setDataSource(ds); + setDbSchemaName(dataSourceLookup.getFullSchema()); + this.dataSourceLookup = dataSourceLookup; + } + + @Override + public int getRecordCountByUploadId(int uploadId) { + JdbcTemplate jdbcTemplate = new JdbcTemplate(getDataSource()); + int insertCount = jdbcTemplate.queryForObject("select count(1) from " + + getDbSchemaName() + " encounter_mapping where upload_id =?", Integer.class, + new Object[] { uploadId }); + return insertCount; + } + + /** + * Function to create temp visit dimension table using stored proc. + * + * @param tempTableName + * @throws Exception + */ + @Override + public void createTempTable(String tempEncounterMappingTableName) + throws I2B2Exception { + Connection conn = null; + try { + conn = getDataSource().getConnection(); + CallableStatement callStmt = conn.prepareCall("{call " + + getDbSchemaName() + "CREATE_TEMP_EID_TABLE(?,?)}"); + callStmt.setString(1, tempEncounterMappingTableName); + callStmt.registerOutParameter(2, java.sql.Types.VARCHAR); + callStmt.execute(); + this.getSQLServerProcedureError(dataSourceLookup.getServerType(), + callStmt, 2); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + throw new I2B2Exception( + "SQLException occured" + sqlEx.getMessage(), sqlEx); + } catch (Exception ex) { + ex.printStackTrace(); + throw new I2B2Exception("Exception occured" + ex.getMessage(), ex); + } finally { + if (conn != null) { + try { + conn.close(); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + log.error("Error while closing connection", sqlEx); + } + } + } + } + + /** + * Create batch insert handle for temp observation fact table. + * + * @param tempTableName + * @return + */ + @Override + public TempEidInsertHandler createTempEidInsert(String tempTableName) { + TempEidInsert tempEidInsert = new TempEidInsert(getDataSource(), + tempTableName, this.getDbSchemaName()); + tempEidInsert.setBatchSize(DB_BATCH_INSERT_SIZE); + return new TempEidInsertHandler(tempEidInsert); + } + + /** + * Function to create new encounter/visit from temp_visit_dimension table + * using stored proc. + * + * @param tempTableName + * @throws Exception + */ + @Override + public void createEidFromTempTable(String tempMapTableName, int uploadId) + throws I2B2Exception { + Connection conn = null; + try { + conn = getDataSource().getConnection(); + CallableStatement callStmt = conn.prepareCall("{call " + + this.getDbSchemaName() + + "INSERT_EID_MAP_FROMTEMP(?,?,?)}"); + callStmt.setString(1, tempMapTableName); + callStmt.setInt(2, uploadId); + callStmt.registerOutParameter(3, java.sql.Types.VARCHAR); + callStmt.execute(); + this.getSQLServerProcedureError(dataSourceLookup.getServerType(), + callStmt, 3); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + throw new I2B2Exception( + "SQLException occured" + sqlEx.getMessage(), sqlEx); + } catch (Exception ex) { + ex.printStackTrace(); + throw new I2B2Exception("Exception occured" + ex.getMessage(), ex); + } finally { + if (conn != null) { + try { + conn.close(); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + log.error("Error while closing connection", sqlEx); + } + } + } + } + + /** + * Patient_Mapping insert code. + */ + protected class TempEidInsert extends BatchSqlUpdate { + + /** + * Create a new instance of Patient_MappingInsert. + * + * @param ds + * the DataSource to use for the insert + */ + protected TempEidInsert(DataSource ds, String tempTableName, + String schemaName) { + + super( + ds, + "INSERT INTO " + + schemaName + + tempTableName + + " (" + + "encounter_map_id, encounter_map_id_source, patient_map_id," + + "patient_map_id_source, encounter_id, " + + "encounter_id_source, " + + "ENCOUNTER_MAP_ID_STATUS ," + " UPDATE_DATE, " + + "DOWNLOAD_DATE," + " SOURCESYSTEM_CD )" + + " VALUES(?,?,?,?,?,?,?,?,?,?)"); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.TIMESTAMP)); + declareParameter(new SqlParameter(Types.TIMESTAMP)); + declareParameter(new SqlParameter(Types.VARCHAR)); + compile(); + } + + protected void insert(EidType eid) { + List mapIdList = eid.getEventMapId(); + String encounterId = eid.getEventId().getValue(); + String encounterIdSource = eid.getEventId().getSource(); + String encounterPatientId = eid.getEventId().getPatientId(); + String encounterPatientIdSource = eid.getEventId() + .getPatientIdSource(); + + for (EventMapId mapId : mapIdList) { + + Object[] objs = new Object[] { + mapId.getValue(), + mapId.getSource(), + mapId.getPatientId(), + mapId.getPatientIdSource(), + encounterId, + encounterIdSource, + mapId.getStatus(), + (mapId.getUpdateDate() != null) ? mapId.getUpdateDate() + .toGregorianCalendar().getTime() : null, + (mapId.getDownloadDate() != null) ? mapId + .getDownloadDate().toGregorianCalendar() + .getTime() : null, mapId.getSourcesystemCd() }; + super.update(objs); + } + // do self insert + Object[] objs = new Object[] { + encounterId, + encounterIdSource, + encounterPatientId, + encounterPatientIdSource, + encounterId, + encounterIdSource, + eid.getEventId().getStatus(), + (eid.getEventId().getUpdateDate() != null) ? eid + .getEventId().getUpdateDate().toGregorianCalendar() + .getTime() : null, + (eid.getEventId().getDownloadDate() != null) ? eid + .getEventId().getDownloadDate() + .toGregorianCalendar().getTime() : null, + eid.getEventId().getSourcesystemCd() }; + super.update(objs); + } + + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/IConceptDAO.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/IConceptDAO.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/IConceptDAO.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/IConceptDAO.java index 2f6184fe..7bf5aff1 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/IConceptDAO.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/IConceptDAO.java @@ -1,54 +1,54 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.dao; - -import edu.harvard.i2b2.common.exception.I2B2Exception; - -public interface IConceptDAO { - - /** - * Function to create temp visit dimension table using stored proc. - * - * @param tempTableName - * @throws Exception - */ - public void createTempTable(String tempPatientMappingTableName) - throws I2B2Exception; - - /** - * Create batch insert handle for temp observation fact table. - * - * @param tempTableName - * @return - */ - public TempConceptInsertHandler createTempConceptInsert(String tempTableName); - - /** - * Function to create new encounter/visit from temp_visit_dimension table - * using stored proc. - * - * @param tempTableName - * @throws Exception - */ - public void createConceptFromTempTable(String tempMapTableName, int uploadId) - throws I2B2Exception; - - public int getRecordCountByUploadId(int uploadId); - - /** - * Function to backup and clear concept dimension table using stored proc. - * - * @param tempTableName - * @throws Exception - */ - public void backupAndSyncConceptDimensionTable(String tempConceptTableName, - String backupConceptDimensionTableName, int uploadId) - throws I2B2Exception; - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.dao; + +import edu.harvard.i2b2.common.exception.I2B2Exception; + +public interface IConceptDAO { + + /** + * Function to create temp visit dimension table using stored proc. + * + * @param tempTableName + * @throws Exception + */ + public void createTempTable(String tempPatientMappingTableName) + throws I2B2Exception; + + /** + * Create batch insert handle for temp observation fact table. + * + * @param tempTableName + * @return + */ + public TempConceptInsertHandler createTempConceptInsert(String tempTableName); + + /** + * Function to create new encounter/visit from temp_visit_dimension table + * using stored proc. + * + * @param tempTableName + * @throws Exception + */ + public void createConceptFromTempTable(String tempMapTableName, int uploadId) + throws I2B2Exception; + + public int getRecordCountByUploadId(int uploadId); + + /** + * Function to backup and clear concept dimension table using stored proc. + * + * @param tempTableName + * @throws Exception + */ + public void backupAndSyncConceptDimensionTable(String tempConceptTableName, + String backupConceptDimensionTableName, int uploadId) + throws I2B2Exception; + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/IEidDAO.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/IEidDAO.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/IEidDAO.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/IEidDAO.java index b3d6562d..aa29b5e6 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/IEidDAO.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/IEidDAO.java @@ -1,44 +1,44 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.dao; - -import edu.harvard.i2b2.common.exception.I2B2Exception; - -public interface IEidDAO { - - public int getRecordCountByUploadId(int uploadId); - - /** - * Function to create temp visit dimension table using stored proc. - * - * @param tempTableName - * @throws Exception - */ - public void createTempTable(String tempEncounterMappingTableName) - throws I2B2Exception; - - /** - * Create batch insert handle for temp observation fact table. - * - * @param tempTableName - * @return - */ - public TempEidInsertHandler createTempEidInsert(String tempTableName); - - /** - * Function to create new encounter/visit from temp_visit_dimension table - * using stored proc. - * - * @param tempTableName - * @throws Exception - */ - public void createEidFromTempTable(String tempMapTableName, int uploadId) - throws I2B2Exception; - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.dao; + +import edu.harvard.i2b2.common.exception.I2B2Exception; + +public interface IEidDAO { + + public int getRecordCountByUploadId(int uploadId); + + /** + * Function to create temp visit dimension table using stored proc. + * + * @param tempTableName + * @throws Exception + */ + public void createTempTable(String tempEncounterMappingTableName) + throws I2B2Exception; + + /** + * Create batch insert handle for temp observation fact table. + * + * @param tempTableName + * @return + */ + public TempEidInsertHandler createTempEidInsert(String tempTableName); + + /** + * Function to create new encounter/visit from temp_visit_dimension table + * using stored proc. + * + * @param tempTableName + * @throws Exception + */ + public void createEidFromTempTable(String tempMapTableName, int uploadId) + throws I2B2Exception; + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/ILoaderDAOFactory.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/ILoaderDAOFactory.java old mode 100755 new mode 100644 similarity index 98% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/ILoaderDAOFactory.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/ILoaderDAOFactory.java index 597a83db..76d9517b --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/ILoaderDAOFactory.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/ILoaderDAOFactory.java @@ -1,15 +1,15 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.dao; - -import edu.harvard.i2b2.common.exception.I2B2Exception; - -public interface ILoaderDAOFactory { - public IUploaderDAOFactory getUpLoaderDAOFactory() throws I2B2Exception ; -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.dao; + +import edu.harvard.i2b2.common.exception.I2B2Exception; + +public interface ILoaderDAOFactory { + public IUploaderDAOFactory getUpLoaderDAOFactory() throws I2B2Exception ; +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/IMissingTermDAO.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/IMissingTermDAO.java old mode 100755 new mode 100644 similarity index 98% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/IMissingTermDAO.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/IMissingTermDAO.java index 375ffc3e..84d453f7 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/IMissingTermDAO.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/IMissingTermDAO.java @@ -1,28 +1,28 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.dao; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.crc.loader.datavo.loader.query.MissingCodesConceptSetType; -import edu.harvard.i2b2.crc.loader.datavo.loader.query.MissingCodesModifierSetType; -import edu.harvard.i2b2.crc.loader.datavo.loader.query.MissingCodesObserverSetType; -import edu.harvard.i2b2.crc.loader.datavo.loader.query.MissingTermSetReportType; - -public interface IMissingTermDAO { - - public MissingCodesConceptSetType getMissingConceptSet(int uploadId, int startPos, int endPos, boolean detailFlag) - throws I2B2DAOException ; - public MissingCodesObserverSetType getMissingObserverSet(int uploadId, int startPos, int endPos, boolean detailFlag) - throws I2B2DAOException ; - public MissingCodesModifierSetType getMissingModifierSet(int uploadId, int startPos, int endPos, boolean detailFlag) - throws I2B2DAOException ; - public MissingTermSetReportType getMissingTermReport(int uploadId, - String setName) throws I2B2DAOException; - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.dao; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.crc.loader.datavo.loader.query.MissingCodesConceptSetType; +import edu.harvard.i2b2.crc.loader.datavo.loader.query.MissingCodesModifierSetType; +import edu.harvard.i2b2.crc.loader.datavo.loader.query.MissingCodesObserverSetType; +import edu.harvard.i2b2.crc.loader.datavo.loader.query.MissingTermSetReportType; + +public interface IMissingTermDAO { + + public MissingCodesConceptSetType getMissingConceptSet(int uploadId, int startPos, int endPos, boolean detailFlag) + throws I2B2DAOException ; + public MissingCodesObserverSetType getMissingObserverSet(int uploadId, int startPos, int endPos, boolean detailFlag) + throws I2B2DAOException ; + public MissingCodesModifierSetType getMissingModifierSet(int uploadId, int startPos, int endPos, boolean detailFlag) + throws I2B2DAOException ; + public MissingTermSetReportType getMissingTermReport(int uploadId, + String setName) throws I2B2DAOException; + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/IModifierDAO.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/IModifierDAO.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/IModifierDAO.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/IModifierDAO.java index 373bc403..e64ddf46 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/IModifierDAO.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/IModifierDAO.java @@ -1,54 +1,54 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.dao; - -import edu.harvard.i2b2.common.exception.I2B2Exception; - -public interface IModifierDAO { - - /** - * Function to create temp modifier dimension table using stored proc. - * - * @param tempTableName - * @throws Exception - */ - public void createTempTable(String tempModifierMappingTableName) - throws I2B2Exception; - - /** - * Create batch insert handle for temp observation fact table. - * - * @param tempTableName - * @return - */ - public TempModifierInsertHandler createTempModifierInsert(String tempTableName); - - /** - * Function to create new encounter/visit from temp_modifier_dimension table - * using stored proc. - * - * @param tempTableName - * @throws Exception - */ - public void createModifierFromTempTable(String tempMapTableName, int uploadId) - throws I2B2Exception; - - public int getRecordCountByUploadId(int uploadId); - - /** - * Function to backup and clear concept dimension table using stored proc. - * - * @param tempTableName - * @throws Exception - */ - public void backupAndSyncModifierDimensionTable(String tempModifierTableName, - String backupModifierDimensionTableName, int uploadId) - throws I2B2Exception; - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.dao; + +import edu.harvard.i2b2.common.exception.I2B2Exception; + +public interface IModifierDAO { + + /** + * Function to create temp modifier dimension table using stored proc. + * + * @param tempTableName + * @throws Exception + */ + public void createTempTable(String tempModifierMappingTableName) + throws I2B2Exception; + + /** + * Create batch insert handle for temp observation fact table. + * + * @param tempTableName + * @return + */ + public TempModifierInsertHandler createTempModifierInsert(String tempTableName); + + /** + * Function to create new encounter/visit from temp_modifier_dimension table + * using stored proc. + * + * @param tempTableName + * @throws Exception + */ + public void createModifierFromTempTable(String tempMapTableName, int uploadId) + throws I2B2Exception; + + public int getRecordCountByUploadId(int uploadId); + + /** + * Function to backup and clear concept dimension table using stored proc. + * + * @param tempTableName + * @throws Exception + */ + public void backupAndSyncModifierDimensionTable(String tempModifierTableName, + String backupModifierDimensionTableName, int uploadId) + throws I2B2Exception; + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/IObservationFactDAO.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/IObservationFactDAO.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/IObservationFactDAO.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/IObservationFactDAO.java index 854b61fc..30ee406e --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/IObservationFactDAO.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/IObservationFactDAO.java @@ -1,65 +1,65 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.dao; - -import java.io.BufferedWriter; - -import edu.harvard.i2b2.common.exception.I2B2Exception; - -public interface IObservationFactDAO { - - public int getRecordCountByUploadId(int uploadId); - - /** - * Create batch insert handle for temp observation fact table. - * - * @param tempTableName - * @return - */ - public ObservationFactInsertHandle createObservationFactInserter( - String tempTableName); - - /** - * Function to check if given table exists - * - * @param tableName - * @return boolean - * @throws Exception - */ - public boolean checkTableExists(String tableName) throws I2B2Exception; - - /** - * Function to call MERGE_TEMP_OBSERVATION_FACT(?) stored procedure. - * - * @param tempTableName - * @throws Exception - */ - public void doTempTableMerge(String tempTableName, int uploadId, - boolean appendFlag) throws I2B2Exception; - - /** - * Function to call remove temp table stored procedure. - * - * @param tempTableName - * @throws Exception - */ - public void removeTempTable(String tempTableName) throws I2B2Exception; - - /** - * Function to create create temp table stored proc. - * - * @param tempTableName - * @throws Exception - */ - public void createTempTable(String tempTableName) throws I2B2Exception; - - public void writeMissedDataLog(BufferedWriter bufWriter, - String tempTableName) throws I2B2Exception; - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.dao; + +import java.io.BufferedWriter; + +import edu.harvard.i2b2.common.exception.I2B2Exception; + +public interface IObservationFactDAO { + + public int getRecordCountByUploadId(int uploadId); + + /** + * Create batch insert handle for temp observation fact table. + * + * @param tempTableName + * @return + */ + public ObservationFactInsertHandle createObservationFactInserter( + String tempTableName); + + /** + * Function to check if given table exists + * + * @param tableName + * @return boolean + * @throws Exception + */ + public boolean checkTableExists(String tableName) throws I2B2Exception; + + /** + * Function to call MERGE_TEMP_OBSERVATION_FACT(?) stored procedure. + * + * @param tempTableName + * @throws Exception + */ + public void doTempTableMerge(String tempTableName, int uploadId, + boolean appendFlag) throws I2B2Exception; + + /** + * Function to call remove temp table stored procedure. + * + * @param tempTableName + * @throws Exception + */ + public void removeTempTable(String tempTableName) throws I2B2Exception; + + /** + * Function to create create temp table stored proc. + * + * @param tempTableName + * @throws Exception + */ + public void createTempTable(String tempTableName) throws I2B2Exception; + + public void writeMissedDataLog(BufferedWriter bufWriter, + String tempTableName) throws I2B2Exception; + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/IObservatonFactDAO.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/IObservatonFactDAO.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/IObservatonFactDAO.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/IObservatonFactDAO.java index 81539fcb..77067b10 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/IObservatonFactDAO.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/IObservatonFactDAO.java @@ -1,65 +1,65 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.dao; - -import java.io.BufferedWriter; - -import edu.harvard.i2b2.common.exception.I2B2Exception; - -public interface IObservatonFactDAO { - - public int getRecordCountByUploadId(int uploadId); - - /** - * Create batch insert handle for temp observation fact table. - * - * @param tempTableName - * @return - */ - public ObservationFactInsertHandle createObservationFactInserter( - String tempTableName); - - /** - * Function to check if given table exists - * - * @param tableName - * @return boolean - * @throws Exception - */ - public boolean checkTableExists(String tableName) throws I2B2Exception; - - /** - * Function to call MERGE_TEMP_OBSERVATION_FACT(?) stored procedure. - * - * @param tempTableName - * @throws Exception - */ - public void doTempTableMerge(String tempTableName, int uploadId, - boolean appendFlag) throws I2B2Exception; - - /** - * Function to call remove temp table stored procedure. - * - * @param tempTableName - * @throws Exception - */ - public void removeTempTable(String tempTableName) throws I2B2Exception; - - /** - * Function to create create temp table stored proc. - * - * @param tempTableName - * @throws Exception - */ - public void createTempTable(String tempTableName) throws I2B2Exception; - - public void writeMissedDataLog(BufferedWriter bufWriter, - String tempTableName) throws I2B2Exception; - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.dao; + +import java.io.BufferedWriter; + +import edu.harvard.i2b2.common.exception.I2B2Exception; + +public interface IObservatonFactDAO { + + public int getRecordCountByUploadId(int uploadId); + + /** + * Create batch insert handle for temp observation fact table. + * + * @param tempTableName + * @return + */ + public ObservationFactInsertHandle createObservationFactInserter( + String tempTableName); + + /** + * Function to check if given table exists + * + * @param tableName + * @return boolean + * @throws Exception + */ + public boolean checkTableExists(String tableName) throws I2B2Exception; + + /** + * Function to call MERGE_TEMP_OBSERVATION_FACT(?) stored procedure. + * + * @param tempTableName + * @throws Exception + */ + public void doTempTableMerge(String tempTableName, int uploadId, + boolean appendFlag) throws I2B2Exception; + + /** + * Function to call remove temp table stored procedure. + * + * @param tempTableName + * @throws Exception + */ + public void removeTempTable(String tempTableName) throws I2B2Exception; + + /** + * Function to create create temp table stored proc. + * + * @param tempTableName + * @throws Exception + */ + public void createTempTable(String tempTableName) throws I2B2Exception; + + public void writeMissedDataLog(BufferedWriter bufWriter, + String tempTableName) throws I2B2Exception; + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/IPatientDAO.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/IPatientDAO.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/IPatientDAO.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/IPatientDAO.java index 7206c9b2..9b4bf4fd --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/IPatientDAO.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/IPatientDAO.java @@ -1,45 +1,45 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.dao; - -import edu.harvard.i2b2.common.exception.I2B2Exception; - -public interface IPatientDAO { - - public int getRecordCountByUploadId(int uploadId); - - /** - * Function to create temp visit dimension table using stored proc. - * - * @param tempTableName - * @throws Exception - */ - public void createTempTable(String tempPatientTableName, - String tempPatientMappingTableName) throws I2B2Exception; - - /** - * Create batch insert handle for temp observation fact table. - * - * @param tempTableName - * @return - */ - public TempPatientDimensionInsertHandler createTempPatientDimensionInsert( - String tempTableName); - - /** - * Function to create new encounter/visit from temp_visit_dimension table - * using stored proc. - * - * @param tempTableName - * @throws Exception - */ - public void createPatientFromTempTable(String tempTableName, - String tempMapTableName, int uploadId) throws I2B2Exception; - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.dao; + +import edu.harvard.i2b2.common.exception.I2B2Exception; + +public interface IPatientDAO { + + public int getRecordCountByUploadId(int uploadId); + + /** + * Function to create temp visit dimension table using stored proc. + * + * @param tempTableName + * @throws Exception + */ + public void createTempTable(String tempPatientTableName, + String tempPatientMappingTableName) throws I2B2Exception; + + /** + * Create batch insert handle for temp observation fact table. + * + * @param tempTableName + * @return + */ + public TempPatientDimensionInsertHandler createTempPatientDimensionInsert( + String tempTableName); + + /** + * Function to create new encounter/visit from temp_visit_dimension table + * using stored proc. + * + * @param tempTableName + * @throws Exception + */ + public void createPatientFromTempTable(String tempTableName, + String tempMapTableName, int uploadId) throws I2B2Exception; + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/IPidDAO.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/IPidDAO.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/IPidDAO.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/IPidDAO.java index 1f3c3417..d03cdc98 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/IPidDAO.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/IPidDAO.java @@ -1,41 +1,41 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.dao; - -import edu.harvard.i2b2.common.exception.I2B2Exception; - -public interface IPidDAO { - - public int getRecordCountByUploadId(int uploadId); - - /** - * Function to create temp visit dimension table using stored proc. - * @param tempTableName - * @throws Exception - */ - public void createTempTable(String tempPatientMappingTableName) - throws I2B2Exception; - - /** - * Create batch insert handle for temp observation fact table. - * @param tempTableName - * @return - */ - public TempPidInsertHandler createTempPidInsert(String tempTableName); - - /** - * Function to create new encounter/visit from temp_visit_dimension table - * using stored proc. - * @param tempTableName - * @throws Exception - */ - public void createPidFromTempTable(String tempMapTableName, int uploadId) - throws I2B2Exception; - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.dao; + +import edu.harvard.i2b2.common.exception.I2B2Exception; + +public interface IPidDAO { + + public int getRecordCountByUploadId(int uploadId); + + /** + * Function to create temp visit dimension table using stored proc. + * @param tempTableName + * @throws Exception + */ + public void createTempTable(String tempPatientMappingTableName) + throws I2B2Exception; + + /** + * Create batch insert handle for temp observation fact table. + * @param tempTableName + * @return + */ + public TempPidInsertHandler createTempPidInsert(String tempTableName); + + /** + * Function to create new encounter/visit from temp_visit_dimension table + * using stored proc. + * @param tempTableName + * @throws Exception + */ + public void createPidFromTempTable(String tempMapTableName, int uploadId) + throws I2B2Exception; + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/IProviderDAO.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/IProviderDAO.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/IProviderDAO.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/IProviderDAO.java index bc6eb81d..e70bc5d2 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/IProviderDAO.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/IProviderDAO.java @@ -1,56 +1,56 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.dao; - -import edu.harvard.i2b2.common.exception.I2B2Exception; - -public interface IProviderDAO { - - public int getRecordCountByUploadId(int uploadId); - - /** - * Function to create temp visit dimension table using stored proc. - * - * @param tempTableName - * @throws Exception - */ - public void createTempTable(String tempProviderTableName) - throws I2B2Exception; - - /** - * Create batch insert handle for temp observation fact table. - * - * @param tempTableName - * @return - */ - public TempProviderInsertHandler createTempProviderInsert( - String tempTableName); - - /** - * Function to create new encounter/visit from temp_visit_dimension table - * using stored proc. - * - * @param tempTableName - * @throws Exception - */ - public void createProviderFromTempTable(String tempProviderTableName, - int uploadId) throws I2B2Exception; - - /** - * Function to backup and clear provider dimension table using stored proc. - * - * @param tempTableName - * @throws Exception - */ - public void backupAndSyncProviderDimensionTable( - String tempConceptTableName, - String backupProviderDimensionTableName, int uploadId) - throws I2B2Exception; - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.dao; + +import edu.harvard.i2b2.common.exception.I2B2Exception; + +public interface IProviderDAO { + + public int getRecordCountByUploadId(int uploadId); + + /** + * Function to create temp visit dimension table using stored proc. + * + * @param tempTableName + * @throws Exception + */ + public void createTempTable(String tempProviderTableName) + throws I2B2Exception; + + /** + * Create batch insert handle for temp observation fact table. + * + * @param tempTableName + * @return + */ + public TempProviderInsertHandler createTempProviderInsert( + String tempTableName); + + /** + * Function to create new encounter/visit from temp_visit_dimension table + * using stored proc. + * + * @param tempTableName + * @throws Exception + */ + public void createProviderFromTempTable(String tempProviderTableName, + int uploadId) throws I2B2Exception; + + /** + * Function to backup and clear provider dimension table using stored proc. + * + * @param tempTableName + * @throws Exception + */ + public void backupAndSyncProviderDimensionTable( + String tempConceptTableName, + String backupProviderDimensionTableName, int uploadId) + throws I2B2Exception; + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/IUploaderDAOFactory.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/IUploaderDAOFactory.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/IUploaderDAOFactory.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/IUploaderDAOFactory.java index 5c115e1f..6d5a5d04 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/IUploaderDAOFactory.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/IUploaderDAOFactory.java @@ -1,42 +1,42 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.dao; - -import javax.sql.DataSource; - -import edu.harvard.i2b2.crc.loader.datavo.loader.DataSourceLookup; - -public interface IUploaderDAOFactory { - public DataSourceLookup getDataSourceLookup(); - - public IConceptDAO getConceptDAO(); - - public IModifierDAO getModifierDAO(); - - public IPatientDAO getPatientDAO(); - - public IPidDAO getPidDAO(); - - public IEidDAO getEidDAO(); - - public IObservationFactDAO getObservationDAO(); - - public UploadStatusDAOI getUploadStatusDAO(); - - public IProviderDAO getProviderDAO(); - - public IVisitDAO getVisitDAO(); - - public IMissingTermDAO getMissingTermDAO(); - - public DataSource getDataSource(); - - public void setDataSource(DataSource dataSource); - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.dao; + +import javax.sql.DataSource; + +import edu.harvard.i2b2.crc.loader.datavo.loader.DataSourceLookup; + +public interface IUploaderDAOFactory { + public DataSourceLookup getDataSourceLookup(); + + public IConceptDAO getConceptDAO(); + + public IModifierDAO getModifierDAO(); + + public IPatientDAO getPatientDAO(); + + public IPidDAO getPidDAO(); + + public IEidDAO getEidDAO(); + + public IObservationFactDAO getObservationDAO(); + + public UploadStatusDAOI getUploadStatusDAO(); + + public IProviderDAO getProviderDAO(); + + public IVisitDAO getVisitDAO(); + + public IMissingTermDAO getMissingTermDAO(); + + public DataSource getDataSource(); + + public void setDataSource(DataSource dataSource); + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/IVisitDAO.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/IVisitDAO.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/IVisitDAO.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/IVisitDAO.java index 434c6ee7..fbae1d52 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/IVisitDAO.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/IVisitDAO.java @@ -1,44 +1,44 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.dao; - -import edu.harvard.i2b2.common.exception.I2B2Exception; - -public interface IVisitDAO { - - public int getRecordCountByUploadId(int uploadId); - - /** - * Create batch insert handle for temp observation fact table. - * - * @param tempTableName - * @return - */ - public TempVisitDimensionInsertHandler createTempVisitDimensionInsert( - String tempTableName); - - /** - * Function to create temp visit dimension table using stored proc. - * - * @param tempTableName - * @throws Exception - */ - public void createTempTable(String tempTableName) throws I2B2Exception; - - /** - * Function to create new encounter/visit from temp_visit_dimension table - * using stored proc. - * - * @param tempTableName - * @throws Exception - */ - public void createVisitFromTempTable(String tempTableName, int uploadId) - throws I2B2Exception; - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.dao; + +import edu.harvard.i2b2.common.exception.I2B2Exception; + +public interface IVisitDAO { + + public int getRecordCountByUploadId(int uploadId); + + /** + * Create batch insert handle for temp observation fact table. + * + * @param tempTableName + * @return + */ + public TempVisitDimensionInsertHandler createTempVisitDimensionInsert( + String tempTableName); + + /** + * Function to create temp visit dimension table using stored proc. + * + * @param tempTableName + * @throws Exception + */ + public void createTempTable(String tempTableName) throws I2B2Exception; + + /** + * Function to create new encounter/visit from temp_visit_dimension table + * using stored proc. + * + * @param tempTableName + * @throws Exception + */ + public void createVisitFromTempTable(String tempTableName, int uploadId) + throws I2B2Exception; + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/LoaderDAOFactoryHelper.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/LoaderDAOFactoryHelper.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/LoaderDAOFactoryHelper.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/LoaderDAOFactoryHelper.java index 81e36c17..94810242 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/LoaderDAOFactoryHelper.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/LoaderDAOFactoryHelper.java @@ -1,59 +1,59 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.dao; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.crc.loader.dao.DataSourceLookupHelper; -import edu.harvard.i2b2.crc.loader.datavo.loader.DataSourceLookup; - -public class LoaderDAOFactoryHelper { - - public static final String ORACLE = "ORACLE"; - public static final String SQLSERVER = "SQLSERVER"; - public static final String POSTGRESQL = "POSTGRESQL"; - DataSourceLookup dataSourceLookup = null; - - public LoaderDAOFactoryHelper(String hiveId, String projectId, String ownerId) throws I2B2DAOException { - try { - DataSourceLookupHelper dsHelper = new DataSourceLookupHelper(); - dataSourceLookup = dsHelper.matchDataSource(hiveId, projectId, ownerId); - } catch(I2B2Exception i2b2Ex) { - throw new I2B2DAOException("DataSource lookup error" +i2b2Ex.getMessage(),i2b2Ex); - } - } - - public LoaderDAOFactoryHelper(DataSourceLookup dataSourceLookup) throws I2B2DAOException { - - if (dataSourceLookup.getDataSource() == null ) { - throw new I2B2DAOException("DataSource value is missing in DataSourceLookup parameter"); - } - if (dataSourceLookup.getServerType() == null ) { - throw new I2B2DAOException("Server type value is missing in DataSourceLookup parameter"); - } - if (dataSourceLookup.getFullSchema() == null) { - throw new I2B2DAOException("Full schema name is missing in DataSourceLookup parameter"); - } - this.dataSourceLookup = dataSourceLookup; - } - - public ILoaderDAOFactory getDAOFactory() throws I2B2DAOException { - String dataSourceName = dataSourceLookup.getServerType(); - if (dataSourceName.equalsIgnoreCase(ORACLE)) { - return new OracleLoaderDAOFactory(dataSourceLookup); - } else if (dataSourceName.equalsIgnoreCase(SQLSERVER)) { - return new OracleLoaderDAOFactory(dataSourceLookup); - } else if (dataSourceName.equalsIgnoreCase(POSTGRESQL)) { - return new OracleLoaderDAOFactory(dataSourceLookup); - } else { - return null; - } - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.dao; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.crc.loader.dao.DataSourceLookupHelper; +import edu.harvard.i2b2.crc.loader.datavo.loader.DataSourceLookup; + +public class LoaderDAOFactoryHelper { + + public static final String ORACLE = "ORACLE"; + public static final String SQLSERVER = "SQLSERVER"; + public static final String POSTGRESQL = "POSTGRESQL"; + DataSourceLookup dataSourceLookup = null; + + public LoaderDAOFactoryHelper(String hiveId, String projectId, String ownerId) throws I2B2DAOException { + try { + DataSourceLookupHelper dsHelper = new DataSourceLookupHelper(); + dataSourceLookup = dsHelper.matchDataSource(hiveId, projectId, ownerId); + } catch(I2B2Exception i2b2Ex) { + throw new I2B2DAOException("DataSource lookup error" +i2b2Ex.getMessage(),i2b2Ex); + } + } + + public LoaderDAOFactoryHelper(DataSourceLookup dataSourceLookup) throws I2B2DAOException { + + if (dataSourceLookup.getDataSource() == null ) { + throw new I2B2DAOException("DataSource value is missing in DataSourceLookup parameter"); + } + if (dataSourceLookup.getServerType() == null ) { + throw new I2B2DAOException("Server type value is missing in DataSourceLookup parameter"); + } + if (dataSourceLookup.getFullSchema() == null) { + throw new I2B2DAOException("Full schema name is missing in DataSourceLookup parameter"); + } + this.dataSourceLookup = dataSourceLookup; + } + + public ILoaderDAOFactory getDAOFactory() throws I2B2DAOException { + String dataSourceName = dataSourceLookup.getServerType(); + if (dataSourceName.equalsIgnoreCase(ORACLE)) { + return new OracleLoaderDAOFactory(dataSourceLookup); + } else if (dataSourceName.equalsIgnoreCase(SQLSERVER)) { + return new OracleLoaderDAOFactory(dataSourceLookup); + } else if (dataSourceName.equalsIgnoreCase(POSTGRESQL)) { + return new OracleLoaderDAOFactory(dataSourceLookup); + } else { + return null; + } + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/MissingTermDAO.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/MissingTermDAO.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/MissingTermDAO.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/MissingTermDAO.java index 10215e06..bf7a1572 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/MissingTermDAO.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/MissingTermDAO.java @@ -1,342 +1,342 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.dao; - -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; - -import javax.sql.DataSource; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.crc.loader.datavo.loader.DataSourceLookup; -import edu.harvard.i2b2.crc.loader.datavo.loader.query.MissingCodesConceptSetType; -import edu.harvard.i2b2.crc.loader.datavo.loader.query.MissingCodesModifierSetType; -import edu.harvard.i2b2.crc.loader.datavo.loader.query.MissingCodesObserverSetType; -import edu.harvard.i2b2.crc.loader.datavo.loader.query.MissingTermSetReportType; - -/** - * Patient Dimension data access object. - * - * @author rk903 - */ -public class MissingTermDAO extends CRCLoaderDAO implements IMissingTermDAO { - - private DataSourceLookup dataSourceLookup = null; - - private static Log log = LogFactory.getLog(MissingTermDAO.class); - - public MissingTermDAO(DataSourceLookup dataSourceLookup, - DataSource dataSource) { - setDataSource(dataSource); - setDbSchemaName(dataSourceLookup.getFullSchema()); - this.dataSourceLookup = dataSourceLookup; - - } - - @Override - public MissingTermSetReportType getMissingTermReport(int uploadId, - String setName) throws I2B2DAOException { - - String uploadConstrainSql = "", uploadConstrainMappedSql = "" ; - Connection conn = null; - MissingTermSetReportType missingTermReport = new MissingTermSetReportType(); - try { - - if (uploadId != 0) { - uploadConstrainSql = " and obs.upload_id = " + uploadId; - uploadConstrainMappedSql = " where obs.upload_id = " + uploadId; - } - conn = getDataSource().getConnection(); - String unmappedSql = "", mappedSql = ""; - - if (setName.equals("observer_set")) { - unmappedSql = " select count(distinct provider_id) from " - + this.getDbSchemaName() + "observation_fact " - + " where " - + " provider_id not in (select provider_id from " - + this.getDbSchemaName() + "provider_dimension) " + uploadConstrainSql; - mappedSql = " select count(distinct provider_id) from " - + this.getDbSchemaName() + "observation_fact obs" + uploadConstrainMappedSql; - - } else if (setName.equals("concept_set")) { - - unmappedSql = " select count(distinct concept_cd) from " - + this.getDbSchemaName() + "observation_fact " - + " where " + uploadConstrainSql - + " concept_cd not in (select concept_cd from " - + this.getDbSchemaName() + "concept_dimension) " + uploadConstrainSql; - mappedSql = " select count(distinct concept_cd) from " - + this.getDbSchemaName() + "observation_fact obs " + uploadConstrainMappedSql; - } else if (setName.equals("modifier_set")) { - unmappedSql = " select count(distinct modifier_cd) from " - + this.getDbSchemaName() + "observation_fact " - + " where " + uploadConstrainSql - + " modifier_cd not in (select modifier_cd from " - + this.getDbSchemaName() + "modifier_dimension) " + uploadConstrainSql; - mappedSql = " select count(distinct modifier_cd) from " - + this.getDbSchemaName() + "observation_fact obs" + uploadConstrainMappedSql; - - } - - Statement stmt = conn.createStatement(); - log.debug("Executing sql [" + unmappedSql + "]"); - ResultSet resultSet = stmt.executeQuery(unmappedSql); - resultSet.next(); - int unmappedCount = resultSet.getInt(1); - log.debug("Executing sql [" + mappedSql + "]"); - stmt = conn.createStatement(); - resultSet = stmt.executeQuery(mappedSql); - resultSet.next(); - int mappedCount = resultSet.getInt(1); - resultSet.close(); - stmt.close(); - - missingTermReport.setUnmapped(unmappedCount); - missingTermReport.setMapped(mappedCount - unmappedCount); - - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - throw new I2B2DAOException("SQLException occured" - + sqlEx.getMessage(), sqlEx); - } catch (Exception ex) { - ex.printStackTrace(); - throw new I2B2DAOException("Exception occured" + ex.getMessage(), - ex); - } finally { - if (conn != null) { - try { - conn.close(); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - log.error("Error while closing connection", sqlEx); - } - } - } - return missingTermReport; - } - - @Override - public MissingCodesConceptSetType getMissingConceptSet(int uploadId, - int startPos, int endPos, boolean detailFlag) - throws I2B2DAOException { - Connection conn = null; - String sql = "", uploadConstrainSql = ""; - MissingCodesConceptSetType missConceptSetType = new MissingCodesConceptSetType(); - try { - - if (uploadId != 0) { - uploadConstrainSql = " and obs.upload_id = " + uploadId; - } - conn = getDataSource().getConnection(); - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DataSourceLookupDAOFactory.SQLSERVER)) { - sql = " select tot,concept_cd, rnum from ( " - + " select count(*) tot, obs1.concept_cd, row_number() over (order by obs1.concept_cd asc) rnum from " - + this.getDbSchemaName() + "observation_fact obs1 where concept_cd not in ( " - + " select concept_cd from " + this.getDbSchemaName() - + "concept_dimension) " - + uploadConstrainSql + " group by obs1.concept_cd) f where rnum between " + startPos + " and " + endPos ; - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DataSourceLookupDAOFactory.ORACLE)) { - sql = " select tot, concept_cd, rnum from (select count(*) tot, obs1.concept_cd, rownum rnum from " - + this.getDbSchemaName() - + "observation_fact obs1 where " - + " concept_cd not in ( " - + " select concept_cd from " - + this.getDbSchemaName() - + "concept_dimension) " - + uploadConstrainSql - + " group by obs1.concept_cd) f where rnum between " - + startPos + " and " + endPos; - - } - Statement stmt = conn.createStatement(); - log.debug("Executing sql ["+ sql + "]"); - ResultSet resultSet = stmt.executeQuery(sql); - - MissingCodesConceptSetType.Concept concept = new MissingCodesConceptSetType.Concept(); - - while (resultSet.next()) { - concept = new MissingCodesConceptSetType.Concept(); - concept.setConceptCd(resultSet.getString("concept_cd")); - concept.setMissingTotal(resultSet.getInt("tot")); - missConceptSetType.getConcept().add(concept); - } - resultSet.close(); - - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - throw new I2B2DAOException("SQLException occured" - + sqlEx.getMessage(), sqlEx); - } catch (Exception ex) { - ex.printStackTrace(); - throw new I2B2DAOException("Exception occured" + ex.getMessage(), - ex); - } finally { - if (conn != null) { - try { - conn.close(); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - log.error("Error while closing connection", sqlEx); - } - } - } - - return missConceptSetType; - } - - @Override - public MissingCodesModifierSetType getMissingModifierSet(int uploadId, - int startPos, int endPos, boolean detailFlag) - throws I2B2DAOException { - Connection conn = null; - String sql = "", uploadConstrainSql = ""; - MissingCodesModifierSetType missModifierSetType = new MissingCodesModifierSetType(); - try { - - if (uploadId != 0) { - uploadConstrainSql = " and obs.upload_id = " + uploadId; - } - conn = getDataSource().getConnection(); - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DataSourceLookupDAOFactory.SQLSERVER)) { - sql = " select tot,modifier_cd, rnum from ( " - + " select count(*) tot, obs1.modifier_cd, row_number() over (order by obs1.modifier_cd asc) rnum from " - + this.getDbSchemaName() + "observation_fact obs1 where modifier_cd not in ( " - + " select modifier_cd from " + this.getDbSchemaName() - + "modifier_dimension) " - + uploadConstrainSql + " group by obs1.modifier_cd) f where rnum between " + startPos + " and " + endPos ; - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DataSourceLookupDAOFactory.ORACLE)) { - sql = " select tot, modifier_cd, rnum from (select count(*) tot, obs1.modifier_cd, rownum rnum from " - + this.getDbSchemaName() - + "observation_fact obs1 where " - + " modifier_cd not in ( " - + " select modifier_cd from " - + this.getDbSchemaName() - + "modifier_dimension) " - + uploadConstrainSql - + " group by obs1.modifier_cd) f where rnum between " - + startPos + " and " + endPos; - - } - Statement stmt = conn.createStatement(); - log.debug("Executing sql ["+ sql + "]"); - ResultSet resultSet = stmt.executeQuery(sql); - - MissingCodesModifierSetType.Modifier modifier = new MissingCodesModifierSetType.Modifier(); - - while (resultSet.next()) { - modifier = new MissingCodesModifierSetType.Modifier(); - modifier.setModifierCd(resultSet.getString("modifier_cd")); - modifier.setMissingTotal(resultSet.getInt("tot")); - missModifierSetType.getModifier().add(modifier); - } - resultSet.close(); - - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - throw new I2B2DAOException("SQLException occured" - + sqlEx.getMessage(), sqlEx); - } catch (Exception ex) { - ex.printStackTrace(); - throw new I2B2DAOException("Exception occured" + ex.getMessage(), - ex); - } finally { - if (conn != null) { - try { - conn.close(); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - log.error("Error while closing connection", sqlEx); - } - } - } - - return missModifierSetType; - } - - @Override - public MissingCodesObserverSetType getMissingObserverSet(int uploadId, - int startPos, int endPos, boolean detailFlag) - throws I2B2DAOException { - Connection conn = null; - String sql = "", uploadConstrainSql = ""; - MissingCodesObserverSetType missObserverSetType = new MissingCodesObserverSetType(); - try { - - if (uploadId != 0) { - uploadConstrainSql = " and obs.upload_id = " + uploadId; - } - conn = getDataSource().getConnection(); - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DataSourceLookupDAOFactory.SQLSERVER)) { - sql = " select tot,provider_id, rnum from ( " - + " select count(*) tot, obs1.provider_id, row_number() over (order by obs1.provider_id asc) rnum from " - + this.getDbSchemaName() + "observation_fact obs1 where provider_id not in ( " - + " select provider_id from " + this.getDbSchemaName() - + "provider_dimension) " - + uploadConstrainSql + " group by obs1.provider_id) f where rnum between " + startPos + " and " + endPos ; - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - DataSourceLookupDAOFactory.ORACLE)) { - sql = " select tot,provider_id, rnum from (select count(*) tot, obs1.provider_id, rownum rnum from " - + this.getDbSchemaName() - + "observation_fact obs1 where " - + " provider_id not in ( " - + " select provider_id from " - + this.getDbSchemaName() - + "provider_dimension) " - + uploadConstrainSql - + " group by obs1.provider_id) f where rnum between " - + startPos + " and " + endPos; - - } - Statement stmt = conn.createStatement(); - log.debug("Executing sql ["+ sql + "]"); - ResultSet resultSet = stmt.executeQuery(sql); - - MissingCodesObserverSetType.Observer observer = new MissingCodesObserverSetType.Observer(); - - while (resultSet.next()) { - observer = new MissingCodesObserverSetType.Observer(); - observer.setObserverCd(resultSet.getString("provider_id")); - observer.setMissingTotal(resultSet.getInt("tot")); - missObserverSetType.getObserver().add(observer); - } - resultSet.close(); - - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - throw new I2B2DAOException("SQLException occured" - + sqlEx.getMessage(), sqlEx); - } catch (Exception ex) { - ex.printStackTrace(); - throw new I2B2DAOException("Exception occured" + ex.getMessage(), - ex); - } finally { - if (conn != null) { - try { - conn.close(); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - log.error("Error while closing connection", sqlEx); - } - } - } - - return missObserverSetType; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.dao; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; + +import javax.sql.DataSource; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.crc.loader.datavo.loader.DataSourceLookup; +import edu.harvard.i2b2.crc.loader.datavo.loader.query.MissingCodesConceptSetType; +import edu.harvard.i2b2.crc.loader.datavo.loader.query.MissingCodesModifierSetType; +import edu.harvard.i2b2.crc.loader.datavo.loader.query.MissingCodesObserverSetType; +import edu.harvard.i2b2.crc.loader.datavo.loader.query.MissingTermSetReportType; + +/** + * Patient Dimension data access object. + * + * @author rk903 + */ +public class MissingTermDAO extends CRCLoaderDAO implements IMissingTermDAO { + + private DataSourceLookup dataSourceLookup = null; + + private static Log log = LogFactory.getLog(MissingTermDAO.class); + + public MissingTermDAO(DataSourceLookup dataSourceLookup, + DataSource dataSource) { + setDataSource(dataSource); + setDbSchemaName(dataSourceLookup.getFullSchema()); + this.dataSourceLookup = dataSourceLookup; + + } + + @Override + public MissingTermSetReportType getMissingTermReport(int uploadId, + String setName) throws I2B2DAOException { + + String uploadConstrainSql = "", uploadConstrainMappedSql = "" ; + Connection conn = null; + MissingTermSetReportType missingTermReport = new MissingTermSetReportType(); + try { + + if (uploadId != 0) { + uploadConstrainSql = " and obs.upload_id = " + uploadId; + uploadConstrainMappedSql = " where obs.upload_id = " + uploadId; + } + conn = getDataSource().getConnection(); + String unmappedSql = "", mappedSql = ""; + + if (setName.equals("observer_set")) { + unmappedSql = " select count(distinct provider_id) from " + + this.getDbSchemaName() + "observation_fact " + + " where " + + " provider_id not in (select provider_id from " + + this.getDbSchemaName() + "provider_dimension) " + uploadConstrainSql; + mappedSql = " select count(distinct provider_id) from " + + this.getDbSchemaName() + "observation_fact obs" + uploadConstrainMappedSql; + + } else if (setName.equals("concept_set")) { + + unmappedSql = " select count(distinct concept_cd) from " + + this.getDbSchemaName() + "observation_fact " + + " where " + uploadConstrainSql + + " concept_cd not in (select concept_cd from " + + this.getDbSchemaName() + "concept_dimension) " + uploadConstrainSql; + mappedSql = " select count(distinct concept_cd) from " + + this.getDbSchemaName() + "observation_fact obs " + uploadConstrainMappedSql; + } else if (setName.equals("modifier_set")) { + unmappedSql = " select count(distinct modifier_cd) from " + + this.getDbSchemaName() + "observation_fact " + + " where " + uploadConstrainSql + + " modifier_cd not in (select modifier_cd from " + + this.getDbSchemaName() + "modifier_dimension) " + uploadConstrainSql; + mappedSql = " select count(distinct modifier_cd) from " + + this.getDbSchemaName() + "observation_fact obs" + uploadConstrainMappedSql; + + } + + Statement stmt = conn.createStatement(); + log.debug("Executing sql [" + unmappedSql + "]"); + ResultSet resultSet = stmt.executeQuery(unmappedSql); + resultSet.next(); + int unmappedCount = resultSet.getInt(1); + log.debug("Executing sql [" + mappedSql + "]"); + stmt = conn.createStatement(); + resultSet = stmt.executeQuery(mappedSql); + resultSet.next(); + int mappedCount = resultSet.getInt(1); + resultSet.close(); + stmt.close(); + + missingTermReport.setUnmapped(unmappedCount); + missingTermReport.setMapped(mappedCount - unmappedCount); + + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + throw new I2B2DAOException("SQLException occured" + + sqlEx.getMessage(), sqlEx); + } catch (Exception ex) { + ex.printStackTrace(); + throw new I2B2DAOException("Exception occured" + ex.getMessage(), + ex); + } finally { + if (conn != null) { + try { + conn.close(); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + log.error("Error while closing connection", sqlEx); + } + } + } + return missingTermReport; + } + + @Override + public MissingCodesConceptSetType getMissingConceptSet(int uploadId, + int startPos, int endPos, boolean detailFlag) + throws I2B2DAOException { + Connection conn = null; + String sql = "", uploadConstrainSql = ""; + MissingCodesConceptSetType missConceptSetType = new MissingCodesConceptSetType(); + try { + + if (uploadId != 0) { + uploadConstrainSql = " and obs.upload_id = " + uploadId; + } + conn = getDataSource().getConnection(); + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DataSourceLookupDAOFactory.SQLSERVER)) { + sql = " select tot,concept_cd, rnum from ( " + + " select count(*) tot, obs1.concept_cd, row_number() over (order by obs1.concept_cd asc) rnum from " + + this.getDbSchemaName() + "observation_fact obs1 where concept_cd not in ( " + + " select concept_cd from " + this.getDbSchemaName() + + "concept_dimension) " + + uploadConstrainSql + " group by obs1.concept_cd) f where rnum between " + startPos + " and " + endPos ; + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DataSourceLookupDAOFactory.ORACLE)) { + sql = " select tot, concept_cd, rnum from (select count(*) tot, obs1.concept_cd, rownum rnum from " + + this.getDbSchemaName() + + "observation_fact obs1 where " + + " concept_cd not in ( " + + " select concept_cd from " + + this.getDbSchemaName() + + "concept_dimension) " + + uploadConstrainSql + + " group by obs1.concept_cd) f where rnum between " + + startPos + " and " + endPos; + + } + Statement stmt = conn.createStatement(); + log.debug("Executing sql ["+ sql + "]"); + ResultSet resultSet = stmt.executeQuery(sql); + + MissingCodesConceptSetType.Concept concept = new MissingCodesConceptSetType.Concept(); + + while (resultSet.next()) { + concept = new MissingCodesConceptSetType.Concept(); + concept.setConceptCd(resultSet.getString("concept_cd")); + concept.setMissingTotal(resultSet.getInt("tot")); + missConceptSetType.getConcept().add(concept); + } + resultSet.close(); + + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + throw new I2B2DAOException("SQLException occured" + + sqlEx.getMessage(), sqlEx); + } catch (Exception ex) { + ex.printStackTrace(); + throw new I2B2DAOException("Exception occured" + ex.getMessage(), + ex); + } finally { + if (conn != null) { + try { + conn.close(); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + log.error("Error while closing connection", sqlEx); + } + } + } + + return missConceptSetType; + } + + @Override + public MissingCodesModifierSetType getMissingModifierSet(int uploadId, + int startPos, int endPos, boolean detailFlag) + throws I2B2DAOException { + Connection conn = null; + String sql = "", uploadConstrainSql = ""; + MissingCodesModifierSetType missModifierSetType = new MissingCodesModifierSetType(); + try { + + if (uploadId != 0) { + uploadConstrainSql = " and obs.upload_id = " + uploadId; + } + conn = getDataSource().getConnection(); + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DataSourceLookupDAOFactory.SQLSERVER)) { + sql = " select tot,modifier_cd, rnum from ( " + + " select count(*) tot, obs1.modifier_cd, row_number() over (order by obs1.modifier_cd asc) rnum from " + + this.getDbSchemaName() + "observation_fact obs1 where modifier_cd not in ( " + + " select modifier_cd from " + this.getDbSchemaName() + + "modifier_dimension) " + + uploadConstrainSql + " group by obs1.modifier_cd) f where rnum between " + startPos + " and " + endPos ; + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DataSourceLookupDAOFactory.ORACLE)) { + sql = " select tot, modifier_cd, rnum from (select count(*) tot, obs1.modifier_cd, rownum rnum from " + + this.getDbSchemaName() + + "observation_fact obs1 where " + + " modifier_cd not in ( " + + " select modifier_cd from " + + this.getDbSchemaName() + + "modifier_dimension) " + + uploadConstrainSql + + " group by obs1.modifier_cd) f where rnum between " + + startPos + " and " + endPos; + + } + Statement stmt = conn.createStatement(); + log.debug("Executing sql ["+ sql + "]"); + ResultSet resultSet = stmt.executeQuery(sql); + + MissingCodesModifierSetType.Modifier modifier = new MissingCodesModifierSetType.Modifier(); + + while (resultSet.next()) { + modifier = new MissingCodesModifierSetType.Modifier(); + modifier.setModifierCd(resultSet.getString("modifier_cd")); + modifier.setMissingTotal(resultSet.getInt("tot")); + missModifierSetType.getModifier().add(modifier); + } + resultSet.close(); + + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + throw new I2B2DAOException("SQLException occured" + + sqlEx.getMessage(), sqlEx); + } catch (Exception ex) { + ex.printStackTrace(); + throw new I2B2DAOException("Exception occured" + ex.getMessage(), + ex); + } finally { + if (conn != null) { + try { + conn.close(); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + log.error("Error while closing connection", sqlEx); + } + } + } + + return missModifierSetType; + } + + @Override + public MissingCodesObserverSetType getMissingObserverSet(int uploadId, + int startPos, int endPos, boolean detailFlag) + throws I2B2DAOException { + Connection conn = null; + String sql = "", uploadConstrainSql = ""; + MissingCodesObserverSetType missObserverSetType = new MissingCodesObserverSetType(); + try { + + if (uploadId != 0) { + uploadConstrainSql = " and obs.upload_id = " + uploadId; + } + conn = getDataSource().getConnection(); + if (dataSourceLookup.getServerType().equalsIgnoreCase( + DataSourceLookupDAOFactory.SQLSERVER)) { + sql = " select tot,provider_id, rnum from ( " + + " select count(*) tot, obs1.provider_id, row_number() over (order by obs1.provider_id asc) rnum from " + + this.getDbSchemaName() + "observation_fact obs1 where provider_id not in ( " + + " select provider_id from " + this.getDbSchemaName() + + "provider_dimension) " + + uploadConstrainSql + " group by obs1.provider_id) f where rnum between " + startPos + " and " + endPos ; + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + DataSourceLookupDAOFactory.ORACLE)) { + sql = " select tot,provider_id, rnum from (select count(*) tot, obs1.provider_id, rownum rnum from " + + this.getDbSchemaName() + + "observation_fact obs1 where " + + " provider_id not in ( " + + " select provider_id from " + + this.getDbSchemaName() + + "provider_dimension) " + + uploadConstrainSql + + " group by obs1.provider_id) f where rnum between " + + startPos + " and " + endPos; + + } + Statement stmt = conn.createStatement(); + log.debug("Executing sql ["+ sql + "]"); + ResultSet resultSet = stmt.executeQuery(sql); + + MissingCodesObserverSetType.Observer observer = new MissingCodesObserverSetType.Observer(); + + while (resultSet.next()) { + observer = new MissingCodesObserverSetType.Observer(); + observer.setObserverCd(resultSet.getString("provider_id")); + observer.setMissingTotal(resultSet.getInt("tot")); + missObserverSetType.getObserver().add(observer); + } + resultSet.close(); + + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + throw new I2B2DAOException("SQLException occured" + + sqlEx.getMessage(), sqlEx); + } catch (Exception ex) { + ex.printStackTrace(); + throw new I2B2DAOException("Exception occured" + ex.getMessage(), + ex); + } finally { + if (conn != null) { + try { + conn.close(); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + log.error("Error while closing connection", sqlEx); + } + } + } + + return missObserverSetType; + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/ModifierDAO.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/ModifierDAO.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/ModifierDAO.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/ModifierDAO.java index f7635629..ecb53e66 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/ModifierDAO.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/ModifierDAO.java @@ -1,245 +1,245 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.dao; - -import java.sql.CallableStatement; -import java.sql.Connection; -import java.sql.SQLException; -import java.sql.Types; - -import javax.sql.DataSource; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.SqlParameter; -import org.springframework.jdbc.object.BatchSqlUpdate; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.crc.loader.datavo.loader.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.pdo.ModifierType; - -/** - * Patient Dimension data access object. - * - * @author rk903 - */ -public class ModifierDAO extends CRCLoaderDAO implements IModifierDAO { - - private int DB_BATCH_INSERT_SIZE = 2000; - private DataSourceLookup dataSourceLookup = null; - - private static Log log = LogFactory.getLog(ModifierDAO.class); - - public ModifierDAO(DataSourceLookup dataSourceLookup, DataSource dataSource) { - setDataSource(dataSource); - setDbSchemaName(dataSourceLookup.getFullSchema()); - this.dataSourceLookup = dataSourceLookup; - - } - - /** - * Function to create temp modifier dimension table using stored proc. - * - * @param tempTableName - * @throws Exception - */ - @Override - public void createTempTable(String tempPatientMappingTableName) - throws I2B2Exception { - Connection conn = null; - try { - conn = getDataSource().getConnection(); - CallableStatement callStmt = conn.prepareCall("{call " - + this.getDbSchemaName() - + "CREATE_TEMP_MODIFIER_TABLE(?,?)}"); - callStmt.setString(1, tempPatientMappingTableName); - callStmt.registerOutParameter(2, java.sql.Types.VARCHAR); - callStmt.execute(); - this.getSQLServerProcedureError(dataSourceLookup.getServerType(), - callStmt, 2); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - throw new I2B2Exception( - "SQLException occured" + sqlEx.getMessage(), sqlEx); - } catch (Exception ex) { - ex.printStackTrace(); - throw new I2B2Exception("Exception occured" + ex.getMessage(), ex); - } finally { - if (conn != null) { - try { - conn.close(); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - log.error("Error while closing connection", sqlEx); - } - } - } - } - - /** - * Create batch insert handle for temp observation fact table. - * - * @param tempTableName - * @return - */ - @Override - public TempModifierInsertHandler createTempModifierInsert(String tempTableName) { - TempModifierInsert tempModifierInsert = new TempModifierInsert( - getDataSource(), tempTableName, getDbSchemaName()); - tempModifierInsert.setBatchSize(DB_BATCH_INSERT_SIZE); - return new TempModifierInsertHandler(tempModifierInsert); - } - - /** - * Function to create new encounter/visit from temp_visit_dimension table - * using stored proc. - * - * @param tempTableName - * @throws Exception - */ - @Override - public void createModifierFromTempTable(String tempMapTableName, int uploadId) - throws I2B2Exception { - Connection conn = null; - try { - conn = getDataSource().getConnection(); - CallableStatement callStmt = conn.prepareCall("{call " - + this.getDbSchemaName() - + "INSERT_MODIFIER_FROMTEMP(?,?,?)}"); - callStmt.setString(1, tempMapTableName); - callStmt.setInt(2, uploadId); - callStmt.registerOutParameter(3, java.sql.Types.VARCHAR); - callStmt.execute(); - this.getSQLServerProcedureError(dataSourceLookup.getServerType(), - callStmt, 3); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - throw new I2B2Exception( - "SQLException occured" + sqlEx.getMessage(), sqlEx); - } catch (Exception ex) { - ex.printStackTrace(); - throw new I2B2Exception("Exception occured" + ex.getMessage(), ex); - } finally { - if (conn != null) { - try { - conn.close(); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - log.error("Error while closing connection", sqlEx); - } - } - } - } - - @Override - public int getRecordCountByUploadId(int uploadId) { - JdbcTemplate jdbcTemplate = new JdbcTemplate(getDataSource()); - int insertCount = jdbcTemplate.queryForObject("select count(1) from " - + this.getDbSchemaName() - + "modifier_dimension where upload_id =?", Integer.class, - new Object[] { uploadId }); - return insertCount; - } - - /** - * Function to backup and clear concept dimension table using stored proc. - * - * @param tempTableName - * @throws Exception - */ - @Override - public void backupAndSyncModifierDimensionTable(String tempModifierTableName, - String backupModifierDimensionTableName, int uploadId) - throws I2B2Exception { - Connection conn = null; - try { - conn = getDataSource().getConnection(); - CallableStatement callStmt = conn.prepareCall("{call " - + this.getDbSchemaName() - + "SYNC_CLEAR_MODIFIER_TABLE(?,?,?,?)}"); - callStmt.setString(1, tempModifierTableName); - callStmt.setString(2, backupModifierDimensionTableName); - callStmt.setInt(3, uploadId); - callStmt.registerOutParameter(4, java.sql.Types.VARCHAR); - callStmt.execute(); - this.getSQLServerProcedureError(dataSourceLookup.getServerType(), - callStmt, 4); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - throw new I2B2Exception( - "SQLException occured" + sqlEx.getMessage(), sqlEx); - } catch (Exception ex) { - ex.printStackTrace(); - throw new I2B2Exception("Exception occured" + ex.getMessage(), ex); - } finally { - if (conn != null) { - try { - conn.close(); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - log.error("Error while closing connection", sqlEx); - } - } - } - } - - /** - * Patient_Mapping insert code. - */ - protected class TempModifierInsert extends BatchSqlUpdate { - - /** - * Create a new instance of Patient_MappingInsert. - * - * @param ds - * the DataSource to use for the insert - */ - protected TempModifierInsert(DataSource ds, String tempTableName, - String dbSchemaName) { - - super(ds, "INSERT INTO " + dbSchemaName + tempTableName + " (" - + "MODIFIER_CD," + "MODIFIER_PATH," + "NAME_CHAR," - + "MODIFIER_BLOB," + "UPDATE_DATE," + "DOWNLOAD_DATE," - + "IMPORT_DATE," + "SOURCESYSTEM_CD" + ")" - + " VALUES(?,?,?,?,?,?,?,?)"); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.TIMESTAMP)); - declareParameter(new SqlParameter(Types.TIMESTAMP)); - declareParameter(new SqlParameter(Types.TIMESTAMP)); - declareParameter(new SqlParameter(Types.VARCHAR)); - compile(); - } - - protected void insert(ModifierType modifier) { - - // do self insert - Object[] objs = new Object[] { - modifier.getModifierCd(), - modifier.getModifierPath(), - modifier.getNameChar(), - (modifier.getModifierBlob() != null) ? modifier - .getModifierBlob().getContent().get(0) : null, - (modifier.getUpdateDate() != null) ? modifier.getUpdateDate() - .toGregorianCalendar().getTime() : null, - (modifier.getDownloadDate() != null) ? modifier - .getDownloadDate().toGregorianCalendar().getTime() - : null, - (modifier.getImportDate() != null) ? modifier.getImportDate() - .toGregorianCalendar().getTime() : null, - modifier.getSourcesystemCd() }; - super.update(objs); - } - - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.dao; + +import java.sql.CallableStatement; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.Types; + +import javax.sql.DataSource; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.SqlParameter; +import org.springframework.jdbc.object.BatchSqlUpdate; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.crc.loader.datavo.loader.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.pdo.ModifierType; + +/** + * Patient Dimension data access object. + * + * @author rk903 + */ +public class ModifierDAO extends CRCLoaderDAO implements IModifierDAO { + + private int DB_BATCH_INSERT_SIZE = 2000; + private DataSourceLookup dataSourceLookup = null; + + private static Log log = LogFactory.getLog(ModifierDAO.class); + + public ModifierDAO(DataSourceLookup dataSourceLookup, DataSource dataSource) { + setDataSource(dataSource); + setDbSchemaName(dataSourceLookup.getFullSchema()); + this.dataSourceLookup = dataSourceLookup; + + } + + /** + * Function to create temp modifier dimension table using stored proc. + * + * @param tempTableName + * @throws Exception + */ + @Override + public void createTempTable(String tempPatientMappingTableName) + throws I2B2Exception { + Connection conn = null; + try { + conn = getDataSource().getConnection(); + CallableStatement callStmt = conn.prepareCall("{call " + + this.getDbSchemaName() + + "CREATE_TEMP_MODIFIER_TABLE(?,?)}"); + callStmt.setString(1, tempPatientMappingTableName); + callStmt.registerOutParameter(2, java.sql.Types.VARCHAR); + callStmt.execute(); + this.getSQLServerProcedureError(dataSourceLookup.getServerType(), + callStmt, 2); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + throw new I2B2Exception( + "SQLException occured" + sqlEx.getMessage(), sqlEx); + } catch (Exception ex) { + ex.printStackTrace(); + throw new I2B2Exception("Exception occured" + ex.getMessage(), ex); + } finally { + if (conn != null) { + try { + conn.close(); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + log.error("Error while closing connection", sqlEx); + } + } + } + } + + /** + * Create batch insert handle for temp observation fact table. + * + * @param tempTableName + * @return + */ + @Override + public TempModifierInsertHandler createTempModifierInsert(String tempTableName) { + TempModifierInsert tempModifierInsert = new TempModifierInsert( + getDataSource(), tempTableName, getDbSchemaName()); + tempModifierInsert.setBatchSize(DB_BATCH_INSERT_SIZE); + return new TempModifierInsertHandler(tempModifierInsert); + } + + /** + * Function to create new encounter/visit from temp_visit_dimension table + * using stored proc. + * + * @param tempTableName + * @throws Exception + */ + @Override + public void createModifierFromTempTable(String tempMapTableName, int uploadId) + throws I2B2Exception { + Connection conn = null; + try { + conn = getDataSource().getConnection(); + CallableStatement callStmt = conn.prepareCall("{call " + + this.getDbSchemaName() + + "INSERT_MODIFIER_FROMTEMP(?,?,?)}"); + callStmt.setString(1, tempMapTableName); + callStmt.setInt(2, uploadId); + callStmt.registerOutParameter(3, java.sql.Types.VARCHAR); + callStmt.execute(); + this.getSQLServerProcedureError(dataSourceLookup.getServerType(), + callStmt, 3); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + throw new I2B2Exception( + "SQLException occured" + sqlEx.getMessage(), sqlEx); + } catch (Exception ex) { + ex.printStackTrace(); + throw new I2B2Exception("Exception occured" + ex.getMessage(), ex); + } finally { + if (conn != null) { + try { + conn.close(); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + log.error("Error while closing connection", sqlEx); + } + } + } + } + + @Override + public int getRecordCountByUploadId(int uploadId) { + JdbcTemplate jdbcTemplate = new JdbcTemplate(getDataSource()); + int insertCount = jdbcTemplate.queryForObject("select count(1) from " + + this.getDbSchemaName() + + "modifier_dimension where upload_id =?", Integer.class, + new Object[] { uploadId }); + return insertCount; + } + + /** + * Function to backup and clear concept dimension table using stored proc. + * + * @param tempTableName + * @throws Exception + */ + @Override + public void backupAndSyncModifierDimensionTable(String tempModifierTableName, + String backupModifierDimensionTableName, int uploadId) + throws I2B2Exception { + Connection conn = null; + try { + conn = getDataSource().getConnection(); + CallableStatement callStmt = conn.prepareCall("{call " + + this.getDbSchemaName() + + "SYNC_CLEAR_MODIFIER_TABLE(?,?,?,?)}"); + callStmt.setString(1, tempModifierTableName); + callStmt.setString(2, backupModifierDimensionTableName); + callStmt.setInt(3, uploadId); + callStmt.registerOutParameter(4, java.sql.Types.VARCHAR); + callStmt.execute(); + this.getSQLServerProcedureError(dataSourceLookup.getServerType(), + callStmt, 4); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + throw new I2B2Exception( + "SQLException occured" + sqlEx.getMessage(), sqlEx); + } catch (Exception ex) { + ex.printStackTrace(); + throw new I2B2Exception("Exception occured" + ex.getMessage(), ex); + } finally { + if (conn != null) { + try { + conn.close(); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + log.error("Error while closing connection", sqlEx); + } + } + } + } + + /** + * Patient_Mapping insert code. + */ + protected class TempModifierInsert extends BatchSqlUpdate { + + /** + * Create a new instance of Patient_MappingInsert. + * + * @param ds + * the DataSource to use for the insert + */ + protected TempModifierInsert(DataSource ds, String tempTableName, + String dbSchemaName) { + + super(ds, "INSERT INTO " + dbSchemaName + tempTableName + " (" + + "MODIFIER_CD," + "MODIFIER_PATH," + "NAME_CHAR," + + "MODIFIER_BLOB," + "UPDATE_DATE," + "DOWNLOAD_DATE," + + "IMPORT_DATE," + "SOURCESYSTEM_CD" + ")" + + " VALUES(?,?,?,?,?,?,?,?)"); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.TIMESTAMP)); + declareParameter(new SqlParameter(Types.TIMESTAMP)); + declareParameter(new SqlParameter(Types.TIMESTAMP)); + declareParameter(new SqlParameter(Types.VARCHAR)); + compile(); + } + + protected void insert(ModifierType modifier) { + + // do self insert + Object[] objs = new Object[] { + modifier.getModifierCd(), + modifier.getModifierPath(), + modifier.getNameChar(), + (modifier.getModifierBlob() != null) ? modifier + .getModifierBlob().getContent().get(0) : null, + (modifier.getUpdateDate() != null) ? modifier.getUpdateDate() + .toGregorianCalendar().getTime() : null, + (modifier.getDownloadDate() != null) ? modifier + .getDownloadDate().toGregorianCalendar().getTime() + : null, + (modifier.getImportDate() != null) ? modifier.getImportDate() + .toGregorianCalendar().getTime() : null, + modifier.getSourcesystemCd() }; + super.update(objs); + } + + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/ObservationFactDAO.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/ObservationFactDAO.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/ObservationFactDAO.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/ObservationFactDAO.java index 2251031d..3fc39ba8 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/ObservationFactDAO.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/ObservationFactDAO.java @@ -1,452 +1,452 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.dao; - -import java.io.BufferedWriter; -import java.io.IOException; -import java.sql.CallableStatement; -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.sql.Types; -import java.util.Date; - -import javax.sql.DataSource; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.SqlParameter; -import org.springframework.jdbc.object.BatchSqlUpdate; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.crc.loader.datavo.loader.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.pdo.ObservationType; - -/** - * Observation Fact data access object. - * - * @author rk903 - * - */ -public class ObservationFactDAO extends CRCLoaderDAO implements - IObservationFactDAO { - - private int DB_BATCH_INSERT_SIZE = 1; - - private static Log log = LogFactory.getLog(ObservationFactDAO.class); - private DataSourceLookup dataSourceLookup = null; - - public ObservationFactDAO(DataSourceLookup dataSourceLookup, DataSource ds) { - setDataSource(ds); - setDbSchemaName(dataSourceLookup.getFullSchema()); - this.dataSourceLookup = dataSourceLookup; - - } - - @Override - public int getRecordCountByUploadId(int uploadId) { - JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); - int insertCount = jdbcTemplate.queryForObject("select count(1) from " - + getDbSchemaName() + "observation_fact where upload_id =?",Integer.class, - new Object[] { uploadId }); - return insertCount; - } - - /** - * Create batch insert handle for temp observation fact table. - * - * @param tempTableName - * @return - */ - @Override - public ObservationFactInsertHandle createObservationFactInserter( - String tempTableName) { - ObservationFactInsert observationFactInsert = new ObservationFactInsert( - getDataSource(), tempTableName, getDbSchemaName()); - observationFactInsert.setBatchSize(DB_BATCH_INSERT_SIZE); - return new ObservationFactInsertHandle(observationFactInsert); - } - - /** - * Function to check if given table exists - * - * @param tableName - * @return boolean - * @throws Exception - */ - @Override - public boolean checkTableExists(String tableName) throws I2B2Exception { - Connection conn = null; - boolean returnFlag = false; - try { - conn = getDataSource().getConnection(); - CallableStatement callStmt = conn.prepareCall("{? = call " - + this.getDbSchemaName() + "isTableExists(?)}"); - callStmt.registerOutParameter(1, Types.VARCHAR); - callStmt.setString(2, tableName.toUpperCase()); - callStmt.execute(); - String stringFlag = callStmt.getString(1); - if (stringFlag.equalsIgnoreCase("TRUE")) { - returnFlag = true; - } else { - returnFlag = false; - } - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - log.error("SQLException occured" + sqlEx.getMessage(), sqlEx); - throw new I2B2Exception( - "SQLException occured" + sqlEx.getMessage(), sqlEx); - } catch (Exception ex) { - ex.printStackTrace(); - throw new I2B2Exception("Exception occured" + ex.getMessage(), ex); - } finally { - if (conn != null) { - try { - conn.close(); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - log.error("Error while closing connection", sqlEx); - } - } - } - return returnFlag; - } - - /** - * Function to call MERGE_TEMP_OBSERVATION_FACT(?) stored procedure. - * - * @param tempTableName - * @throws Exception - */ - @Override - public void doTempTableMerge(String tempTableName, int uploadId, - boolean appendFlag) throws I2B2Exception { - Connection conn = null; - try { - conn = getDataSource().getConnection(); - CallableStatement callStmt = conn.prepareCall("{call " - + this.getDbSchemaName() - + "UPDATE_OBSERVATION_FACT(?,?,?,?)}"); - callStmt.setString(1, tempTableName); - callStmt.setInt(2, uploadId); - - if (appendFlag == true) { - callStmt.setInt(3, 1); - } else { - callStmt.setInt(3, 0); - } - callStmt.registerOutParameter(4, java.sql.Types.VARCHAR); - callStmt.execute(); - this.getSQLServerProcedureError(dataSourceLookup.getServerType(), - callStmt, 4); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - throw new I2B2Exception( - "SQLException occured" + sqlEx.getMessage(), sqlEx); - } catch (Exception ex) { - ex.printStackTrace(); - throw new I2B2Exception("Exception occured" + ex.getMessage(), ex); - } finally { - if (conn != null) { - try { - conn.close(); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - log.error("Error while closing connection", sqlEx); - } - } - } - - } - - /** - * Function to call remove temp table stored procedure. - * - * @param tempTableName - * @throws Exception - */ - @Override - public void removeTempTable(String tempTableName) throws I2B2Exception { - Connection conn = null; - try { - - conn = getDataSource().getConnection(); - CallableStatement callStmt = conn.prepareCall("{call " - + this.getDbSchemaName() + "REMOVE_TEMP_TABLE(?)}"); - callStmt.setString(1, tempTableName); - callStmt.execute(); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - throw new I2B2Exception( - "SQLException occured" + sqlEx.getMessage(), sqlEx); - } catch (Exception ex) { - ex.printStackTrace(); - throw new I2B2Exception("Exception occured" + ex.getMessage(), ex); - } finally { - if (conn != null) { - try { - conn.close(); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - log.error("Error while closing connection", sqlEx); - } - } - } - } - - /** - * Function to create create temp table stored proc. - * - * @param tempTableName - * @throws Exception - */ - @Override - public void createTempTable(String tempTableName) throws I2B2Exception { - Connection conn = null; - try { - conn = getDataSource().getConnection(); - CallableStatement callStmt = conn.prepareCall("{call " - + this.getDbSchemaName() + "CREATE_TEMP_TABLE(?,?)}"); - callStmt.setString(1, tempTableName); - callStmt.registerOutParameter(2, java.sql.Types.VARCHAR); - callStmt.execute(); - this.getSQLServerProcedureError(dataSourceLookup.getServerType(), - callStmt, 2); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - throw new I2B2Exception( - "SQLException occured" + sqlEx.getMessage(), sqlEx); - } catch (Exception ex) { - ex.printStackTrace(); - throw new I2B2Exception("Exception occured" + ex.getMessage(), ex); - } finally { - if (conn != null) { - try { - conn.close(); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - log.error("Error while closing connection", sqlEx); - } - } - } - } - - @Override - public void writeMissedDataLog(BufferedWriter bufWriter, - String tempTableName) throws I2B2Exception { - String queryString = "select a.* " - + " from (select utemp.encounter_ide, utemp.patient_ide, utemp.concept_cd, " - + " utemp.provider_id,utemp.start_date,utemp.modifier_cd " - + " from temp_upload_try1 utemp " - + " where utemp.encounter_ide not in (select emap.encounter_ide from encounter_mapping emap) " - + " union " - + " select utemp1.encounter_ide, utemp1.patient_ide, utemp1.concept_cd, " - + " utemp1.provider_id,utemp1.start_date,utemp1.modifier_cd " - + " from temp_upload_try1 utemp1 " - + " where utemp1.patient_ide not in (select patmap.patient_ide from patient_mapping patmap ) " - + " union " - + " select utemp.encounter_ide, utemp.patient_ide, utemp.concept_cd, " - + " utemp.provider_id,utemp.start_date,utemp.modifier_cd " - + " from temp_upload_try1 utemp " - + " where utemp.concept_cd is null " + " ) a "; - - Statement stmt = null; - try { - stmt = getDataSource().getConnection().createStatement(); - stmt.setFetchSize(5000); - ResultSet resultSet = stmt.executeQuery(queryString); - String encounterIde = "", patientIde = "", conceptCd = "", providerId = ""; - Date startDate = null; - while (resultSet.next()) { - encounterIde = resultSet.getString("encounter_ide"); - patientIde = resultSet.getString("patient_ide"); - conceptCd = resultSet.getString("concept_cd"); - providerId = resultSet.getString("provider_id"); - startDate = resultSet.getDate("start_date"); - // write to logwriter - bufWriter.write(encounterIde + "|" + patientIde + "|" - + conceptCd + "|" + providerId + "\n"); - } - } catch (IOException ioEx) { - log.error("IOException ", ioEx); - throw new I2B2Exception("IOException " + ioEx.getMessage(), ioEx); - } catch (SQLException sqlEx) { - log.error("SQLException ", sqlEx); - throw new I2B2Exception("SQLException " + sqlEx.getMessage(), sqlEx); - } catch (Exception ex) { - log.error("Exception ", ex); - throw new I2B2Exception("Exception " + ex.getMessage(), ex); - } finally { - try { - stmt.close(); - } catch (SQLException sqlEx) { - log.info("Unable to close statment", sqlEx); - } - } - - } - - // ************* Operation Objects section *************** - - /** - * ObservationFact Insert Object. - */ - protected class ObservationFactInsert extends BatchSqlUpdate { - /** - * Create a new instance of ObservationInsert. - * - * @param ds - * the DataSource to use for the insert - */ - protected ObservationFactInsert(DataSource ds, - String observationFactTable, String schemaName) { - super( - ds, - "INSERT INTO " - + schemaName - + observationFactTable - + " (" - + "encounter_id, " - + "encounter_id_source, " - + "concept_cd, " - + "patient_id, " - + "patient_id_source, " - + "provider_id, " - + "start_date, " - + "modifier_cd, " - + "instance_num, " - + "valtype_cd, " - + "tval_char, " - + "nval_num, " - + "valueflag_cd, " - + "quantity_num, " - + "confidence_num, " - + "observation_blob, " - + "units_cd, " - + "end_date, " - + "location_cd, " - + "update_date, " - + "download_date, " - + "import_Date, " - + "sourcesystem_cd," - + "upload_id) " - + " VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.TIMESTAMP)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.INTEGER)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.FLOAT)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.FLOAT)); - declareParameter(new SqlParameter(Types.BIGINT)); - declareParameter(new SqlParameter(Types.LONGVARCHAR)); // Types.CLOB - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.TIMESTAMP)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.TIMESTAMP)); - declareParameter(new SqlParameter(Types.TIMESTAMP)); - declareParameter(new SqlParameter(Types.TIMESTAMP)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.INTEGER)); - compile(); - } - - protected void insert(ObservationType observationType) { - - // new SqlLobValue(observationType - // .getObservationBlob().getContent().get(0)) - - Object[] objs = new Object[] { - // observationFactMap.get("encounter_ide"), - observationType.getEventId().getValue(), - observationType.getEventId().getSource(), - // observationFactMap.get("concept_cd"), - observationType.getConceptCd().getValue(), - // observationFactMap.get("patient_ide"), - (observationType.getPatientId() != null) ? observationType - .getPatientId().getValue() : null, - (observationType.getPatientId() != null) ? observationType - .getPatientId().getSource() : null, - // observationFactMap.get("provider_id"), - (observationType.getObserverCd() != null) ? observationType - .getObserverCd().getValue() : null, - // observationFactMap.get("start_date"), - (observationType.getStartDate() != null) ? observationType - .getStartDate().toGregorianCalendar().getTime() - : null, - // observationFactMap.get("modifier_cd"), - (observationType.getModifierCd() != null) ? observationType - .getModifierCd().getValue() : null, - (observationType.getInstanceNum() != null) ? observationType - .getInstanceNum().getValue() - : null, - // observationFactMap.get("valtype_cd"), - observationType.getValuetypeCd(), - // observationFactMap.get("tval_char"), - observationType.getTvalChar(), - // (Float)observationFactMap.get("nval_num"), - (observationType.getNvalNum() != null) ? observationType - .getNvalNum().getValue() : null, - // observationFactMap.get("valueflag_cd"), - (observationType.getValueflagCd() != null) ? observationType - .getValueflagCd().getValue() - : null, - // (Float)observationFactMap.get("quantity_num"), - (observationType.getQuantityNum() != null) ? observationType - .getQuantityNum() - : null, - // observationFactMap.get("confidence_num"), - - // TODO add confidence number to observation - null, - // observationFactMap.get("observation_blob"), - (observationType.getObservationBlob() != null) ? observationType - .getObservationBlob().getContent().get(0) - .toString() - : null, - // observationFactMap.get("units_cd"), - observationType.getUnitsCd(), - // observationFactMap.get("end_date"), - (observationType.getEndDate() != null) ? observationType - .getEndDate().toGregorianCalendar().getTime() - : null, - // observationFactMap.get("location_cd"), - (observationType.getLocationCd() != null) ? observationType - .getLocationCd().getValue() : null, - // (Date) observationFactMap.get("update_date"), - (observationType.getUpdateDate() != null) ? observationType - .getUpdateDate().toGregorianCalendar().getTime() - : null, - // (Date) observationFactMap.get("download_date"), - (observationType.getDownloadDate() != null) ? observationType - .getDownloadDate().toGregorianCalendar().getTime() - : null, - // (Date) observationFactMap.get("import_date"), - (observationType.getImportDate() != null) ? observationType - .getImportDate().toGregorianCalendar().getTime() - : null, - // observationFactMap.get("sourcesystem_cd"), - observationType.getSourcesystemCd(), - // observationFactMap.get("upload_id") - observationType.getUploadId() }; - update(objs); - } - - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.dao; + +import java.io.BufferedWriter; +import java.io.IOException; +import java.sql.CallableStatement; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.sql.Types; +import java.util.Date; + +import javax.sql.DataSource; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.SqlParameter; +import org.springframework.jdbc.object.BatchSqlUpdate; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.crc.loader.datavo.loader.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.pdo.ObservationType; + +/** + * Observation Fact data access object. + * + * @author rk903 + * + */ +public class ObservationFactDAO extends CRCLoaderDAO implements + IObservationFactDAO { + + private int DB_BATCH_INSERT_SIZE = 1; + + private static Log log = LogFactory.getLog(ObservationFactDAO.class); + private DataSourceLookup dataSourceLookup = null; + + public ObservationFactDAO(DataSourceLookup dataSourceLookup, DataSource ds) { + setDataSource(ds); + setDbSchemaName(dataSourceLookup.getFullSchema()); + this.dataSourceLookup = dataSourceLookup; + + } + + @Override + public int getRecordCountByUploadId(int uploadId) { + JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); + int insertCount = jdbcTemplate.queryForObject("select count(1) from " + + getDbSchemaName() + "observation_fact where upload_id =?",Integer.class, + new Object[] { uploadId }); + return insertCount; + } + + /** + * Create batch insert handle for temp observation fact table. + * + * @param tempTableName + * @return + */ + @Override + public ObservationFactInsertHandle createObservationFactInserter( + String tempTableName) { + ObservationFactInsert observationFactInsert = new ObservationFactInsert( + getDataSource(), tempTableName, getDbSchemaName()); + observationFactInsert.setBatchSize(DB_BATCH_INSERT_SIZE); + return new ObservationFactInsertHandle(observationFactInsert); + } + + /** + * Function to check if given table exists + * + * @param tableName + * @return boolean + * @throws Exception + */ + @Override + public boolean checkTableExists(String tableName) throws I2B2Exception { + Connection conn = null; + boolean returnFlag = false; + try { + conn = getDataSource().getConnection(); + CallableStatement callStmt = conn.prepareCall("{? = call " + + this.getDbSchemaName() + "isTableExists(?)}"); + callStmt.registerOutParameter(1, Types.VARCHAR); + callStmt.setString(2, tableName.toUpperCase()); + callStmt.execute(); + String stringFlag = callStmt.getString(1); + if (stringFlag.equalsIgnoreCase("TRUE")) { + returnFlag = true; + } else { + returnFlag = false; + } + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + log.error("SQLException occured" + sqlEx.getMessage(), sqlEx); + throw new I2B2Exception( + "SQLException occured" + sqlEx.getMessage(), sqlEx); + } catch (Exception ex) { + ex.printStackTrace(); + throw new I2B2Exception("Exception occured" + ex.getMessage(), ex); + } finally { + if (conn != null) { + try { + conn.close(); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + log.error("Error while closing connection", sqlEx); + } + } + } + return returnFlag; + } + + /** + * Function to call MERGE_TEMP_OBSERVATION_FACT(?) stored procedure. + * + * @param tempTableName + * @throws Exception + */ + @Override + public void doTempTableMerge(String tempTableName, int uploadId, + boolean appendFlag) throws I2B2Exception { + Connection conn = null; + try { + conn = getDataSource().getConnection(); + CallableStatement callStmt = conn.prepareCall("{call " + + this.getDbSchemaName() + + "UPDATE_OBSERVATION_FACT(?,?,?,?)}"); + callStmt.setString(1, tempTableName); + callStmt.setInt(2, uploadId); + + if (appendFlag == true) { + callStmt.setInt(3, 1); + } else { + callStmt.setInt(3, 0); + } + callStmt.registerOutParameter(4, java.sql.Types.VARCHAR); + callStmt.execute(); + this.getSQLServerProcedureError(dataSourceLookup.getServerType(), + callStmt, 4); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + throw new I2B2Exception( + "SQLException occured" + sqlEx.getMessage(), sqlEx); + } catch (Exception ex) { + ex.printStackTrace(); + throw new I2B2Exception("Exception occured" + ex.getMessage(), ex); + } finally { + if (conn != null) { + try { + conn.close(); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + log.error("Error while closing connection", sqlEx); + } + } + } + + } + + /** + * Function to call remove temp table stored procedure. + * + * @param tempTableName + * @throws Exception + */ + @Override + public void removeTempTable(String tempTableName) throws I2B2Exception { + Connection conn = null; + try { + + conn = getDataSource().getConnection(); + CallableStatement callStmt = conn.prepareCall("{call " + + this.getDbSchemaName() + "REMOVE_TEMP_TABLE(?)}"); + callStmt.setString(1, tempTableName); + callStmt.execute(); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + throw new I2B2Exception( + "SQLException occured" + sqlEx.getMessage(), sqlEx); + } catch (Exception ex) { + ex.printStackTrace(); + throw new I2B2Exception("Exception occured" + ex.getMessage(), ex); + } finally { + if (conn != null) { + try { + conn.close(); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + log.error("Error while closing connection", sqlEx); + } + } + } + } + + /** + * Function to create create temp table stored proc. + * + * @param tempTableName + * @throws Exception + */ + @Override + public void createTempTable(String tempTableName) throws I2B2Exception { + Connection conn = null; + try { + conn = getDataSource().getConnection(); + CallableStatement callStmt = conn.prepareCall("{call " + + this.getDbSchemaName() + "CREATE_TEMP_TABLE(?,?)}"); + callStmt.setString(1, tempTableName); + callStmt.registerOutParameter(2, java.sql.Types.VARCHAR); + callStmt.execute(); + this.getSQLServerProcedureError(dataSourceLookup.getServerType(), + callStmt, 2); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + throw new I2B2Exception( + "SQLException occured" + sqlEx.getMessage(), sqlEx); + } catch (Exception ex) { + ex.printStackTrace(); + throw new I2B2Exception("Exception occured" + ex.getMessage(), ex); + } finally { + if (conn != null) { + try { + conn.close(); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + log.error("Error while closing connection", sqlEx); + } + } + } + } + + @Override + public void writeMissedDataLog(BufferedWriter bufWriter, + String tempTableName) throws I2B2Exception { + String queryString = "select a.* " + + " from (select utemp.encounter_ide, utemp.patient_ide, utemp.concept_cd, " + + " utemp.provider_id,utemp.start_date,utemp.modifier_cd " + + " from temp_upload_try1 utemp " + + " where utemp.encounter_ide not in (select emap.encounter_ide from encounter_mapping emap) " + + " union " + + " select utemp1.encounter_ide, utemp1.patient_ide, utemp1.concept_cd, " + + " utemp1.provider_id,utemp1.start_date,utemp1.modifier_cd " + + " from temp_upload_try1 utemp1 " + + " where utemp1.patient_ide not in (select patmap.patient_ide from patient_mapping patmap ) " + + " union " + + " select utemp.encounter_ide, utemp.patient_ide, utemp.concept_cd, " + + " utemp.provider_id,utemp.start_date,utemp.modifier_cd " + + " from temp_upload_try1 utemp " + + " where utemp.concept_cd is null " + " ) a "; + + Statement stmt = null; + try { + stmt = getDataSource().getConnection().createStatement(); + stmt.setFetchSize(5000); + ResultSet resultSet = stmt.executeQuery(queryString); + String encounterIde = "", patientIde = "", conceptCd = "", providerId = ""; + Date startDate = null; + while (resultSet.next()) { + encounterIde = resultSet.getString("encounter_ide"); + patientIde = resultSet.getString("patient_ide"); + conceptCd = resultSet.getString("concept_cd"); + providerId = resultSet.getString("provider_id"); + startDate = resultSet.getDate("start_date"); + // write to logwriter + bufWriter.write(encounterIde + "|" + patientIde + "|" + + conceptCd + "|" + providerId + "\n"); + } + } catch (IOException ioEx) { + log.error("IOException ", ioEx); + throw new I2B2Exception("IOException " + ioEx.getMessage(), ioEx); + } catch (SQLException sqlEx) { + log.error("SQLException ", sqlEx); + throw new I2B2Exception("SQLException " + sqlEx.getMessage(), sqlEx); + } catch (Exception ex) { + log.error("Exception ", ex); + throw new I2B2Exception("Exception " + ex.getMessage(), ex); + } finally { + try { + stmt.close(); + } catch (SQLException sqlEx) { + log.info("Unable to close statment", sqlEx); + } + } + + } + + // ************* Operation Objects section *************** + + /** + * ObservationFact Insert Object. + */ + protected class ObservationFactInsert extends BatchSqlUpdate { + /** + * Create a new instance of ObservationInsert. + * + * @param ds + * the DataSource to use for the insert + */ + protected ObservationFactInsert(DataSource ds, + String observationFactTable, String schemaName) { + super( + ds, + "INSERT INTO " + + schemaName + + observationFactTable + + " (" + + "encounter_id, " + + "encounter_id_source, " + + "concept_cd, " + + "patient_id, " + + "patient_id_source, " + + "provider_id, " + + "start_date, " + + "modifier_cd, " + + "instance_num, " + + "valtype_cd, " + + "tval_char, " + + "nval_num, " + + "valueflag_cd, " + + "quantity_num, " + + "confidence_num, " + + "observation_blob, " + + "units_cd, " + + "end_date, " + + "location_cd, " + + "update_date, " + + "download_date, " + + "import_Date, " + + "sourcesystem_cd," + + "upload_id) " + + " VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.TIMESTAMP)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.INTEGER)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.FLOAT)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.FLOAT)); + declareParameter(new SqlParameter(Types.BIGINT)); + declareParameter(new SqlParameter(Types.LONGVARCHAR)); // Types.CLOB + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.TIMESTAMP)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.TIMESTAMP)); + declareParameter(new SqlParameter(Types.TIMESTAMP)); + declareParameter(new SqlParameter(Types.TIMESTAMP)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.INTEGER)); + compile(); + } + + protected void insert(ObservationType observationType) { + + // new SqlLobValue(observationType + // .getObservationBlob().getContent().get(0)) + + Object[] objs = new Object[] { + // observationFactMap.get("encounter_ide"), + observationType.getEventId().getValue(), + observationType.getEventId().getSource(), + // observationFactMap.get("concept_cd"), + observationType.getConceptCd().getValue(), + // observationFactMap.get("patient_ide"), + (observationType.getPatientId() != null) ? observationType + .getPatientId().getValue() : null, + (observationType.getPatientId() != null) ? observationType + .getPatientId().getSource() : null, + // observationFactMap.get("provider_id"), + (observationType.getObserverCd() != null) ? observationType + .getObserverCd().getValue() : null, + // observationFactMap.get("start_date"), + (observationType.getStartDate() != null) ? observationType + .getStartDate().toGregorianCalendar().getTime() + : null, + // observationFactMap.get("modifier_cd"), + (observationType.getModifierCd() != null) ? observationType + .getModifierCd().getValue() : null, + (observationType.getInstanceNum() != null) ? observationType + .getInstanceNum().getValue() + : null, + // observationFactMap.get("valtype_cd"), + observationType.getValuetypeCd(), + // observationFactMap.get("tval_char"), + observationType.getTvalChar(), + // (Float)observationFactMap.get("nval_num"), + (observationType.getNvalNum() != null) ? observationType + .getNvalNum().getValue() : null, + // observationFactMap.get("valueflag_cd"), + (observationType.getValueflagCd() != null) ? observationType + .getValueflagCd().getValue() + : null, + // (Float)observationFactMap.get("quantity_num"), + (observationType.getQuantityNum() != null) ? observationType + .getQuantityNum() + : null, + // observationFactMap.get("confidence_num"), + + // TODO add confidence number to observation + null, + // observationFactMap.get("observation_blob"), + (observationType.getObservationBlob() != null) ? observationType + .getObservationBlob().getContent().get(0) + .toString() + : null, + // observationFactMap.get("units_cd"), + observationType.getUnitsCd(), + // observationFactMap.get("end_date"), + (observationType.getEndDate() != null) ? observationType + .getEndDate().toGregorianCalendar().getTime() + : null, + // observationFactMap.get("location_cd"), + (observationType.getLocationCd() != null) ? observationType + .getLocationCd().getValue() : null, + // (Date) observationFactMap.get("update_date"), + (observationType.getUpdateDate() != null) ? observationType + .getUpdateDate().toGregorianCalendar().getTime() + : null, + // (Date) observationFactMap.get("download_date"), + (observationType.getDownloadDate() != null) ? observationType + .getDownloadDate().toGregorianCalendar().getTime() + : null, + // (Date) observationFactMap.get("import_date"), + (observationType.getImportDate() != null) ? observationType + .getImportDate().toGregorianCalendar().getTime() + : null, + // observationFactMap.get("sourcesystem_cd"), + observationType.getSourcesystemCd(), + // observationFactMap.get("upload_id") + observationType.getUploadId() }; + update(objs); + } + + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/ObservationFactInsertHandle.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/ObservationFactInsertHandle.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/ObservationFactInsertHandle.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/ObservationFactInsertHandle.java index b84249ba..e3634f66 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/ObservationFactInsertHandle.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/ObservationFactInsertHandle.java @@ -1,44 +1,44 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.dao; - -import edu.harvard.i2b2.crc.datavo.pdo.ObservationType; - -/** - * Handle to insert temp obervation fact data. Wraps Springs batch inserter. - * - * @author rk903 - * - */ -public class ObservationFactInsertHandle { - private ObservationFactDAO.ObservationFactInsert observationFactInsert = null; - - public ObservationFactInsertHandle( - ObservationFactDAO.ObservationFactInsert observationFactInsert) { - this.observationFactInsert = observationFactInsert; - } - - /** - * Submit individual inserts to batch. - * - * @param observationFact - */ - public void insertObservationFact(ObservationType observation) { - observationFactInsert.insert(observation); - } - - /** - * Manual submit of batched inserts. - */ - public void flush() { - observationFactInsert.flush(); - observationFactInsert.reset(); - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.dao; + +import edu.harvard.i2b2.crc.datavo.pdo.ObservationType; + +/** + * Handle to insert temp obervation fact data. Wraps Springs batch inserter. + * + * @author rk903 + * + */ +public class ObservationFactInsertHandle { + private ObservationFactDAO.ObservationFactInsert observationFactInsert = null; + + public ObservationFactInsertHandle( + ObservationFactDAO.ObservationFactInsert observationFactInsert) { + this.observationFactInsert = observationFactInsert; + } + + /** + * Submit individual inserts to batch. + * + * @param observationFact + */ + public void insertObservationFact(ObservationType observation) { + observationFactInsert.insert(observation); + } + + /** + * Manual submit of batched inserts. + */ + public void flush() { + observationFactInsert.flush(); + observationFactInsert.reset(); + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/OracleDataSourceLookupDAO.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/OracleDataSourceLookupDAO.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/OracleDataSourceLookupDAO.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/OracleDataSourceLookupDAO.java index a8ba234d..f75030e8 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/OracleDataSourceLookupDAO.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/OracleDataSourceLookupDAO.java @@ -1,78 +1,78 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.dao; - -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Types; -import java.util.List; - -import javax.sql.DataSource; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.jdbc.core.RowMapper; - -import edu.harvard.i2b2.common.util.db.JDBCUtil; -import edu.harvard.i2b2.crc.loader.datavo.loader.DataSourceLookup; - -public class OracleDataSourceLookupDAO extends DataSourceLookupDAO { - - /** log **/ - protected final Log log = LogFactory.getLog(OracleDataSourceLookupDAO.class); - - private String schemaName = null; - - public OracleDataSourceLookupDAO(DataSource dataSource,String schemaName) { - setDataSource(dataSource); - this.schemaName = schemaName; - } - - @Override - public List getDbLookupByHiveOwner(String domainId,String ownerId) { - String sql = "select * from crc_db_lookup where LOWER(c_domain_id) = ? and c_project_path = ? and (LOWER(c_owner_id) = ? or c_owner_id ='@') order by c_project_path"; - String projectId = "@"; - List dataSourceLookupList = - this.query(sql, new Object[]{domainId.toLowerCase(),projectId,ownerId.toLowerCase()}, new mapper()); - return dataSourceLookupList; - } - - @Override - public List getDbLookupByHiveProjectOwner(String domainId, String projectId, - String ownerId) { - String sql = "select * from crc_db_lookup where LOWER(c_domain_id) = ? and c_project_path like ? and (LOWER(c_owner_id) =? or c_owner_id = '@') order by c_project_path"; - List dataSourceLookupList = this.query(sql, new Object[]{domainId.toLowerCase(),projectId+"%",ownerId.toLowerCase()},new int[]{Types.VARCHAR,Types.VARCHAR,Types.VARCHAR},new mapper() ); - return dataSourceLookupList; - } - - - public class mapper implements RowMapper { - - @Override - public Object mapRow(ResultSet rs, int rowNum) throws SQLException { - DataSourceLookup dataSourceLookup = new DataSourceLookup(); - dataSourceLookup.setDomainId(rs.getString("c_domain_id")); - dataSourceLookup.setProjectPath(rs.getString("c_project_path")); - dataSourceLookup.setOwnerId(rs.getString("c_owner_id")); - dataSourceLookup.setFullSchema(rs.getString("c_db_fullschema")); - dataSourceLookup.setDataSource(rs.getString("c_db_datasource")); - dataSourceLookup.setServerType(rs.getString("c_db_servertype")); - dataSourceLookup.setNiceName(rs.getString("c_db_nicename")); - dataSourceLookup.setToolTip(rs.getString("c_db_tooltip")); - dataSourceLookup.setComment(rs.getString("c_comment")); - dataSourceLookup.setEntryDate(rs.getDate("c_entry_date")); - dataSourceLookup.setChangeDate(rs.getDate("c_change_date")); - dataSourceLookup.setStatusCd(rs.getString("c_status_cd")); - return dataSourceLookup; - } - } -} - - - +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.dao; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Types; +import java.util.List; + +import javax.sql.DataSource; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.jdbc.core.RowMapper; + +import edu.harvard.i2b2.common.util.db.JDBCUtil; +import edu.harvard.i2b2.crc.loader.datavo.loader.DataSourceLookup; + +public class OracleDataSourceLookupDAO extends DataSourceLookupDAO { + + /** log **/ + protected final Log log = LogFactory.getLog(OracleDataSourceLookupDAO.class); + + private String schemaName = null; + + public OracleDataSourceLookupDAO(DataSource dataSource,String schemaName) { + setDataSource(dataSource); + this.schemaName = schemaName; + } + + @Override + public List getDbLookupByHiveOwner(String domainId,String ownerId) { + String sql = "select * from crc_db_lookup where LOWER(c_domain_id) = ? and c_project_path = ? and (LOWER(c_owner_id) = ? or c_owner_id ='@') order by c_project_path"; + String projectId = "@"; + List dataSourceLookupList = + this.query(sql, new Object[]{domainId.toLowerCase(),projectId,ownerId.toLowerCase()}, new mapper()); + return dataSourceLookupList; + } + + @Override + public List getDbLookupByHiveProjectOwner(String domainId, String projectId, + String ownerId) { + String sql = "select * from crc_db_lookup where LOWER(c_domain_id) = ? and c_project_path like ? and (LOWER(c_owner_id) =? or c_owner_id = '@') order by c_project_path"; + List dataSourceLookupList = this.query(sql, new Object[]{domainId.toLowerCase(),projectId+"%",ownerId.toLowerCase()},new int[]{Types.VARCHAR,Types.VARCHAR,Types.VARCHAR},new mapper() ); + return dataSourceLookupList; + } + + + public class mapper implements RowMapper { + + @Override + public Object mapRow(ResultSet rs, int rowNum) throws SQLException { + DataSourceLookup dataSourceLookup = new DataSourceLookup(); + dataSourceLookup.setDomainId(rs.getString("c_domain_id")); + dataSourceLookup.setProjectPath(rs.getString("c_project_path")); + dataSourceLookup.setOwnerId(rs.getString("c_owner_id")); + dataSourceLookup.setFullSchema(rs.getString("c_db_fullschema")); + dataSourceLookup.setDataSource(rs.getString("c_db_datasource")); + dataSourceLookup.setServerType(rs.getString("c_db_servertype")); + dataSourceLookup.setNiceName(rs.getString("c_db_nicename")); + dataSourceLookup.setToolTip(rs.getString("c_db_tooltip")); + dataSourceLookup.setComment(rs.getString("c_comment")); + dataSourceLookup.setEntryDate(rs.getDate("c_entry_date")); + dataSourceLookup.setChangeDate(rs.getDate("c_change_date")); + dataSourceLookup.setStatusCd(rs.getString("c_status_cd")); + return dataSourceLookup; + } + } +} + + + diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/OracleLoaderDAOFactory.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/OracleLoaderDAOFactory.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/OracleLoaderDAOFactory.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/OracleLoaderDAOFactory.java index d89c599a..cf2eedd5 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/OracleLoaderDAOFactory.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/OracleLoaderDAOFactory.java @@ -1,26 +1,26 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.dao; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.crc.loader.datavo.loader.DataSourceLookup; - -public class OracleLoaderDAOFactory implements ILoaderDAOFactory { - - private DataSourceLookup dataSourceLookup = null; - - public OracleLoaderDAOFactory(DataSourceLookup dataSourceLookup) { - this.dataSourceLookup = dataSourceLookup; - } - - @Override - public IUploaderDAOFactory getUpLoaderDAOFactory() throws I2B2Exception { - return new OracleUploaderDAOFactory(dataSourceLookup); - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.dao; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.crc.loader.datavo.loader.DataSourceLookup; + +public class OracleLoaderDAOFactory implements ILoaderDAOFactory { + + private DataSourceLookup dataSourceLookup = null; + + public OracleLoaderDAOFactory(DataSourceLookup dataSourceLookup) { + this.dataSourceLookup = dataSourceLookup; + } + + @Override + public IUploaderDAOFactory getUpLoaderDAOFactory() throws I2B2Exception { + return new OracleUploaderDAOFactory(dataSourceLookup); + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/OracleUploaderDAOFactory.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/OracleUploaderDAOFactory.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/OracleUploaderDAOFactory.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/OracleUploaderDAOFactory.java index d4595e13..daaf9ef1 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/OracleUploaderDAOFactory.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/OracleUploaderDAOFactory.java @@ -1,130 +1,130 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.dao; - -import javax.sql.DataSource; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.ServiceLocator; -import edu.harvard.i2b2.crc.loader.datavo.loader.DataSourceLookup; - -public class OracleUploaderDAOFactory implements IUploaderDAOFactory { - - private DataSourceLookup dataSourceLookup = null; - private DataSource dataSource = null; - - /** log **/ - protected final static Log log = LogFactory - .getLog(OracleUploaderDAOFactory.class); - - public OracleUploaderDAOFactory(DataSourceLookup dataSourceLookup) - throws I2B2Exception { - this.dataSourceLookup = dataSourceLookup; - String dataSourceName = dataSourceLookup.getDataSource(); - log.info("Using datasource " + dataSourceName); - try { - // dataSource = (DataSource) - // crcUtil.getSpringDataSource(dataSourceName); - dataSource = ServiceLocator.getInstance().getAppServerDataSource( - dataSourceName); - } catch (I2B2Exception i2b2Ex) { - log.error(i2b2Ex); - throw new I2B2DAOException( - "Error getting application/spring datasource " - + dataSourceName + " : " + i2b2Ex.getMessage(), - i2b2Ex); - } - } - - /** - * Constructor for testing, datasource can be passed as parameter. - * - * @param dataSourceLookup - * @param dataSource - */ - public OracleUploaderDAOFactory(DataSourceLookup dataSourceLookup, - DataSource dataSource) { - this.dataSourceLookup = dataSourceLookup; - this.dataSource = dataSource; - } - - @Override - public IConceptDAO getConceptDAO() { - return new ConceptDAO(dataSourceLookup, dataSource); - } - - @Override - public IModifierDAO getModifierDAO() { - return new ModifierDAO(dataSourceLookup, dataSource); - } - - @Override - public IObservationFactDAO getObservationDAO() { - return new ObservationFactDAO(dataSourceLookup, dataSource); - } - - @Override - public IPatientDAO getPatientDAO() { - return new PatientDAO(dataSourceLookup, dataSource); - } - - @Override - public IPidDAO getPidDAO() { - return new PidDAO(dataSourceLookup, dataSource); - } - - @Override - public IEidDAO getEidDAO() { - return new EidDAO(dataSourceLookup, dataSource); - } - - @Override - public IProviderDAO getProviderDAO() { - return new ProviderDAO(dataSourceLookup, dataSource); - } - - @Override - public UploadStatusDAOI getUploadStatusDAO() { - return new UploadStatusDAO(dataSourceLookup, dataSource); - } - - @Override - public IVisitDAO getVisitDAO() { - return new VisitDAO(dataSourceLookup, dataSource); - } - - - @Override - public IMissingTermDAO getMissingTermDAO() { - return new MissingTermDAO(dataSourceLookup, dataSource); - } - - - @Override - public DataSourceLookup getDataSourceLookup() { - // TODO Auto-generated method stub - return dataSourceLookup; - } - - @Override - public DataSource getDataSource() { - return this.dataSource; - } - - @Override - public void setDataSource(DataSource dataSource) { - this.dataSource = dataSource; - - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.dao; + +import javax.sql.DataSource; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.ServiceLocator; +import edu.harvard.i2b2.crc.loader.datavo.loader.DataSourceLookup; + +public class OracleUploaderDAOFactory implements IUploaderDAOFactory { + + private DataSourceLookup dataSourceLookup = null; + private DataSource dataSource = null; + + /** log **/ + protected final static Log log = LogFactory + .getLog(OracleUploaderDAOFactory.class); + + public OracleUploaderDAOFactory(DataSourceLookup dataSourceLookup) + throws I2B2Exception { + this.dataSourceLookup = dataSourceLookup; + String dataSourceName = dataSourceLookup.getDataSource(); + log.info("Using datasource " + dataSourceName); + try { + // dataSource = (DataSource) + // crcUtil.getSpringDataSource(dataSourceName); + dataSource = ServiceLocator.getInstance().getAppServerDataSource( + dataSourceName); + } catch (I2B2Exception i2b2Ex) { + log.error(i2b2Ex); + throw new I2B2DAOException( + "Error getting application/spring datasource " + + dataSourceName + " : " + i2b2Ex.getMessage(), + i2b2Ex); + } + } + + /** + * Constructor for testing, datasource can be passed as parameter. + * + * @param dataSourceLookup + * @param dataSource + */ + public OracleUploaderDAOFactory(DataSourceLookup dataSourceLookup, + DataSource dataSource) { + this.dataSourceLookup = dataSourceLookup; + this.dataSource = dataSource; + } + + @Override + public IConceptDAO getConceptDAO() { + return new ConceptDAO(dataSourceLookup, dataSource); + } + + @Override + public IModifierDAO getModifierDAO() { + return new ModifierDAO(dataSourceLookup, dataSource); + } + + @Override + public IObservationFactDAO getObservationDAO() { + return new ObservationFactDAO(dataSourceLookup, dataSource); + } + + @Override + public IPatientDAO getPatientDAO() { + return new PatientDAO(dataSourceLookup, dataSource); + } + + @Override + public IPidDAO getPidDAO() { + return new PidDAO(dataSourceLookup, dataSource); + } + + @Override + public IEidDAO getEidDAO() { + return new EidDAO(dataSourceLookup, dataSource); + } + + @Override + public IProviderDAO getProviderDAO() { + return new ProviderDAO(dataSourceLookup, dataSource); + } + + @Override + public UploadStatusDAOI getUploadStatusDAO() { + return new UploadStatusDAO(dataSourceLookup, dataSource); + } + + @Override + public IVisitDAO getVisitDAO() { + return new VisitDAO(dataSourceLookup, dataSource); + } + + + @Override + public IMissingTermDAO getMissingTermDAO() { + return new MissingTermDAO(dataSourceLookup, dataSource); + } + + + @Override + public DataSourceLookup getDataSourceLookup() { + // TODO Auto-generated method stub + return dataSourceLookup; + } + + @Override + public DataSource getDataSource() { + return this.dataSource; + } + + @Override + public void setDataSource(DataSource dataSource) { + this.dataSource = dataSource; + + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/PatientDAO.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/PatientDAO.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/PatientDAO.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/PatientDAO.java index dd4e7f83..a86daf7f --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/PatientDAO.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/PatientDAO.java @@ -1,362 +1,362 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.dao; - -import java.sql.CallableStatement; -import java.sql.Connection; -import java.sql.SQLException; -import java.sql.Types; -import java.util.HashMap; -import java.util.Map; - -import javax.sql.DataSource; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.SqlParameter; -import org.springframework.jdbc.object.BatchSqlUpdate; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.crc.loader.datavo.loader.DataSourceLookup; -import edu.harvard.i2b2.crc.loader.datavo.loader.Patient; -import edu.harvard.i2b2.crc.datavo.pdo.ParamType; -import edu.harvard.i2b2.crc.datavo.pdo.PatientType; - -/** - * Patient Dimension data access object. - * - * @author rk903 - */ -public class PatientDAO extends CRCLoaderDAO implements IPatientDAO { - - private int DB_BATCH_INSERT_SIZE = 2000; - - private static Log log = LogFactory.getLog(PatientDAO.class); - private DataSourceLookup dataSourceLookup = null; - - public PatientDAO(DataSourceLookup dataSourceLookup, DataSource ds) { - setDataSource(ds); - setDbSchemaName(dataSourceLookup.getFullSchema()); - this.dataSourceLookup = dataSourceLookup; - - } - - @Override - public int getRecordCountByUploadId(int uploadId) { - JdbcTemplate jdbcTemplate = new JdbcTemplate(getDataSource()); - int insertCount = jdbcTemplate.queryForObject("select count(1) from " - + getDbSchemaName() + "patient_dimension where upload_id =?",Integer.class, - new Object[] { uploadId }); - return insertCount; - } - - /** - * Function to create temp visit dimension table using stored proc. - * - * @param tempTableName - * @throws Exception - */ - @Override - public void createTempTable(String tempPatientTableName, - String tempPatientMappingTableName) throws I2B2Exception { - Connection conn = null; - try { - conn = getDataSource().getConnection(); - CallableStatement callStmt = conn.prepareCall("{call " - + getDbSchemaName() + "CREATE_TEMP_PATIENT_TABLE(?,?)}"); - callStmt.setString(1, tempPatientTableName); - callStmt.registerOutParameter(2, java.sql.Types.VARCHAR); - // callStmt.setString(2, tempPatientMappingTableName); - callStmt.execute(); - this.getSQLServerProcedureError(dataSourceLookup.getServerType(), - callStmt, 2); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - throw new I2B2Exception( - "SQLException occured" + sqlEx.getMessage(), sqlEx); - } catch (Exception ex) { - ex.printStackTrace(); - throw new I2B2Exception("Exception occured" + ex.getMessage(), ex); - } finally { - if (conn != null) { - try { - conn.close(); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - log.error("Error while closing connection", sqlEx); - } - } - } - } - - /** - * Create batch insert handle for temp observation fact table. - * - * @param tempTableName - * @return - */ - @Override - public TempPatientDimensionInsertHandler createTempPatientDimensionInsert( - String tempTableName) { - TempPatientInsert tempPatientInsert = new TempPatientInsert( - getDataSource(), tempTableName, getDbSchemaName()); - tempPatientInsert.setBatchSize(DB_BATCH_INSERT_SIZE); - return new TempPatientDimensionInsertHandler(tempPatientInsert); - } - - /** - * Function to create new encounter/visit from temp_visit_dimension table - * using stored proc. - * - * @param tempTableName - * @throws Exception - */ - @Override - public void createPatientFromTempTable(String tempTableName, - String tempMapTableName, int uploadId) throws I2B2Exception { - Connection conn = null; - try { - conn = getDataSource().getConnection(); - CallableStatement callStmt = conn.prepareCall("{call " - + getDbSchemaName() + "INSERT_PATIENT_FROMTEMP(?,?,?)}"); - callStmt.setString(1, tempTableName); - callStmt.setInt(2, uploadId); - callStmt.registerOutParameter(3, java.sql.Types.VARCHAR); - callStmt.execute(); - this.getSQLServerProcedureError(dataSourceLookup.getServerType(), - callStmt, 3); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - throw new I2B2Exception( - "SQLException occured" + sqlEx.getMessage(), sqlEx); - } catch (Exception ex) { - ex.printStackTrace(); - throw new I2B2Exception("Exception occured" + ex.getMessage(), ex); - } finally { - if (conn != null) { - try { - conn.close(); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - log.error("Error while closing connection", sqlEx); - } - } - } - } - - // ************* Operation Objects section *************** - - /** - * Patient Insert Object. - */ - protected class TempPatientInsert extends BatchSqlUpdate { - - /** - * Create a new instance of PatientInsert. - * - * @param ds - * the DataSource to use for the insert - */ - protected TempPatientInsert(DataSource ds, String tableName, - String schemaName) { - super(ds, "INSERT INTO " + schemaName + tableName + " (" - + "patient_id," + "patient_id_source," - + "age_in_years_num, " + "birth_date, " + "death_date, " - + "language_cd, " + "marital_status_cd, " + "race_cd, " - + "religion_cd, " + "sex_cd, " + "vital_status_cd, " - + "zip_cd, " + "statecityzip_path, " + "patient_blob," - + "sourcesystem_cd, " + "update_date, " + "download_date, " - + "import_date) " - + " VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.INTEGER)); - declareParameter(new SqlParameter(Types.TIMESTAMP)); - declareParameter(new SqlParameter(Types.TIMESTAMP)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.LONGVARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.TIMESTAMP)); - declareParameter(new SqlParameter(Types.TIMESTAMP)); - declareParameter(new SqlParameter(Types.TIMESTAMP)); - compile(); - } - - protected void insert(PatientType patient) { - Map paramMap = null; - - if (patient.getParam() != null) { - paramMap = buildNVParam(patient.getParam()); - } else { - paramMap = new HashMap(); - } - - Object[] objs = new Object[] { - (patient.getPatientId() != null) ? patient.getPatientId() - .getValue() : null, - (patient.getPatientId() != null) ? patient.getPatientId() - .getSource() : null, - (paramMap.get("age_in_years_num") != null) ? paramMap.get( - "age_in_years_num").getValue() : null, // patient. - // getAgeInYearsNum - (paramMap.get("birth_date") != null) ? paramMap.get( - "birth_date").getValue() : null,// patient. - // getBirthDate(), - (paramMap.get("death_date") != null) ? paramMap.get( - "death_date").getValue() : null,// patient. - // getDeathDate(), - (paramMap.get("language_cd") != null) ? paramMap.get( - "language_cd").getValue() : null,// patient. - // getDownloadDate - // (), - (paramMap.get("marital_status_cd") != null) ? paramMap.get( - "marital_status_cd").getValue() : null,// patient. - // getImportDate - // (), - (paramMap.get("race_cd") != null) ? paramMap.get("race_cd") - .getValue() : null,// patient.getLanguageCd(), - (paramMap.get("religion_cd") != null) ? paramMap.get( - "religion_cd").getValue() : null,// patient. - // getMaritalStatusCd - // (), - (paramMap.get("sex_cd") != null) ? paramMap.get("sex_cd") - .getValue() : null,// patient.getRaceCd(), - (paramMap.get("vital_status_cd") != null) ? paramMap.get( - "vital_status_cd").getValue() : null,// patient. - // getReligionCd - // (), - (paramMap.get("zip_cd") != null) ? paramMap.get("zip_cd") - .getValue() : null,// patient.getSexCd(), - (paramMap.get("statecityzip_path") != null) ? paramMap.get( - "statecityzip_path").getValue() : null,// patient. - // getSourceSystemCd - // (), - (patient.getPatientBlob() != null) ? patient - .getPatientBlob().getContent().get(0) : null, - (paramMap.get("sourcesystem_cd") != null) ? paramMap.get( - "sourcesystem_cd").getValue() : null, - - (paramMap.get("update_date") != null) ? paramMap.get( - "update_date").getValue() : null,// patient. - // getUpdateDate - // (), - (paramMap.get("download_date") != null) ? paramMap.get( - "download_date").getValue() : null,// patient. - // getVitalStatusCd - // (), - (paramMap.get("import_date") != null) ? paramMap.get( - "import_date").getValue() : null // patient.getZipCd( - // ) - - }; - - super.update(objs); - // retrieveIdentity(patient); - } - } - - /** - * Patient Update Object. - */ - protected class PatientUpdate extends BatchSqlUpdate { - - /** - * Create a new instance of PatientUpdate. - * - * @param ds - * the DataSource to use for the update - */ - protected PatientUpdate(DataSource ds) { - super(ds, "UPDATE patient_dimension SET " + "age_in_years_num=?, " - + "birth_date=?, " + "death_date=?, " + "download_date=?, " - + "import_date=?, " + "language_cd=?, " - + "marital_status_cd=?, " + "race_cd=?, " - + "religion_cd=?, " + "sex_cd=?, " + "sourcesystem_cd=?, " - + "statecityzip_path=?, " + "update_date=?, " - + "vital_status_cd=?, " + "zip_cd=? " - + "WHERE patient_num=?"); - declareParameter(new SqlParameter(Types.INTEGER)); - declareParameter(new SqlParameter(Types.DATE)); - declareParameter(new SqlParameter(Types.DATE)); - declareParameter(new SqlParameter(Types.DATE)); - declareParameter(new SqlParameter(Types.DATE)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.DATE)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - compile(); - } - - /** - * Method to update an Patient's data. - * - * @param patient - * to update - * @return the number of rows affected by the update - */ - protected int update(Patient patient) { - return this.update(new Object[] { patient.getAgeInYearsNum(), - patient.getBirthDate(), patient.getDeathDate(), - patient.getDownloadDate(), patient.getImportDate(), - patient.getLanguageCd(), patient.getMaritalStatusCd(), - patient.getRaceCd(), patient.getReligionCd(), - patient.getSexCd(), patient.getSourceSystemCd(), - patient.getStateCityZipPath(), patient.getUpdateDate(), - patient.getVitalStatusCd(), patient.getZipCd(), - patient.getPatientNum() }); - } - } - - /** - * Patient_Mapping insert code. - */ - protected class PatientMappingInsert extends BatchSqlUpdate { - - /** - * Create a new instance of Patient_MappingInsert. - * - * @param ds - * the DataSource to use for the insert - */ - protected PatientMappingInsert(DataSource ds) { - - super(ds, "INSERT INTO patient_mapping (" + "patient_ide, " - + "patient_ide_source, " + "patient_ide_status, " - + "patient_num " + ")" + " VALUES(?,?,?)"); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.INTEGER)); - compile(); - } - - protected void insert(Patient patient) { - Object[] objs = new Object[] { patient.getPatientIde(), - patient.getSource(), patient.getPatientIdeStatus(), - patient.getPatientNum() }; - super.update(objs); - } - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.dao; + +import java.sql.CallableStatement; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.Types; +import java.util.HashMap; +import java.util.Map; + +import javax.sql.DataSource; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.SqlParameter; +import org.springframework.jdbc.object.BatchSqlUpdate; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.crc.loader.datavo.loader.DataSourceLookup; +import edu.harvard.i2b2.crc.loader.datavo.loader.Patient; +import edu.harvard.i2b2.crc.datavo.pdo.ParamType; +import edu.harvard.i2b2.crc.datavo.pdo.PatientType; + +/** + * Patient Dimension data access object. + * + * @author rk903 + */ +public class PatientDAO extends CRCLoaderDAO implements IPatientDAO { + + private int DB_BATCH_INSERT_SIZE = 2000; + + private static Log log = LogFactory.getLog(PatientDAO.class); + private DataSourceLookup dataSourceLookup = null; + + public PatientDAO(DataSourceLookup dataSourceLookup, DataSource ds) { + setDataSource(ds); + setDbSchemaName(dataSourceLookup.getFullSchema()); + this.dataSourceLookup = dataSourceLookup; + + } + + @Override + public int getRecordCountByUploadId(int uploadId) { + JdbcTemplate jdbcTemplate = new JdbcTemplate(getDataSource()); + int insertCount = jdbcTemplate.queryForObject("select count(1) from " + + getDbSchemaName() + "patient_dimension where upload_id =?",Integer.class, + new Object[] { uploadId }); + return insertCount; + } + + /** + * Function to create temp visit dimension table using stored proc. + * + * @param tempTableName + * @throws Exception + */ + @Override + public void createTempTable(String tempPatientTableName, + String tempPatientMappingTableName) throws I2B2Exception { + Connection conn = null; + try { + conn = getDataSource().getConnection(); + CallableStatement callStmt = conn.prepareCall("{call " + + getDbSchemaName() + "CREATE_TEMP_PATIENT_TABLE(?,?)}"); + callStmt.setString(1, tempPatientTableName); + callStmt.registerOutParameter(2, java.sql.Types.VARCHAR); + // callStmt.setString(2, tempPatientMappingTableName); + callStmt.execute(); + this.getSQLServerProcedureError(dataSourceLookup.getServerType(), + callStmt, 2); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + throw new I2B2Exception( + "SQLException occured" + sqlEx.getMessage(), sqlEx); + } catch (Exception ex) { + ex.printStackTrace(); + throw new I2B2Exception("Exception occured" + ex.getMessage(), ex); + } finally { + if (conn != null) { + try { + conn.close(); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + log.error("Error while closing connection", sqlEx); + } + } + } + } + + /** + * Create batch insert handle for temp observation fact table. + * + * @param tempTableName + * @return + */ + @Override + public TempPatientDimensionInsertHandler createTempPatientDimensionInsert( + String tempTableName) { + TempPatientInsert tempPatientInsert = new TempPatientInsert( + getDataSource(), tempTableName, getDbSchemaName()); + tempPatientInsert.setBatchSize(DB_BATCH_INSERT_SIZE); + return new TempPatientDimensionInsertHandler(tempPatientInsert); + } + + /** + * Function to create new encounter/visit from temp_visit_dimension table + * using stored proc. + * + * @param tempTableName + * @throws Exception + */ + @Override + public void createPatientFromTempTable(String tempTableName, + String tempMapTableName, int uploadId) throws I2B2Exception { + Connection conn = null; + try { + conn = getDataSource().getConnection(); + CallableStatement callStmt = conn.prepareCall("{call " + + getDbSchemaName() + "INSERT_PATIENT_FROMTEMP(?,?,?)}"); + callStmt.setString(1, tempTableName); + callStmt.setInt(2, uploadId); + callStmt.registerOutParameter(3, java.sql.Types.VARCHAR); + callStmt.execute(); + this.getSQLServerProcedureError(dataSourceLookup.getServerType(), + callStmt, 3); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + throw new I2B2Exception( + "SQLException occured" + sqlEx.getMessage(), sqlEx); + } catch (Exception ex) { + ex.printStackTrace(); + throw new I2B2Exception("Exception occured" + ex.getMessage(), ex); + } finally { + if (conn != null) { + try { + conn.close(); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + log.error("Error while closing connection", sqlEx); + } + } + } + } + + // ************* Operation Objects section *************** + + /** + * Patient Insert Object. + */ + protected class TempPatientInsert extends BatchSqlUpdate { + + /** + * Create a new instance of PatientInsert. + * + * @param ds + * the DataSource to use for the insert + */ + protected TempPatientInsert(DataSource ds, String tableName, + String schemaName) { + super(ds, "INSERT INTO " + schemaName + tableName + " (" + + "patient_id," + "patient_id_source," + + "age_in_years_num, " + "birth_date, " + "death_date, " + + "language_cd, " + "marital_status_cd, " + "race_cd, " + + "religion_cd, " + "sex_cd, " + "vital_status_cd, " + + "zip_cd, " + "statecityzip_path, " + "patient_blob," + + "sourcesystem_cd, " + "update_date, " + "download_date, " + + "import_date) " + + " VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.INTEGER)); + declareParameter(new SqlParameter(Types.TIMESTAMP)); + declareParameter(new SqlParameter(Types.TIMESTAMP)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.LONGVARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.TIMESTAMP)); + declareParameter(new SqlParameter(Types.TIMESTAMP)); + declareParameter(new SqlParameter(Types.TIMESTAMP)); + compile(); + } + + protected void insert(PatientType patient) { + Map paramMap = null; + + if (patient.getParam() != null) { + paramMap = buildNVParam(patient.getParam()); + } else { + paramMap = new HashMap(); + } + + Object[] objs = new Object[] { + (patient.getPatientId() != null) ? patient.getPatientId() + .getValue() : null, + (patient.getPatientId() != null) ? patient.getPatientId() + .getSource() : null, + (paramMap.get("age_in_years_num") != null) ? paramMap.get( + "age_in_years_num").getValue() : null, // patient. + // getAgeInYearsNum + (paramMap.get("birth_date") != null) ? paramMap.get( + "birth_date").getValue() : null,// patient. + // getBirthDate(), + (paramMap.get("death_date") != null) ? paramMap.get( + "death_date").getValue() : null,// patient. + // getDeathDate(), + (paramMap.get("language_cd") != null) ? paramMap.get( + "language_cd").getValue() : null,// patient. + // getDownloadDate + // (), + (paramMap.get("marital_status_cd") != null) ? paramMap.get( + "marital_status_cd").getValue() : null,// patient. + // getImportDate + // (), + (paramMap.get("race_cd") != null) ? paramMap.get("race_cd") + .getValue() : null,// patient.getLanguageCd(), + (paramMap.get("religion_cd") != null) ? paramMap.get( + "religion_cd").getValue() : null,// patient. + // getMaritalStatusCd + // (), + (paramMap.get("sex_cd") != null) ? paramMap.get("sex_cd") + .getValue() : null,// patient.getRaceCd(), + (paramMap.get("vital_status_cd") != null) ? paramMap.get( + "vital_status_cd").getValue() : null,// patient. + // getReligionCd + // (), + (paramMap.get("zip_cd") != null) ? paramMap.get("zip_cd") + .getValue() : null,// patient.getSexCd(), + (paramMap.get("statecityzip_path") != null) ? paramMap.get( + "statecityzip_path").getValue() : null,// patient. + // getSourceSystemCd + // (), + (patient.getPatientBlob() != null) ? patient + .getPatientBlob().getContent().get(0) : null, + (paramMap.get("sourcesystem_cd") != null) ? paramMap.get( + "sourcesystem_cd").getValue() : null, + + (paramMap.get("update_date") != null) ? paramMap.get( + "update_date").getValue() : null,// patient. + // getUpdateDate + // (), + (paramMap.get("download_date") != null) ? paramMap.get( + "download_date").getValue() : null,// patient. + // getVitalStatusCd + // (), + (paramMap.get("import_date") != null) ? paramMap.get( + "import_date").getValue() : null // patient.getZipCd( + // ) + + }; + + super.update(objs); + // retrieveIdentity(patient); + } + } + + /** + * Patient Update Object. + */ + protected class PatientUpdate extends BatchSqlUpdate { + + /** + * Create a new instance of PatientUpdate. + * + * @param ds + * the DataSource to use for the update + */ + protected PatientUpdate(DataSource ds) { + super(ds, "UPDATE patient_dimension SET " + "age_in_years_num=?, " + + "birth_date=?, " + "death_date=?, " + "download_date=?, " + + "import_date=?, " + "language_cd=?, " + + "marital_status_cd=?, " + "race_cd=?, " + + "religion_cd=?, " + "sex_cd=?, " + "sourcesystem_cd=?, " + + "statecityzip_path=?, " + "update_date=?, " + + "vital_status_cd=?, " + "zip_cd=? " + + "WHERE patient_num=?"); + declareParameter(new SqlParameter(Types.INTEGER)); + declareParameter(new SqlParameter(Types.DATE)); + declareParameter(new SqlParameter(Types.DATE)); + declareParameter(new SqlParameter(Types.DATE)); + declareParameter(new SqlParameter(Types.DATE)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.DATE)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + compile(); + } + + /** + * Method to update an Patient's data. + * + * @param patient + * to update + * @return the number of rows affected by the update + */ + protected int update(Patient patient) { + return this.update(new Object[] { patient.getAgeInYearsNum(), + patient.getBirthDate(), patient.getDeathDate(), + patient.getDownloadDate(), patient.getImportDate(), + patient.getLanguageCd(), patient.getMaritalStatusCd(), + patient.getRaceCd(), patient.getReligionCd(), + patient.getSexCd(), patient.getSourceSystemCd(), + patient.getStateCityZipPath(), patient.getUpdateDate(), + patient.getVitalStatusCd(), patient.getZipCd(), + patient.getPatientNum() }); + } + } + + /** + * Patient_Mapping insert code. + */ + protected class PatientMappingInsert extends BatchSqlUpdate { + + /** + * Create a new instance of Patient_MappingInsert. + * + * @param ds + * the DataSource to use for the insert + */ + protected PatientMappingInsert(DataSource ds) { + + super(ds, "INSERT INTO patient_mapping (" + "patient_ide, " + + "patient_ide_source, " + "patient_ide_status, " + + "patient_num " + ")" + " VALUES(?,?,?)"); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.INTEGER)); + compile(); + } + + protected void insert(Patient patient) { + Object[] objs = new Object[] { patient.getPatientIde(), + patient.getSource(), patient.getPatientIdeStatus(), + patient.getPatientNum() }; + super.update(objs); + } + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/PidDAO.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/PidDAO.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/PidDAO.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/PidDAO.java index 41ba4db1..82ba8915 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/PidDAO.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/PidDAO.java @@ -1,218 +1,218 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.dao; - -import java.sql.CallableStatement; -import java.sql.Connection; -import java.sql.SQLException; -import java.sql.Types; -import java.util.List; - -import javax.sql.DataSource; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.SqlParameter; -import org.springframework.jdbc.object.BatchSqlUpdate; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.crc.loader.datavo.loader.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.pdo.PidType; -import edu.harvard.i2b2.crc.datavo.pdo.PidType.PatientMapId; - -/** - * Patient Dimension data access object. - * - * @author rk903 - */ -public class PidDAO extends CRCLoaderDAO implements IPidDAO { - - private int DB_BATCH_INSERT_SIZE = 1; - - private static Log log = LogFactory.getLog(PidDAO.class); - private DataSourceLookup dataSourceLookup = null; - - public PidDAO(DataSourceLookup dataSourceLookup, DataSource ds) { - setDataSource(ds); - setDbSchemaName(dataSourceLookup.getFullSchema()); - this.dataSourceLookup = dataSourceLookup; - } - - @Override - public int getRecordCountByUploadId(int uploadId) { - JdbcTemplate jdbcTemplate = new JdbcTemplate(getDataSource()); - int insertCount = jdbcTemplate.queryForObject("select count(1) from " - + getDbSchemaName() + " patient_mapping where upload_id =?",Integer.class, - new Object[] { uploadId }); - return insertCount; - } - - /** - * Function to create temp visit dimension table using stored proc. - * - * @param tempTableName - * @throws Exception - */ - @Override - public void createTempTable(String tempPatientMappingTableName) - throws I2B2Exception { - Connection conn = null; - try { - conn = getDataSource().getConnection(); - CallableStatement callStmt = conn.prepareCall("{call " - + getDbSchemaName() + "CREATE_TEMP_PID_TABLE(?,?)}"); - callStmt.setString(1, tempPatientMappingTableName); - callStmt.registerOutParameter(2, java.sql.Types.VARCHAR); - callStmt.execute(); - this.getSQLServerProcedureError(dataSourceLookup.getServerType(), - callStmt, 2); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - throw new I2B2Exception( - "SQLException occured" + sqlEx.getMessage(), sqlEx); - } catch (Exception ex) { - ex.printStackTrace(); - throw new I2B2Exception("Exception occured" + ex.getMessage(), ex); - } finally { - if (conn != null) { - try { - conn.close(); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - log.error("Error while closing connection", sqlEx); - } - } - } - } - - /** - * Create batch insert handle for temp observation fact table. - * - * @param tempTableName - * @return - */ - @Override - public TempPidInsertHandler createTempPidInsert(String tempTableName) { - TempPidInsert tempPidInsert = new TempPidInsert(getDataSource(), - tempTableName, this.getDbSchemaName()); - tempPidInsert.setBatchSize(DB_BATCH_INSERT_SIZE); - return new TempPidInsertHandler(tempPidInsert); - } - - /** - * Function to create new encounter/visit from temp_visit_dimension table - * using stored proc. - * - * @param tempTableName - * @throws Exception - */ - @Override - public void createPidFromTempTable(String tempMapTableName, int uploadId) - throws I2B2Exception { - Connection conn = null; - try { - conn = getDataSource().getConnection(); - CallableStatement callStmt = conn.prepareCall("{call " - + this.getDbSchemaName() - + "INSERT_PID_MAP_FROMTEMP(?,?,?)}"); - callStmt.setString(1, tempMapTableName); - callStmt.setInt(2, uploadId); - callStmt.registerOutParameter(3, java.sql.Types.VARCHAR); - callStmt.execute(); - this.getSQLServerProcedureError(dataSourceLookup.getServerType(), - callStmt, 3); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - throw new I2B2Exception( - "SQLException occured" + sqlEx.getMessage(), sqlEx); - } catch (Exception ex) { - ex.printStackTrace(); - throw new I2B2Exception("Exception occured" + ex.getMessage(), ex); - } finally { - if (conn != null) { - try { - conn.close(); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - log.error("Error while closing connection", sqlEx); - } - } - } - } - - /** - * Patient_Mapping insert code. - */ - protected class TempPidInsert extends BatchSqlUpdate { - - /** - * Create a new instance of Patient_MappingInsert. - * - * @param ds - * the DataSource to use for the insert - */ - protected TempPidInsert(DataSource ds, String tempTableName, - String schemaName) { - - super(ds, "INSERT INTO " + schemaName + tempTableName + " (" - + "patient_map_id, " + "patient_map_id_source, " - + "patient_id, " + "patient_id_source, " - + "PATIENT_MAP_ID_STATUS, " + " UPDATE_DATE, " - + "DOWNLOAD_DATE," + " SOURCESYSTEM_CD )" - + " VALUES(?,?,?,?,?,?,?,?)"); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.TIMESTAMP)); - declareParameter(new SqlParameter(Types.TIMESTAMP)); - declareParameter(new SqlParameter(Types.VARCHAR)); - compile(); - } - - protected void insert(PidType pid) { - String patientId = pid.getPatientId().getValue(); - String patientIdSource = pid.getPatientId().getSource(); - List mapIdList = pid.getPatientMapId(); - for (PatientMapId mapId : mapIdList) { - Object[] objs = new Object[] { - mapId.getValue(), - mapId.getSource(), - patientId, - patientIdSource, - mapId.getStatus(), - (mapId.getUpdateDate() != null) ? mapId.getUpdateDate() - .toGregorianCalendar().getTime() : null, - (mapId.getDownloadDate() != null) ? mapId - .getDownloadDate().toGregorianCalendar() - .getTime() : null, mapId.getSourcesystemCd() }; - super.update(objs); - } - // do self insert - Object[] objs = new Object[] { - patientId, - patientIdSource, - patientId, - patientIdSource, - pid.getPatientId().getStatus(), - (pid.getPatientId().getUpdateDate() != null) ? pid - .getPatientId().getUpdateDate() - .toGregorianCalendar().getTime() : null, - (pid.getPatientId().getDownloadDate() != null) ? pid - .getPatientId().getDownloadDate() - .toGregorianCalendar().getTime() : null, - pid.getPatientId().getSourcesystemCd() }; - update(objs); - } - - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.dao; + +import java.sql.CallableStatement; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.Types; +import java.util.List; + +import javax.sql.DataSource; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.SqlParameter; +import org.springframework.jdbc.object.BatchSqlUpdate; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.crc.loader.datavo.loader.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.pdo.PidType; +import edu.harvard.i2b2.crc.datavo.pdo.PidType.PatientMapId; + +/** + * Patient Dimension data access object. + * + * @author rk903 + */ +public class PidDAO extends CRCLoaderDAO implements IPidDAO { + + private int DB_BATCH_INSERT_SIZE = 1; + + private static Log log = LogFactory.getLog(PidDAO.class); + private DataSourceLookup dataSourceLookup = null; + + public PidDAO(DataSourceLookup dataSourceLookup, DataSource ds) { + setDataSource(ds); + setDbSchemaName(dataSourceLookup.getFullSchema()); + this.dataSourceLookup = dataSourceLookup; + } + + @Override + public int getRecordCountByUploadId(int uploadId) { + JdbcTemplate jdbcTemplate = new JdbcTemplate(getDataSource()); + int insertCount = jdbcTemplate.queryForObject("select count(1) from " + + getDbSchemaName() + " patient_mapping where upload_id =?",Integer.class, + new Object[] { uploadId }); + return insertCount; + } + + /** + * Function to create temp visit dimension table using stored proc. + * + * @param tempTableName + * @throws Exception + */ + @Override + public void createTempTable(String tempPatientMappingTableName) + throws I2B2Exception { + Connection conn = null; + try { + conn = getDataSource().getConnection(); + CallableStatement callStmt = conn.prepareCall("{call " + + getDbSchemaName() + "CREATE_TEMP_PID_TABLE(?,?)}"); + callStmt.setString(1, tempPatientMappingTableName); + callStmt.registerOutParameter(2, java.sql.Types.VARCHAR); + callStmt.execute(); + this.getSQLServerProcedureError(dataSourceLookup.getServerType(), + callStmt, 2); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + throw new I2B2Exception( + "SQLException occured" + sqlEx.getMessage(), sqlEx); + } catch (Exception ex) { + ex.printStackTrace(); + throw new I2B2Exception("Exception occured" + ex.getMessage(), ex); + } finally { + if (conn != null) { + try { + conn.close(); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + log.error("Error while closing connection", sqlEx); + } + } + } + } + + /** + * Create batch insert handle for temp observation fact table. + * + * @param tempTableName + * @return + */ + @Override + public TempPidInsertHandler createTempPidInsert(String tempTableName) { + TempPidInsert tempPidInsert = new TempPidInsert(getDataSource(), + tempTableName, this.getDbSchemaName()); + tempPidInsert.setBatchSize(DB_BATCH_INSERT_SIZE); + return new TempPidInsertHandler(tempPidInsert); + } + + /** + * Function to create new encounter/visit from temp_visit_dimension table + * using stored proc. + * + * @param tempTableName + * @throws Exception + */ + @Override + public void createPidFromTempTable(String tempMapTableName, int uploadId) + throws I2B2Exception { + Connection conn = null; + try { + conn = getDataSource().getConnection(); + CallableStatement callStmt = conn.prepareCall("{call " + + this.getDbSchemaName() + + "INSERT_PID_MAP_FROMTEMP(?,?,?)}"); + callStmt.setString(1, tempMapTableName); + callStmt.setInt(2, uploadId); + callStmt.registerOutParameter(3, java.sql.Types.VARCHAR); + callStmt.execute(); + this.getSQLServerProcedureError(dataSourceLookup.getServerType(), + callStmt, 3); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + throw new I2B2Exception( + "SQLException occured" + sqlEx.getMessage(), sqlEx); + } catch (Exception ex) { + ex.printStackTrace(); + throw new I2B2Exception("Exception occured" + ex.getMessage(), ex); + } finally { + if (conn != null) { + try { + conn.close(); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + log.error("Error while closing connection", sqlEx); + } + } + } + } + + /** + * Patient_Mapping insert code. + */ + protected class TempPidInsert extends BatchSqlUpdate { + + /** + * Create a new instance of Patient_MappingInsert. + * + * @param ds + * the DataSource to use for the insert + */ + protected TempPidInsert(DataSource ds, String tempTableName, + String schemaName) { + + super(ds, "INSERT INTO " + schemaName + tempTableName + " (" + + "patient_map_id, " + "patient_map_id_source, " + + "patient_id, " + "patient_id_source, " + + "PATIENT_MAP_ID_STATUS, " + " UPDATE_DATE, " + + "DOWNLOAD_DATE," + " SOURCESYSTEM_CD )" + + " VALUES(?,?,?,?,?,?,?,?)"); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.TIMESTAMP)); + declareParameter(new SqlParameter(Types.TIMESTAMP)); + declareParameter(new SqlParameter(Types.VARCHAR)); + compile(); + } + + protected void insert(PidType pid) { + String patientId = pid.getPatientId().getValue(); + String patientIdSource = pid.getPatientId().getSource(); + List mapIdList = pid.getPatientMapId(); + for (PatientMapId mapId : mapIdList) { + Object[] objs = new Object[] { + mapId.getValue(), + mapId.getSource(), + patientId, + patientIdSource, + mapId.getStatus(), + (mapId.getUpdateDate() != null) ? mapId.getUpdateDate() + .toGregorianCalendar().getTime() : null, + (mapId.getDownloadDate() != null) ? mapId + .getDownloadDate().toGregorianCalendar() + .getTime() : null, mapId.getSourcesystemCd() }; + super.update(objs); + } + // do self insert + Object[] objs = new Object[] { + patientId, + patientIdSource, + patientId, + patientIdSource, + pid.getPatientId().getStatus(), + (pid.getPatientId().getUpdateDate() != null) ? pid + .getPatientId().getUpdateDate() + .toGregorianCalendar().getTime() : null, + (pid.getPatientId().getDownloadDate() != null) ? pid + .getPatientId().getDownloadDate() + .toGregorianCalendar().getTime() : null, + pid.getPatientId().getSourcesystemCd() }; + update(objs); + } + + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/ProviderDAO.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/ProviderDAO.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/ProviderDAO.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/ProviderDAO.java index f9647b56..f44a59da --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/ProviderDAO.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/ProviderDAO.java @@ -1,249 +1,249 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.dao; - -import java.sql.CallableStatement; -import java.sql.Connection; -import java.sql.SQLException; -import java.sql.Types; - -import javax.sql.DataSource; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.SqlParameter; -import org.springframework.jdbc.object.BatchSqlUpdate; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.crc.loader.datavo.loader.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.pdo.ObserverType; - -/** - * Patient Dimension data access object. - * - * @author rk903 - */ -public class ProviderDAO extends CRCLoaderDAO implements IProviderDAO { - - private int DB_BATCH_INSERT_SIZE = 2000; - - private static Log log = LogFactory.getLog(ProviderDAO.class); - private DataSourceLookup dataSourceLookup = null; - - public ProviderDAO(DataSourceLookup dataSourceLookup, DataSource ds) { - setDataSource(ds); - setDbSchemaName(dataSourceLookup.getFullSchema()); - this.dataSourceLookup = dataSourceLookup; - } - - @Override - public int getRecordCountByUploadId(int uploadId) { - JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); - int insertCount = jdbcTemplate.queryForObject("select count(1) from " - + this.getDbSchemaName() - + "provider_dimension where upload_id =?",Integer.class, - new Object[] { uploadId }); - return insertCount; - } - - /** - * Function to create temp visit dimension table using stored proc. - * - * @param tempTableName - * @throws Exception - */ - @Override - public void createTempTable(String tempProviderTableName) - throws I2B2Exception { - Connection conn = null; - try { - conn = this.getDataSource().getConnection(); - CallableStatement callStmt = conn.prepareCall("{call " - + this.getDbSchemaName() - + "CREATE_TEMP_PROVIDER_TABLE(?,?)}"); - callStmt.setString(1, tempProviderTableName); - callStmt.registerOutParameter(2, java.sql.Types.VARCHAR); - callStmt.execute(); - this.getSQLServerProcedureError(dataSourceLookup.getServerType(), - callStmt, 2); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - throw new I2B2Exception( - "SQLException occured" + sqlEx.getMessage(), sqlEx); - } catch (Exception ex) { - ex.printStackTrace(); - throw new I2B2Exception("Exception occured" + ex.getMessage(), ex); - } finally { - if (conn != null) { - try { - conn.close(); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - log.error("Error while closing connection", sqlEx); - } - } - } - } - - /** - * Create batch insert handle for temp observation fact table. - * - * @param tempTableName - * @return - */ - @Override - public TempProviderInsertHandler createTempProviderInsert( - String tempTableName) { - TempProviderInsert tempProviderInsert = new TempProviderInsert( - getDataSource(), tempTableName, this.getDbSchemaName()); - tempProviderInsert.setBatchSize(DB_BATCH_INSERT_SIZE); - return new TempProviderInsertHandler(tempProviderInsert); - } - - /** - * Function to create new encounter/visit from temp_visit_dimension table - * using stored proc. - * - * @param tempTableName - * @throws Exception - */ - @Override - public void createProviderFromTempTable(String tempProviderTableName, - int uploadId) throws I2B2Exception { - Connection conn = null; - try { - conn = this.getDataSource().getConnection(); - CallableStatement callStmt = conn.prepareCall("{call " - + this.getDbSchemaName() - + "INSERT_PROVIDER_FROMTEMP(?,?,?)}"); - callStmt.setString(1, tempProviderTableName); - callStmt.setInt(2, uploadId); - callStmt.registerOutParameter(3, java.sql.Types.VARCHAR); - callStmt.execute(); - this.getSQLServerProcedureError(dataSourceLookup.getServerType(), - callStmt, 3); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - throw new I2B2Exception( - "SQLException occured" + sqlEx.getMessage(), sqlEx); - } catch (Exception ex) { - ex.printStackTrace(); - throw new I2B2Exception("Exception occured" + ex.getMessage(), ex); - } finally { - if (conn != null) { - try { - conn.close(); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - log.error("Error while closing connection", sqlEx); - } - } - } - } - - /** - * Function to backup and clear provider dimension table using stored proc. - * - * @param tempTableName - * @throws Exception - */ - @Override - public void backupAndSyncProviderDimensionTable( - String tempConceptTableName, - String backupProviderDimensionTableName, int uploadId) - throws I2B2Exception { - Connection conn = null; - try { - conn = getDataSource().getConnection(); - CallableStatement callStmt = conn.prepareCall("{call " - + this.getDbSchemaName() - + "SYNC_CLEAR_PROVIDER_TABLE(?,?,?,?)}"); - callStmt.setString(1, tempConceptTableName); - callStmt.setString(2, backupProviderDimensionTableName); - callStmt.setInt(3, uploadId); - callStmt.registerOutParameter(4, java.sql.Types.VARCHAR); - callStmt.execute(); - this.getSQLServerProcedureError(dataSourceLookup.getServerType(), - callStmt, 4); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - throw new I2B2Exception( - "SQLException occured" + sqlEx.getMessage(), sqlEx); - } catch (Exception ex) { - ex.printStackTrace(); - throw new I2B2Exception("Exception occured" + ex.getMessage(), ex); - } finally { - if (conn != null) { - try { - conn.close(); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - log.error("Error while closing connection", sqlEx); - } - } - } - } - - /** - * Patient_Mapping insert code. - */ - protected class TempProviderInsert extends BatchSqlUpdate { - - /** - * Create a new instance of Patient_MappingInsert. - * - * @param ds - * the DataSource to use for the insert - */ - protected TempProviderInsert(DataSource ds, String tempTableName, - String schemaName) { - - super(ds, "INSERT INTO " + schemaName + tempTableName + " (" - + "PROVIDER_ID," + "PROVIDER_PATH," + "NAME_CHAR," - + "PROVIDER_BLOB," + "UPDATE_DATE," + "DOWNLOAD_DATE," - + "IMPORT_DATE," + "SOURCESYSTEM_CD," + "UPLOAD_ID" + ")" - + " VALUES(?,?,?,?,?,?,?,?,?)"); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.TIMESTAMP)); - declareParameter(new SqlParameter(Types.TIMESTAMP)); - declareParameter(new SqlParameter(Types.TIMESTAMP)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.INTEGER)); - compile(); - } - - protected void insert(ObserverType provider) { - - // do self insert - Object[] objs = new Object[] { - provider.getObserverCd(), - provider.getObserverPath(), - provider.getNameChar(), - (provider.getObserverBlob() != null) ? provider - .getObserverBlob().getContent().get(0) : null, - (provider.getUpdateDate() != null) ? provider - .getUpdateDate().toGregorianCalendar().getTime() - : null, - (provider.getDownloadDate() != null) ? provider - .getDownloadDate().toGregorianCalendar().getTime() - : null, - (provider.getImportDate() != null) ? provider - .getImportDate().toGregorianCalendar().getTime() - : null, provider.getSourcesystemCd(), - provider.getUploadId() }; - super.update(objs); - } - - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.dao; + +import java.sql.CallableStatement; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.Types; + +import javax.sql.DataSource; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.SqlParameter; +import org.springframework.jdbc.object.BatchSqlUpdate; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.crc.loader.datavo.loader.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.pdo.ObserverType; + +/** + * Patient Dimension data access object. + * + * @author rk903 + */ +public class ProviderDAO extends CRCLoaderDAO implements IProviderDAO { + + private int DB_BATCH_INSERT_SIZE = 2000; + + private static Log log = LogFactory.getLog(ProviderDAO.class); + private DataSourceLookup dataSourceLookup = null; + + public ProviderDAO(DataSourceLookup dataSourceLookup, DataSource ds) { + setDataSource(ds); + setDbSchemaName(dataSourceLookup.getFullSchema()); + this.dataSourceLookup = dataSourceLookup; + } + + @Override + public int getRecordCountByUploadId(int uploadId) { + JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); + int insertCount = jdbcTemplate.queryForObject("select count(1) from " + + this.getDbSchemaName() + + "provider_dimension where upload_id =?",Integer.class, + new Object[] { uploadId }); + return insertCount; + } + + /** + * Function to create temp visit dimension table using stored proc. + * + * @param tempTableName + * @throws Exception + */ + @Override + public void createTempTable(String tempProviderTableName) + throws I2B2Exception { + Connection conn = null; + try { + conn = this.getDataSource().getConnection(); + CallableStatement callStmt = conn.prepareCall("{call " + + this.getDbSchemaName() + + "CREATE_TEMP_PROVIDER_TABLE(?,?)}"); + callStmt.setString(1, tempProviderTableName); + callStmt.registerOutParameter(2, java.sql.Types.VARCHAR); + callStmt.execute(); + this.getSQLServerProcedureError(dataSourceLookup.getServerType(), + callStmt, 2); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + throw new I2B2Exception( + "SQLException occured" + sqlEx.getMessage(), sqlEx); + } catch (Exception ex) { + ex.printStackTrace(); + throw new I2B2Exception("Exception occured" + ex.getMessage(), ex); + } finally { + if (conn != null) { + try { + conn.close(); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + log.error("Error while closing connection", sqlEx); + } + } + } + } + + /** + * Create batch insert handle for temp observation fact table. + * + * @param tempTableName + * @return + */ + @Override + public TempProviderInsertHandler createTempProviderInsert( + String tempTableName) { + TempProviderInsert tempProviderInsert = new TempProviderInsert( + getDataSource(), tempTableName, this.getDbSchemaName()); + tempProviderInsert.setBatchSize(DB_BATCH_INSERT_SIZE); + return new TempProviderInsertHandler(tempProviderInsert); + } + + /** + * Function to create new encounter/visit from temp_visit_dimension table + * using stored proc. + * + * @param tempTableName + * @throws Exception + */ + @Override + public void createProviderFromTempTable(String tempProviderTableName, + int uploadId) throws I2B2Exception { + Connection conn = null; + try { + conn = this.getDataSource().getConnection(); + CallableStatement callStmt = conn.prepareCall("{call " + + this.getDbSchemaName() + + "INSERT_PROVIDER_FROMTEMP(?,?,?)}"); + callStmt.setString(1, tempProviderTableName); + callStmt.setInt(2, uploadId); + callStmt.registerOutParameter(3, java.sql.Types.VARCHAR); + callStmt.execute(); + this.getSQLServerProcedureError(dataSourceLookup.getServerType(), + callStmt, 3); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + throw new I2B2Exception( + "SQLException occured" + sqlEx.getMessage(), sqlEx); + } catch (Exception ex) { + ex.printStackTrace(); + throw new I2B2Exception("Exception occured" + ex.getMessage(), ex); + } finally { + if (conn != null) { + try { + conn.close(); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + log.error("Error while closing connection", sqlEx); + } + } + } + } + + /** + * Function to backup and clear provider dimension table using stored proc. + * + * @param tempTableName + * @throws Exception + */ + @Override + public void backupAndSyncProviderDimensionTable( + String tempConceptTableName, + String backupProviderDimensionTableName, int uploadId) + throws I2B2Exception { + Connection conn = null; + try { + conn = getDataSource().getConnection(); + CallableStatement callStmt = conn.prepareCall("{call " + + this.getDbSchemaName() + + "SYNC_CLEAR_PROVIDER_TABLE(?,?,?,?)}"); + callStmt.setString(1, tempConceptTableName); + callStmt.setString(2, backupProviderDimensionTableName); + callStmt.setInt(3, uploadId); + callStmt.registerOutParameter(4, java.sql.Types.VARCHAR); + callStmt.execute(); + this.getSQLServerProcedureError(dataSourceLookup.getServerType(), + callStmt, 4); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + throw new I2B2Exception( + "SQLException occured" + sqlEx.getMessage(), sqlEx); + } catch (Exception ex) { + ex.printStackTrace(); + throw new I2B2Exception("Exception occured" + ex.getMessage(), ex); + } finally { + if (conn != null) { + try { + conn.close(); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + log.error("Error while closing connection", sqlEx); + } + } + } + } + + /** + * Patient_Mapping insert code. + */ + protected class TempProviderInsert extends BatchSqlUpdate { + + /** + * Create a new instance of Patient_MappingInsert. + * + * @param ds + * the DataSource to use for the insert + */ + protected TempProviderInsert(DataSource ds, String tempTableName, + String schemaName) { + + super(ds, "INSERT INTO " + schemaName + tempTableName + " (" + + "PROVIDER_ID," + "PROVIDER_PATH," + "NAME_CHAR," + + "PROVIDER_BLOB," + "UPDATE_DATE," + "DOWNLOAD_DATE," + + "IMPORT_DATE," + "SOURCESYSTEM_CD," + "UPLOAD_ID" + ")" + + " VALUES(?,?,?,?,?,?,?,?,?)"); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.TIMESTAMP)); + declareParameter(new SqlParameter(Types.TIMESTAMP)); + declareParameter(new SqlParameter(Types.TIMESTAMP)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.INTEGER)); + compile(); + } + + protected void insert(ObserverType provider) { + + // do self insert + Object[] objs = new Object[] { + provider.getObserverCd(), + provider.getObserverPath(), + provider.getNameChar(), + (provider.getObserverBlob() != null) ? provider + .getObserverBlob().getContent().get(0) : null, + (provider.getUpdateDate() != null) ? provider + .getUpdateDate().toGregorianCalendar().getTime() + : null, + (provider.getDownloadDate() != null) ? provider + .getDownloadDate().toGregorianCalendar().getTime() + : null, + (provider.getImportDate() != null) ? provider + .getImportDate().toGregorianCalendar().getTime() + : null, provider.getSourcesystemCd(), + provider.getUploadId() }; + super.update(objs); + } + + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/SQLServerDataSourceLookupDAO.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/SQLServerDataSourceLookupDAO.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/SQLServerDataSourceLookupDAO.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/SQLServerDataSourceLookupDAO.java index b95e7d89..6aa4662e --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/SQLServerDataSourceLookupDAO.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/SQLServerDataSourceLookupDAO.java @@ -1,42 +1,42 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.dao; - -import java.util.List; - -import javax.sql.DataSource; - -import edu.harvard.i2b2.crc.loader.datavo.loader.DataSourceLookup; - - - -public class SQLServerDataSourceLookupDAO extends DataSourceLookupDAO { - - public SQLServerDataSourceLookupDAO(DataSource dataSource,String schemaName) { - - } - - @Override - public List getDbLookupByHiveOwner(String hiveId, - String ownerId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List getDbLookupByHiveProjectOwner(String hiveId, - String projectId, String ownerId) { - // TODO Auto-generated method stub - return null; - } - - - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.dao; + +import java.util.List; + +import javax.sql.DataSource; + +import edu.harvard.i2b2.crc.loader.datavo.loader.DataSourceLookup; + + + +public class SQLServerDataSourceLookupDAO extends DataSourceLookupDAO { + + public SQLServerDataSourceLookupDAO(DataSource dataSource,String schemaName) { + + } + + @Override + public List getDbLookupByHiveOwner(String hiveId, + String ownerId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List getDbLookupByHiveProjectOwner(String hiveId, + String projectId, String ownerId) { + // TODO Auto-generated method stub + return null; + } + + + + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/TempConceptInsertHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/TempConceptInsertHandler.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/TempConceptInsertHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/TempConceptInsertHandler.java index ae6eb153..461471ae --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/TempConceptInsertHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/TempConceptInsertHandler.java @@ -1,52 +1,52 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.dao; - -import javax.sql.DataSource; - -import org.springframework.jdbc.core.support.JdbcDaoSupport; - -import edu.harvard.i2b2.crc.datavo.pdo.ConceptType; - -/** - * Handle to insert temp obervation fact data. Wraps Springs batch inserter. - * - * @author rk903 - * - */ -public class TempConceptInsertHandler extends JdbcDaoSupport { - private ConceptDAO.TempConceptInsert tempConceptInsert = null; - - public TempConceptInsertHandler(DataSource ds) { - setDataSource(ds); - } - - public TempConceptInsertHandler( - ConceptDAO.TempConceptInsert tempConceptInsert) { - this.tempConceptInsert = tempConceptInsert; - } - - /** - * Submit individual inserts to batch. - * - * @param observationFact - */ - public void insertConcept(ConceptType concept) { - tempConceptInsert.insert(concept); - } - - /** - * Manual submit of batched inserts. - */ - public void flush() { - tempConceptInsert.flush(); - tempConceptInsert.reset(); - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.dao; + +import javax.sql.DataSource; + +import org.springframework.jdbc.core.support.JdbcDaoSupport; + +import edu.harvard.i2b2.crc.datavo.pdo.ConceptType; + +/** + * Handle to insert temp obervation fact data. Wraps Springs batch inserter. + * + * @author rk903 + * + */ +public class TempConceptInsertHandler extends JdbcDaoSupport { + private ConceptDAO.TempConceptInsert tempConceptInsert = null; + + public TempConceptInsertHandler(DataSource ds) { + setDataSource(ds); + } + + public TempConceptInsertHandler( + ConceptDAO.TempConceptInsert tempConceptInsert) { + this.tempConceptInsert = tempConceptInsert; + } + + /** + * Submit individual inserts to batch. + * + * @param observationFact + */ + public void insertConcept(ConceptType concept) { + tempConceptInsert.insert(concept); + } + + /** + * Manual submit of batched inserts. + */ + public void flush() { + tempConceptInsert.flush(); + tempConceptInsert.reset(); + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/TempEidInsertHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/TempEidInsertHandler.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/TempEidInsertHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/TempEidInsertHandler.java index 22e0c6f1..8927c918 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/TempEidInsertHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/TempEidInsertHandler.java @@ -1,51 +1,51 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.dao; - -import javax.sql.DataSource; - -import org.springframework.jdbc.core.support.JdbcDaoSupport; - -import edu.harvard.i2b2.crc.datavo.pdo.EidType; - -/** - * Handle to insert temp obervation fact data. Wraps Springs batch inserter. - * - * @author rk903 - * - */ -public class TempEidInsertHandler extends JdbcDaoSupport { - private EidDAO.TempEidInsert tempEidInsert = null; - - public TempEidInsertHandler(DataSource ds) { - setDataSource(ds); - } - - public TempEidInsertHandler(EidDAO.TempEidInsert tempEidInsert) { - this.tempEidInsert = tempEidInsert; - } - - /** - * Submit individual inserts to batch. - * - * @param observationFact - */ - public void insertEid(EidType eid) { - tempEidInsert.insert(eid); - } - - /** - * Manual submit of batched inserts. - */ - public void flush() { - tempEidInsert.flush(); - tempEidInsert.reset(); - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.dao; + +import javax.sql.DataSource; + +import org.springframework.jdbc.core.support.JdbcDaoSupport; + +import edu.harvard.i2b2.crc.datavo.pdo.EidType; + +/** + * Handle to insert temp obervation fact data. Wraps Springs batch inserter. + * + * @author rk903 + * + */ +public class TempEidInsertHandler extends JdbcDaoSupport { + private EidDAO.TempEidInsert tempEidInsert = null; + + public TempEidInsertHandler(DataSource ds) { + setDataSource(ds); + } + + public TempEidInsertHandler(EidDAO.TempEidInsert tempEidInsert) { + this.tempEidInsert = tempEidInsert; + } + + /** + * Submit individual inserts to batch. + * + * @param observationFact + */ + public void insertEid(EidType eid) { + tempEidInsert.insert(eid); + } + + /** + * Manual submit of batched inserts. + */ + public void flush() { + tempEidInsert.flush(); + tempEidInsert.reset(); + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/TempModifierInsertHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/TempModifierInsertHandler.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/TempModifierInsertHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/TempModifierInsertHandler.java index f4597485..b3ee2cec --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/TempModifierInsertHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/TempModifierInsertHandler.java @@ -1,52 +1,52 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.dao; - -import javax.sql.DataSource; - -import org.springframework.jdbc.core.support.JdbcDaoSupport; - -import edu.harvard.i2b2.crc.datavo.pdo.ModifierType; - -/** - * Handle to insert temp obervation fact data. Wraps Springs batch inserter. - * - * @author rk903 - * - */ -public class TempModifierInsertHandler extends JdbcDaoSupport { - private ModifierDAO.TempModifierInsert tempModifierInsert = null; - - public TempModifierInsertHandler(DataSource ds) { - setDataSource(ds); - } - - public TempModifierInsertHandler( - ModifierDAO.TempModifierInsert tempModifierInsert) { - this.tempModifierInsert = tempModifierInsert; - } - - /** - * Submit individual inserts to batch. - * - * @param observationFact - */ - public void insertModifier(ModifierType modifier) { - tempModifierInsert.insert(modifier); - } - - /** - * Manual submit of batched inserts. - */ - public void flush() { - tempModifierInsert.flush(); - tempModifierInsert.reset(); - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.dao; + +import javax.sql.DataSource; + +import org.springframework.jdbc.core.support.JdbcDaoSupport; + +import edu.harvard.i2b2.crc.datavo.pdo.ModifierType; + +/** + * Handle to insert temp obervation fact data. Wraps Springs batch inserter. + * + * @author rk903 + * + */ +public class TempModifierInsertHandler extends JdbcDaoSupport { + private ModifierDAO.TempModifierInsert tempModifierInsert = null; + + public TempModifierInsertHandler(DataSource ds) { + setDataSource(ds); + } + + public TempModifierInsertHandler( + ModifierDAO.TempModifierInsert tempModifierInsert) { + this.tempModifierInsert = tempModifierInsert; + } + + /** + * Submit individual inserts to batch. + * + * @param observationFact + */ + public void insertModifier(ModifierType modifier) { + tempModifierInsert.insert(modifier); + } + + /** + * Manual submit of batched inserts. + */ + public void flush() { + tempModifierInsert.flush(); + tempModifierInsert.reset(); + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/TempPatientDimensionInsertHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/TempPatientDimensionInsertHandler.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/TempPatientDimensionInsertHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/TempPatientDimensionInsertHandler.java index 78a8a0a6..dd1b0fe6 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/TempPatientDimensionInsertHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/TempPatientDimensionInsertHandler.java @@ -1,52 +1,52 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.dao; - -import javax.sql.DataSource; - -import org.springframework.jdbc.core.support.JdbcDaoSupport; - -import edu.harvard.i2b2.crc.datavo.pdo.PatientType; - -/** - * Handle to insert temp obervation fact data. Wraps Springs batch inserter. - * - * @author rk903 - * - */ -public class TempPatientDimensionInsertHandler extends JdbcDaoSupport { - private PatientDAO.TempPatientInsert tempPatientInsert = null; - - public TempPatientDimensionInsertHandler(DataSource ds) { - setDataSource(ds); - } - - public TempPatientDimensionInsertHandler( - PatientDAO.TempPatientInsert tempPatientInsert) { - this.tempPatientInsert = tempPatientInsert; - } - - /** - * Submit individual inserts to batch. - * - * @param observationFact - */ - public void insertPatientDimension(PatientType patient) { - tempPatientInsert.insert(patient); - } - - /** - * Manual submit of batched inserts. - */ - public void flush() { - tempPatientInsert.flush(); - tempPatientInsert.reset(); - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.dao; + +import javax.sql.DataSource; + +import org.springframework.jdbc.core.support.JdbcDaoSupport; + +import edu.harvard.i2b2.crc.datavo.pdo.PatientType; + +/** + * Handle to insert temp obervation fact data. Wraps Springs batch inserter. + * + * @author rk903 + * + */ +public class TempPatientDimensionInsertHandler extends JdbcDaoSupport { + private PatientDAO.TempPatientInsert tempPatientInsert = null; + + public TempPatientDimensionInsertHandler(DataSource ds) { + setDataSource(ds); + } + + public TempPatientDimensionInsertHandler( + PatientDAO.TempPatientInsert tempPatientInsert) { + this.tempPatientInsert = tempPatientInsert; + } + + /** + * Submit individual inserts to batch. + * + * @param observationFact + */ + public void insertPatientDimension(PatientType patient) { + tempPatientInsert.insert(patient); + } + + /** + * Manual submit of batched inserts. + */ + public void flush() { + tempPatientInsert.flush(); + tempPatientInsert.reset(); + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/TempPidInsertHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/TempPidInsertHandler.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/TempPidInsertHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/TempPidInsertHandler.java index 61e5a3eb..fe8a9623 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/TempPidInsertHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/TempPidInsertHandler.java @@ -1,51 +1,51 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.dao; - -import javax.sql.DataSource; - -import org.springframework.jdbc.core.support.JdbcDaoSupport; - -import edu.harvard.i2b2.crc.datavo.pdo.PidType; - -/** - * Handle to insert temp obervation fact data. Wraps Springs batch inserter. - * - * @author rk903 - * - */ -public class TempPidInsertHandler extends JdbcDaoSupport { - private PidDAO.TempPidInsert tempPidInsert = null; - - public TempPidInsertHandler(DataSource ds) { - setDataSource(ds); - } - - public TempPidInsertHandler(PidDAO.TempPidInsert tempPidInsert) { - this.tempPidInsert = tempPidInsert; - } - - /** - * Submit individual inserts to batch. - * - * @param observationFact - */ - public void insertPid(PidType pid) { - tempPidInsert.insert(pid); - } - - /** - * Manual submit of batched inserts. - */ - public void flush() { - tempPidInsert.flush(); - tempPidInsert.reset(); - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.dao; + +import javax.sql.DataSource; + +import org.springframework.jdbc.core.support.JdbcDaoSupport; + +import edu.harvard.i2b2.crc.datavo.pdo.PidType; + +/** + * Handle to insert temp obervation fact data. Wraps Springs batch inserter. + * + * @author rk903 + * + */ +public class TempPidInsertHandler extends JdbcDaoSupport { + private PidDAO.TempPidInsert tempPidInsert = null; + + public TempPidInsertHandler(DataSource ds) { + setDataSource(ds); + } + + public TempPidInsertHandler(PidDAO.TempPidInsert tempPidInsert) { + this.tempPidInsert = tempPidInsert; + } + + /** + * Submit individual inserts to batch. + * + * @param observationFact + */ + public void insertPid(PidType pid) { + tempPidInsert.insert(pid); + } + + /** + * Manual submit of batched inserts. + */ + public void flush() { + tempPidInsert.flush(); + tempPidInsert.reset(); + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/TempProviderInsertHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/TempProviderInsertHandler.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/TempProviderInsertHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/TempProviderInsertHandler.java index 440001f1..274da945 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/TempProviderInsertHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/TempProviderInsertHandler.java @@ -1,52 +1,52 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.dao; - -import javax.sql.DataSource; - -import org.springframework.jdbc.core.support.JdbcDaoSupport; - -import edu.harvard.i2b2.crc.datavo.pdo.ObserverType; - -/** - * Handle to insert temp obervation fact data. Wraps Springs batch inserter. - * - * @author rk903 - * - */ -public class TempProviderInsertHandler extends JdbcDaoSupport { - private ProviderDAO.TempProviderInsert tempProviderInsert = null; - - public TempProviderInsertHandler(DataSource ds) { - setDataSource(ds); - } - - public TempProviderInsertHandler( - ProviderDAO.TempProviderInsert tempProviderInsert) { - this.tempProviderInsert = tempProviderInsert; - } - - /** - * Submit individual inserts to batch. - * - * @param observationFact - */ - public void insertProvider(ObserverType provider) { - tempProviderInsert.insert(provider); - } - - /** - * Manual submit of batched inserts. - */ - public void flush() { - tempProviderInsert.flush(); - tempProviderInsert.reset(); - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.dao; + +import javax.sql.DataSource; + +import org.springframework.jdbc.core.support.JdbcDaoSupport; + +import edu.harvard.i2b2.crc.datavo.pdo.ObserverType; + +/** + * Handle to insert temp obervation fact data. Wraps Springs batch inserter. + * + * @author rk903 + * + */ +public class TempProviderInsertHandler extends JdbcDaoSupport { + private ProviderDAO.TempProviderInsert tempProviderInsert = null; + + public TempProviderInsertHandler(DataSource ds) { + setDataSource(ds); + } + + public TempProviderInsertHandler( + ProviderDAO.TempProviderInsert tempProviderInsert) { + this.tempProviderInsert = tempProviderInsert; + } + + /** + * Submit individual inserts to batch. + * + * @param observationFact + */ + public void insertProvider(ObserverType provider) { + tempProviderInsert.insert(provider); + } + + /** + * Manual submit of batched inserts. + */ + public void flush() { + tempProviderInsert.flush(); + tempProviderInsert.reset(); + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/TempVisitDimensionInsertHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/TempVisitDimensionInsertHandler.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/TempVisitDimensionInsertHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/TempVisitDimensionInsertHandler.java index e14360cd..01930f37 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/TempVisitDimensionInsertHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/TempVisitDimensionInsertHandler.java @@ -1,44 +1,44 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.dao; - -import edu.harvard.i2b2.crc.datavo.pdo.EventType; - -/** - * Handle to insert temp obervation fact data. Wraps Springs batch inserter. - * - * @author rk903 - * - */ -public class TempVisitDimensionInsertHandler { - private VisitDAO.TempEncounterVisitInsert tempEncounterVisitInsert = null; - - public TempVisitDimensionInsertHandler( - VisitDAO.TempEncounterVisitInsert tempEncounterVisitInsert) { - this.tempEncounterVisitInsert = tempEncounterVisitInsert; - } - - /** - * Submit individual inserts to batch. - * - * @param observationFact - */ - public void insertVisitDimension(EventType event) { - tempEncounterVisitInsert.insert(event); - } - - /** - * Manual submit of batched inserts. - */ - public void flush() { - tempEncounterVisitInsert.flush(); - tempEncounterVisitInsert.reset(); - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.dao; + +import edu.harvard.i2b2.crc.datavo.pdo.EventType; + +/** + * Handle to insert temp obervation fact data. Wraps Springs batch inserter. + * + * @author rk903 + * + */ +public class TempVisitDimensionInsertHandler { + private VisitDAO.TempEncounterVisitInsert tempEncounterVisitInsert = null; + + public TempVisitDimensionInsertHandler( + VisitDAO.TempEncounterVisitInsert tempEncounterVisitInsert) { + this.tempEncounterVisitInsert = tempEncounterVisitInsert; + } + + /** + * Submit individual inserts to batch. + * + * @param observationFact + */ + public void insertVisitDimension(EventType event) { + tempEncounterVisitInsert.insert(event); + } + + /** + * Manual submit of batched inserts. + */ + public void flush() { + tempEncounterVisitInsert.flush(); + tempEncounterVisitInsert.reset(); + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/UniqueKeyException.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/UniqueKeyException.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/UniqueKeyException.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/UniqueKeyException.java index f3fb89aa..47feae8f --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/UniqueKeyException.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/UniqueKeyException.java @@ -1,24 +1,24 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.dao; - -import edu.harvard.i2b2.common.exception.I2B2Exception; - -public class UniqueKeyException extends I2B2Exception { - - public UniqueKeyException() { - - } - - public UniqueKeyException(String message) { - - } - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.dao; + +import edu.harvard.i2b2.common.exception.I2B2Exception; + +public class UniqueKeyException extends I2B2Exception { + + public UniqueKeyException() { + + } + + public UniqueKeyException(String message) { + + } + + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/UploadDAOFactory.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/UploadDAOFactory.java old mode 100755 new mode 100644 similarity index 95% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/UploadDAOFactory.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/UploadDAOFactory.java index 3366c99f..e106725f --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/UploadDAOFactory.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/UploadDAOFactory.java @@ -1,95 +1,95 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.dao; - -import javax.sql.DataSource; - -import edu.harvard.i2b2.crc.loader.datavo.loader.DataSourceLookup; - -public class UploadDAOFactory implements IUploaderDAOFactory { - - @Override - public ConceptDAO getConceptDAO() { - // TODO Auto-generated method stub - return null; - } - - @Override - public ModifierDAO getModifierDAO() { - // TODO Auto-generated method stub - return null; - } - - @Override - public ObservationFactDAO getObservationDAO() { - // TODO Auto-generated method stub - return null; - } - - @Override - public PatientDAO getPatientDAO() { - // TODO Auto-generated method stub - return null; - } - - @Override - public PidDAO getPidDAO() { - // TODO Auto-generated method stub - return null; - } - - @Override - public ProviderDAO getProviderDAO() { - // TODO Auto-generated method stub - return null; - } - - @Override - public UploadStatusDAO getUploadStatusDAO() { - // TODO Auto-generated method stub - return null; - } - - @Override - public VisitDAO getVisitDAO() { - // TODO Auto-generated method stub - return null; - } - - @Override - public DataSourceLookup getDataSourceLookup() { - // TODO Auto-generated method stub - return null; - } - - @Override - public DataSource getDataSource() { - // TODO Auto-generated method stub - return null; - } - - @Override - public void setDataSource(DataSource dataSource) { - // TODO Auto-generated method stub - - } - - @Override - public IEidDAO getEidDAO() { - // TODO Auto-generated method stub - return null; - } - - @Override - public IMissingTermDAO getMissingTermDAO() { - // TODO Auto-generated method stub - return null; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.dao; + +import javax.sql.DataSource; + +import edu.harvard.i2b2.crc.loader.datavo.loader.DataSourceLookup; + +public class UploadDAOFactory implements IUploaderDAOFactory { + + @Override + public ConceptDAO getConceptDAO() { + // TODO Auto-generated method stub + return null; + } + + @Override + public ModifierDAO getModifierDAO() { + // TODO Auto-generated method stub + return null; + } + + @Override + public ObservationFactDAO getObservationDAO() { + // TODO Auto-generated method stub + return null; + } + + @Override + public PatientDAO getPatientDAO() { + // TODO Auto-generated method stub + return null; + } + + @Override + public PidDAO getPidDAO() { + // TODO Auto-generated method stub + return null; + } + + @Override + public ProviderDAO getProviderDAO() { + // TODO Auto-generated method stub + return null; + } + + @Override + public UploadStatusDAO getUploadStatusDAO() { + // TODO Auto-generated method stub + return null; + } + + @Override + public VisitDAO getVisitDAO() { + // TODO Auto-generated method stub + return null; + } + + @Override + public DataSourceLookup getDataSourceLookup() { + // TODO Auto-generated method stub + return null; + } + + @Override + public DataSource getDataSource() { + // TODO Auto-generated method stub + return null; + } + + @Override + public void setDataSource(DataSource dataSource) { + // TODO Auto-generated method stub + + } + + @Override + public IEidDAO getEidDAO() { + // TODO Auto-generated method stub + return null; + } + + @Override + public IMissingTermDAO getMissingTermDAO() { + // TODO Auto-generated method stub + return null; + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/UploadStatusDAO.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/UploadStatusDAO.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/UploadStatusDAO.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/UploadStatusDAO.java index 50dd0ddf..7193bb1e --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/UploadStatusDAO.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/UploadStatusDAO.java @@ -1,695 +1,695 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.dao; - -import java.sql.CallableStatement; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Types; -import java.util.ArrayList; -import java.util.List; - -import javax.sql.DataSource; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.PreparedStatementSetter; -import org.springframework.jdbc.core.RowMapper; -import org.springframework.jdbc.core.SqlParameter; -import org.springframework.jdbc.object.BatchSqlUpdate; -import org.springframework.jdbc.object.MappingSqlQuery; -import org.springframework.jdbc.object.SqlUpdate; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.crc.loader.datavo.loader.DataSourceLookup; -import edu.harvard.i2b2.crc.loader.datavo.loader.UploadSetStatus; -import edu.harvard.i2b2.crc.loader.datavo.loader.UploadStatus; - -/** - * Upload Status data access object. - * - * @author rk903 - */ -public class UploadStatusDAO extends CRCLoaderDAO implements UploadStatusDAOI { - - private static Log log = LogFactory.getLog(UploadStatusDAO.class); - - public static final int EVENT_SET = 1; - public static final int PATIENT_SET = 2; - public static final int CONCEPT_SET = 3; - public static final int OBSERVER_SET = 4; - public static final int OBSERVATION_SET = 5; - public static final int PID_SET = 6; - public static final int EID_SET = 7; - public static final int MODIFIER_SET = 8; - - private DataSourceLookup dataSourceLookup = null; - private JdbcTemplate jdbcTemplate = null; - - public UploadStatusDAO(DataSourceLookup dataSourceLookup, DataSource ds) { - setDataSource(ds); - setDbSchemaName(dataSourceLookup.getFullSchema()); - this.dataSourceLookup = dataSourceLookup; - jdbcTemplate = new JdbcTemplate( - getDataSource()); - // jdbcTemplate = new JdbcTemplate(dsTm.getDataSource()); - } - - /** - * Fetch Upload Status info. - * - * @param uploadStatusId - * @return - * @throws UniqueKeyException - */ - @Override - public UploadStatus findById(int uploadStatusId) throws UniqueKeyException { - UploadStatusQuery uploadStatusQuery = new UploadStatusQuery( - getDataSource(), this.getDbSchemaName(), dataSourceLookup); - - java.util.List uploadList = uploadStatusQuery - .execute(new Object[] { uploadStatusId }); - UploadStatus uploadStatus = null; - if (uploadList != null) { - if (uploadList.size() > 1) { - throw new UniqueKeyException( - "More than one upload for upload id " + uploadStatusId); - } else { - if (uploadList.size() > 0) { - uploadStatus = (UploadStatus) uploadList.get(0); - } - } - } - return uploadStatus; - } - - @Override - public void dropTempTable(String tempTable) { - final String sql = "{call " + getDbSchemaName() - + "REMOVE_TEMP_TABLE(?)}"; - jdbcTemplate.update(sql, new Object[] { tempTable }); - } - - /** - * Insert UploadStatus - * - * @param uploadStatus - * @return - */ - @Override - public int insertUploadStatus(UploadStatus uploadStatus) { - UploadStatusInsert uploadStatusInsert = new UploadStatusInsert( - getDataSource(), this.getDbSchemaName(), dataSourceLookup); - // if (dataSourceLookup.getServerType().equalsIgnoreCase( - // LoaderDAOFactoryHelper.ORACLE)) { - //uploadStatus.setUploadId(uploadStatusInsert.generateUploadStatusId()); - // } - uploadStatusInsert.insert(uploadStatus); - // uploadStatusInsert.flush(); - return uploadStatus.getUploadId(); - } - - /** - * Insert SetUploadStatus - * - * @param uploadStatus - * @return - */ - @Override - public void insertUploadSetStatus(final UploadSetStatus uploadSetStatus) { - String insertSql = "insert into " + this.getDbSchemaName() - + "SET_UPLOAD_STATUS(UPLOAD_ID, " + "SET_TYPE_ID," - + "SOURCE_CD, " + "NO_OF_RECORD," + "LOADED_RECORD," - + "DELETED_RECORD," + "LOAD_DATE," + "END_DATE," - + "LOAD_STATUS," + "MESSAGE," + "INPUT_FILE_NAME," - + "LOG_FILE_NAME," - + "TRANSFORM_NAME) values(?,?,?,?,?,?,?,?,?,?,?,?,?)"; - - /* - * jdbcTemplate.update(insertSql, new - * Object[]{uploadSetStatus.getUploadId(), - * uploadSetStatus.getSetTypeId(), uploadSetStatus.getSourceCd(), - * uploadSetStatus.getNoOfRecord(), uploadSetStatus.getLoadedRecord(), - * uploadSetStatus.getDeletedRecord(), uploadSetStatus.getLoadDate(), - * uploadSetStatus.getEndDate(), uploadSetStatus.getLoadStatus(), - * uploadSetStatus.getMessage(), uploadSetStatus.getInputFileName(), - * uploadSetStatus.getLogFileName(), - * uploadSetStatus.getTransformName()}); - */ - - jdbcTemplate.update(insertSql, new PreparedStatementSetter() { - @Override - public void setValues(PreparedStatement ps) throws SQLException { - ps.setInt(1, uploadSetStatus.getUploadId()); - ps.setInt(2, uploadSetStatus.getSetTypeId()); - ps.setString(3, uploadSetStatus.getSourceCd()); - ps.setInt(4, uploadSetStatus.getNoOfRecord()); - ps.setInt(5, uploadSetStatus.getLoadedRecord()); - ps.setInt(6, uploadSetStatus.getDeletedRecord()); - ps.setTimestamp(7, new java.sql.Timestamp(uploadSetStatus - .getLoadDate().getTime())); - ps - .setTimestamp( - 8, - (uploadSetStatus.getEndDate() != null) ? new java.sql.Timestamp( - uploadSetStatus.getEndDate().getTime()) - : null); - ps.setString(9, uploadSetStatus.getLoadStatus()); - ps.setString(10, uploadSetStatus.getMessage()); - ps.setString(11, uploadSetStatus.getInputFileName()); - ps.setString(12, uploadSetStatus.getLogFileName()); - ps.setString(13, uploadSetStatus.getTransformName()); - } - }); - - } - - /** - * update SetUploadStatus - * - * @param uploadSetStatus - * @return - */ - @Override - public void updateUploadSetStatus(final UploadSetStatus uploadSetStatus) { - String updateSql = "update " + this.getDbSchemaName() - + "SET_UPLOAD_STATUS " + "set NO_OF_RECORD = ?," - + " LOADED_RECORD =?," + " DELETED_RECORD=?," + " LOAD_DATE=?," - + " END_DATE=?," + " LOAD_STATUS=?," + " MESSAGE=?," - + " INPUT_FILE_NAME=?," + " LOG_FILE_NAME=?," - + " TRANSFORM_NAME=? where UPLOAD_ID =? and SET_TYPE_ID=?"; - - /* - * jdbcTemplate.update(updateSql, new Object[]{ - * uploadSetStatus.getNoOfRecord(), uploadSetStatus.getLoadedRecord(), - * uploadSetStatus.getDeletedRecord(), uploadSetStatus.getLoadDate(), - * uploadSetStatus.getEndDate(), uploadSetStatus.getLoadStatus(), - * uploadSetStatus.getMessage(), uploadSetStatus.getInputFileName(), - * uploadSetStatus.getLogFileName(), uploadSetStatus.getTransformName(), - * uploadSetStatus.getUploadId(), uploadSetStatus.getSetTypeId()}); - */ - - jdbcTemplate.update(updateSql, new PreparedStatementSetter() { - @Override - public void setValues(PreparedStatement ps) throws SQLException { - ps.setInt(1, uploadSetStatus.getNoOfRecord()); - ps.setInt(2, uploadSetStatus.getLoadedRecord()); - ps.setInt(3, uploadSetStatus.getDeletedRecord()); - ps - .setTimestamp( - 4, - (uploadSetStatus.getLoadDate() != null) ? new java.sql.Timestamp( - uploadSetStatus.getLoadDate().getTime()) - : null); - ps - .setTimestamp( - 5, - (uploadSetStatus.getEndDate() != null) ? new java.sql.Timestamp( - uploadSetStatus.getEndDate().getTime()) - : null); - ps.setString(6, uploadSetStatus.getLoadStatus()); - ps.setString(7, uploadSetStatus.getMessage()); - ps.setString(8, uploadSetStatus.getInputFileName()); - ps.setString(9, uploadSetStatus.getLogFileName()); - ps.setString(10, uploadSetStatus.getTransformName()); - ps.setInt(11, uploadSetStatus.getUploadId()); - ps.setInt(12, uploadSetStatus.getSetTypeId()); - } - }); - - } - - /** - * - */ - @Override - public UploadSetStatus getUploadSetStatus(int uploadId, int setId) { - UploadSetStatus uploadSetStatus = (UploadSetStatus) jdbcTemplate - .queryForObject( - "select * from " - + this.getDbSchemaName() - + "SET_UPLOAD_STATUS where UPLOAD_ID=? and SET_TYPE_ID=?", - new Object[] { uploadId, setId }, new RowMapper() { - - @Override - public Object mapRow(ResultSet rs, int rowNum) - throws SQLException { - UploadSetStatus uploadSetStatus = new UploadSetStatus(); - uploadSetStatus.setUploadId(rs - .getInt("UPLOAD_ID")); - uploadSetStatus.setSetTypeId(rs - .getInt("SET_TYPE_ID")); - uploadSetStatus.setLoadDate(rs - .getTimestamp("LOAD_DATE")); - uploadSetStatus.setEndDate(rs - .getTimestamp("END_DATE")); - uploadSetStatus.setDeletedRecord(rs - .getInt("DELETED_RECORD")); - uploadSetStatus.setLoadedRecord(rs - .getInt("LOADED_RECORD")); - uploadSetStatus.setLoadStatus(rs - .getString("LOAD_STATUS")); - uploadSetStatus.setLogFileName(rs - .getString("LOG_FILE_NAME")); - uploadSetStatus.setMessage(rs - .getString("MESSAGE")); - uploadSetStatus.setNoOfRecord(rs - .getInt("NO_OF_RECORD")); - uploadSetStatus.setSourceCd(rs - .getString("SOURCE_CD")); - uploadSetStatus.setTransformName(rs - .getString("TRANSFORM_NAME")); - return uploadSetStatus; - } - }); - - return uploadSetStatus; - } - - /** - * Return load status of individual sets in patient data objects - * - * @param uploadId - * @return - */ - @Override - public List getUploadSetStatusByLoadId(int uploadId) { - List setUploadStatusList = new ArrayList(); - int rowCount = jdbcTemplate.queryForObject("select count(1) from " - + this.getDbSchemaName() - + "SET_UPLOAD_STATUS where UPLOAD_ID=?",Integer.class, - new Object[] { uploadId }); - if (rowCount < 1) { - return setUploadStatusList; - } - log.debug("ROW COUNT " + rowCount); - Connection conn = null; - try { - String sql = "select upload_id as upload_id, " - + " set_type_id as set_type_id," - + " load_date,end_date ,deleted_record as deleted_record, " - + "loaded_record as loaded_record, " - + "load_status, log_file_name, message,no_of_record as no_of_record," - + "source_cd, transform_name from " - + this.getDbSchemaName() - + "SET_UPLOAD_STATUS where UPLOAD_ID=?"; - - conn = jdbcTemplate.getDataSource().getConnection(); - PreparedStatement stmt = conn.prepareStatement(sql); - stmt.setInt(1, uploadId); - ResultSet rs = stmt.executeQuery(); - while (rs.next()) { - UploadSetStatus uploadSetStatus = new UploadSetStatus(); - uploadSetStatus.setUploadId(rs.getInt("UPLOAD_ID")); - uploadSetStatus.setSetTypeId(rs.getInt("SET_TYPE_ID")); - uploadSetStatus.setLoadDate(rs.getTimestamp("LOAD_DATE")); - uploadSetStatus.setEndDate(rs.getTimestamp("END_DATE")); - uploadSetStatus.setDeletedRecord(rs.getInt("DELETED_RECORD")); - uploadSetStatus.setLoadedRecord(rs.getInt("LOADED_RECORD")); - uploadSetStatus.setLoadStatus(rs.getString("LOAD_STATUS")); - uploadSetStatus.setLogFileName(rs.getString("LOG_FILE_NAME")); - uploadSetStatus.setMessage(rs.getString("MESSAGE")); - uploadSetStatus.setNoOfRecord(rs.getInt("NO_OF_RECORD")); - uploadSetStatus.setSourceCd(rs.getString("SOURCE_CD")); - uploadSetStatus - .setTransformName(rs.getString("TRANSFORM_NAME")); - setUploadStatusList.add(uploadSetStatus); - } - - } catch (SQLException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } finally { - if (conn != null) { - try { - conn.close(); - } catch (SQLException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } - - /* - * SqlRowSet rs = - * jdbcTemplate.queryForRowSet("select upload_id as upload_id, " + - * " set_type_id as set_type_id," + - * " load_date,end_date ,deleted_record as deleted_record, " + - * "loaded_record as loaded_record, " + - * "load_status, log_file_name, message,no_of_record as no_of_record," + - * "source_cd, transform_name from "+ this.getDbSchemaName() - * +"SET_UPLOAD_STATUS where UPLOAD_ID=?", new Object[]{uploadId}); - */ - return setUploadStatusList; - - } - - /** - * Update UploadStatus information based on upload_id. - */ - @Override - public void updateUploadStatus(UploadStatus uploadStatus) { - UploadStatusUpdate uploadStatusUpdate = new UploadStatusUpdate( - getDataSource(), this.getDbSchemaName()); - uploadStatusUpdate.update(uploadStatus); - uploadStatusUpdate.flush(); - } - - @Override - public List getAllUploadStatus() { - List uploadStatusList = null; - UploadStatusQuery uploadStatusQuery = new UploadStatusQuery( - getDataSource(), "select * from " + this.getDbSchemaName() - + "upload_status order by upload_id desc"); - uploadStatusList = uploadStatusQuery.execute(); - return uploadStatusList; - } - - @Override - @SuppressWarnings("unchecked") - public List getUpoadStatusByUser(String userId) { - List uploadStatusList = null; - UploadStatusQuery uploadStatusQuery = new UploadStatusQuery( - getDataSource(), - "select * from " - + this.getDbSchemaName() - + "upload_status where user_id = ? order by upload_id desc"); - uploadStatusQuery.declareParameter(new SqlParameter("user_id", - Types.CHAR)); - uploadStatusList = uploadStatusQuery - .execute(userId); - return uploadStatusList; - } - - /** - * Calculate upload status information like records loaded,etc for given - * upload id using stored proc. - * - * @param upload - * id - * @throws Exception - */ - @Override - public void calculateUploadStatus(int uploadId) throws I2B2Exception { - Connection conn = null; - try { - conn = this.getDataSource().getConnection(); - CallableStatement callStmt = conn.prepareCall("{call " - + this.getDbSchemaName() + "CALCULATE_UPLOAD_STATUS(?)}"); - callStmt.setInt(1, uploadId); - callStmt.execute(); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - throw new I2B2Exception( - "SQLException occured" + sqlEx.getMessage(), sqlEx); - } catch (Exception ex) { - ex.printStackTrace(); - throw new I2B2Exception("Exception occured" + ex.getMessage(), ex); - } finally { - if (conn != null) { - try { - conn.close(); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - log.error("Error while closing connection", sqlEx); - } - } - } - } - - /** - * Function to delete upload data(observation_fact) based on upload id using - * stored proc. - * - * @param upload - * id - * @throws Exception - */ - @Override - public void deleteUploadData(int uploadId) throws I2B2Exception { - Connection conn = null; - try { - conn = this.getDataSource().getConnection(); - CallableStatement callStmt = conn.prepareCall("{call " - + this.getDbSchemaName() + "DELETE_UPLOAD_DATA(?)}"); - callStmt.setInt(1, uploadId); - callStmt.execute(); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - throw new I2B2Exception( - "SQLException occured" + sqlEx.getMessage(), sqlEx); - } catch (Exception ex) { - ex.printStackTrace(); - throw new I2B2Exception("Exception occured" + ex.getMessage(), ex); - } finally { - if (conn != null) { - try { - conn.close(); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - log.error("Error while closing connection", sqlEx); - } - } - } - } - - /** - * Base class for all UploadStatus Query Objects. - */ - protected class UploadStatusQuery extends MappingSqlQuery { - - /** - * Create a new instance of UploadStatusQuery. - * - * @param ds - * the DataSource to use for the query - * @param sql - * SQL string to use for the query - */ - protected UploadStatusQuery(DataSource ds, String sql) { - super(ds, sql); - } - - /** - * Create a new instance of UploadStatusQuery that returns all - * UploadStatus. - * - * @param ds - * the DataSource to use for the query - */ - protected UploadStatusQuery(DataSource ds, String schemaName, - DataSourceLookup dataSourceLookup) { - - super(ds, "SELECT upload_id, " + " upload_label, " + " user_id, " - + " source_cd, " + " no_of_record, " + " deleted_record, " - + " loaded_record, " + " load_date, " + " end_date, " - + " load_status, " + " input_file_name, " - + " log_file_name, " + " transform_name ," + "message " - + " FROM " + schemaName - + "upload_status WHERE upload_id = ? "); - declareParameter(new SqlParameter(Types.INTEGER)); - compile(); - } - - @Override - protected Object mapRow(ResultSet rs, int rownum) throws SQLException { - UploadStatus uploadStatus = new UploadStatus(); - uploadStatus.setUploadId(rs.getInt("upload_id")); - uploadStatus.setUploadLabel(rs.getString("upload_label")); - uploadStatus.setUserId(rs.getString("user_id")); - uploadStatus.setSourceCd(rs.getString("source_cd")); - uploadStatus.setNoOfRecord(rs.getInt("no_of_record")); - uploadStatus.setDeletedRecord(rs.getInt("deleted_record")); - uploadStatus.setLoadedRecord(rs.getInt("loaded_record")); - uploadStatus.setLoadDate(rs.getTimestamp("load_date")); - uploadStatus.setEndDate(rs.getTimestamp("end_date")); - uploadStatus.setLoadStatus(rs.getString("load_status")); - uploadStatus.setInputFileName(rs.getString("input_file_name")); - uploadStatus.setLogFileName(rs.getString("log_file_name")); - uploadStatus.setTransformName(rs.getString("transform_name")); - uploadStatus.setMessage(rs.getString("message")); - return uploadStatus; - } - } - - /** - * Visit Insert Object. - */ - protected class UploadStatusInsert extends SqlUpdate { - /** - * Create a new instance of OwnerInsert. - * - * @param ds - * the DataSource to use for the insert - */ - protected UploadStatusInsert(DataSource ds, String schemaName, - DataSourceLookup dataSourceLookup) { - - String sql = null; - if (dataSourceLookup.getServerType().equalsIgnoreCase( - LoaderDAOFactoryHelper.SQLSERVER) || (dataSourceLookup.getServerType().equalsIgnoreCase( - LoaderDAOFactoryHelper.POSTGRESQL))) { - sql = "INSERT INTO " + schemaName + "upload_status (" + - - " upload_label, " + " user_id, " + " source_cd, " - + " no_of_record, " + " deleted_record, " - + " loaded_record, " + " load_date, " + " end_date, " - + " load_status, " + " input_file_name, " - + " log_file_name, " + " message, " - + " transform_name) " - + " VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)"; - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - LoaderDAOFactoryHelper.ORACLE)) { - sql = "INSERT INTO " + schemaName + "upload_status (" - + " upload_id," + " upload_label, " + " user_id, " - + " source_cd, " + " no_of_record, " - + " deleted_record, " + " loaded_record, " - + " load_date, " + " end_date, " + " load_status, " - + " input_file_name, " + " log_file_name, " - + " message, " + " transform_name) " - + " VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; - } - this.setSql(sql); - this.setDataSource(dataSource); - - if (dataSourceLookup.getServerType().equalsIgnoreCase( - LoaderDAOFactoryHelper.ORACLE) || dataSourceLookup.getServerType().equalsIgnoreCase( - LoaderDAOFactoryHelper.POSTGRESQL)) { - declareParameter(new SqlParameter(Types.INTEGER)); - } - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.INTEGER)); - declareParameter(new SqlParameter(Types.INTEGER)); - declareParameter(new SqlParameter(Types.INTEGER)); - declareParameter(new SqlParameter(Types.TIMESTAMP)); - declareParameter(new SqlParameter(Types.TIMESTAMP)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - compile(); - } - - protected void insert(UploadStatus uploadStatus) { - int uploadId = 0; - Object[] objs = null; - if (dataSourceLookup.getServerType().equalsIgnoreCase( - LoaderDAOFactoryHelper.ORACLE) || dataSourceLookup.getServerType().equalsIgnoreCase( - LoaderDAOFactoryHelper.POSTGRESQL)) { - uploadId = getJdbcTemplate().queryForObject( - "select sq_uploadstatus_uploadid.nextval from dual",Integer.class); - uploadStatus.setUploadId(uploadId); - objs = new Object[] { uploadStatus.getUploadId(), - uploadStatus.getUploadLabel(), - uploadStatus.getUserId(), uploadStatus.getSourceCd(), - uploadStatus.getNoOfRecord(), - uploadStatus.getDeletedRecord(), - uploadStatus.getLoadedRecord(), - uploadStatus.getLoadDate(), uploadStatus.getEndDate(), - uploadStatus.getLoadStatus(), - uploadStatus.getInputFileName(), - uploadStatus.getLogFileName(), - uploadStatus.getMessage(), - uploadStatus.getTransformName() }; - update(objs); - - } else if (dataSourceLookup.getServerType().equalsIgnoreCase( - LoaderDAOFactoryHelper.SQLSERVER)) { - objs = new Object[] { uploadStatus.getUploadLabel(), - uploadStatus.getUserId(), uploadStatus.getSourceCd(), - uploadStatus.getNoOfRecord(), - uploadStatus.getDeletedRecord(), - uploadStatus.getLoadedRecord(), - uploadStatus.getLoadDate(), uploadStatus.getEndDate(), - uploadStatus.getLoadStatus(), - uploadStatus.getInputFileName(), - uploadStatus.getLogFileName(), - uploadStatus.getMessage(), - uploadStatus.getTransformName() }; - update(objs); - uploadId = getJdbcTemplate().queryForObject("SELECT @@IDENTITY", Integer.class); - } - - uploadStatus.setUploadId(uploadId); - } - - protected int generateUploadStatusId() { - return getJdbcTemplate().queryForObject( - "select sq_uploadstatus_uploadid.nextval from dual", Integer.class); - } - - } - - /** - * UploadStatus Update Object. - */ - protected class UploadStatusUpdate extends BatchSqlUpdate { - - /** - * Create a new instance of UploadStatusUpdate. - * - * @param ds - * the DataSource to use for the update - */ - protected UploadStatusUpdate(DataSource ds, String schemaName) { - super(ds, "UPDATE " + schemaName + "upload_status SET " - + "upload_label=?, " + "user_id=?, " + "source_cd=?, " - + "no_of_record=?, " + "deleted_record=?, " - + "loaded_record=?, " + "load_date=?, " + "end_date=?," - + "load_status=?, " + "input_file_name=?, " - + "log_file_name=?, " + "transform_name=?, " + "message=? " - + "WHERE upload_id=?"); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.INTEGER)); - declareParameter(new SqlParameter(Types.INTEGER)); - declareParameter(new SqlParameter(Types.INTEGER)); - declareParameter(new SqlParameter(Types.TIMESTAMP)); - declareParameter(new SqlParameter(Types.TIMESTAMP)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.LONGVARCHAR)); - declareParameter(new SqlParameter(Types.INTEGER)); - compile(); - } - - /** - * Method to update UploadStatus's data. - * - * @param UploadStatus - * to update - * @return the number of rows affected by the update - */ - protected int update(UploadStatus uploadStatus) { - return this.update(new Object[] { uploadStatus.getUploadLabel(), - uploadStatus.getUserId(), uploadStatus.getSourceCd(), - uploadStatus.getNoOfRecord(), - uploadStatus.getDeletedRecord(), - uploadStatus.getLoadedRecord(), uploadStatus.getLoadDate(), - uploadStatus.getEndDate(), uploadStatus.getLoadStatus(), - uploadStatus.getInputFileName(), - uploadStatus.getLogFileName(), - uploadStatus.getTransformName(), uploadStatus.getMessage(), - uploadStatus.getUploadId() - - }); - - } - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.dao; + +import java.sql.CallableStatement; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Types; +import java.util.ArrayList; +import java.util.List; + +import javax.sql.DataSource; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.PreparedStatementSetter; +import org.springframework.jdbc.core.RowMapper; +import org.springframework.jdbc.core.SqlParameter; +import org.springframework.jdbc.object.BatchSqlUpdate; +import org.springframework.jdbc.object.MappingSqlQuery; +import org.springframework.jdbc.object.SqlUpdate; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.crc.loader.datavo.loader.DataSourceLookup; +import edu.harvard.i2b2.crc.loader.datavo.loader.UploadSetStatus; +import edu.harvard.i2b2.crc.loader.datavo.loader.UploadStatus; + +/** + * Upload Status data access object. + * + * @author rk903 + */ +public class UploadStatusDAO extends CRCLoaderDAO implements UploadStatusDAOI { + + private static Log log = LogFactory.getLog(UploadStatusDAO.class); + + public static final int EVENT_SET = 1; + public static final int PATIENT_SET = 2; + public static final int CONCEPT_SET = 3; + public static final int OBSERVER_SET = 4; + public static final int OBSERVATION_SET = 5; + public static final int PID_SET = 6; + public static final int EID_SET = 7; + public static final int MODIFIER_SET = 8; + + private DataSourceLookup dataSourceLookup = null; + private JdbcTemplate jdbcTemplate = null; + + public UploadStatusDAO(DataSourceLookup dataSourceLookup, DataSource ds) { + setDataSource(ds); + setDbSchemaName(dataSourceLookup.getFullSchema()); + this.dataSourceLookup = dataSourceLookup; + jdbcTemplate = new JdbcTemplate( + getDataSource()); + // jdbcTemplate = new JdbcTemplate(dsTm.getDataSource()); + } + + /** + * Fetch Upload Status info. + * + * @param uploadStatusId + * @return + * @throws UniqueKeyException + */ + @Override + public UploadStatus findById(int uploadStatusId) throws UniqueKeyException { + UploadStatusQuery uploadStatusQuery = new UploadStatusQuery( + getDataSource(), this.getDbSchemaName(), dataSourceLookup); + + java.util.List uploadList = uploadStatusQuery + .execute(new Object[] { uploadStatusId }); + UploadStatus uploadStatus = null; + if (uploadList != null) { + if (uploadList.size() > 1) { + throw new UniqueKeyException( + "More than one upload for upload id " + uploadStatusId); + } else { + if (uploadList.size() > 0) { + uploadStatus = (UploadStatus) uploadList.get(0); + } + } + } + return uploadStatus; + } + + @Override + public void dropTempTable(String tempTable) { + final String sql = "{call " + getDbSchemaName() + + "REMOVE_TEMP_TABLE(?)}"; + jdbcTemplate.update(sql, new Object[] { tempTable }); + } + + /** + * Insert UploadStatus + * + * @param uploadStatus + * @return + */ + @Override + public int insertUploadStatus(UploadStatus uploadStatus) { + UploadStatusInsert uploadStatusInsert = new UploadStatusInsert( + getDataSource(), this.getDbSchemaName(), dataSourceLookup); + // if (dataSourceLookup.getServerType().equalsIgnoreCase( + // LoaderDAOFactoryHelper.ORACLE)) { + //uploadStatus.setUploadId(uploadStatusInsert.generateUploadStatusId()); + // } + uploadStatusInsert.insert(uploadStatus); + // uploadStatusInsert.flush(); + return uploadStatus.getUploadId(); + } + + /** + * Insert SetUploadStatus + * + * @param uploadStatus + * @return + */ + @Override + public void insertUploadSetStatus(final UploadSetStatus uploadSetStatus) { + String insertSql = "insert into " + this.getDbSchemaName() + + "SET_UPLOAD_STATUS(UPLOAD_ID, " + "SET_TYPE_ID," + + "SOURCE_CD, " + "NO_OF_RECORD," + "LOADED_RECORD," + + "DELETED_RECORD," + "LOAD_DATE," + "END_DATE," + + "LOAD_STATUS," + "MESSAGE," + "INPUT_FILE_NAME," + + "LOG_FILE_NAME," + + "TRANSFORM_NAME) values(?,?,?,?,?,?,?,?,?,?,?,?,?)"; + + /* + * jdbcTemplate.update(insertSql, new + * Object[]{uploadSetStatus.getUploadId(), + * uploadSetStatus.getSetTypeId(), uploadSetStatus.getSourceCd(), + * uploadSetStatus.getNoOfRecord(), uploadSetStatus.getLoadedRecord(), + * uploadSetStatus.getDeletedRecord(), uploadSetStatus.getLoadDate(), + * uploadSetStatus.getEndDate(), uploadSetStatus.getLoadStatus(), + * uploadSetStatus.getMessage(), uploadSetStatus.getInputFileName(), + * uploadSetStatus.getLogFileName(), + * uploadSetStatus.getTransformName()}); + */ + + jdbcTemplate.update(insertSql, new PreparedStatementSetter() { + @Override + public void setValues(PreparedStatement ps) throws SQLException { + ps.setInt(1, uploadSetStatus.getUploadId()); + ps.setInt(2, uploadSetStatus.getSetTypeId()); + ps.setString(3, uploadSetStatus.getSourceCd()); + ps.setInt(4, uploadSetStatus.getNoOfRecord()); + ps.setInt(5, uploadSetStatus.getLoadedRecord()); + ps.setInt(6, uploadSetStatus.getDeletedRecord()); + ps.setTimestamp(7, new java.sql.Timestamp(uploadSetStatus + .getLoadDate().getTime())); + ps + .setTimestamp( + 8, + (uploadSetStatus.getEndDate() != null) ? new java.sql.Timestamp( + uploadSetStatus.getEndDate().getTime()) + : null); + ps.setString(9, uploadSetStatus.getLoadStatus()); + ps.setString(10, uploadSetStatus.getMessage()); + ps.setString(11, uploadSetStatus.getInputFileName()); + ps.setString(12, uploadSetStatus.getLogFileName()); + ps.setString(13, uploadSetStatus.getTransformName()); + } + }); + + } + + /** + * update SetUploadStatus + * + * @param uploadSetStatus + * @return + */ + @Override + public void updateUploadSetStatus(final UploadSetStatus uploadSetStatus) { + String updateSql = "update " + this.getDbSchemaName() + + "SET_UPLOAD_STATUS " + "set NO_OF_RECORD = ?," + + " LOADED_RECORD =?," + " DELETED_RECORD=?," + " LOAD_DATE=?," + + " END_DATE=?," + " LOAD_STATUS=?," + " MESSAGE=?," + + " INPUT_FILE_NAME=?," + " LOG_FILE_NAME=?," + + " TRANSFORM_NAME=? where UPLOAD_ID =? and SET_TYPE_ID=?"; + + /* + * jdbcTemplate.update(updateSql, new Object[]{ + * uploadSetStatus.getNoOfRecord(), uploadSetStatus.getLoadedRecord(), + * uploadSetStatus.getDeletedRecord(), uploadSetStatus.getLoadDate(), + * uploadSetStatus.getEndDate(), uploadSetStatus.getLoadStatus(), + * uploadSetStatus.getMessage(), uploadSetStatus.getInputFileName(), + * uploadSetStatus.getLogFileName(), uploadSetStatus.getTransformName(), + * uploadSetStatus.getUploadId(), uploadSetStatus.getSetTypeId()}); + */ + + jdbcTemplate.update(updateSql, new PreparedStatementSetter() { + @Override + public void setValues(PreparedStatement ps) throws SQLException { + ps.setInt(1, uploadSetStatus.getNoOfRecord()); + ps.setInt(2, uploadSetStatus.getLoadedRecord()); + ps.setInt(3, uploadSetStatus.getDeletedRecord()); + ps + .setTimestamp( + 4, + (uploadSetStatus.getLoadDate() != null) ? new java.sql.Timestamp( + uploadSetStatus.getLoadDate().getTime()) + : null); + ps + .setTimestamp( + 5, + (uploadSetStatus.getEndDate() != null) ? new java.sql.Timestamp( + uploadSetStatus.getEndDate().getTime()) + : null); + ps.setString(6, uploadSetStatus.getLoadStatus()); + ps.setString(7, uploadSetStatus.getMessage()); + ps.setString(8, uploadSetStatus.getInputFileName()); + ps.setString(9, uploadSetStatus.getLogFileName()); + ps.setString(10, uploadSetStatus.getTransformName()); + ps.setInt(11, uploadSetStatus.getUploadId()); + ps.setInt(12, uploadSetStatus.getSetTypeId()); + } + }); + + } + + /** + * + */ + @Override + public UploadSetStatus getUploadSetStatus(int uploadId, int setId) { + UploadSetStatus uploadSetStatus = (UploadSetStatus) jdbcTemplate + .queryForObject( + "select * from " + + this.getDbSchemaName() + + "SET_UPLOAD_STATUS where UPLOAD_ID=? and SET_TYPE_ID=?", + new Object[] { uploadId, setId }, new RowMapper() { + + @Override + public Object mapRow(ResultSet rs, int rowNum) + throws SQLException { + UploadSetStatus uploadSetStatus = new UploadSetStatus(); + uploadSetStatus.setUploadId(rs + .getInt("UPLOAD_ID")); + uploadSetStatus.setSetTypeId(rs + .getInt("SET_TYPE_ID")); + uploadSetStatus.setLoadDate(rs + .getTimestamp("LOAD_DATE")); + uploadSetStatus.setEndDate(rs + .getTimestamp("END_DATE")); + uploadSetStatus.setDeletedRecord(rs + .getInt("DELETED_RECORD")); + uploadSetStatus.setLoadedRecord(rs + .getInt("LOADED_RECORD")); + uploadSetStatus.setLoadStatus(rs + .getString("LOAD_STATUS")); + uploadSetStatus.setLogFileName(rs + .getString("LOG_FILE_NAME")); + uploadSetStatus.setMessage(rs + .getString("MESSAGE")); + uploadSetStatus.setNoOfRecord(rs + .getInt("NO_OF_RECORD")); + uploadSetStatus.setSourceCd(rs + .getString("SOURCE_CD")); + uploadSetStatus.setTransformName(rs + .getString("TRANSFORM_NAME")); + return uploadSetStatus; + } + }); + + return uploadSetStatus; + } + + /** + * Return load status of individual sets in patient data objects + * + * @param uploadId + * @return + */ + @Override + public List getUploadSetStatusByLoadId(int uploadId) { + List setUploadStatusList = new ArrayList(); + int rowCount = jdbcTemplate.queryForObject("select count(1) from " + + this.getDbSchemaName() + + "SET_UPLOAD_STATUS where UPLOAD_ID=?",Integer.class, + new Object[] { uploadId }); + if (rowCount < 1) { + return setUploadStatusList; + } + log.debug("ROW COUNT " + rowCount); + Connection conn = null; + try { + String sql = "select upload_id as upload_id, " + + " set_type_id as set_type_id," + + " load_date,end_date ,deleted_record as deleted_record, " + + "loaded_record as loaded_record, " + + "load_status, log_file_name, message,no_of_record as no_of_record," + + "source_cd, transform_name from " + + this.getDbSchemaName() + + "SET_UPLOAD_STATUS where UPLOAD_ID=?"; + + conn = jdbcTemplate.getDataSource().getConnection(); + PreparedStatement stmt = conn.prepareStatement(sql); + stmt.setInt(1, uploadId); + ResultSet rs = stmt.executeQuery(); + while (rs.next()) { + UploadSetStatus uploadSetStatus = new UploadSetStatus(); + uploadSetStatus.setUploadId(rs.getInt("UPLOAD_ID")); + uploadSetStatus.setSetTypeId(rs.getInt("SET_TYPE_ID")); + uploadSetStatus.setLoadDate(rs.getTimestamp("LOAD_DATE")); + uploadSetStatus.setEndDate(rs.getTimestamp("END_DATE")); + uploadSetStatus.setDeletedRecord(rs.getInt("DELETED_RECORD")); + uploadSetStatus.setLoadedRecord(rs.getInt("LOADED_RECORD")); + uploadSetStatus.setLoadStatus(rs.getString("LOAD_STATUS")); + uploadSetStatus.setLogFileName(rs.getString("LOG_FILE_NAME")); + uploadSetStatus.setMessage(rs.getString("MESSAGE")); + uploadSetStatus.setNoOfRecord(rs.getInt("NO_OF_RECORD")); + uploadSetStatus.setSourceCd(rs.getString("SOURCE_CD")); + uploadSetStatus + .setTransformName(rs.getString("TRANSFORM_NAME")); + setUploadStatusList.add(uploadSetStatus); + } + + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } finally { + if (conn != null) { + try { + conn.close(); + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + + /* + * SqlRowSet rs = + * jdbcTemplate.queryForRowSet("select upload_id as upload_id, " + + * " set_type_id as set_type_id," + + * " load_date,end_date ,deleted_record as deleted_record, " + + * "loaded_record as loaded_record, " + + * "load_status, log_file_name, message,no_of_record as no_of_record," + + * "source_cd, transform_name from "+ this.getDbSchemaName() + * +"SET_UPLOAD_STATUS where UPLOAD_ID=?", new Object[]{uploadId}); + */ + return setUploadStatusList; + + } + + /** + * Update UploadStatus information based on upload_id. + */ + @Override + public void updateUploadStatus(UploadStatus uploadStatus) { + UploadStatusUpdate uploadStatusUpdate = new UploadStatusUpdate( + getDataSource(), this.getDbSchemaName()); + uploadStatusUpdate.update(uploadStatus); + uploadStatusUpdate.flush(); + } + + @Override + public List getAllUploadStatus() { + List uploadStatusList = null; + UploadStatusQuery uploadStatusQuery = new UploadStatusQuery( + getDataSource(), "select * from " + this.getDbSchemaName() + + "upload_status order by upload_id desc"); + uploadStatusList = uploadStatusQuery.execute(); + return uploadStatusList; + } + + @Override + @SuppressWarnings("unchecked") + public List getUpoadStatusByUser(String userId) { + List uploadStatusList = null; + UploadStatusQuery uploadStatusQuery = new UploadStatusQuery( + getDataSource(), + "select * from " + + this.getDbSchemaName() + + "upload_status where user_id = ? order by upload_id desc"); + uploadStatusQuery.declareParameter(new SqlParameter("user_id", + Types.CHAR)); + uploadStatusList = uploadStatusQuery + .execute(userId); + return uploadStatusList; + } + + /** + * Calculate upload status information like records loaded,etc for given + * upload id using stored proc. + * + * @param upload + * id + * @throws Exception + */ + @Override + public void calculateUploadStatus(int uploadId) throws I2B2Exception { + Connection conn = null; + try { + conn = this.getDataSource().getConnection(); + CallableStatement callStmt = conn.prepareCall("{call " + + this.getDbSchemaName() + "CALCULATE_UPLOAD_STATUS(?)}"); + callStmt.setInt(1, uploadId); + callStmt.execute(); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + throw new I2B2Exception( + "SQLException occured" + sqlEx.getMessage(), sqlEx); + } catch (Exception ex) { + ex.printStackTrace(); + throw new I2B2Exception("Exception occured" + ex.getMessage(), ex); + } finally { + if (conn != null) { + try { + conn.close(); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + log.error("Error while closing connection", sqlEx); + } + } + } + } + + /** + * Function to delete upload data(observation_fact) based on upload id using + * stored proc. + * + * @param upload + * id + * @throws Exception + */ + @Override + public void deleteUploadData(int uploadId) throws I2B2Exception { + Connection conn = null; + try { + conn = this.getDataSource().getConnection(); + CallableStatement callStmt = conn.prepareCall("{call " + + this.getDbSchemaName() + "DELETE_UPLOAD_DATA(?)}"); + callStmt.setInt(1, uploadId); + callStmt.execute(); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + throw new I2B2Exception( + "SQLException occured" + sqlEx.getMessage(), sqlEx); + } catch (Exception ex) { + ex.printStackTrace(); + throw new I2B2Exception("Exception occured" + ex.getMessage(), ex); + } finally { + if (conn != null) { + try { + conn.close(); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + log.error("Error while closing connection", sqlEx); + } + } + } + } + + /** + * Base class for all UploadStatus Query Objects. + */ + protected class UploadStatusQuery extends MappingSqlQuery { + + /** + * Create a new instance of UploadStatusQuery. + * + * @param ds + * the DataSource to use for the query + * @param sql + * SQL string to use for the query + */ + protected UploadStatusQuery(DataSource ds, String sql) { + super(ds, sql); + } + + /** + * Create a new instance of UploadStatusQuery that returns all + * UploadStatus. + * + * @param ds + * the DataSource to use for the query + */ + protected UploadStatusQuery(DataSource ds, String schemaName, + DataSourceLookup dataSourceLookup) { + + super(ds, "SELECT upload_id, " + " upload_label, " + " user_id, " + + " source_cd, " + " no_of_record, " + " deleted_record, " + + " loaded_record, " + " load_date, " + " end_date, " + + " load_status, " + " input_file_name, " + + " log_file_name, " + " transform_name ," + "message " + + " FROM " + schemaName + + "upload_status WHERE upload_id = ? "); + declareParameter(new SqlParameter(Types.INTEGER)); + compile(); + } + + @Override + protected Object mapRow(ResultSet rs, int rownum) throws SQLException { + UploadStatus uploadStatus = new UploadStatus(); + uploadStatus.setUploadId(rs.getInt("upload_id")); + uploadStatus.setUploadLabel(rs.getString("upload_label")); + uploadStatus.setUserId(rs.getString("user_id")); + uploadStatus.setSourceCd(rs.getString("source_cd")); + uploadStatus.setNoOfRecord(rs.getInt("no_of_record")); + uploadStatus.setDeletedRecord(rs.getInt("deleted_record")); + uploadStatus.setLoadedRecord(rs.getInt("loaded_record")); + uploadStatus.setLoadDate(rs.getTimestamp("load_date")); + uploadStatus.setEndDate(rs.getTimestamp("end_date")); + uploadStatus.setLoadStatus(rs.getString("load_status")); + uploadStatus.setInputFileName(rs.getString("input_file_name")); + uploadStatus.setLogFileName(rs.getString("log_file_name")); + uploadStatus.setTransformName(rs.getString("transform_name")); + uploadStatus.setMessage(rs.getString("message")); + return uploadStatus; + } + } + + /** + * Visit Insert Object. + */ + protected class UploadStatusInsert extends SqlUpdate { + /** + * Create a new instance of OwnerInsert. + * + * @param ds + * the DataSource to use for the insert + */ + protected UploadStatusInsert(DataSource ds, String schemaName, + DataSourceLookup dataSourceLookup) { + + String sql = null; + if (dataSourceLookup.getServerType().equalsIgnoreCase( + LoaderDAOFactoryHelper.SQLSERVER) || (dataSourceLookup.getServerType().equalsIgnoreCase( + LoaderDAOFactoryHelper.POSTGRESQL))) { + sql = "INSERT INTO " + schemaName + "upload_status (" + + + " upload_label, " + " user_id, " + " source_cd, " + + " no_of_record, " + " deleted_record, " + + " loaded_record, " + " load_date, " + " end_date, " + + " load_status, " + " input_file_name, " + + " log_file_name, " + " message, " + + " transform_name) " + + " VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)"; + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + LoaderDAOFactoryHelper.ORACLE)) { + sql = "INSERT INTO " + schemaName + "upload_status (" + + " upload_id," + " upload_label, " + " user_id, " + + " source_cd, " + " no_of_record, " + + " deleted_record, " + " loaded_record, " + + " load_date, " + " end_date, " + " load_status, " + + " input_file_name, " + " log_file_name, " + + " message, " + " transform_name) " + + " VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; + } + this.setSql(sql); + this.setDataSource(dataSource); + + if (dataSourceLookup.getServerType().equalsIgnoreCase( + LoaderDAOFactoryHelper.ORACLE) || dataSourceLookup.getServerType().equalsIgnoreCase( + LoaderDAOFactoryHelper.POSTGRESQL)) { + declareParameter(new SqlParameter(Types.INTEGER)); + } + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.INTEGER)); + declareParameter(new SqlParameter(Types.INTEGER)); + declareParameter(new SqlParameter(Types.INTEGER)); + declareParameter(new SqlParameter(Types.TIMESTAMP)); + declareParameter(new SqlParameter(Types.TIMESTAMP)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + compile(); + } + + protected void insert(UploadStatus uploadStatus) { + int uploadId = 0; + Object[] objs = null; + if (dataSourceLookup.getServerType().equalsIgnoreCase( + LoaderDAOFactoryHelper.ORACLE) || dataSourceLookup.getServerType().equalsIgnoreCase( + LoaderDAOFactoryHelper.POSTGRESQL)) { + uploadId = getJdbcTemplate().queryForObject( + "select sq_uploadstatus_uploadid.nextval from dual",Integer.class); + uploadStatus.setUploadId(uploadId); + objs = new Object[] { uploadStatus.getUploadId(), + uploadStatus.getUploadLabel(), + uploadStatus.getUserId(), uploadStatus.getSourceCd(), + uploadStatus.getNoOfRecord(), + uploadStatus.getDeletedRecord(), + uploadStatus.getLoadedRecord(), + uploadStatus.getLoadDate(), uploadStatus.getEndDate(), + uploadStatus.getLoadStatus(), + uploadStatus.getInputFileName(), + uploadStatus.getLogFileName(), + uploadStatus.getMessage(), + uploadStatus.getTransformName() }; + update(objs); + + } else if (dataSourceLookup.getServerType().equalsIgnoreCase( + LoaderDAOFactoryHelper.SQLSERVER)) { + objs = new Object[] { uploadStatus.getUploadLabel(), + uploadStatus.getUserId(), uploadStatus.getSourceCd(), + uploadStatus.getNoOfRecord(), + uploadStatus.getDeletedRecord(), + uploadStatus.getLoadedRecord(), + uploadStatus.getLoadDate(), uploadStatus.getEndDate(), + uploadStatus.getLoadStatus(), + uploadStatus.getInputFileName(), + uploadStatus.getLogFileName(), + uploadStatus.getMessage(), + uploadStatus.getTransformName() }; + update(objs); + uploadId = getJdbcTemplate().queryForObject("SELECT @@IDENTITY", Integer.class); + } + + uploadStatus.setUploadId(uploadId); + } + + protected int generateUploadStatusId() { + return getJdbcTemplate().queryForObject( + "select sq_uploadstatus_uploadid.nextval from dual", Integer.class); + } + + } + + /** + * UploadStatus Update Object. + */ + protected class UploadStatusUpdate extends BatchSqlUpdate { + + /** + * Create a new instance of UploadStatusUpdate. + * + * @param ds + * the DataSource to use for the update + */ + protected UploadStatusUpdate(DataSource ds, String schemaName) { + super(ds, "UPDATE " + schemaName + "upload_status SET " + + "upload_label=?, " + "user_id=?, " + "source_cd=?, " + + "no_of_record=?, " + "deleted_record=?, " + + "loaded_record=?, " + "load_date=?, " + "end_date=?," + + "load_status=?, " + "input_file_name=?, " + + "log_file_name=?, " + "transform_name=?, " + "message=? " + + "WHERE upload_id=?"); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.INTEGER)); + declareParameter(new SqlParameter(Types.INTEGER)); + declareParameter(new SqlParameter(Types.INTEGER)); + declareParameter(new SqlParameter(Types.TIMESTAMP)); + declareParameter(new SqlParameter(Types.TIMESTAMP)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.LONGVARCHAR)); + declareParameter(new SqlParameter(Types.INTEGER)); + compile(); + } + + /** + * Method to update UploadStatus's data. + * + * @param UploadStatus + * to update + * @return the number of rows affected by the update + */ + protected int update(UploadStatus uploadStatus) { + return this.update(new Object[] { uploadStatus.getUploadLabel(), + uploadStatus.getUserId(), uploadStatus.getSourceCd(), + uploadStatus.getNoOfRecord(), + uploadStatus.getDeletedRecord(), + uploadStatus.getLoadedRecord(), uploadStatus.getLoadDate(), + uploadStatus.getEndDate(), uploadStatus.getLoadStatus(), + uploadStatus.getInputFileName(), + uploadStatus.getLogFileName(), + uploadStatus.getTransformName(), uploadStatus.getMessage(), + uploadStatus.getUploadId() + + }); + + } + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/UploadStatusDAOI.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/UploadStatusDAOI.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/UploadStatusDAOI.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/UploadStatusDAOI.java index 33bca17d..cab17e07 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/UploadStatusDAOI.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/UploadStatusDAOI.java @@ -1,41 +1,41 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.dao; - -import java.util.List; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.crc.loader.datavo.loader.UploadSetStatus; -import edu.harvard.i2b2.crc.loader.datavo.loader.UploadStatus; - -public interface UploadStatusDAOI { - public int insertUploadStatus(UploadStatus uploadStatus); - - public void updateUploadStatus(UploadStatus uploadStatus); - - public List getAllUploadStatus(); - - public void dropTempTable(String tempTable); - - public void calculateUploadStatus(int uploadId) throws I2B2Exception; - - public void deleteUploadData(int uploadId) throws I2B2Exception; - - public void insertUploadSetStatus(UploadSetStatus uploadSetStatus); - - public UploadStatus findById(int uploadStatusId) throws UniqueKeyException; - - public List getUploadSetStatusByLoadId(int uploadId); - - public List getUpoadStatusByUser(String userId); - - public void updateUploadSetStatus(UploadSetStatus uploadSetStatus); - - public UploadSetStatus getUploadSetStatus(int uploadId, int setId); -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.dao; + +import java.util.List; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.crc.loader.datavo.loader.UploadSetStatus; +import edu.harvard.i2b2.crc.loader.datavo.loader.UploadStatus; + +public interface UploadStatusDAOI { + public int insertUploadStatus(UploadStatus uploadStatus); + + public void updateUploadStatus(UploadStatus uploadStatus); + + public List getAllUploadStatus(); + + public void dropTempTable(String tempTable); + + public void calculateUploadStatus(int uploadId) throws I2B2Exception; + + public void deleteUploadData(int uploadId) throws I2B2Exception; + + public void insertUploadSetStatus(UploadSetStatus uploadSetStatus); + + public UploadStatus findById(int uploadStatusId) throws UniqueKeyException; + + public List getUploadSetStatusByLoadId(int uploadId); + + public List getUpoadStatusByUser(String userId); + + public void updateUploadSetStatus(UploadSetStatus uploadSetStatus); + + public UploadSetStatus getUploadSetStatus(int uploadId, int setId); +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/VisitDAO.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/VisitDAO.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/VisitDAO.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/VisitDAO.java index 7a48ee9e..b7037c55 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/dao/VisitDAO.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/dao/VisitDAO.java @@ -1,242 +1,242 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.dao; - -import java.sql.CallableStatement; -import java.sql.Connection; -import java.sql.SQLException; -import java.sql.Types; -import java.util.HashMap; -import java.util.Map; - -import javax.sql.DataSource; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.SqlParameter; -import org.springframework.jdbc.object.BatchSqlUpdate; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.crc.loader.datavo.loader.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.pdo.EventType; -import edu.harvard.i2b2.crc.datavo.pdo.ParamType; - -/** - * Encounter mapping and Visit data access object. - * - * @author rk903 - */ -public class VisitDAO extends CRCLoaderDAO implements IVisitDAO { - - private int DB_BATCH_INSERT_SIZE = 2000; - - private static Log log = LogFactory.getLog(VisitDAO.class); - private DataSourceLookup dataSourceLookup = null; - - public VisitDAO(DataSourceLookup dataSourceLookup, DataSource ds) { - setDataSource(ds); - setDbSchemaName(dataSourceLookup.getFullSchema()); - this.dataSourceLookup = dataSourceLookup; - } - - @Override - public int getRecordCountByUploadId(int uploadId) { - JdbcTemplate jdbcTemplate = new JdbcTemplate(this.getDataSource()); - int insertCount = jdbcTemplate.queryForObject( - "select count(1) from " + this.getDbSchemaName() - + "visit_dimension where upload_id =?",Integer.class, - new Object[] { uploadId }); - return insertCount; - } - - /** - * Create batch insert handle for temp observation fact table. - * - * @param tempTableName - * @return - */ - @Override - public TempVisitDimensionInsertHandler createTempVisitDimensionInsert( - String tempTableName) { - TempEncounterVisitInsert tempEncounterVisitInsert = new TempEncounterVisitInsert( - getDataSource(), tempTableName, this.getDbSchemaName()); - tempEncounterVisitInsert.setBatchSize(DB_BATCH_INSERT_SIZE); - return new TempVisitDimensionInsertHandler(tempEncounterVisitInsert); - } - - /** - * Function to create temp visit dimension table using stored proc. - * - * @param tempTableName - * @throws Exception - */ - @Override - public void createTempTable(String tempTableName) throws I2B2Exception { - Connection conn = null; - try { - conn = this.getDataSource().getConnection(); - CallableStatement callStmt = conn.prepareCall("{call " - + this.getDbSchemaName() + "CREATE_TEMP_VISIT_TABLE(?,?)}"); - callStmt.setString(1, tempTableName); - callStmt.registerOutParameter(2, java.sql.Types.VARCHAR); - callStmt.execute(); - this.getSQLServerProcedureError(dataSourceLookup.getServerType(), - callStmt, 2); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - throw new I2B2Exception( - "SQLException occured" + sqlEx.getMessage(), sqlEx); - } catch (Exception ex) { - ex.printStackTrace(); - throw new I2B2Exception("Exception occured" + ex.getMessage(), ex); - } finally { - if (conn != null) { - try { - conn.close(); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - log.error("Error while closing connection", sqlEx); - } - } - } - } - - /** - * Function to create new encounter/visit from temp_visit_dimension table - * using stored proc. - * - * @param tempTableName - * @throws Exception - */ - @Override - public void createVisitFromTempTable(String tempTableName, int uploadId) - throws I2B2Exception { - Connection conn = null; - try { - conn = this.getDataSource().getConnection(); - CallableStatement callStmt = conn.prepareCall("{call " - + this.getDbSchemaName() - + "INSERT_ENCOUNTERVISIT_FROMTEMP(?,?,?)}"); - callStmt.setString(1, tempTableName); - callStmt.setInt(2, uploadId); - callStmt.registerOutParameter(3, java.sql.Types.VARCHAR); - callStmt.execute(); - this.getSQLServerProcedureError(dataSourceLookup.getServerType(), - callStmt, 3); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - throw new I2B2Exception( - "SQLException occured" + sqlEx.getMessage(), sqlEx); - } catch (Exception ex) { - ex.printStackTrace(); - throw new I2B2Exception("Exception occured" + ex.getMessage(), ex); - } finally { - if (conn != null) { - try { - conn.close(); - } catch (SQLException sqlEx) { - sqlEx.printStackTrace(); - log.error("Error while closing connection", sqlEx); - } - } - } - } - - // ************* Operation Objects section *************** - - /** - * TempEncounterVisitInsert Insert Object. - */ - protected class TempEncounterVisitInsert extends BatchSqlUpdate { - /** - * Create a new instance of TempEncounterVisitInsert. - * - * @param ds - * the DataSource to use for the insert - */ - protected TempEncounterVisitInsert(DataSource ds, String tempTableName, - String schemaName) { - super(ds, "INSERT INTO " + schemaName + tempTableName + " (" - + "encounter_id," + "encounter_id_source," + "patient_id," - + "patient_id_source," + "inout_cd," + "location_cd," - + "location_path," + "start_date," + "end_date," - + "visit_blob," + "update_date," + "download_date," - + "import_date," + "sourcesystem_cd)" - + " VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.VARCHAR)); - declareParameter(new SqlParameter(Types.TIMESTAMP)); - declareParameter(new SqlParameter(Types.TIMESTAMP)); - declareParameter(new SqlParameter(Types.LONGVARCHAR)); - declareParameter(new SqlParameter(Types.TIMESTAMP)); - declareParameter(new SqlParameter(Types.TIMESTAMP)); - declareParameter(new SqlParameter(Types.TIMESTAMP)); - declareParameter(new SqlParameter(Types.VARCHAR)); - compile(); - } - - protected void insert(EventType event) { - Map paramMap = null; - if (event.getParam() != null) { - paramMap = buildNVParam(event.getParam()); - } else { - paramMap = new HashMap(); - } - Object[] objs = new Object[] { - // encounterVisitMap.get("encounter_ide"), - event.getEventId().getValue(), - // encounterVisitMap.get("encounter_ide_source"), - event.getEventId().getSource(), - // encounterVisitMap.get("patient_ide"), - (event.getPatientId() != null) ? event.getPatientId() - .getValue() : null, - // encounterVisitMap.get("patient_ide_source"), - (event.getPatientId() != null) ? event.getPatientId() - .getSource() : null, - // encounterVisitMap.get("inout_cd"), - (paramMap.get("inout_cd") != null) ? paramMap.get( - "inout_cd").getValue() : null, - // encounterVisitMap.get("location_cd"), - (paramMap.get("location_cd") != null) ? paramMap.get( - "location_cd").getValue() : null, - // encounterVisitMap.get("location_path"), - (paramMap.get("location_path") != null) ? paramMap.get( - "location_path").getValue() : null, - // encounterVisitMap.get("start_date"), - (event.getStartDate() != null) ? event.getStartDate() - .toGregorianCalendar().getTime() : null, - // encounterVisitMap.get("end_date"), - (event.getEndDate() != null) ? event.getEndDate() - .toGregorianCalendar().getTime() : null, - // encounterVisitMap.get("visit_blob"), - (event.getEventBlob() != null) ? event.getEventBlob() - .getContent().get(0).toString() : null, - // encounterVisitMap.get("update_date"), - (event.getUpdateDate() != null) ? event.getUpdateDate() - .toGregorianCalendar().getTime() : null, - // encounterVisitMap.get("download_date"), - (event.getDownloadDate() != null) ? event.getDownloadDate() - .toGregorianCalendar().getTime() : null, - // encounterVisitMap.get("import_date"), - (event.getImportDate() != null) ? event.getImportDate() - .toGregorianCalendar().getTime() : null, - // encounterVisitMap.get("source_system_cd") - event.getSourcesystemCd() }; - super.update(objs); - - } - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.dao; + +import java.sql.CallableStatement; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.Types; +import java.util.HashMap; +import java.util.Map; + +import javax.sql.DataSource; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.SqlParameter; +import org.springframework.jdbc.object.BatchSqlUpdate; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.crc.loader.datavo.loader.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.pdo.EventType; +import edu.harvard.i2b2.crc.datavo.pdo.ParamType; + +/** + * Encounter mapping and Visit data access object. + * + * @author rk903 + */ +public class VisitDAO extends CRCLoaderDAO implements IVisitDAO { + + private int DB_BATCH_INSERT_SIZE = 2000; + + private static Log log = LogFactory.getLog(VisitDAO.class); + private DataSourceLookup dataSourceLookup = null; + + public VisitDAO(DataSourceLookup dataSourceLookup, DataSource ds) { + setDataSource(ds); + setDbSchemaName(dataSourceLookup.getFullSchema()); + this.dataSourceLookup = dataSourceLookup; + } + + @Override + public int getRecordCountByUploadId(int uploadId) { + JdbcTemplate jdbcTemplate = new JdbcTemplate(this.getDataSource()); + int insertCount = jdbcTemplate.queryForObject( + "select count(1) from " + this.getDbSchemaName() + + "visit_dimension where upload_id =?",Integer.class, + new Object[] { uploadId }); + return insertCount; + } + + /** + * Create batch insert handle for temp observation fact table. + * + * @param tempTableName + * @return + */ + @Override + public TempVisitDimensionInsertHandler createTempVisitDimensionInsert( + String tempTableName) { + TempEncounterVisitInsert tempEncounterVisitInsert = new TempEncounterVisitInsert( + getDataSource(), tempTableName, this.getDbSchemaName()); + tempEncounterVisitInsert.setBatchSize(DB_BATCH_INSERT_SIZE); + return new TempVisitDimensionInsertHandler(tempEncounterVisitInsert); + } + + /** + * Function to create temp visit dimension table using stored proc. + * + * @param tempTableName + * @throws Exception + */ + @Override + public void createTempTable(String tempTableName) throws I2B2Exception { + Connection conn = null; + try { + conn = this.getDataSource().getConnection(); + CallableStatement callStmt = conn.prepareCall("{call " + + this.getDbSchemaName() + "CREATE_TEMP_VISIT_TABLE(?,?)}"); + callStmt.setString(1, tempTableName); + callStmt.registerOutParameter(2, java.sql.Types.VARCHAR); + callStmt.execute(); + this.getSQLServerProcedureError(dataSourceLookup.getServerType(), + callStmt, 2); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + throw new I2B2Exception( + "SQLException occured" + sqlEx.getMessage(), sqlEx); + } catch (Exception ex) { + ex.printStackTrace(); + throw new I2B2Exception("Exception occured" + ex.getMessage(), ex); + } finally { + if (conn != null) { + try { + conn.close(); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + log.error("Error while closing connection", sqlEx); + } + } + } + } + + /** + * Function to create new encounter/visit from temp_visit_dimension table + * using stored proc. + * + * @param tempTableName + * @throws Exception + */ + @Override + public void createVisitFromTempTable(String tempTableName, int uploadId) + throws I2B2Exception { + Connection conn = null; + try { + conn = this.getDataSource().getConnection(); + CallableStatement callStmt = conn.prepareCall("{call " + + this.getDbSchemaName() + + "INSERT_ENCOUNTERVISIT_FROMTEMP(?,?,?)}"); + callStmt.setString(1, tempTableName); + callStmt.setInt(2, uploadId); + callStmt.registerOutParameter(3, java.sql.Types.VARCHAR); + callStmt.execute(); + this.getSQLServerProcedureError(dataSourceLookup.getServerType(), + callStmt, 3); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + throw new I2B2Exception( + "SQLException occured" + sqlEx.getMessage(), sqlEx); + } catch (Exception ex) { + ex.printStackTrace(); + throw new I2B2Exception("Exception occured" + ex.getMessage(), ex); + } finally { + if (conn != null) { + try { + conn.close(); + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + log.error("Error while closing connection", sqlEx); + } + } + } + } + + // ************* Operation Objects section *************** + + /** + * TempEncounterVisitInsert Insert Object. + */ + protected class TempEncounterVisitInsert extends BatchSqlUpdate { + /** + * Create a new instance of TempEncounterVisitInsert. + * + * @param ds + * the DataSource to use for the insert + */ + protected TempEncounterVisitInsert(DataSource ds, String tempTableName, + String schemaName) { + super(ds, "INSERT INTO " + schemaName + tempTableName + " (" + + "encounter_id," + "encounter_id_source," + "patient_id," + + "patient_id_source," + "inout_cd," + "location_cd," + + "location_path," + "start_date," + "end_date," + + "visit_blob," + "update_date," + "download_date," + + "import_date," + "sourcesystem_cd)" + + " VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.VARCHAR)); + declareParameter(new SqlParameter(Types.TIMESTAMP)); + declareParameter(new SqlParameter(Types.TIMESTAMP)); + declareParameter(new SqlParameter(Types.LONGVARCHAR)); + declareParameter(new SqlParameter(Types.TIMESTAMP)); + declareParameter(new SqlParameter(Types.TIMESTAMP)); + declareParameter(new SqlParameter(Types.TIMESTAMP)); + declareParameter(new SqlParameter(Types.VARCHAR)); + compile(); + } + + protected void insert(EventType event) { + Map paramMap = null; + if (event.getParam() != null) { + paramMap = buildNVParam(event.getParam()); + } else { + paramMap = new HashMap(); + } + Object[] objs = new Object[] { + // encounterVisitMap.get("encounter_ide"), + event.getEventId().getValue(), + // encounterVisitMap.get("encounter_ide_source"), + event.getEventId().getSource(), + // encounterVisitMap.get("patient_ide"), + (event.getPatientId() != null) ? event.getPatientId() + .getValue() : null, + // encounterVisitMap.get("patient_ide_source"), + (event.getPatientId() != null) ? event.getPatientId() + .getSource() : null, + // encounterVisitMap.get("inout_cd"), + (paramMap.get("inout_cd") != null) ? paramMap.get( + "inout_cd").getValue() : null, + // encounterVisitMap.get("location_cd"), + (paramMap.get("location_cd") != null) ? paramMap.get( + "location_cd").getValue() : null, + // encounterVisitMap.get("location_path"), + (paramMap.get("location_path") != null) ? paramMap.get( + "location_path").getValue() : null, + // encounterVisitMap.get("start_date"), + (event.getStartDate() != null) ? event.getStartDate() + .toGregorianCalendar().getTime() : null, + // encounterVisitMap.get("end_date"), + (event.getEndDate() != null) ? event.getEndDate() + .toGregorianCalendar().getTime() : null, + // encounterVisitMap.get("visit_blob"), + (event.getEventBlob() != null) ? event.getEventBlob() + .getContent().get(0).toString() : null, + // encounterVisitMap.get("update_date"), + (event.getUpdateDate() != null) ? event.getUpdateDate() + .toGregorianCalendar().getTime() : null, + // encounterVisitMap.get("download_date"), + (event.getDownloadDate() != null) ? event.getDownloadDate() + .toGregorianCalendar().getTime() : null, + // encounterVisitMap.get("import_date"), + (event.getImportDate() != null) ? event.getImportDate() + .toGregorianCalendar().getTime() : null, + // encounterVisitMap.get("source_system_cd") + event.getSourcesystemCd() }; + super.update(objs); + + } + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/datavo/CRCLoaderJAXBUtil.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/datavo/CRCLoaderJAXBUtil.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/datavo/CRCLoaderJAXBUtil.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/datavo/CRCLoaderJAXBUtil.java index 7ad1a87d..46c9c7ca --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/datavo/CRCLoaderJAXBUtil.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/datavo/CRCLoaderJAXBUtil.java @@ -1,44 +1,44 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.loader.datavo; - -import java.util.List; - - -import edu.harvard.i2b2.crc.loader.util.CRCLoaderUtil; - -/** - * Factory class to create jaxb context Since jaxb context is tread safe, only - * one instance is created for this cell. The package used for jaxb context is - * read from spring config file $Id: CRCLoaderJAXBUtil.java,v 1.1 2008/01/21 - * 16:09:02 rk903 Exp $ - * - * @author rkuttan - */ -public class CRCLoaderJAXBUtil { - private static edu.harvard.i2b2.common.util.jaxb.JAXBUtil jaxbUtil = null; - - private CRCLoaderJAXBUtil() { - } - - @SuppressWarnings("unchecked") - public static edu.harvard.i2b2.common.util.jaxb.JAXBUtil getJAXBUtil() { - if (jaxbUtil == null) { - jaxbUtil = new edu.harvard.i2b2.common.util.jaxb.JAXBUtil(edu.harvard.i2b2.crc.util.JAXBConstant.DEFAULT_PACKAGE_NAME); - } - return jaxbUtil; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.loader.datavo; + +import java.util.List; + + +import edu.harvard.i2b2.crc.loader.util.CRCLoaderUtil; + +/** + * Factory class to create jaxb context Since jaxb context is tread safe, only + * one instance is created for this cell. The package used for jaxb context is + * read from spring config file $Id: CRCLoaderJAXBUtil.java,v 1.1 2008/01/21 + * 16:09:02 rk903 Exp $ + * + * @author rkuttan + */ +public class CRCLoaderJAXBUtil { + private static edu.harvard.i2b2.common.util.jaxb.JAXBUtil jaxbUtil = null; + + private CRCLoaderJAXBUtil() { + } + + @SuppressWarnings("unchecked") + public static edu.harvard.i2b2.common.util.jaxb.JAXBUtil getJAXBUtil() { + if (jaxbUtil == null) { + jaxbUtil = new edu.harvard.i2b2.common.util.jaxb.JAXBUtil(edu.harvard.i2b2.crc.util.JAXBConstant.DEFAULT_PACKAGE_NAME); + } + return jaxbUtil; + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/datavo/I2B2MessageResponseFactory.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/datavo/I2B2MessageResponseFactory.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/datavo/I2B2MessageResponseFactory.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/datavo/I2B2MessageResponseFactory.java index 34e4d0cd..f5bae4d6 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/datavo/I2B2MessageResponseFactory.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/datavo/I2B2MessageResponseFactory.java @@ -1,180 +1,180 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.loader.datavo; - -import java.io.StringWriter; -import java.math.BigDecimal; - -import jakarta.xml.bind.JAXBElement; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.datavo.i2b2message.ApplicationType; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2message.FacilityType; -import edu.harvard.i2b2.crc.datavo.i2b2message.InfoType; -import edu.harvard.i2b2.crc.datavo.i2b2message.MessageControlIdType; -import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.PollingUrlType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResultStatusType; -import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; - - -public class I2B2MessageResponseFactory { - - /** log * */ - protected final static Log log = LogFactory - .getLog(I2B2MessageResponseFactory.class); - - /** - * Function to build response message type using given bodytype and request - * xml - * - * @param requestXml - * @param bodyType - * @return i2b2 response message xml - * @throws JAXBUtilException - */ - public static String buildResponseMessage(String requestXml, - StatusType statusType, BodyType bodyType, boolean splCharFilterFlag) - throws JAXBUtilException { - JAXBUtil util = CRCLoaderJAXBUtil.getJAXBUtil(); - - MessageHeaderType messageHeader = new MessageHeaderType(); - ApplicationType appType = new ApplicationType(); - appType.setApplicationName("edu.harvard.i2b2.crc.loader"); - appType.setApplicationVersion("1.0"); - - - if (requestXml != null) { - RequestMessageType requestMsgType = getI2B2RequestMessageType(requestXml); - MessageHeaderType clientMessageHeader = requestMsgType.getMessageHeader(); - // reverse sending and receiving app - if (clientMessageHeader != null) { - ApplicationType sendingApp = clientMessageHeader - .getSendingApplication(); - messageHeader.setSendingApplication(appType); - messageHeader.setReceivingApplication(sendingApp); - messageHeader.setProjectId(clientMessageHeader.getProjectId()); - } - } else { - messageHeader = new MessageHeaderType(); - messageHeader.setSendingApplication(appType); - } - - messageHeader.setI2B2VersionCompatible(new BigDecimal("1.1")); - messageHeader.setHl7VersionCompatible(new BigDecimal("2.4")); - - MessageControlIdType messageControlIdType = new MessageControlIdType(); - messageControlIdType.setInstanceNum(1); - messageHeader.setMessageControlId(messageControlIdType); - - FacilityType facility = new FacilityType(); - facility.setFacilityName("i2b2 Hive"); - messageHeader.setSendingFacility(facility); - messageHeader.setReceivingFacility(facility); - - // :TODO statusType.setValue(sessionId); - PollingUrlType pollingType = new PollingUrlType(); - pollingType.setIntervalMs(100); - - // :TODO value come from property file - // pollingType.setValue("http://localhost:8080/QueryProcessor/getResult"); - ResultStatusType resultStatusType = new ResultStatusType(); - resultStatusType.setStatus(statusType); - resultStatusType.setPollingUrl(pollingType); - - InfoType infoType = new InfoType(); - // :TODO value come from property file - // infoType.setUrl("http://localhost:8080/QueryProcessor/getStatus"); - infoType.setValue("Log information"); - - ResponseHeaderType responseHeader = new ResponseHeaderType(); - responseHeader.setResultStatus(resultStatusType); - responseHeader.setInfo(infoType); - - ResponseMessageType responseMessageType = new ResponseMessageType(); - responseMessageType.setMessageHeader(messageHeader); - responseMessageType.setResponseHeader(responseHeader); - responseMessageType.setMessageBody(bodyType); - - edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory(); - StringWriter strWriter = new StringWriter(); - util.marshaller(of.createResponse(responseMessageType), strWriter, - splCharFilterFlag); - return strWriter.toString(); - } - - /** - * Function to build response message type using given bodytype and request - * xml - * - * @param requestXml - * @param bodyType - * @return i2b2 response message xml - * @throws JAXBUtilException - */ - public static String buildResponseMessage(String requestXml, - StatusType statusType, BodyType bodyType) throws JAXBUtilException { - return buildResponseMessage(requestXml, statusType, bodyType, false); - } - - /** - * Function to unmarshall i2b2 request message type - * - * @param requestXml - * @return RequestMessageType - * @throws JAXBUtilException - */ - private static RequestMessageType getI2B2RequestMessageType( - String requestXml) throws JAXBUtilException { - JAXBUtil jaxbUtil = CRCLoaderJAXBUtil.getJAXBUtil(); - JAXBElement jaxbElement = jaxbUtil.unMashallFromString(requestXml); - RequestMessageType requestMessageType = (RequestMessageType) jaxbElement - .getValue(); - - return requestMessageType; - } - - /** - * Function marshall i2b2 response message type - * - * @param responseMessageType - * @return - */ - public static String getResponseString( - ResponseMessageType responseMessageType) { - StringWriter strWriter = new StringWriter(); - - try { - edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory(); - JAXBUtil jaxbUtil = CRCLoaderJAXBUtil.getJAXBUtil(); - jaxbUtil.marshaller(of.createResponse(responseMessageType), - strWriter); - } catch (JAXBUtilException e) { - log.error("Error while generating response message" - + e.getMessage()); - } - - return strWriter.toString(); - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.loader.datavo; + +import java.io.StringWriter; +import java.math.BigDecimal; + +import jakarta.xml.bind.JAXBElement; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.datavo.i2b2message.ApplicationType; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2message.FacilityType; +import edu.harvard.i2b2.crc.datavo.i2b2message.InfoType; +import edu.harvard.i2b2.crc.datavo.i2b2message.MessageControlIdType; +import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.PollingUrlType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResultStatusType; +import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; + + +public class I2B2MessageResponseFactory { + + /** log * */ + protected final static Log log = LogFactory + .getLog(I2B2MessageResponseFactory.class); + + /** + * Function to build response message type using given bodytype and request + * xml + * + * @param requestXml + * @param bodyType + * @return i2b2 response message xml + * @throws JAXBUtilException + */ + public static String buildResponseMessage(String requestXml, + StatusType statusType, BodyType bodyType, boolean splCharFilterFlag) + throws JAXBUtilException { + JAXBUtil util = CRCLoaderJAXBUtil.getJAXBUtil(); + + MessageHeaderType messageHeader = new MessageHeaderType(); + ApplicationType appType = new ApplicationType(); + appType.setApplicationName("edu.harvard.i2b2.crc.loader"); + appType.setApplicationVersion("1.0"); + + + if (requestXml != null) { + RequestMessageType requestMsgType = getI2B2RequestMessageType(requestXml); + MessageHeaderType clientMessageHeader = requestMsgType.getMessageHeader(); + // reverse sending and receiving app + if (clientMessageHeader != null) { + ApplicationType sendingApp = clientMessageHeader + .getSendingApplication(); + messageHeader.setSendingApplication(appType); + messageHeader.setReceivingApplication(sendingApp); + messageHeader.setProjectId(clientMessageHeader.getProjectId()); + } + } else { + messageHeader = new MessageHeaderType(); + messageHeader.setSendingApplication(appType); + } + + messageHeader.setI2B2VersionCompatible(new BigDecimal("1.1")); + messageHeader.setHl7VersionCompatible(new BigDecimal("2.4")); + + MessageControlIdType messageControlIdType = new MessageControlIdType(); + messageControlIdType.setInstanceNum(1); + messageHeader.setMessageControlId(messageControlIdType); + + FacilityType facility = new FacilityType(); + facility.setFacilityName("i2b2 Hive"); + messageHeader.setSendingFacility(facility); + messageHeader.setReceivingFacility(facility); + + // :TODO statusType.setValue(sessionId); + PollingUrlType pollingType = new PollingUrlType(); + pollingType.setIntervalMs(100); + + // :TODO value come from property file + // pollingType.setValue("http://localhost:8080/QueryProcessor/getResult"); + ResultStatusType resultStatusType = new ResultStatusType(); + resultStatusType.setStatus(statusType); + resultStatusType.setPollingUrl(pollingType); + + InfoType infoType = new InfoType(); + // :TODO value come from property file + // infoType.setUrl("http://localhost:8080/QueryProcessor/getStatus"); + infoType.setValue("Log information"); + + ResponseHeaderType responseHeader = new ResponseHeaderType(); + responseHeader.setResultStatus(resultStatusType); + responseHeader.setInfo(infoType); + + ResponseMessageType responseMessageType = new ResponseMessageType(); + responseMessageType.setMessageHeader(messageHeader); + responseMessageType.setResponseHeader(responseHeader); + responseMessageType.setMessageBody(bodyType); + + edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory(); + StringWriter strWriter = new StringWriter(); + util.marshaller(of.createResponse(responseMessageType), strWriter, + splCharFilterFlag); + return strWriter.toString(); + } + + /** + * Function to build response message type using given bodytype and request + * xml + * + * @param requestXml + * @param bodyType + * @return i2b2 response message xml + * @throws JAXBUtilException + */ + public static String buildResponseMessage(String requestXml, + StatusType statusType, BodyType bodyType) throws JAXBUtilException { + return buildResponseMessage(requestXml, statusType, bodyType, false); + } + + /** + * Function to unmarshall i2b2 request message type + * + * @param requestXml + * @return RequestMessageType + * @throws JAXBUtilException + */ + private static RequestMessageType getI2B2RequestMessageType( + String requestXml) throws JAXBUtilException { + JAXBUtil jaxbUtil = CRCLoaderJAXBUtil.getJAXBUtil(); + JAXBElement jaxbElement = jaxbUtil.unMashallFromString(requestXml); + RequestMessageType requestMessageType = (RequestMessageType) jaxbElement + .getValue(); + + return requestMessageType; + } + + /** + * Function marshall i2b2 response message type + * + * @param responseMessageType + * @return + */ + public static String getResponseString( + ResponseMessageType responseMessageType) { + StringWriter strWriter = new StringWriter(); + + try { + edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory(); + JAXBUtil jaxbUtil = CRCLoaderJAXBUtil.getJAXBUtil(); + jaxbUtil.marshaller(of.createResponse(responseMessageType), + strWriter); + } catch (JAXBUtilException e) { + log.error("Error while generating response message" + + e.getMessage()); + } + + return strWriter.toString(); + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/datavo/loader/Bronchodilator.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/datavo/loader/Bronchodilator.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/datavo/loader/Bronchodilator.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/datavo/loader/Bronchodilator.java index 7ca70d40..d2afe0ff --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/datavo/loader/Bronchodilator.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/datavo/loader/Bronchodilator.java @@ -1,64 +1,64 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.datavo.loader; - -import java.util.Calendar; - -public class Bronchodilator { - private double noObserved; - private double noPredicted; - private double noPercentPred; - private double afterObserved; - private double afterPercentChange; - private double afterPercentPred; - private Calendar bronchodilatorDate; - - public double getAfterObserved() { - return afterObserved; - } - public void setAfterObserved(double afterObserved) { - this.afterObserved = afterObserved; - } - public double getAfterPercentChange() { - return afterPercentChange; - } - public void setAfterPercentChange(double afterPercentChange) { - this.afterPercentChange = afterPercentChange; - } - public double getAfterPercentPred() { - return afterPercentPred; - } - public void setAfterPercentPred(double afterPercentPred) { - this.afterPercentPred = afterPercentPred; - } - public double getNoObserved() { - return noObserved; - } - public void setNoObserved(double noObserved) { - this.noObserved = noObserved; - } - public double getNoPercentPred() { - return noPercentPred; - } - public void setNoPercentPred(double noPercentPred) { - this.noPercentPred = noPercentPred; - } - public double getNoPredicted() { - return noPredicted; - } - public void setNoPredicted(double noPredicted) { - this.noPredicted = noPredicted; - } - public Calendar getBronchodilatorDate() { - return bronchodilatorDate; - } - public void setBronchodilatorDate(Calendar bronchodilatorDate) { - this.bronchodilatorDate = bronchodilatorDate; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.datavo.loader; + +import java.util.Calendar; + +public class Bronchodilator { + private double noObserved; + private double noPredicted; + private double noPercentPred; + private double afterObserved; + private double afterPercentChange; + private double afterPercentPred; + private Calendar bronchodilatorDate; + + public double getAfterObserved() { + return afterObserved; + } + public void setAfterObserved(double afterObserved) { + this.afterObserved = afterObserved; + } + public double getAfterPercentChange() { + return afterPercentChange; + } + public void setAfterPercentChange(double afterPercentChange) { + this.afterPercentChange = afterPercentChange; + } + public double getAfterPercentPred() { + return afterPercentPred; + } + public void setAfterPercentPred(double afterPercentPred) { + this.afterPercentPred = afterPercentPred; + } + public double getNoObserved() { + return noObserved; + } + public void setNoObserved(double noObserved) { + this.noObserved = noObserved; + } + public double getNoPercentPred() { + return noPercentPred; + } + public void setNoPercentPred(double noPercentPred) { + this.noPercentPred = noPercentPred; + } + public double getNoPredicted() { + return noPredicted; + } + public void setNoPredicted(double noPredicted) { + this.noPredicted = noPredicted; + } + public Calendar getBronchodilatorDate() { + return bronchodilatorDate; + } + public void setBronchodilatorDate(Calendar bronchodilatorDate) { + this.bronchodilatorDate = bronchodilatorDate; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/datavo/loader/DataMartReport.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/datavo/loader/DataMartReport.java old mode 100755 new mode 100644 similarity index 95% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/datavo/loader/DataMartReport.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/datavo/loader/DataMartReport.java index f7b4e24f..91db3403 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/datavo/loader/DataMartReport.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/datavo/loader/DataMartReport.java @@ -1,71 +1,71 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.datavo.loader; - -import java.io.Serializable; -import java.util.Date; - - -/** - * User profile data object - * @author rk903 - * - */ -public class DataMartReport implements Serializable { - - - private static final long serialVersionUID = 1L; - - private long totalObservationFact = 0; - private long totalPatient = 0; - private long totalVisit = 0; - private Date reportDate; - - public DataMartReport() { - } - - public static long getSerialVersionUID() { - return serialVersionUID; - } - - public long getTotalObservationFact() { - return totalObservationFact; - } - - public void setTotalObservationFact(long totalObservationFact) { - this.totalObservationFact = totalObservationFact; - } - - public Date getReportDate() { - return reportDate; - } - - public void setReportDate(Date reportDate) { - this.reportDate = reportDate; - } - - public long getTotalPatient() { - return totalPatient; - } - - public void setTotalPatient(long totalPatient) { - this.totalPatient = totalPatient; - } - - public long getTotalVisit() { - return totalVisit; - } - - public void setTotalVisit(long totalVisit) { - this.totalVisit = totalVisit; - } - - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.datavo.loader; + +import java.io.Serializable; +import java.util.Date; + + +/** + * User profile data object + * @author rk903 + * + */ +public class DataMartReport implements Serializable { + + + private static final long serialVersionUID = 1L; + + private long totalObservationFact = 0; + private long totalPatient = 0; + private long totalVisit = 0; + private Date reportDate; + + public DataMartReport() { + } + + public static long getSerialVersionUID() { + return serialVersionUID; + } + + public long getTotalObservationFact() { + return totalObservationFact; + } + + public void setTotalObservationFact(long totalObservationFact) { + this.totalObservationFact = totalObservationFact; + } + + public Date getReportDate() { + return reportDate; + } + + public void setReportDate(Date reportDate) { + this.reportDate = reportDate; + } + + public long getTotalPatient() { + return totalPatient; + } + + public void setTotalPatient(long totalPatient) { + this.totalPatient = totalPatient; + } + + public long getTotalVisit() { + return totalVisit; + } + + public void setTotalVisit(long totalVisit) { + this.totalVisit = totalVisit; + } + + + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/datavo/loader/DataSourceLookup.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/datavo/loader/DataSourceLookup.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/datavo/loader/DataSourceLookup.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/datavo/loader/DataSourceLookup.java index 7a2bdfb8..cf18a661 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/datavo/loader/DataSourceLookup.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/datavo/loader/DataSourceLookup.java @@ -1,102 +1,102 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.datavo.loader; - -import java.util.Date; - -public class DataSourceLookup { - private String domainId; - private String projectPath; - private String ownerId; - private String fullSchema; - private String dataSource; - private String serverType; - private String niceName; - private String toolTip; - private String comment; - private Date entryDate; - private Date changeDate; - private String statusCd; - - - public String getDomainId() { - return domainId; - } - public void setDomainId(String domainId) { - this.domainId = domainId; - } - public String getProjectPath() { - return projectPath; - } - public void setProjectPath(String projectPath) { - this.projectPath = projectPath; - } - public String getOwnerId() { - return ownerId; - } - public void setOwnerId(String ownerId) { - this.ownerId = ownerId; - } - public String getDataSource() { - return dataSource; - } - public void setDataSource(String dataSource) { - this.dataSource = dataSource; - } - public String getFullSchema() { - return fullSchema; - } - public void setFullSchema(String fullSchema) { - this.fullSchema = fullSchema; - } - public String getServerType() { - return serverType; - } - public void setServerType(String serverType) { - this.serverType = serverType; - } - public String getNiceName() { - return niceName; - } - public void setNiceName(String niceName) { - this.niceName = niceName; - } - public String getToolTip() { - return toolTip; - } - public void setToolTip(String toolTip) { - this.toolTip = toolTip; - } - public String getComment() { - return comment; - } - public void setComment(String comment) { - this.comment = comment; - } - public Date getEntryDate() { - return entryDate; - } - public void setEntryDate(Date entryDate) { - this.entryDate = entryDate; - } - public Date getChangeDate() { - return changeDate; - } - public void setChangeDate(Date changeDate) { - this.changeDate = changeDate; - } - public String getStatusCd() { - return statusCd; - } - public void setStatusCd(String statusCd) { - this.statusCd = statusCd; - } - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.datavo.loader; + +import java.util.Date; + +public class DataSourceLookup { + private String domainId; + private String projectPath; + private String ownerId; + private String fullSchema; + private String dataSource; + private String serverType; + private String niceName; + private String toolTip; + private String comment; + private Date entryDate; + private Date changeDate; + private String statusCd; + + + public String getDomainId() { + return domainId; + } + public void setDomainId(String domainId) { + this.domainId = domainId; + } + public String getProjectPath() { + return projectPath; + } + public void setProjectPath(String projectPath) { + this.projectPath = projectPath; + } + public String getOwnerId() { + return ownerId; + } + public void setOwnerId(String ownerId) { + this.ownerId = ownerId; + } + public String getDataSource() { + return dataSource; + } + public void setDataSource(String dataSource) { + this.dataSource = dataSource; + } + public String getFullSchema() { + return fullSchema; + } + public void setFullSchema(String fullSchema) { + this.fullSchema = fullSchema; + } + public String getServerType() { + return serverType; + } + public void setServerType(String serverType) { + this.serverType = serverType; + } + public String getNiceName() { + return niceName; + } + public void setNiceName(String niceName) { + this.niceName = niceName; + } + public String getToolTip() { + return toolTip; + } + public void setToolTip(String toolTip) { + this.toolTip = toolTip; + } + public String getComment() { + return comment; + } + public void setComment(String comment) { + this.comment = comment; + } + public Date getEntryDate() { + return entryDate; + } + public void setEntryDate(Date entryDate) { + this.entryDate = entryDate; + } + public Date getChangeDate() { + return changeDate; + } + public void setChangeDate(Date changeDate) { + this.changeDate = changeDate; + } + public String getStatusCd() { + return statusCd; + } + public void setStatusCd(String statusCd) { + this.statusCd = statusCd; + } + + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/datavo/loader/EncounterVisit.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/datavo/loader/EncounterVisit.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/datavo/loader/EncounterVisit.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/datavo/loader/EncounterVisit.java index 7c900c4f..04992342 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/datavo/loader/EncounterVisit.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/datavo/loader/EncounterVisit.java @@ -1,107 +1,107 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.datavo.loader; - -import java.util.Date; - -/** - * Object to hold Encounter and Visit values. - * @author rk903 - * - */ -public class EncounterVisit { - - private String encounterIde = null; - private String source = null; - private int encounterNum = 0 ; - private int patientNum = 0; - private String inOutCd = null; - private String locationPath = null; - private String visitBlob = null; - - private Date startDate = null; - private Date endDate = null; - private Date updateDate = null; - private Date downloadDate = null; - private Date importDate = null; - - public Date getDownloadDate() { - return downloadDate; - } - public void setDownloadDate(Date downloadDate) { - this.downloadDate = downloadDate; - } - public String getEncounterIde() { - return encounterIde; - } - public void setEncounterIde(String encounterIde) { - this.encounterIde = encounterIde; - } - public int getEncounterNum() { - return encounterNum; - } - public void setEncounterNum(int encounterNum) { - this.encounterNum = encounterNum; - } - public Date getEndDate() { - return endDate; - } - public void setEndDate(Date endDate) { - this.endDate = endDate; - } - public Date getImportDate() { - return importDate; - } - public void setImportDate(Date importDate) { - this.importDate = importDate; - } - public String getInOutCd() { - return inOutCd; - } - public void setInOutCd(String inOutCd) { - this.inOutCd = inOutCd; - } - public String getLocationPath() { - return locationPath; - } - public void setLocationPath(String locationPath) { - this.locationPath = locationPath; - } - public String getSource() { - return source; - } - public void setSource(String source) { - this.source = source; - } - public Date getStartDate() { - return startDate; - } - public void setStartDate(Date startDate) { - this.startDate = startDate; - } - public Date getUpdateDate() { - return updateDate; - } - public void setUpdateDate(Date updateDate) { - this.updateDate = updateDate; - } - public String getVisitBlob() { - return visitBlob; - } - public void setVisitBlob(String visitBlob) { - this.visitBlob = visitBlob; - } - public int getPatientNum() { - return patientNum; - } - public void setPatientNum(int patientNum) { - this.patientNum = patientNum; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.datavo.loader; + +import java.util.Date; + +/** + * Object to hold Encounter and Visit values. + * @author rk903 + * + */ +public class EncounterVisit { + + private String encounterIde = null; + private String source = null; + private int encounterNum = 0 ; + private int patientNum = 0; + private String inOutCd = null; + private String locationPath = null; + private String visitBlob = null; + + private Date startDate = null; + private Date endDate = null; + private Date updateDate = null; + private Date downloadDate = null; + private Date importDate = null; + + public Date getDownloadDate() { + return downloadDate; + } + public void setDownloadDate(Date downloadDate) { + this.downloadDate = downloadDate; + } + public String getEncounterIde() { + return encounterIde; + } + public void setEncounterIde(String encounterIde) { + this.encounterIde = encounterIde; + } + public int getEncounterNum() { + return encounterNum; + } + public void setEncounterNum(int encounterNum) { + this.encounterNum = encounterNum; + } + public Date getEndDate() { + return endDate; + } + public void setEndDate(Date endDate) { + this.endDate = endDate; + } + public Date getImportDate() { + return importDate; + } + public void setImportDate(Date importDate) { + this.importDate = importDate; + } + public String getInOutCd() { + return inOutCd; + } + public void setInOutCd(String inOutCd) { + this.inOutCd = inOutCd; + } + public String getLocationPath() { + return locationPath; + } + public void setLocationPath(String locationPath) { + this.locationPath = locationPath; + } + public String getSource() { + return source; + } + public void setSource(String source) { + this.source = source; + } + public Date getStartDate() { + return startDate; + } + public void setStartDate(Date startDate) { + this.startDate = startDate; + } + public Date getUpdateDate() { + return updateDate; + } + public void setUpdateDate(Date updateDate) { + this.updateDate = updateDate; + } + public String getVisitBlob() { + return visitBlob; + } + public void setVisitBlob(String visitBlob) { + this.visitBlob = visitBlob; + } + public int getPatientNum() { + return patientNum; + } + public void setPatientNum(int patientNum) { + this.patientNum = patientNum; + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/datavo/loader/ObservationFact.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/datavo/loader/ObservationFact.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/datavo/loader/ObservationFact.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/datavo/loader/ObservationFact.java index 069db377..ff7b8b0d --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/datavo/loader/ObservationFact.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/datavo/loader/ObservationFact.java @@ -1,200 +1,200 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.datavo.loader; - -import java.util.Date; - - -/** - * Object to hold observation fact values. - * @author rk903 - * - */ -public class ObservationFact { - private int encounterNum = 0; - private String conceptCd = null; - private int patientNum = 0; - private String providerId = null; - private Date startDate = null; - private String modifierCd = null; - private String valtypeCd = null; - private String observationBlob = null; - private String tvalChar = null; - private Float nvalNum = null; - private String valueflagCd = null; - private Float quantityNum = null; - private Integer confidenceNum = null; - private String unitsCd = null; - private Date endDate = null; - private String locationCd = null; - private Date updateDate = null; - private Date downloadDate = null; - private Date importDate = null; - private String sourcesystemCd = null; - private String patientIde = null; - private String encounterIde = null; - private int uploadId = 0; - - - - public int getUploadId() { - return uploadId; - } - public void setUploadId(int uploadId) { - this.uploadId = uploadId; - } - public String getEncounterIde() { - return encounterIde; - } - public void setEncounterIde(String encounterIde) { - this.encounterIde = encounterIde; - } - public String getPatientIde() { - return patientIde; - } - public void setPatientIde(String patientIde) { - this.patientIde = patientIde; - } - public String getConceptCd() { - return conceptCd; - } - public void setConceptCd(String conceptCd) { - this.conceptCd = conceptCd; - } - public Integer getConfidenceNum() { - return confidenceNum; - } - public void setConfidenceNum(Integer confidenceNum) { - this.confidenceNum = confidenceNum; - } - public Date getDownloadDate() { - return downloadDate; - } - public void setDownloadDate(Date downloadDate) { - this.downloadDate = downloadDate; - } - public int getEncounterNum() { - return encounterNum; - } - public void setEncounterNum(int encounterNum) { - this.encounterNum = encounterNum; - } - public Date getEndDate() { - return endDate; - } - public void setEndDate(Date endDate) { - this.endDate = endDate; - } - public Date getImportDate() { - return importDate; - } - public void setImportDate(Date importDate) { - this.importDate = importDate; - } - public String getLocationCd() { - return locationCd; - } - public void setLocationCd(String locationCd) { - this.locationCd = locationCd; - } - public Float getNvalNum() { - return nvalNum; - } - public void setNvalNum(Float nvalNum) { - this.nvalNum = nvalNum; - } - public int getPatientNum() { - return patientNum; - } - public void setPatientNum(int patientNum) { - this.patientNum = patientNum; - } - - public String getProviderId() { - return providerId; - } - - public void setProviderId(String providerId) { - this.providerId = providerId; - } - public Float getQuantityNum() { - return quantityNum; - } - public void setQuantityNum(Float quantityNum) { - this.quantityNum = quantityNum; - } - public String getSourcesystemCd() { - return sourcesystemCd; - } - public void setSourcesystemCd(String sourcesystemCd) { - this.sourcesystemCd = sourcesystemCd; - } - public Date getStartDate() { - return startDate; - } - public void setStartDate(Date startDate) { - this.startDate = startDate; - } - public String getTvalChar() { - return tvalChar; - } - public void setTvalChar(String tvalChar) { - this.tvalChar = tvalChar; - } - public String getUnitsCd() { - return unitsCd; - } - public void setUnitsCd(String unitsCd) { - this.unitsCd = unitsCd; - } - public Date getUpdateDate() { - return updateDate; - } - public void setUpdateDate(Date updateDate) { - this.updateDate = updateDate; - } - public String getValtypeCd() { - return valtypeCd; - } - public void setValtypeCd(String valtypeCd) { - this.valtypeCd = valtypeCd; - } - public String getValueflagCd() { - return valueflagCd; - } - public void setValueflagCd(String valueflagCd) { - this.valueflagCd = valueflagCd; - } - public String getObservationBlob() { - return observationBlob; - } - public void setObservationBlob(String observationBlob) { - this.observationBlob = observationBlob; - } - - @Override - public String toString() { - return this.getEncounterNum() + - " " + - this.getConceptCd() + - " " + - this.getPatientNum() + - " " + - this.getProviderId() + - " " + - this.getStartDate(); - } - - public String getModifierCd() { - return modifierCd; - } - public void setModifierCd(String modifierCd) { - this.modifierCd = modifierCd; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.datavo.loader; + +import java.util.Date; + + +/** + * Object to hold observation fact values. + * @author rk903 + * + */ +public class ObservationFact { + private int encounterNum = 0; + private String conceptCd = null; + private int patientNum = 0; + private String providerId = null; + private Date startDate = null; + private String modifierCd = null; + private String valtypeCd = null; + private String observationBlob = null; + private String tvalChar = null; + private Float nvalNum = null; + private String valueflagCd = null; + private Float quantityNum = null; + private Integer confidenceNum = null; + private String unitsCd = null; + private Date endDate = null; + private String locationCd = null; + private Date updateDate = null; + private Date downloadDate = null; + private Date importDate = null; + private String sourcesystemCd = null; + private String patientIde = null; + private String encounterIde = null; + private int uploadId = 0; + + + + public int getUploadId() { + return uploadId; + } + public void setUploadId(int uploadId) { + this.uploadId = uploadId; + } + public String getEncounterIde() { + return encounterIde; + } + public void setEncounterIde(String encounterIde) { + this.encounterIde = encounterIde; + } + public String getPatientIde() { + return patientIde; + } + public void setPatientIde(String patientIde) { + this.patientIde = patientIde; + } + public String getConceptCd() { + return conceptCd; + } + public void setConceptCd(String conceptCd) { + this.conceptCd = conceptCd; + } + public Integer getConfidenceNum() { + return confidenceNum; + } + public void setConfidenceNum(Integer confidenceNum) { + this.confidenceNum = confidenceNum; + } + public Date getDownloadDate() { + return downloadDate; + } + public void setDownloadDate(Date downloadDate) { + this.downloadDate = downloadDate; + } + public int getEncounterNum() { + return encounterNum; + } + public void setEncounterNum(int encounterNum) { + this.encounterNum = encounterNum; + } + public Date getEndDate() { + return endDate; + } + public void setEndDate(Date endDate) { + this.endDate = endDate; + } + public Date getImportDate() { + return importDate; + } + public void setImportDate(Date importDate) { + this.importDate = importDate; + } + public String getLocationCd() { + return locationCd; + } + public void setLocationCd(String locationCd) { + this.locationCd = locationCd; + } + public Float getNvalNum() { + return nvalNum; + } + public void setNvalNum(Float nvalNum) { + this.nvalNum = nvalNum; + } + public int getPatientNum() { + return patientNum; + } + public void setPatientNum(int patientNum) { + this.patientNum = patientNum; + } + + public String getProviderId() { + return providerId; + } + + public void setProviderId(String providerId) { + this.providerId = providerId; + } + public Float getQuantityNum() { + return quantityNum; + } + public void setQuantityNum(Float quantityNum) { + this.quantityNum = quantityNum; + } + public String getSourcesystemCd() { + return sourcesystemCd; + } + public void setSourcesystemCd(String sourcesystemCd) { + this.sourcesystemCd = sourcesystemCd; + } + public Date getStartDate() { + return startDate; + } + public void setStartDate(Date startDate) { + this.startDate = startDate; + } + public String getTvalChar() { + return tvalChar; + } + public void setTvalChar(String tvalChar) { + this.tvalChar = tvalChar; + } + public String getUnitsCd() { + return unitsCd; + } + public void setUnitsCd(String unitsCd) { + this.unitsCd = unitsCd; + } + public Date getUpdateDate() { + return updateDate; + } + public void setUpdateDate(Date updateDate) { + this.updateDate = updateDate; + } + public String getValtypeCd() { + return valtypeCd; + } + public void setValtypeCd(String valtypeCd) { + this.valtypeCd = valtypeCd; + } + public String getValueflagCd() { + return valueflagCd; + } + public void setValueflagCd(String valueflagCd) { + this.valueflagCd = valueflagCd; + } + public String getObservationBlob() { + return observationBlob; + } + public void setObservationBlob(String observationBlob) { + this.observationBlob = observationBlob; + } + + @Override + public String toString() { + return this.getEncounterNum() + + " " + + this.getConceptCd() + + " " + + this.getPatientNum() + + " " + + this.getProviderId() + + " " + + this.getStartDate(); + } + + public String getModifierCd() { + return modifierCd; + } + public void setModifierCd(String modifierCd) { + this.modifierCd = modifierCd; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/datavo/loader/Patient.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/datavo/loader/Patient.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/datavo/loader/Patient.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/datavo/loader/Patient.java index 898c0415..007d0a2e --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/datavo/loader/Patient.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/datavo/loader/Patient.java @@ -1,159 +1,159 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.datavo.loader; - -import java.util.Date; - -public class Patient { - - private String patientIde = null; - private String patientIdeStatus = null; - private int patientNum = 0; - private String sexCd = null; - private int ageInYearsNum = 0; - private String languageCd = null; - private String raceCd = null; - private String maritalStatusCd = null; - private String religionCd = null; - private String zipCd = null; - private String vitalStatusCd = null; - private Date birthDate = null; - private Date deathDate = null; - private String stateCityZipPath = null; -// skiping patientBlob - private Date updateDate = null; - private Date downloadDate = null; - private Date importDate = null; - private String sourceSystemCd = null; - private String source = null; - - - public Patient() { - - } - - public int getAgeInYearsNum() { - return ageInYearsNum; - } - public void setAgeInYearsNum(int ageInYearsNum) { - this.ageInYearsNum = ageInYearsNum; - } - public Date getBirthDate() { - return birthDate; - } - public void setBirthDate(Date birthDate) { - this.birthDate = birthDate; - } - public Date getDeathDate() { - return deathDate; - } - public void setDeathDate(Date deathDate) { - this.deathDate = deathDate; - } - public Date getDownloadDate() { - return downloadDate; - } - public void setDownloadDate(Date downloadDate) { - this.downloadDate = downloadDate; - } - public Date getImportDate() { - return importDate; - } - public void setImportDate(Date importDate) { - this.importDate = importDate; - } - public String getLanguageCd() { - return languageCd; - } - public void setLanguageCd(String languageCd) { - this.languageCd = languageCd; - } - public String getMaritalStatusCd() { - return maritalStatusCd; - } - public void setMaritalStatusCd(String maritalStatusCd) { - this.maritalStatusCd = maritalStatusCd; - } - public String getPatientIde() { - return patientIde; - } - public void setPatientIde(String patientIde) { - this.patientIde = patientIde; - } - public String getPatientIdeStatus() { - return patientIdeStatus; - } - public void setPatientIdeStatus(String patientIdeStatus) { - this.patientIdeStatus = patientIdeStatus; - } - public int getPatientNum() { - return patientNum; - } - public void setPatientNum(int patientNum) { - this.patientNum = patientNum; - } - public String getRaceCd() { - return raceCd; - } - public void setRaceCd(String raceCd) { - this.raceCd = raceCd; - } - public String getReligionCd() { - return religionCd; - } - public void setReligionCd(String religionCd) { - this.religionCd = religionCd; - } - public String getSexCd() { - return sexCd; - } - public void setSexCd(String sexCd) { - this.sexCd = sexCd; - } - public String getSource() { - return source; - } - public void setSource(String source) { - this.source = source; - } - public String getSourceSystemCd() { - return sourceSystemCd; - } - public void setSourceSystemCd(String sourceSystemCd) { - this.sourceSystemCd = sourceSystemCd; - } - public String getStateCityZipPath() { - return stateCityZipPath; - } - public void setStateCityZipPath(String stateCityZipPath) { - this.stateCityZipPath = stateCityZipPath; - } - public Date getUpdateDate() { - return updateDate; - } - public void setUpdateDate(Date updateDate) { - this.updateDate = updateDate; - } - public String getVitalStatusCd() { - return vitalStatusCd; - } - public void setVitalStatusCd(String vitalStatusCd) { - this.vitalStatusCd = vitalStatusCd; - } - public String getZipCd() { - return zipCd; - } - public void setZipCd(String zipCd) { - this.zipCd = zipCd; - } - - - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.datavo.loader; + +import java.util.Date; + +public class Patient { + + private String patientIde = null; + private String patientIdeStatus = null; + private int patientNum = 0; + private String sexCd = null; + private int ageInYearsNum = 0; + private String languageCd = null; + private String raceCd = null; + private String maritalStatusCd = null; + private String religionCd = null; + private String zipCd = null; + private String vitalStatusCd = null; + private Date birthDate = null; + private Date deathDate = null; + private String stateCityZipPath = null; +// skiping patientBlob + private Date updateDate = null; + private Date downloadDate = null; + private Date importDate = null; + private String sourceSystemCd = null; + private String source = null; + + + public Patient() { + + } + + public int getAgeInYearsNum() { + return ageInYearsNum; + } + public void setAgeInYearsNum(int ageInYearsNum) { + this.ageInYearsNum = ageInYearsNum; + } + public Date getBirthDate() { + return birthDate; + } + public void setBirthDate(Date birthDate) { + this.birthDate = birthDate; + } + public Date getDeathDate() { + return deathDate; + } + public void setDeathDate(Date deathDate) { + this.deathDate = deathDate; + } + public Date getDownloadDate() { + return downloadDate; + } + public void setDownloadDate(Date downloadDate) { + this.downloadDate = downloadDate; + } + public Date getImportDate() { + return importDate; + } + public void setImportDate(Date importDate) { + this.importDate = importDate; + } + public String getLanguageCd() { + return languageCd; + } + public void setLanguageCd(String languageCd) { + this.languageCd = languageCd; + } + public String getMaritalStatusCd() { + return maritalStatusCd; + } + public void setMaritalStatusCd(String maritalStatusCd) { + this.maritalStatusCd = maritalStatusCd; + } + public String getPatientIde() { + return patientIde; + } + public void setPatientIde(String patientIde) { + this.patientIde = patientIde; + } + public String getPatientIdeStatus() { + return patientIdeStatus; + } + public void setPatientIdeStatus(String patientIdeStatus) { + this.patientIdeStatus = patientIdeStatus; + } + public int getPatientNum() { + return patientNum; + } + public void setPatientNum(int patientNum) { + this.patientNum = patientNum; + } + public String getRaceCd() { + return raceCd; + } + public void setRaceCd(String raceCd) { + this.raceCd = raceCd; + } + public String getReligionCd() { + return religionCd; + } + public void setReligionCd(String religionCd) { + this.religionCd = religionCd; + } + public String getSexCd() { + return sexCd; + } + public void setSexCd(String sexCd) { + this.sexCd = sexCd; + } + public String getSource() { + return source; + } + public void setSource(String source) { + this.source = source; + } + public String getSourceSystemCd() { + return sourceSystemCd; + } + public void setSourceSystemCd(String sourceSystemCd) { + this.sourceSystemCd = sourceSystemCd; + } + public String getStateCityZipPath() { + return stateCityZipPath; + } + public void setStateCityZipPath(String stateCityZipPath) { + this.stateCityZipPath = stateCityZipPath; + } + public Date getUpdateDate() { + return updateDate; + } + public void setUpdateDate(Date updateDate) { + this.updateDate = updateDate; + } + public String getVitalStatusCd() { + return vitalStatusCd; + } + public void setVitalStatusCd(String vitalStatusCd) { + this.vitalStatusCd = vitalStatusCd; + } + public String getZipCd() { + return zipCd; + } + public void setZipCd(String zipCd) { + this.zipCd = zipCd; + } + + + + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/datavo/loader/ProcessPulmonary.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/datavo/loader/ProcessPulmonary.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/datavo/loader/ProcessPulmonary.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/datavo/loader/ProcessPulmonary.java index c8c86e1f..459fb9a7 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/datavo/loader/ProcessPulmonary.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/datavo/loader/ProcessPulmonary.java @@ -1,104 +1,104 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/** - * - */ -package edu.harvard.i2b2.crc.loader.datavo.loader; - -import java.io.*; - - -//import sun.security.krb5.internal.s; -/** - * @author mem61 - * - */ -public class ProcessPulmonary { - - /** - * @param args - */ - public static void main(String[] args) { - Pulmonary p = new Pulmonary(); - - String dataIn = ""; - if ( args.length > 0) { - try { - FileInputStream fin = new FileInputStream(args[0]); - // JDK1.1+ - BufferedReader myInput = new BufferedReader - (new InputStreamReader(fin)); - while ((dataIn = myInput.readLine()) != null) { - if (dataIn.toUpperCase().indexOf("HEIGHT") > -1) - { - // Found a Height, find the next ":" and than - // the number will be the height - int heightLocBegin = dataIn.indexOf(":", dataIn.toUpperCase().indexOf("HEIGHT")) + 2; - int heightLocEnd = dataIn.indexOf(" ", heightLocBegin+1); - p.setHeight(Double.parseDouble(dataIn.substring(heightLocBegin,heightLocEnd).trim())); - } - if (dataIn.toUpperCase().indexOf("WEIGHT") > -1) - { - // Found a Height, find the next ":" and than - // the number will be the height - int heightLocBegin = dataIn.indexOf(":", dataIn.toUpperCase().indexOf("WEIGHT")) + 2; - int heightLocEnd = dataIn.indexOf(" ", heightLocBegin+1); - p.setHeight(Double.parseDouble(dataIn.substring( - heightLocBegin,(heightLocEnd > -1 ? - heightLocEnd : dataIn.length())).trim())); - } - if (dataIn.toUpperCase().indexOf("FIRST SEC VC (L)") > -1) - { - Bronchodilator bronchodilator = new Bronchodilator(); - - int locBegin = dataIn.toUpperCase().indexOf("FIRST SEC VC (L)") + 17; - java.util.StringTokenizer st = new java.util.StringTokenizer (dataIn.substring(locBegin)); - String[] array = new String[st.countTokens()]; - for (int i =0; i < st.countTokens(); i++) { - array[i] = st.nextToken (); - } - bronchodilator.setNoObserved(Double.parseDouble(array[0])); - bronchodilator.setNoPredicted(Double.parseDouble(array[2])); - p.setFirstSecVC(bronchodilator); - } - if (dataIn.toUpperCase().indexOf("VITAL CAPACITY (L)") > -1) - { - Bronchodilator bronchodilator = new Bronchodilator(); - - int locBegin = dataIn.toUpperCase().indexOf("VITAL CAPACITY (L)") + 19; - java.util.StringTokenizer st = new java.util.StringTokenizer (dataIn.substring(locBegin)); - String[] array = new String[st.countTokens()]; - for (int i =0; i < st.countTokens(); i++) { - array[i] = st.nextToken (); - } - bronchodilator.setNoObserved(Double.parseDouble(array[0])); - bronchodilator.setNoPredicted(Double.parseDouble(array[2])); - p.setVitalCapacity(bronchodilator); - } - - - if (dataIn.toUpperCase().indexOf("HEIGHT") > -1) - { - // Found a Height, find the next ":" and than - // the number will be the height - int heightLocBegin = dataIn.indexOf(":", dataIn.toUpperCase().indexOf("HEIGHT")) + 2; - int heightLocEnd = dataIn.indexOf(" ", heightLocBegin+1); - p.setHeight(Double.parseDouble(dataIn.substring(heightLocBegin,heightLocEnd).trim())); - } - } - } - catch (Exception e) { - e.printStackTrace(); - } - } - - - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/** + * + */ +package edu.harvard.i2b2.crc.loader.datavo.loader; + +import java.io.*; + + +//import sun.security.krb5.internal.s; +/** + * @author mem61 + * + */ +public class ProcessPulmonary { + + /** + * @param args + */ + public static void main(String[] args) { + Pulmonary p = new Pulmonary(); + + String dataIn = ""; + if ( args.length > 0) { + try { + FileInputStream fin = new FileInputStream(args[0]); + // JDK1.1+ + BufferedReader myInput = new BufferedReader + (new InputStreamReader(fin)); + while ((dataIn = myInput.readLine()) != null) { + if (dataIn.toUpperCase().indexOf("HEIGHT") > -1) + { + // Found a Height, find the next ":" and than + // the number will be the height + int heightLocBegin = dataIn.indexOf(":", dataIn.toUpperCase().indexOf("HEIGHT")) + 2; + int heightLocEnd = dataIn.indexOf(" ", heightLocBegin+1); + p.setHeight(Double.parseDouble(dataIn.substring(heightLocBegin,heightLocEnd).trim())); + } + if (dataIn.toUpperCase().indexOf("WEIGHT") > -1) + { + // Found a Height, find the next ":" and than + // the number will be the height + int heightLocBegin = dataIn.indexOf(":", dataIn.toUpperCase().indexOf("WEIGHT")) + 2; + int heightLocEnd = dataIn.indexOf(" ", heightLocBegin+1); + p.setHeight(Double.parseDouble(dataIn.substring( + heightLocBegin,(heightLocEnd > -1 ? + heightLocEnd : dataIn.length())).trim())); + } + if (dataIn.toUpperCase().indexOf("FIRST SEC VC (L)") > -1) + { + Bronchodilator bronchodilator = new Bronchodilator(); + + int locBegin = dataIn.toUpperCase().indexOf("FIRST SEC VC (L)") + 17; + java.util.StringTokenizer st = new java.util.StringTokenizer (dataIn.substring(locBegin)); + String[] array = new String[st.countTokens()]; + for (int i =0; i < st.countTokens(); i++) { + array[i] = st.nextToken (); + } + bronchodilator.setNoObserved(Double.parseDouble(array[0])); + bronchodilator.setNoPredicted(Double.parseDouble(array[2])); + p.setFirstSecVC(bronchodilator); + } + if (dataIn.toUpperCase().indexOf("VITAL CAPACITY (L)") > -1) + { + Bronchodilator bronchodilator = new Bronchodilator(); + + int locBegin = dataIn.toUpperCase().indexOf("VITAL CAPACITY (L)") + 19; + java.util.StringTokenizer st = new java.util.StringTokenizer (dataIn.substring(locBegin)); + String[] array = new String[st.countTokens()]; + for (int i =0; i < st.countTokens(); i++) { + array[i] = st.nextToken (); + } + bronchodilator.setNoObserved(Double.parseDouble(array[0])); + bronchodilator.setNoPredicted(Double.parseDouble(array[2])); + p.setVitalCapacity(bronchodilator); + } + + + if (dataIn.toUpperCase().indexOf("HEIGHT") > -1) + { + // Found a Height, find the next ":" and than + // the number will be the height + int heightLocBegin = dataIn.indexOf(":", dataIn.toUpperCase().indexOf("HEIGHT")) + 2; + int heightLocEnd = dataIn.indexOf(" ", heightLocBegin+1); + p.setHeight(Double.parseDouble(dataIn.substring(heightLocBegin,heightLocEnd).trim())); + } + } + } + catch (Exception e) { + e.printStackTrace(); + } + } + + + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/datavo/loader/Pulmonary.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/datavo/loader/Pulmonary.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/datavo/loader/Pulmonary.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/datavo/loader/Pulmonary.java index cd7c470b..461f72d5 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/datavo/loader/Pulmonary.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/datavo/loader/Pulmonary.java @@ -1,50 +1,50 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.datavo.loader; -import java.util.Calendar; - - -public class Pulmonary { - private double height; - private double wieght; - private Bronchodilator firstSecVC; - private Bronchodilator vitalCapacity; - private Calendar reportDate; - - public Bronchodilator getFirstSecVC() { - return firstSecVC; - } - public void setFirstSecVC(Bronchodilator firstSecVC) { - this.firstSecVC = firstSecVC; - } - public double getHeight() { - return height; - } - public void setHeight(double height) { - this.height = height; - } - public Bronchodilator getVitalCapacity() { - return vitalCapacity; - } - public void setVitalCapacity(Bronchodilator vitalCapacity) { - this.vitalCapacity = vitalCapacity; - } - public double getWieght() { - return wieght; - } - public void setWieght(double wieght) { - this.wieght = wieght; - } - public Calendar getReportDate() { - return reportDate; - } - public void setReportDate(Calendar reportDate) { - this.reportDate = reportDate; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.datavo.loader; +import java.util.Calendar; + + +public class Pulmonary { + private double height; + private double wieght; + private Bronchodilator firstSecVC; + private Bronchodilator vitalCapacity; + private Calendar reportDate; + + public Bronchodilator getFirstSecVC() { + return firstSecVC; + } + public void setFirstSecVC(Bronchodilator firstSecVC) { + this.firstSecVC = firstSecVC; + } + public double getHeight() { + return height; + } + public void setHeight(double height) { + this.height = height; + } + public Bronchodilator getVitalCapacity() { + return vitalCapacity; + } + public void setVitalCapacity(Bronchodilator vitalCapacity) { + this.vitalCapacity = vitalCapacity; + } + public double getWieght() { + return wieght; + } + public void setWieght(double wieght) { + this.wieght = wieght; + } + public Calendar getReportDate() { + return reportDate; + } + public void setReportDate(Calendar reportDate) { + this.reportDate = reportDate; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/datavo/loader/UploadSetStatus.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/datavo/loader/UploadSetStatus.java old mode 100755 new mode 100644 similarity index 95% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/datavo/loader/UploadSetStatus.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/datavo/loader/UploadSetStatus.java index b462cf45..0543b6a5 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/datavo/loader/UploadSetStatus.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/datavo/loader/UploadSetStatus.java @@ -1,161 +1,161 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.datavo.loader; - -import java.util.Date; - -/** - * Object to hold Upload_Status values. - * - * @author rk903 - * - */ -public class UploadSetStatus { - - public static final String SUCCESS_STATUS = "SUCCESS" ; - public static final String ERROR_STATUS = "ERROR" ; - - private int uploadId = 0; - - private int setTypeId = 0; - - private String sourceCd = null; - - private int noOfRecord = 0; - - private int deletedRecord = 0; - - private int loadedRecord = 0; - - private Date loadDate = null; - - private Date endDate = null; - - private String loadStatus = null; - - private String inputFileName = null; - - private String logFileName = null; - - private String transformName = null; - - private String message = null; - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - public String getInputFileName() { - return inputFileName; - } - - public void setInputFileName(String inputFileName) { - this.inputFileName = inputFileName; - } - - public Date getLoadDate() { - return loadDate; - } - - public void setLoadDate(Date loadDate) { - this.loadDate = loadDate; - } - - public int getLoadedRecord() { - return loadedRecord; - } - - public void setLoadedRecord(int loadedRecord) { - this.loadedRecord = loadedRecord; - } - - - public int getDeletedRecord() { - return deletedRecord; - } - - public void setDeletedRecord(int deletedRecord) { - this.deletedRecord = deletedRecord; - } - - public String getLoadStatus() { - return loadStatus; - } - - public void setLoadStatus(String loadStatus) { - this.loadStatus = loadStatus; - } - - public String getLogFileName() { - return logFileName; - } - - public void setLogFileName(String logFileName) { - this.logFileName = logFileName; - } - - public int getNoOfRecord() { - return noOfRecord; - } - - public void setNoOfRecord(int noOfRecord) { - this.noOfRecord = noOfRecord; - } - - public String getSourceCd() { - return sourceCd; - } - - public void setSourceCd(String sourceCd) { - this.sourceCd = sourceCd; - } - - public String getTransformName() { - return transformName; - } - - public void setTransformName(String transformName) { - this.transformName = transformName; - } - - public int getUploadId() { - return uploadId; - } - - public void setUploadId(int uploadId) { - this.uploadId = uploadId; - } - - public int getSetTypeId() { - return setTypeId; - } - - public void setSetTypeId(int setTypeId) { - this.setTypeId = setTypeId; - } - - public Date getEndDate() { - return endDate; - } - - public void setEndDate(Date endDate) { - this.endDate = endDate; - } - - - - - - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.datavo.loader; + +import java.util.Date; + +/** + * Object to hold Upload_Status values. + * + * @author rk903 + * + */ +public class UploadSetStatus { + + public static final String SUCCESS_STATUS = "SUCCESS" ; + public static final String ERROR_STATUS = "ERROR" ; + + private int uploadId = 0; + + private int setTypeId = 0; + + private String sourceCd = null; + + private int noOfRecord = 0; + + private int deletedRecord = 0; + + private int loadedRecord = 0; + + private Date loadDate = null; + + private Date endDate = null; + + private String loadStatus = null; + + private String inputFileName = null; + + private String logFileName = null; + + private String transformName = null; + + private String message = null; + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public String getInputFileName() { + return inputFileName; + } + + public void setInputFileName(String inputFileName) { + this.inputFileName = inputFileName; + } + + public Date getLoadDate() { + return loadDate; + } + + public void setLoadDate(Date loadDate) { + this.loadDate = loadDate; + } + + public int getLoadedRecord() { + return loadedRecord; + } + + public void setLoadedRecord(int loadedRecord) { + this.loadedRecord = loadedRecord; + } + + + public int getDeletedRecord() { + return deletedRecord; + } + + public void setDeletedRecord(int deletedRecord) { + this.deletedRecord = deletedRecord; + } + + public String getLoadStatus() { + return loadStatus; + } + + public void setLoadStatus(String loadStatus) { + this.loadStatus = loadStatus; + } + + public String getLogFileName() { + return logFileName; + } + + public void setLogFileName(String logFileName) { + this.logFileName = logFileName; + } + + public int getNoOfRecord() { + return noOfRecord; + } + + public void setNoOfRecord(int noOfRecord) { + this.noOfRecord = noOfRecord; + } + + public String getSourceCd() { + return sourceCd; + } + + public void setSourceCd(String sourceCd) { + this.sourceCd = sourceCd; + } + + public String getTransformName() { + return transformName; + } + + public void setTransformName(String transformName) { + this.transformName = transformName; + } + + public int getUploadId() { + return uploadId; + } + + public void setUploadId(int uploadId) { + this.uploadId = uploadId; + } + + public int getSetTypeId() { + return setTypeId; + } + + public void setSetTypeId(int setTypeId) { + this.setTypeId = setTypeId; + } + + public Date getEndDate() { + return endDate; + } + + public void setEndDate(Date endDate) { + this.endDate = endDate; + } + + + + + + + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/datavo/loader/UploadStatus.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/datavo/loader/UploadStatus.java old mode 100755 new mode 100644 similarity index 95% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/datavo/loader/UploadStatus.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/datavo/loader/UploadStatus.java index 443695ba..cd74b50b --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/datavo/loader/UploadStatus.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/datavo/loader/UploadStatus.java @@ -1,167 +1,167 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.datavo.loader; - -import java.util.Date; - -/** - * Object to hold Upload_Status values. - * - * @author rk903 - * - */ -public class UploadStatus { - - public static final String SUCCESS_STATUS = "SUCCESS" ; - public static final String ERROR_STATUS = "ERROR" ; - - private int uploadId = 0; - - private String uploadLabel = null; - - private String userId = null; - - private String sourceCd = null; - - private int noOfRecord = 0; - - private int deletedRecord = 0; - - private int loadedRecord = 0; - - private Date loadDate = null; - - private Date endDate = null; - - private String loadStatus = null; - - private String inputFileName = null; - - private String logFileName = null; - - private String transformName = null; - - private String message = null; - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - public String getInputFileName() { - return inputFileName; - } - - public void setInputFileName(String inputFileName) { - this.inputFileName = inputFileName; - } - - public Date getLoadDate() { - return loadDate; - } - - public void setLoadDate(Date loadDate) { - this.loadDate = loadDate; - } - - public int getLoadedRecord() { - return loadedRecord; - } - - public void setLoadedRecord(int loadedRecord) { - this.loadedRecord = loadedRecord; - } - - - public int getDeletedRecord() { - return deletedRecord; - } - - public void setDeletedRecord(int deletedRecord) { - this.deletedRecord = deletedRecord; - } - - public String getLoadStatus() { - return loadStatus; - } - - public void setLoadStatus(String loadStatus) { - this.loadStatus = loadStatus; - } - - public String getLogFileName() { - return logFileName; - } - - public void setLogFileName(String logFileName) { - this.logFileName = logFileName; - } - - public int getNoOfRecord() { - return noOfRecord; - } - - public void setNoOfRecord(int noOfRecord) { - this.noOfRecord = noOfRecord; - } - - public String getSourceCd() { - return sourceCd; - } - - public void setSourceCd(String sourceCd) { - this.sourceCd = sourceCd; - } - - public String getTransformName() { - return transformName; - } - - public void setTransformName(String transformName) { - this.transformName = transformName; - } - - public int getUploadId() { - return uploadId; - } - - public void setUploadId(int uploadId) { - this.uploadId = uploadId; - } - - public String getUploadLabel() { - return uploadLabel; - } - - public void setUploadLabel(String uploadLabel) { - this.uploadLabel = uploadLabel; - } - - public String getUserId() { - return userId; - } - - public void setUserId(String userId) { - this.userId = userId; - } - - public Date getEndDate() { - return endDate; - } - - public void setEndDate(Date endDate) { - this.endDate = endDate; - } - - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.datavo.loader; + +import java.util.Date; + +/** + * Object to hold Upload_Status values. + * + * @author rk903 + * + */ +public class UploadStatus { + + public static final String SUCCESS_STATUS = "SUCCESS" ; + public static final String ERROR_STATUS = "ERROR" ; + + private int uploadId = 0; + + private String uploadLabel = null; + + private String userId = null; + + private String sourceCd = null; + + private int noOfRecord = 0; + + private int deletedRecord = 0; + + private int loadedRecord = 0; + + private Date loadDate = null; + + private Date endDate = null; + + private String loadStatus = null; + + private String inputFileName = null; + + private String logFileName = null; + + private String transformName = null; + + private String message = null; + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public String getInputFileName() { + return inputFileName; + } + + public void setInputFileName(String inputFileName) { + this.inputFileName = inputFileName; + } + + public Date getLoadDate() { + return loadDate; + } + + public void setLoadDate(Date loadDate) { + this.loadDate = loadDate; + } + + public int getLoadedRecord() { + return loadedRecord; + } + + public void setLoadedRecord(int loadedRecord) { + this.loadedRecord = loadedRecord; + } + + + public int getDeletedRecord() { + return deletedRecord; + } + + public void setDeletedRecord(int deletedRecord) { + this.deletedRecord = deletedRecord; + } + + public String getLoadStatus() { + return loadStatus; + } + + public void setLoadStatus(String loadStatus) { + this.loadStatus = loadStatus; + } + + public String getLogFileName() { + return logFileName; + } + + public void setLogFileName(String logFileName) { + this.logFileName = logFileName; + } + + public int getNoOfRecord() { + return noOfRecord; + } + + public void setNoOfRecord(int noOfRecord) { + this.noOfRecord = noOfRecord; + } + + public String getSourceCd() { + return sourceCd; + } + + public void setSourceCd(String sourceCd) { + this.sourceCd = sourceCd; + } + + public String getTransformName() { + return transformName; + } + + public void setTransformName(String transformName) { + this.transformName = transformName; + } + + public int getUploadId() { + return uploadId; + } + + public void setUploadId(int uploadId) { + this.uploadId = uploadId; + } + + public String getUploadLabel() { + return uploadLabel; + } + + public void setUploadLabel(String uploadLabel) { + this.uploadLabel = uploadLabel; + } + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public Date getEndDate() { + return endDate; + } + + public void setEndDate(Date endDate) { + this.endDate = endDate; + } + + + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/datavo/loader/UserProfile.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/datavo/loader/UserProfile.java old mode 100755 new mode 100644 similarity index 95% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/datavo/loader/UserProfile.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/datavo/loader/UserProfile.java index a1c59726..f15d10d2 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/datavo/loader/UserProfile.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/datavo/loader/UserProfile.java @@ -1,51 +1,51 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.datavo.loader; - -import java.io.Serializable; - - -/** - * User profile data object - * @author rk903 - * - */ -public class UserProfile implements Serializable { - - - private static final long serialVersionUID = 1L; - - private String userId = null; - private String password = null; - - - public UserProfile() { - } - - - public String getPassword() { - return password; - } - - - public void setPassword(String password) { - this.password = password; - } - - - public String getUserId() { - return userId; - } - - - public void setUserId(String userId) { - this.userId = userId; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.datavo.loader; + +import java.io.Serializable; + + +/** + * User profile data object + * @author rk903 + * + */ +public class UserProfile implements Serializable { + + + private static final long serialVersionUID = 1L; + + private String userId = null; + private String password = null; + + + public UserProfile() { + } + + + public String getPassword() { + return password; + } + + + public void setPassword(String password) { + this.password = password; + } + + + public String getUserId() { + return userId; + } + + + public void setUserId(String userId) { + this.userId = userId; + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/delegate/BulkLoadRequestHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/delegate/BulkLoadRequestHandler.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/delegate/BulkLoadRequestHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/delegate/BulkLoadRequestHandler.java index c4c99ee3..a48cacf1 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/delegate/BulkLoadRequestHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/delegate/BulkLoadRequestHandler.java @@ -1,101 +1,101 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.delegate; - -import java.io.StringWriter; - -import jakarta.xml.bind.JAXBElement; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.loader.datavo.CRCLoaderJAXBUtil; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; -import edu.harvard.i2b2.crc.loader.datavo.loader.query.BulkLoadRequestType; -import edu.harvard.i2b2.crc.loader.datavo.loader.query.LoadDataResponseType; -import edu.harvard.i2b2.crc.loader.ejb.DataMartLoaderAsyncBean; - -public class BulkLoadRequestHandler extends RequestHandler { - - BulkLoadRequestType bulkLoadRequestType = null; - MessageHeaderType messageHeaderType = null; - long timeout = 1; - protected String irodsDefaultStorageResource = null; - - public BulkLoadRequestHandler(String requestXml) throws I2B2Exception { - try { - bulkLoadRequestType = (BulkLoadRequestType) this - .getRequestType( - requestXml, - edu.harvard.i2b2.crc.loader.datavo.loader.query.BulkLoadRequestType.class); - messageHeaderType = getMessageHeaderType(requestXml); - timeout = getTimeout(requestXml); - this.setDataSourceLookup(requestXml); - } catch (JAXBUtilException jaxbUtilEx) { - throw new I2B2Exception("Error ", jaxbUtilEx); - } - } - - @Override - public BodyType execute() throws I2B2Exception { - edu.harvard.i2b2.crc.loader.datavo.loader.query.ObjectFactory objectFactory = new edu.harvard.i2b2.crc.loader.datavo.loader.query.ObjectFactory(); - // call ejb and pass input object - String responseString = null; - BodyType bodyType = new BodyType(); - - DataMartLoaderAsyncBean loader = new DataMartLoaderAsyncBean(); - JAXBUtil jaxbUtil = CRCLoaderJAXBUtil.getJAXBUtil(); - StringWriter strWriter = new StringWriter(); - try { - jaxbUtil.marshaller(objectFactory - .createBulkLoadRequest(bulkLoadRequestType), strWriter); - } catch (JAXBUtilException jaxbEx) { - throw new I2B2Exception("Error in marshalling bulk load request", - jaxbEx); - } - SecurityType securityType = messageHeaderType.getSecurity(); - - LoadDataResponseType response = loader.bulkLoad(this.getDataSourceLookup(), - strWriter.toString(), securityType, timeout); - - bodyType.getAny().add(objectFactory.createLoadDataResponse(response)); - - return bodyType; - - } - - - public long getTimeout(String xmlRequest) { - JAXBUtil jaxbUtil = CRCLoaderJAXBUtil.getJAXBUtil(); - JAXBElement jaxbElement = null; - long timeOutValue = 1; - try { - jaxbElement = jaxbUtil.unMashallFromString(xmlRequest); - - RequestMessageType requestMessageType = (RequestMessageType) jaxbElement - .getValue(); - - RequestHeaderType requestHeader = requestMessageType - .getRequestHeader(); - - if (requestHeader != null - && requestHeader.getResultWaittimeMs() > -1) { - timeOutValue = requestHeader.getResultWaittimeMs(); - } - } catch (JAXBUtilException e) { - log.error("Failed to read wait time from the request ", e); - } - return timeOutValue; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.delegate; + +import java.io.StringWriter; + +import jakarta.xml.bind.JAXBElement; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.loader.datavo.CRCLoaderJAXBUtil; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; +import edu.harvard.i2b2.crc.loader.datavo.loader.query.BulkLoadRequestType; +import edu.harvard.i2b2.crc.loader.datavo.loader.query.LoadDataResponseType; +import edu.harvard.i2b2.crc.loader.ejb.DataMartLoaderAsyncBean; + +public class BulkLoadRequestHandler extends RequestHandler { + + BulkLoadRequestType bulkLoadRequestType = null; + MessageHeaderType messageHeaderType = null; + long timeout = 1; + protected String irodsDefaultStorageResource = null; + + public BulkLoadRequestHandler(String requestXml) throws I2B2Exception { + try { + bulkLoadRequestType = (BulkLoadRequestType) this + .getRequestType( + requestXml, + edu.harvard.i2b2.crc.loader.datavo.loader.query.BulkLoadRequestType.class); + messageHeaderType = getMessageHeaderType(requestXml); + timeout = getTimeout(requestXml); + this.setDataSourceLookup(requestXml); + } catch (JAXBUtilException jaxbUtilEx) { + throw new I2B2Exception("Error ", jaxbUtilEx); + } + } + + @Override + public BodyType execute() throws I2B2Exception { + edu.harvard.i2b2.crc.loader.datavo.loader.query.ObjectFactory objectFactory = new edu.harvard.i2b2.crc.loader.datavo.loader.query.ObjectFactory(); + // call ejb and pass input object + String responseString = null; + BodyType bodyType = new BodyType(); + + DataMartLoaderAsyncBean loader = new DataMartLoaderAsyncBean(); + JAXBUtil jaxbUtil = CRCLoaderJAXBUtil.getJAXBUtil(); + StringWriter strWriter = new StringWriter(); + try { + jaxbUtil.marshaller(objectFactory + .createBulkLoadRequest(bulkLoadRequestType), strWriter); + } catch (JAXBUtilException jaxbEx) { + throw new I2B2Exception("Error in marshalling bulk load request", + jaxbEx); + } + SecurityType securityType = messageHeaderType.getSecurity(); + + LoadDataResponseType response = loader.bulkLoad(this.getDataSourceLookup(), + strWriter.toString(), securityType, timeout); + + bodyType.getAny().add(objectFactory.createLoadDataResponse(response)); + + return bodyType; + + } + + + public long getTimeout(String xmlRequest) { + JAXBUtil jaxbUtil = CRCLoaderJAXBUtil.getJAXBUtil(); + JAXBElement jaxbElement = null; + long timeOutValue = 1; + try { + jaxbElement = jaxbUtil.unMashallFromString(xmlRequest); + + RequestMessageType requestMessageType = (RequestMessageType) jaxbElement + .getValue(); + + RequestHeaderType requestHeader = requestMessageType + .getRequestHeader(); + + if (requestHeader != null + && requestHeader.getResultWaittimeMs() > -1) { + timeOutValue = requestHeader.getResultWaittimeMs(); + } + } catch (JAXBUtilException e) { + log.error("Failed to read wait time from the request ", e); + } + return timeOutValue; + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/delegate/GetLoadStatusRequestHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/delegate/GetLoadStatusRequestHandler.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/delegate/GetLoadStatusRequestHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/delegate/GetLoadStatusRequestHandler.java index b90a97bb..46cde2f3 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/delegate/GetLoadStatusRequestHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/delegate/GetLoadStatusRequestHandler.java @@ -1,86 +1,86 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.delegate; - -import java.io.StringWriter; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.loader.datavo.CRCLoaderJAXBUtil; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; -import edu.harvard.i2b2.crc.loader.datavo.loader.query.GetUploadInfoRequestType; -import edu.harvard.i2b2.crc.loader.datavo.loader.query.LoadDataListResponseType; -import edu.harvard.i2b2.crc.loader.datavo.loader.query.LoadDataResponseType; -import edu.harvard.i2b2.crc.loader.ejb.LoaderStatusBean; - -public class GetLoadStatusRequestHandler extends RequestHandler { - - GetUploadInfoRequestType getUploadInfoRequest = null; - MessageHeaderType messageHeaderType = null; - - public GetLoadStatusRequestHandler(String requestXml) throws I2B2Exception { - try { - getUploadInfoRequest = (GetUploadInfoRequestType) this - .getRequestType( - requestXml, - edu.harvard.i2b2.crc.loader.datavo.loader.query.GetUploadInfoRequestType.class); - messageHeaderType = getMessageHeaderType(requestXml); - this.setDataSourceLookup(requestXml); - } catch (JAXBUtilException jaxbUtilEx) { - throw new I2B2Exception("Error ", jaxbUtilEx); - } - } - - @Override - public BodyType execute() throws I2B2Exception { - edu.harvard.i2b2.crc.loader.datavo.loader.query.ObjectFactory objectFactory = new edu.harvard.i2b2.crc.loader.datavo.loader.query.ObjectFactory(); - // call ejb and pass input object - String responseString = null; - BodyType bodyType = new BodyType(); - - //LoaderStatusBeanLocal loaderStatusBean = CRCLoaderUtil.getInstance() - // .getLoaderStatusBean(); - - LoaderStatusBean loaderStatusBean = new LoaderStatusBean(); - - JAXBUtil jaxbUtil = CRCLoaderJAXBUtil.getJAXBUtil(); - StringWriter strWriter = new StringWriter(); - try { - jaxbUtil.marshaller(objectFactory - .createGetUploadInfoRequest(getUploadInfoRequest), - strWriter); - } catch (JAXBUtilException jaxbEx) { - throw new I2B2Exception("Error in marshalling publishdata request", - jaxbEx); - } - String uploadId = getUploadInfoRequest.getLoadId(); - String userId = getUploadInfoRequest.getUserId(); - if (uploadId != null) { - LoadDataResponseType response = loaderStatusBean - .getLoadDataResponseByUploadId(this.getDataSourceLookup(), - Integer.parseInt(uploadId)); - bodyType.getAny().add( - objectFactory.createLoadDataResponse(response)); - } else if (userId != null) { - LoadDataListResponseType response = loaderStatusBean - .getLoadDataResponseByUserId(this.getDataSourceLookup(), - userId); - - bodyType.getAny().add( - objectFactory.createLoadDataListResponse(response)); - - } - - return bodyType; - - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.delegate; + +import java.io.StringWriter; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.loader.datavo.CRCLoaderJAXBUtil; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; +import edu.harvard.i2b2.crc.loader.datavo.loader.query.GetUploadInfoRequestType; +import edu.harvard.i2b2.crc.loader.datavo.loader.query.LoadDataListResponseType; +import edu.harvard.i2b2.crc.loader.datavo.loader.query.LoadDataResponseType; +import edu.harvard.i2b2.crc.loader.ejb.LoaderStatusBean; + +public class GetLoadStatusRequestHandler extends RequestHandler { + + GetUploadInfoRequestType getUploadInfoRequest = null; + MessageHeaderType messageHeaderType = null; + + public GetLoadStatusRequestHandler(String requestXml) throws I2B2Exception { + try { + getUploadInfoRequest = (GetUploadInfoRequestType) this + .getRequestType( + requestXml, + edu.harvard.i2b2.crc.loader.datavo.loader.query.GetUploadInfoRequestType.class); + messageHeaderType = getMessageHeaderType(requestXml); + this.setDataSourceLookup(requestXml); + } catch (JAXBUtilException jaxbUtilEx) { + throw new I2B2Exception("Error ", jaxbUtilEx); + } + } + + @Override + public BodyType execute() throws I2B2Exception { + edu.harvard.i2b2.crc.loader.datavo.loader.query.ObjectFactory objectFactory = new edu.harvard.i2b2.crc.loader.datavo.loader.query.ObjectFactory(); + // call ejb and pass input object + String responseString = null; + BodyType bodyType = new BodyType(); + + //LoaderStatusBeanLocal loaderStatusBean = CRCLoaderUtil.getInstance() + // .getLoaderStatusBean(); + + LoaderStatusBean loaderStatusBean = new LoaderStatusBean(); + + JAXBUtil jaxbUtil = CRCLoaderJAXBUtil.getJAXBUtil(); + StringWriter strWriter = new StringWriter(); + try { + jaxbUtil.marshaller(objectFactory + .createGetUploadInfoRequest(getUploadInfoRequest), + strWriter); + } catch (JAXBUtilException jaxbEx) { + throw new I2B2Exception("Error in marshalling publishdata request", + jaxbEx); + } + String uploadId = getUploadInfoRequest.getLoadId(); + String userId = getUploadInfoRequest.getUserId(); + if (uploadId != null) { + LoadDataResponseType response = loaderStatusBean + .getLoadDataResponseByUploadId(this.getDataSourceLookup(), + Integer.parseInt(uploadId)); + bodyType.getAny().add( + objectFactory.createLoadDataResponse(response)); + } else if (userId != null) { + LoadDataListResponseType response = loaderStatusBean + .getLoadDataResponseByUserId(this.getDataSourceLookup(), + userId); + + bodyType.getAny().add( + objectFactory.createLoadDataListResponse(response)); + + } + + return bodyType; + + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/delegate/GetMissingTermRequestHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/delegate/GetMissingTermRequestHandler.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/delegate/GetMissingTermRequestHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/delegate/GetMissingTermRequestHandler.java index 7d3cbf08..32540a50 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/delegate/GetMissingTermRequestHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/delegate/GetMissingTermRequestHandler.java @@ -1,60 +1,60 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.delegate; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; -import edu.harvard.i2b2.crc.loader.datavo.loader.query.GetMissingTermRequestType; -import edu.harvard.i2b2.crc.loader.datavo.loader.query.MissingTermReportResponseType; -import edu.harvard.i2b2.crc.loader.ejb.MissingTermReportBean; - -public class GetMissingTermRequestHandler extends RequestHandler { - - GetMissingTermRequestType getMissingTermRequest = null; - MessageHeaderType messageHeaderType = null; - - public GetMissingTermRequestHandler(String requestXml) throws I2B2Exception { - try { - getMissingTermRequest = (GetMissingTermRequestType) this - .getRequestType( - requestXml, - edu.harvard.i2b2.crc.loader.datavo.loader.query.GetMissingTermRequestType.class); - messageHeaderType = getMessageHeaderType(requestXml); - this.setDataSourceLookup(requestXml); - } catch (JAXBUtilException jaxbUtilEx) { - throw new I2B2Exception("Error ", jaxbUtilEx); - } - } - - @Override - public BodyType execute() throws I2B2Exception { - edu.harvard.i2b2.crc.loader.datavo.loader.query.ObjectFactory objectFactory = new edu.harvard.i2b2.crc.loader.datavo.loader.query.ObjectFactory(); - // call ejb and pass input object - - - BodyType bodyType = new BodyType(); - - //MissingTermReportBeanLocal missingTermReportBean = CRCLoaderUtil - // .getInstance().getMissingTermReportBean(); - - MissingTermReportBean missingTermReportBean = new MissingTermReportBean(); - - MissingTermReportResponseType response = missingTermReportBean - .getMissingTermReport(dataSourceLookup, getMissingTermRequest); - - bodyType.getAny().add( - objectFactory.createMissingTermReportResponse(response)); - - return bodyType; - - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.delegate; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; +import edu.harvard.i2b2.crc.loader.datavo.loader.query.GetMissingTermRequestType; +import edu.harvard.i2b2.crc.loader.datavo.loader.query.MissingTermReportResponseType; +import edu.harvard.i2b2.crc.loader.ejb.MissingTermReportBean; + +public class GetMissingTermRequestHandler extends RequestHandler { + + GetMissingTermRequestType getMissingTermRequest = null; + MessageHeaderType messageHeaderType = null; + + public GetMissingTermRequestHandler(String requestXml) throws I2B2Exception { + try { + getMissingTermRequest = (GetMissingTermRequestType) this + .getRequestType( + requestXml, + edu.harvard.i2b2.crc.loader.datavo.loader.query.GetMissingTermRequestType.class); + messageHeaderType = getMessageHeaderType(requestXml); + this.setDataSourceLookup(requestXml); + } catch (JAXBUtilException jaxbUtilEx) { + throw new I2B2Exception("Error ", jaxbUtilEx); + } + } + + @Override + public BodyType execute() throws I2B2Exception { + edu.harvard.i2b2.crc.loader.datavo.loader.query.ObjectFactory objectFactory = new edu.harvard.i2b2.crc.loader.datavo.loader.query.ObjectFactory(); + // call ejb and pass input object + + + BodyType bodyType = new BodyType(); + + //MissingTermReportBeanLocal missingTermReportBean = CRCLoaderUtil + // .getInstance().getMissingTermReportBean(); + + MissingTermReportBean missingTermReportBean = new MissingTermReportBean(); + + MissingTermReportResponseType response = missingTermReportBean + .getMissingTermReport(dataSourceLookup, getMissingTermRequest); + + bodyType.getAny().add( + objectFactory.createMissingTermReportResponse(response)); + + return bodyType; + + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/delegate/LoaderQueryRequestDelegate.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/delegate/LoaderQueryRequestDelegate.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/delegate/LoaderQueryRequestDelegate.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/delegate/LoaderQueryRequestDelegate.java index 605596a3..463c143d --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/delegate/LoaderQueryRequestDelegate.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/delegate/LoaderQueryRequestDelegate.java @@ -1,209 +1,209 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.loader.delegate; - -import jakarta.xml.bind.JAXBElement; - -import org.apache.axis2.AxisFault; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.exception.StackTraceUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.loader.datavo.CRCLoaderJAXBUtil; -import edu.harvard.i2b2.crc.loader.datavo.I2B2MessageResponseFactory; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; -import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; -import edu.harvard.i2b2.crc.datavo.pm.ParamType; -import edu.harvard.i2b2.crc.datavo.pm.ProjectType; -import edu.harvard.i2b2.crc.loader.delegate.pm.PMServiceDriver; -import edu.harvard.i2b2.crc.util.I2B2RequestMessageHelper; - -/** - * PDO query request delegate class $Id: LoaderQueryRequestDelegate.java,v 1.3 - * 2008/02/26 23:09:59 rk903 Exp $ - * - * @author rkuttan - */ -public class LoaderQueryRequestDelegate extends RequestHandlerDelegate { - /** log **/ - protected final Log log = LogFactory.getLog(getClass()); - protected static Log logesapi = LogFactory.getLog(LoaderQueryRequestDelegate.class); - - /** - * @see edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate#handleRequest(java.lang.String) - */ - @Override - public String handleRequest(String requestXml, RequestHandler requestHandler) - throws I2B2Exception { - String response = null; - JAXBUtil jaxbUtil = CRCLoaderJAXBUtil.getJAXBUtil(); - - try { - JAXBElement jaxbElement = jaxbUtil.unMashallFromString(requestXml); - RequestMessageType requestMessageType = (RequestMessageType) jaxbElement - .getValue(); - BodyType bodyType = requestMessageType.getMessageBody(); - - if (bodyType == null) { - log.error("null value in body type"); - throw new I2B2Exception("null value in body type"); - } - - // Call PM cell to validate user - StatusType procStatus = null; - ProjectType projectType = null; - String projectId = null; - try { - - SecurityType securityType = null; - if (requestMessageType.getMessageHeader() != null) { - if (requestMessageType.getMessageHeader().getSecurity() != null) { - securityType = requestMessageType.getMessageHeader() - .getSecurity(); - } - projectId = requestMessageType.getMessageHeader() - .getProjectId(); - } - if (securityType == null) { - procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus - .setValue("Request message missing user/password"); - response = I2B2MessageResponseFactory.buildResponseMessage( - requestXml, procStatus, bodyType); - return response; - } - - PMServiceDriver pmServiceDriver = new PMServiceDriver(); - projectType = pmServiceDriver.checkValidUser(securityType, - projectId); - if (projectType == null) { - procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus - .setValue("Invalid user/password for the given domain"); - response = I2B2MessageResponseFactory.buildResponseMessage( - requestXml, procStatus, bodyType); - return response; - } - - log.debug("project name from PM " + projectType.getName()); - logesapi.debug("project id from PM " + projectType.getId()); - if (projectType.getRole().get(0) != null) { - log.debug("Project role from PM " - + projectType.getRole().get(0)); - } else { - log.warn("project role not set for user [" - + securityType.getUsername() + "]"); - } - - } catch (AxisFault e) { - procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus.setValue("Could not connect to server"); - response = I2B2MessageResponseFactory.buildResponseMessage( - requestXml, procStatus, bodyType); - return response; - } catch (I2B2Exception e) { - procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus - .setValue("Message error connecting Project Management cell"); - response = I2B2MessageResponseFactory.buildResponseMessage( - requestXml, procStatus, bodyType); - return response; - } catch (JAXBUtilException e) { - procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus - .setValue("Message error from Project Management cell"); - response = I2B2MessageResponseFactory.buildResponseMessage( - requestXml, procStatus, bodyType); - return response; - } - - JAXBUnWrapHelper unWrapHelper = new JAXBUnWrapHelper(); - - BodyType responseBodyType = null; - if (requestHandler instanceof PublishDataRequestHandler) { - String irodsStorageResource = null; - for (ParamType paramType : projectType.getParam()) { - - if (paramType.getName().equalsIgnoreCase( - "SRBDefaultStorageResource")) { - irodsStorageResource = paramType.getValue(); - log.debug("param value for SRBDefaultStorageResource" - + paramType.getValue()); - } - } - ((PublishDataRequestHandler) requestHandler) - .setIrodsDefaultStorageResource(irodsStorageResource); - } - - responseBodyType = requestHandler.execute(); - - procStatus = new StatusType(); - procStatus.setType("DONE"); - procStatus.setValue("DONE"); - - response = I2B2MessageResponseFactory.buildResponseMessage( - requestXml, procStatus, responseBodyType, true); - - } catch (JAXBUtilException e) { - log.error("JAXBUtil exception", e); - StatusType procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus.setValue(requestXml + "\n\n" - + StackTraceUtil.getStackTrace(e)); - try { - response = I2B2MessageResponseFactory.buildResponseMessage( - null, procStatus, null); - } catch (JAXBUtilException e1) { - e1.printStackTrace(); - } - } catch (I2B2Exception e) { - log.error("I2B2Exception", e); - StatusType procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus.setValue(StackTraceUtil.getStackTrace(e)); - try { - response = I2B2MessageResponseFactory.buildResponseMessage( - requestXml, procStatus, null); - } catch (JAXBUtilException e1) { - e1.printStackTrace(); - } - } catch (Throwable e) { - log.error("Throwable", e); - StatusType procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus.setValue(StackTraceUtil.getStackTrace(e)); - try { - response = I2B2MessageResponseFactory.buildResponseMessage( - requestXml, procStatus, null); - } catch (JAXBUtilException e1) { - e1.printStackTrace(); - } - } - return response; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.loader.delegate; + +import jakarta.xml.bind.JAXBElement; + +import org.apache.axis2.AxisFault; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.exception.StackTraceUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.loader.datavo.CRCLoaderJAXBUtil; +import edu.harvard.i2b2.crc.loader.datavo.I2B2MessageResponseFactory; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; +import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; +import edu.harvard.i2b2.crc.datavo.pm.ParamType; +import edu.harvard.i2b2.crc.datavo.pm.ProjectType; +import edu.harvard.i2b2.crc.loader.delegate.pm.PMServiceDriver; +import edu.harvard.i2b2.crc.util.I2B2RequestMessageHelper; + +/** + * PDO query request delegate class $Id: LoaderQueryRequestDelegate.java,v 1.3 + * 2008/02/26 23:09:59 rk903 Exp $ + * + * @author rkuttan + */ +public class LoaderQueryRequestDelegate extends RequestHandlerDelegate { + /** log **/ + protected final Log log = LogFactory.getLog(getClass()); + protected static Log logesapi = LogFactory.getLog(LoaderQueryRequestDelegate.class); + + /** + * @see edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate#handleRequest(java.lang.String) + */ + @Override + public String handleRequest(String requestXml, RequestHandler requestHandler) + throws I2B2Exception { + String response = null; + JAXBUtil jaxbUtil = CRCLoaderJAXBUtil.getJAXBUtil(); + + try { + JAXBElement jaxbElement = jaxbUtil.unMashallFromString(requestXml); + RequestMessageType requestMessageType = (RequestMessageType) jaxbElement + .getValue(); + BodyType bodyType = requestMessageType.getMessageBody(); + + if (bodyType == null) { + log.error("null value in body type"); + throw new I2B2Exception("null value in body type"); + } + + // Call PM cell to validate user + StatusType procStatus = null; + ProjectType projectType = null; + String projectId = null; + try { + + SecurityType securityType = null; + if (requestMessageType.getMessageHeader() != null) { + if (requestMessageType.getMessageHeader().getSecurity() != null) { + securityType = requestMessageType.getMessageHeader() + .getSecurity(); + } + projectId = requestMessageType.getMessageHeader() + .getProjectId(); + } + if (securityType == null) { + procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus + .setValue("Request message missing user/password"); + response = I2B2MessageResponseFactory.buildResponseMessage( + requestXml, procStatus, bodyType); + return response; + } + + PMServiceDriver pmServiceDriver = new PMServiceDriver(); + projectType = pmServiceDriver.checkValidUser(securityType, + projectId); + if (projectType == null) { + procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus + .setValue("Invalid user/password for the given domain"); + response = I2B2MessageResponseFactory.buildResponseMessage( + requestXml, procStatus, bodyType); + return response; + } + + log.debug("project name from PM " + projectType.getName()); + logesapi.debug("project id from PM " + projectType.getId()); + if (projectType.getRole().get(0) != null) { + log.debug("Project role from PM " + + projectType.getRole().get(0)); + } else { + log.warn("project role not set for user [" + + securityType.getUsername() + "]"); + } + + } catch (AxisFault e) { + procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus.setValue("Could not connect to server"); + response = I2B2MessageResponseFactory.buildResponseMessage( + requestXml, procStatus, bodyType); + return response; + } catch (I2B2Exception e) { + procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus + .setValue("Message error connecting Project Management cell"); + response = I2B2MessageResponseFactory.buildResponseMessage( + requestXml, procStatus, bodyType); + return response; + } catch (JAXBUtilException e) { + procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus + .setValue("Message error from Project Management cell"); + response = I2B2MessageResponseFactory.buildResponseMessage( + requestXml, procStatus, bodyType); + return response; + } + + JAXBUnWrapHelper unWrapHelper = new JAXBUnWrapHelper(); + + BodyType responseBodyType = null; + if (requestHandler instanceof PublishDataRequestHandler) { + String irodsStorageResource = null; + for (ParamType paramType : projectType.getParam()) { + + if (paramType.getName().equalsIgnoreCase( + "SRBDefaultStorageResource")) { + irodsStorageResource = paramType.getValue(); + log.debug("param value for SRBDefaultStorageResource" + + paramType.getValue()); + } + } + ((PublishDataRequestHandler) requestHandler) + .setIrodsDefaultStorageResource(irodsStorageResource); + } + + responseBodyType = requestHandler.execute(); + + procStatus = new StatusType(); + procStatus.setType("DONE"); + procStatus.setValue("DONE"); + + response = I2B2MessageResponseFactory.buildResponseMessage( + requestXml, procStatus, responseBodyType, true); + + } catch (JAXBUtilException e) { + log.error("JAXBUtil exception", e); + StatusType procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus.setValue(requestXml + "\n\n" + + StackTraceUtil.getStackTrace(e)); + try { + response = I2B2MessageResponseFactory.buildResponseMessage( + null, procStatus, null); + } catch (JAXBUtilException e1) { + e1.printStackTrace(); + } + } catch (I2B2Exception e) { + log.error("I2B2Exception", e); + StatusType procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus.setValue(StackTraceUtil.getStackTrace(e)); + try { + response = I2B2MessageResponseFactory.buildResponseMessage( + requestXml, procStatus, null); + } catch (JAXBUtilException e1) { + e1.printStackTrace(); + } + } catch (Throwable e) { + log.error("Throwable", e); + StatusType procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus.setValue(StackTraceUtil.getStackTrace(e)); + try { + response = I2B2MessageResponseFactory.buildResponseMessage( + requestXml, procStatus, null); + } catch (JAXBUtilException e1) { + e1.printStackTrace(); + } + } + return response; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/delegate/PublishDataRequestHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/delegate/PublishDataRequestHandler.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/delegate/PublishDataRequestHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/delegate/PublishDataRequestHandler.java index ee751dc7..8cb31d82 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/delegate/PublishDataRequestHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/delegate/PublishDataRequestHandler.java @@ -1,113 +1,113 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.delegate; - -import java.io.StringWriter; - -import jakarta.xml.bind.JAXBElement; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.loader.datavo.CRCLoaderJAXBUtil; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; -import edu.harvard.i2b2.crc.loader.datavo.loader.query.LoadDataResponseType; -import edu.harvard.i2b2.crc.loader.datavo.loader.query.PublishDataRequestType; -import edu.harvard.i2b2.crc.loader.ejb.DataMartLoaderAsyncBean; - -public class PublishDataRequestHandler extends RequestHandler { - - PublishDataRequestType publishDataRequest = null; - MessageHeaderType messageHeaderType = null; - long timeout = 1; - protected String irodsDefaultStorageResource = null; - - public PublishDataRequestHandler(String requestXml) throws I2B2Exception { - try { - publishDataRequest = (PublishDataRequestType) this - .getRequestType( - requestXml, - edu.harvard.i2b2.crc.loader.datavo.loader.query.PublishDataRequestType.class); - messageHeaderType = getMessageHeaderType(requestXml); - timeout = getTimeout(requestXml); - this.setDataSourceLookup(requestXml); - } catch (JAXBUtilException jaxbUtilEx) { - throw new I2B2Exception("Error ", jaxbUtilEx); - } - } - - @Override - public BodyType execute() throws I2B2Exception { - edu.harvard.i2b2.crc.loader.datavo.loader.query.ObjectFactory objectFactory = new edu.harvard.i2b2.crc.loader.datavo.loader.query.ObjectFactory(); - // call ejb and pass input object - String responseString = null; - BodyType bodyType = new BodyType(); - - // DataMartLoaderAsyncBeanLocal loader = CRCLoaderUtil.getInstance() - // .getDataMartLoaderBean(); - - DataMartLoaderAsyncBean loader = new DataMartLoaderAsyncBean(); - JAXBUtil jaxbUtil = CRCLoaderJAXBUtil.getJAXBUtil(); - StringWriter strWriter = new StringWriter(); - try { - jaxbUtil.marshaller(objectFactory - .createPublishDataRequest(publishDataRequest), strWriter); - } catch (JAXBUtilException jaxbEx) { - throw new I2B2Exception("Error in marshalling publishdata request", - jaxbEx); - } - SecurityType securityType = messageHeaderType.getSecurity(); - - LoadDataResponseType response = loader.load(this.getDataSourceLookup(), - strWriter.toString(), securityType, timeout, this - .getIrodsDefaultStorageResource()); - - bodyType.getAny().add(objectFactory.createLoadDataResponse(response)); - - return bodyType; - - } - - public String getIrodsDefaultStorageResource() { - return irodsDefaultStorageResource; - } - - public void setIrodsDefaultStorageResource( - String irodsDefaultStorageResource) { - this.irodsDefaultStorageResource = irodsDefaultStorageResource; - } - - public long getTimeout(String xmlRequest) { - JAXBUtil jaxbUtil = CRCLoaderJAXBUtil.getJAXBUtil(); - JAXBElement jaxbElement = null; - long timeOutValue = 1; - try { - jaxbElement = jaxbUtil.unMashallFromString(xmlRequest); - - RequestMessageType requestMessageType = (RequestMessageType) jaxbElement - .getValue(); - - RequestHeaderType requestHeader = requestMessageType - .getRequestHeader(); - - if (requestHeader != null - && requestHeader.getResultWaittimeMs() > -1) { - timeOutValue = requestHeader.getResultWaittimeMs(); - } - } catch (JAXBUtilException e) { - log.error("Failed to read wait time from the request ", e); - } - return timeOutValue; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.delegate; + +import java.io.StringWriter; + +import jakarta.xml.bind.JAXBElement; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.loader.datavo.CRCLoaderJAXBUtil; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; +import edu.harvard.i2b2.crc.loader.datavo.loader.query.LoadDataResponseType; +import edu.harvard.i2b2.crc.loader.datavo.loader.query.PublishDataRequestType; +import edu.harvard.i2b2.crc.loader.ejb.DataMartLoaderAsyncBean; + +public class PublishDataRequestHandler extends RequestHandler { + + PublishDataRequestType publishDataRequest = null; + MessageHeaderType messageHeaderType = null; + long timeout = 1; + protected String irodsDefaultStorageResource = null; + + public PublishDataRequestHandler(String requestXml) throws I2B2Exception { + try { + publishDataRequest = (PublishDataRequestType) this + .getRequestType( + requestXml, + edu.harvard.i2b2.crc.loader.datavo.loader.query.PublishDataRequestType.class); + messageHeaderType = getMessageHeaderType(requestXml); + timeout = getTimeout(requestXml); + this.setDataSourceLookup(requestXml); + } catch (JAXBUtilException jaxbUtilEx) { + throw new I2B2Exception("Error ", jaxbUtilEx); + } + } + + @Override + public BodyType execute() throws I2B2Exception { + edu.harvard.i2b2.crc.loader.datavo.loader.query.ObjectFactory objectFactory = new edu.harvard.i2b2.crc.loader.datavo.loader.query.ObjectFactory(); + // call ejb and pass input object + String responseString = null; + BodyType bodyType = new BodyType(); + + // DataMartLoaderAsyncBeanLocal loader = CRCLoaderUtil.getInstance() + // .getDataMartLoaderBean(); + + DataMartLoaderAsyncBean loader = new DataMartLoaderAsyncBean(); + JAXBUtil jaxbUtil = CRCLoaderJAXBUtil.getJAXBUtil(); + StringWriter strWriter = new StringWriter(); + try { + jaxbUtil.marshaller(objectFactory + .createPublishDataRequest(publishDataRequest), strWriter); + } catch (JAXBUtilException jaxbEx) { + throw new I2B2Exception("Error in marshalling publishdata request", + jaxbEx); + } + SecurityType securityType = messageHeaderType.getSecurity(); + + LoadDataResponseType response = loader.load(this.getDataSourceLookup(), + strWriter.toString(), securityType, timeout, this + .getIrodsDefaultStorageResource()); + + bodyType.getAny().add(objectFactory.createLoadDataResponse(response)); + + return bodyType; + + } + + public String getIrodsDefaultStorageResource() { + return irodsDefaultStorageResource; + } + + public void setIrodsDefaultStorageResource( + String irodsDefaultStorageResource) { + this.irodsDefaultStorageResource = irodsDefaultStorageResource; + } + + public long getTimeout(String xmlRequest) { + JAXBUtil jaxbUtil = CRCLoaderJAXBUtil.getJAXBUtil(); + JAXBElement jaxbElement = null; + long timeOutValue = 1; + try { + jaxbElement = jaxbUtil.unMashallFromString(xmlRequest); + + RequestMessageType requestMessageType = (RequestMessageType) jaxbElement + .getValue(); + + RequestHeaderType requestHeader = requestMessageType + .getRequestHeader(); + + if (requestHeader != null + && requestHeader.getResultWaittimeMs() > -1) { + timeOutValue = requestHeader.getResultWaittimeMs(); + } + } catch (JAXBUtilException e) { + log.error("Failed to read wait time from the request ", e); + } + return timeOutValue; + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/delegate/RequestHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/delegate/RequestHandler.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/delegate/RequestHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/delegate/RequestHandler.java index ea03f874..fee443a6 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/delegate/RequestHandler.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/delegate/RequestHandler.java @@ -1,218 +1,218 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.loader.delegate; - -import java.io.StringWriter; - -import jakarta.xml.bind.JAXBElement; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; - -import edu.harvard.i2b2.crc.loader.datavo.CRCLoaderJAXBUtil; -import edu.harvard.i2b2.crc.datavo.i2b2message.ApplicationType; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2message.InfoType; -import edu.harvard.i2b2.crc.datavo.i2b2message.MessageControlIdType; -import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.PollingUrlType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResultStatusType; -import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; -import edu.harvard.i2b2.crc.loader.datavo.loader.DataSourceLookup; - - -/** - * Top level class to process the request. There will be - * seperate requesthandler class for each request type. - * The main processing of for the request will be done inside - * execute function - * $Id: RequestHandler.java,v 1.4 2008/06/03 20:48:19 rk903 Exp $ - * @author rkuttan - */ -public abstract class RequestHandler { - /** log **/ - protected final Log log = LogFactory.getLog(getClass()); - protected DataSourceLookup dataSourceLookup = null; - - /** - * Function to perform operation on the given - * request - * @return response xml message - */ - public abstract BodyType execute() throws I2B2Exception; - - /** - * Class to fetch specific request message - * from i2b2 message xml - * @param requestXml - * @param classname - * @return object which is of type classname - * @throws JAXBUtilException - */ - protected Object getRequestType(String requestXml, Class classname) - throws JAXBUtilException { - Object returnObject = null; - - JAXBUtil jaxbUtil = CRCLoaderJAXBUtil.getJAXBUtil(); - JAXBElement jaxbElement = jaxbUtil.unMashallFromString(requestXml); - RequestMessageType requestMessageType = (RequestMessageType) jaxbElement.getValue(); - BodyType bodyType = requestMessageType.getMessageBody(); - JAXBUnWrapHelper unWrapHelper = new JAXBUnWrapHelper(); - //get request header type - returnObject = unWrapHelper.getObjectByClass(bodyType.getAny(), - classname); - return returnObject; - } - - protected MessageHeaderType getMessageHeaderType(String requestXml) - throws JAXBUtilException { - JAXBUtil jaxbUtil = CRCLoaderJAXBUtil.getJAXBUtil(); - JAXBElement jaxbElement = jaxbUtil.unMashallFromString(requestXml); - RequestMessageType requestMessageType = (RequestMessageType) jaxbElement.getValue(); - - return requestMessageType.getMessageHeader(); - } - - /** - * Function to build response message type - * using given bodytype and request xml - * @param requestXml - * @param bodyType - * @return i2b2 response message xml - * @throws JAXBUtilException - */ - protected String buildResponseMessage(String requestXml, BodyType bodyType) - throws JAXBUtilException { - JAXBUtil util = CRCLoaderJAXBUtil.getJAXBUtil(); - RequestMessageType requestMsgType = getI2B2RequestMessageType(requestXml); - MessageHeaderType messageHeader = requestMsgType.getMessageHeader(); - - //reverse sending and receiving app - ApplicationType sendingApp = messageHeader.getSendingApplication(); - ApplicationType receiveApp = messageHeader.getReceivingApplication(); - messageHeader.setSendingApplication(receiveApp); - messageHeader.setReceivingApplication(sendingApp); - - //set instance num - MessageControlIdType messageControlIdType = messageHeader.getMessageControlId(); - - if (messageControlIdType != null) { - messageControlIdType.setInstanceNum(1); - } - - StatusType statusType = new StatusType(); - statusType.setType("DONE"); - - //:TODO statusType.setValue(sessionId); - PollingUrlType pollingType = new PollingUrlType(); - pollingType.setIntervalMs(100); - - //:TODO value come from property file - - ResultStatusType resultStatusType = new ResultStatusType(); - resultStatusType.setStatus(statusType); - resultStatusType.setPollingUrl(pollingType); - - InfoType infoType = new InfoType(); - //:TODO value come from property file - - infoType.setValue("Log information"); - - ResponseHeaderType responseHeader = new ResponseHeaderType(); - responseHeader.setResultStatus(resultStatusType); - responseHeader.setInfo(infoType); - - ResponseMessageType responseMessageType = new ResponseMessageType(); - responseMessageType.setMessageHeader(messageHeader); - responseMessageType.setResponseHeader(responseHeader); - responseMessageType.setMessageBody(bodyType); - - edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory(); - StringWriter strWriter = new StringWriter(); - util.marshaller(of.createResponse(responseMessageType), strWriter); - - return strWriter.toString(); - } - - /** - * Function to unmarshall i2b2 request message type - * @param requestXml - * @return RequestMessageType - * @throws JAXBUtilException - */ - protected RequestMessageType getI2B2RequestMessageType(String requestXml) - throws JAXBUtilException { - JAXBUtil jaxbUtil = CRCLoaderJAXBUtil.getJAXBUtil(); - JAXBElement jaxbElement = jaxbUtil.unMashallFromString(requestXml); - RequestMessageType requestMessageType = (RequestMessageType) jaxbElement.getValue(); - - return requestMessageType; - } - - /** - * Function marshall i2b2 response message type - * @param responseMessageType - * @return - */ - protected String getResponseString(ResponseMessageType responseMessageType) { - StringWriter strWriter = new StringWriter(); - - try { - edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory(); - JAXBUtil jaxbUtil = CRCLoaderJAXBUtil.getJAXBUtil(); - jaxbUtil.marshaller(of.createResponse(responseMessageType), - strWriter); - } catch (JAXBUtilException e) { - log.error("Error while generating response message" + - e.getMessage()); - } - - return strWriter.toString(); - } - - protected edu.harvard.i2b2.crc.loader.datavo.loader.query.StatusType buildCRCStausType(String statusType,String message) { - edu.harvard.i2b2.crc.loader.datavo.loader.query.StatusType st = new edu.harvard.i2b2.crc.loader.datavo.loader.query.StatusType(); - edu.harvard.i2b2.crc.loader.datavo.loader.query.StatusType.Condition condition = new edu.harvard.i2b2.crc.loader.datavo.loader.query.StatusType.Condition(); - condition.setType(statusType); - condition.setValue(message); - st.getCondition().add(condition); - return st; - } - - protected void setDataSourceLookup(String requestXml) throws JAXBUtilException { - RequestMessageType reqMessage = getI2B2RequestMessageType(requestXml); - String projectId = reqMessage.getMessageHeader().getProjectId(); - String domainId = reqMessage.getMessageHeader().getSecurity().getDomain(); - String userId = reqMessage.getMessageHeader().getSecurity().getUsername(); - dataSourceLookup = new DataSourceLookup(); - dataSourceLookup.setProjectPath(projectId); - dataSourceLookup.setDomainId(domainId); - dataSourceLookup.setOwnerId(userId); - - } - - protected DataSourceLookup getDataSourceLookup() { - return dataSourceLookup; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.loader.delegate; + +import java.io.StringWriter; + +import jakarta.xml.bind.JAXBElement; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; + +import edu.harvard.i2b2.crc.loader.datavo.CRCLoaderJAXBUtil; +import edu.harvard.i2b2.crc.datavo.i2b2message.ApplicationType; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2message.InfoType; +import edu.harvard.i2b2.crc.datavo.i2b2message.MessageControlIdType; +import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.PollingUrlType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResultStatusType; +import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; +import edu.harvard.i2b2.crc.loader.datavo.loader.DataSourceLookup; + + +/** + * Top level class to process the request. There will be + * seperate requesthandler class for each request type. + * The main processing of for the request will be done inside + * execute function + * $Id: RequestHandler.java,v 1.4 2008/06/03 20:48:19 rk903 Exp $ + * @author rkuttan + */ +public abstract class RequestHandler { + /** log **/ + protected final Log log = LogFactory.getLog(getClass()); + protected DataSourceLookup dataSourceLookup = null; + + /** + * Function to perform operation on the given + * request + * @return response xml message + */ + public abstract BodyType execute() throws I2B2Exception; + + /** + * Class to fetch specific request message + * from i2b2 message xml + * @param requestXml + * @param classname + * @return object which is of type classname + * @throws JAXBUtilException + */ + protected Object getRequestType(String requestXml, Class classname) + throws JAXBUtilException { + Object returnObject = null; + + JAXBUtil jaxbUtil = CRCLoaderJAXBUtil.getJAXBUtil(); + JAXBElement jaxbElement = jaxbUtil.unMashallFromString(requestXml); + RequestMessageType requestMessageType = (RequestMessageType) jaxbElement.getValue(); + BodyType bodyType = requestMessageType.getMessageBody(); + JAXBUnWrapHelper unWrapHelper = new JAXBUnWrapHelper(); + //get request header type + returnObject = unWrapHelper.getObjectByClass(bodyType.getAny(), + classname); + return returnObject; + } + + protected MessageHeaderType getMessageHeaderType(String requestXml) + throws JAXBUtilException { + JAXBUtil jaxbUtil = CRCLoaderJAXBUtil.getJAXBUtil(); + JAXBElement jaxbElement = jaxbUtil.unMashallFromString(requestXml); + RequestMessageType requestMessageType = (RequestMessageType) jaxbElement.getValue(); + + return requestMessageType.getMessageHeader(); + } + + /** + * Function to build response message type + * using given bodytype and request xml + * @param requestXml + * @param bodyType + * @return i2b2 response message xml + * @throws JAXBUtilException + */ + protected String buildResponseMessage(String requestXml, BodyType bodyType) + throws JAXBUtilException { + JAXBUtil util = CRCLoaderJAXBUtil.getJAXBUtil(); + RequestMessageType requestMsgType = getI2B2RequestMessageType(requestXml); + MessageHeaderType messageHeader = requestMsgType.getMessageHeader(); + + //reverse sending and receiving app + ApplicationType sendingApp = messageHeader.getSendingApplication(); + ApplicationType receiveApp = messageHeader.getReceivingApplication(); + messageHeader.setSendingApplication(receiveApp); + messageHeader.setReceivingApplication(sendingApp); + + //set instance num + MessageControlIdType messageControlIdType = messageHeader.getMessageControlId(); + + if (messageControlIdType != null) { + messageControlIdType.setInstanceNum(1); + } + + StatusType statusType = new StatusType(); + statusType.setType("DONE"); + + //:TODO statusType.setValue(sessionId); + PollingUrlType pollingType = new PollingUrlType(); + pollingType.setIntervalMs(100); + + //:TODO value come from property file + + ResultStatusType resultStatusType = new ResultStatusType(); + resultStatusType.setStatus(statusType); + resultStatusType.setPollingUrl(pollingType); + + InfoType infoType = new InfoType(); + //:TODO value come from property file + + infoType.setValue("Log information"); + + ResponseHeaderType responseHeader = new ResponseHeaderType(); + responseHeader.setResultStatus(resultStatusType); + responseHeader.setInfo(infoType); + + ResponseMessageType responseMessageType = new ResponseMessageType(); + responseMessageType.setMessageHeader(messageHeader); + responseMessageType.setResponseHeader(responseHeader); + responseMessageType.setMessageBody(bodyType); + + edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory(); + StringWriter strWriter = new StringWriter(); + util.marshaller(of.createResponse(responseMessageType), strWriter); + + return strWriter.toString(); + } + + /** + * Function to unmarshall i2b2 request message type + * @param requestXml + * @return RequestMessageType + * @throws JAXBUtilException + */ + protected RequestMessageType getI2B2RequestMessageType(String requestXml) + throws JAXBUtilException { + JAXBUtil jaxbUtil = CRCLoaderJAXBUtil.getJAXBUtil(); + JAXBElement jaxbElement = jaxbUtil.unMashallFromString(requestXml); + RequestMessageType requestMessageType = (RequestMessageType) jaxbElement.getValue(); + + return requestMessageType; + } + + /** + * Function marshall i2b2 response message type + * @param responseMessageType + * @return + */ + protected String getResponseString(ResponseMessageType responseMessageType) { + StringWriter strWriter = new StringWriter(); + + try { + edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory(); + JAXBUtil jaxbUtil = CRCLoaderJAXBUtil.getJAXBUtil(); + jaxbUtil.marshaller(of.createResponse(responseMessageType), + strWriter); + } catch (JAXBUtilException e) { + log.error("Error while generating response message" + + e.getMessage()); + } + + return strWriter.toString(); + } + + protected edu.harvard.i2b2.crc.loader.datavo.loader.query.StatusType buildCRCStausType(String statusType,String message) { + edu.harvard.i2b2.crc.loader.datavo.loader.query.StatusType st = new edu.harvard.i2b2.crc.loader.datavo.loader.query.StatusType(); + edu.harvard.i2b2.crc.loader.datavo.loader.query.StatusType.Condition condition = new edu.harvard.i2b2.crc.loader.datavo.loader.query.StatusType.Condition(); + condition.setType(statusType); + condition.setValue(message); + st.getCondition().add(condition); + return st; + } + + protected void setDataSourceLookup(String requestXml) throws JAXBUtilException { + RequestMessageType reqMessage = getI2B2RequestMessageType(requestXml); + String projectId = reqMessage.getMessageHeader().getProjectId(); + String domainId = reqMessage.getMessageHeader().getSecurity().getDomain(); + String userId = reqMessage.getMessageHeader().getSecurity().getUsername(); + dataSourceLookup = new DataSourceLookup(); + dataSourceLookup.setProjectPath(projectId); + dataSourceLookup.setDomainId(domainId); + dataSourceLookup.setOwnerId(userId); + + } + + protected DataSourceLookup getDataSourceLookup() { + return dataSourceLookup; + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/delegate/RequestHandlerDelegate.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/delegate/RequestHandlerDelegate.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/delegate/RequestHandlerDelegate.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/delegate/RequestHandlerDelegate.java index ff911cbf..5332a15a --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/delegate/RequestHandlerDelegate.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/delegate/RequestHandlerDelegate.java @@ -1,96 +1,96 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.loader.delegate; - -import java.io.StringWriter; - -import jakarta.xml.bind.JAXBElement; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.crc.loader.datavo.CRCLoaderJAXBUtil; - - -/** - * Class to delegate i2b2 requests to appropriate - * {@link RequestHandler} - * Class unwraps i2b2 request message and based on the - * request type, the request will be delegated to appropriate - * request handler by calling execute function. The return value - * from execute function is just passed back to the client - * $Id: RequestHandlerDelegate.java,v 1.2 2008/02/04 22:14:28 rk903 Exp $ - * @author rkuttan - */ -public abstract class RequestHandlerDelegate { - /** log **/ - protected final Log log = LogFactory.getLog(getClass()); - - public static final String ERROR_TYPE = "ERROR"; - public static final String DONE_TYPE = "DONE"; - - /** - * Function to delegate request to appropriate - * request handler class and passes back the - * response message output back to client - * @param requestXml - * @return response message xml - * @throws I2B2Exception - */ - public abstract String handleRequest(String requestXml,RequestHandler requestHandler) throws I2B2Exception; - - - - /** - * Function to unmarshall i2b2 request message type - * @param requestXml - * @return RequestMessageType - * @throws JAXBUtilException - */ - protected RequestMessageType getI2B2RequestMessageType(String requestXml) - throws JAXBUtilException { - JAXBUtil jaxbUtil = CRCLoaderJAXBUtil.getJAXBUtil(); - JAXBElement jaxbElement = jaxbUtil.unMashallFromString(requestXml); - RequestMessageType requestMessageType = (RequestMessageType) jaxbElement.getValue(); - - return requestMessageType; - } - - /** - * Function marshall i2b2 response message type - * @param responseMessageType - * @return - */ - protected String getResponseString(ResponseMessageType responseMessageType) { - StringWriter strWriter = new StringWriter(); - - try { - edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory(); - JAXBUtil jaxbUtil = CRCLoaderJAXBUtil.getJAXBUtil(); - jaxbUtil.marshaller(of.createResponse(responseMessageType), - strWriter); - } catch (JAXBUtilException e) { - log.error("Error while generating response message" + - e.getMessage()); - } - - return strWriter.toString(); - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.loader.delegate; + +import java.io.StringWriter; + +import jakarta.xml.bind.JAXBElement; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.crc.loader.datavo.CRCLoaderJAXBUtil; + + +/** + * Class to delegate i2b2 requests to appropriate + * {@link RequestHandler} + * Class unwraps i2b2 request message and based on the + * request type, the request will be delegated to appropriate + * request handler by calling execute function. The return value + * from execute function is just passed back to the client + * $Id: RequestHandlerDelegate.java,v 1.2 2008/02/04 22:14:28 rk903 Exp $ + * @author rkuttan + */ +public abstract class RequestHandlerDelegate { + /** log **/ + protected final Log log = LogFactory.getLog(getClass()); + + public static final String ERROR_TYPE = "ERROR"; + public static final String DONE_TYPE = "DONE"; + + /** + * Function to delegate request to appropriate + * request handler class and passes back the + * response message output back to client + * @param requestXml + * @return response message xml + * @throws I2B2Exception + */ + public abstract String handleRequest(String requestXml,RequestHandler requestHandler) throws I2B2Exception; + + + + /** + * Function to unmarshall i2b2 request message type + * @param requestXml + * @return RequestMessageType + * @throws JAXBUtilException + */ + protected RequestMessageType getI2B2RequestMessageType(String requestXml) + throws JAXBUtilException { + JAXBUtil jaxbUtil = CRCLoaderJAXBUtil.getJAXBUtil(); + JAXBElement jaxbElement = jaxbUtil.unMashallFromString(requestXml); + RequestMessageType requestMessageType = (RequestMessageType) jaxbElement.getValue(); + + return requestMessageType; + } + + /** + * Function marshall i2b2 response message type + * @param responseMessageType + * @return + */ + protected String getResponseString(ResponseMessageType responseMessageType) { + StringWriter strWriter = new StringWriter(); + + try { + edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory(); + JAXBUtil jaxbUtil = CRCLoaderJAXBUtil.getJAXBUtil(); + jaxbUtil.marshaller(of.createResponse(responseMessageType), + strWriter); + } catch (JAXBUtilException e) { + log.error("Error while generating response message" + + e.getMessage()); + } + + return strWriter.toString(); + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/delegate/fr/CallFileRepositoryUtil.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/delegate/fr/CallFileRepositoryUtil.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/delegate/fr/CallFileRepositoryUtil.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/delegate/fr/CallFileRepositoryUtil.java index c830744b..db3e8f60 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/delegate/fr/CallFileRepositoryUtil.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/delegate/fr/CallFileRepositoryUtil.java @@ -1,338 +1,338 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.delegate.fr; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.StringReader; -import java.io.StringWriter; - -import javax.xml.stream.XMLInputFactory; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamReader; - -import jakarta.xml.bind.JAXBElement; - -import edu.harvard.i2b2.common.util.axis2.ServiceClient; -import org.apache.axiom.om.OMXMLBuilderFactory; - -import org.apache.axiom.attachments.Attachments; -import org.apache.axiom.om.OMElement; -import org.apache.axiom.soap.SOAPBody; -import org.apache.axis2.AxisFault; -import org.apache.axis2.client.Options; -import org.apache.axis2.context.MessageContext; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -//import edu.harvard.i2b2.common.util.axis2.ServiceClient; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.loader.datavo.CRCLoaderJAXBUtil; -import edu.harvard.i2b2.crc.loader.datavo.fr.ObjectFactory; -import edu.harvard.i2b2.crc.loader.datavo.fr.RecvfileRequestType; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2message.FacilityType; -import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResultStatusType; -import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; -import edu.harvard.i2b2.crc.loader.util.CRCLoaderUtil; - -/** - * - * @author rk903 - * - */ -public class CallFileRepositoryUtil { - - /** log **/ - protected final Log log = LogFactory.getLog(getClass()); - - private SecurityType securityType = null; - private String projectId = null; - private String frUrl = null; - - public CallFileRepositoryUtil(String requestXml) throws JAXBUtilException, - I2B2Exception { - JAXBElement responseJaxb = CRCLoaderJAXBUtil.getJAXBUtil() - .unMashallFromString(requestXml); - RequestMessageType request = (RequestMessageType) responseJaxb - .getValue(); - this.securityType = request.getMessageHeader().getSecurity(); - this.projectId = request.getMessageHeader().getProjectId(); - this.frUrl = CRCLoaderUtil.getInstance().getFileManagentCellUrl(); - - } - - public CallFileRepositoryUtil(SecurityType securityType, String projectId) - throws I2B2Exception { - this.securityType = securityType; - this.projectId = projectId; - this.frUrl = CRCLoaderUtil.getInstance().getFileManagentCellUrl(); - log.debug("file repository url " + frUrl); - } - - public CallFileRepositoryUtil(String frUrl, SecurityType securityType, - String projectId) throws I2B2Exception { - this(securityType, projectId); - this.frUrl = frUrl; - } - - public String callFileRepository(int uploadId, String fileRepositoryFileName) - throws I2B2Exception, AxisFault, JAXBUtilException { - String localFileName = null; - RequestMessageType requestMessageType = getI2B2RequestMessage(fileRepositoryFileName); - OMElement requestElement = buildOMElement(requestMessageType); - log.debug("FileRespository request message [" + requestElement + "]"); - MessageContext response = getResponseSOAPBody(requestElement); - localFileName = writeFileFromResponse(uploadId, response); - return localFileName; - } - - private ResultStatusType getI2B2ResponseStatus(OMElement response) - throws JAXBUtilException { - JAXBElement responseJaxb = CRCLoaderJAXBUtil.getJAXBUtil() - .unMashallFromString(response.toString()); - ResponseMessageType r = (ResponseMessageType) responseJaxb.getValue(); - return r.getResponseHeader().getResultStatus(); - } - - private OMElement buildOMElement(RequestMessageType requestMessageType) - throws I2B2Exception { - StringWriter strWriter = new StringWriter(); - edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory hiveof = new edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory(); - OMElement request = null; - try { - CRCLoaderJAXBUtil.getJAXBUtil().marshaller( - hiveof.createRequest(requestMessageType), strWriter); - StringReader strReader = new StringReader(strWriter.toString()); - XMLInputFactory xif = XMLInputFactory.newInstance(); - XMLStreamReader reader = xif.createXMLStreamReader(strReader); - request = OMXMLBuilderFactory.createStAXOMBuilder(reader).getDocumentElement(); - - } catch (XMLStreamException xmlEx) { - throw new I2B2Exception("FileRepository request omelement failed [" - + xmlEx.getMessage() + "]"); - } catch (JAXBUtilException jaxbEx) { - throw new I2B2Exception("FileRepository request omelement failed [" - + jaxbEx.getMessage() + "]"); - } - return request; - } - - private RequestMessageType getI2B2RequestMessage(String recvFileName) { - CRCLoaderUtil queryUtil = CRCLoaderUtil.getInstance(); - MessageHeaderType messageHeaderType = new MessageHeaderType(); - - //(MessageHeaderType) queryUtil - //.getSpringBeanFactory().getBean("message_header"); - messageHeaderType.setSecurity(securityType); - messageHeaderType.setProjectId(projectId); - - messageHeaderType.setReceivingApplication(messageHeaderType - .getSendingApplication()); - FacilityType facilityType = new FacilityType(); - facilityType.setFacilityName("sample"); - messageHeaderType.setSendingFacility(facilityType); - messageHeaderType.setReceivingFacility(facilityType); - // build message body - RecvfileRequestType recvFileRequestType = new RecvfileRequestType(); - recvFileRequestType.setFilename(recvFileName); - - RequestMessageType requestMessageType = new RequestMessageType(); - ObjectFactory of = new ObjectFactory(); - BodyType bodyType = new BodyType(); - bodyType.getAny().add(of.createRecvfileRequest(recvFileRequestType)); - requestMessageType.setMessageBody(bodyType); - - requestMessageType.setMessageHeader(messageHeaderType); - - RequestHeaderType requestHeader = new RequestHeaderType(); - requestHeader.setResultWaittimeMs(180000); - requestMessageType.setRequestHeader(requestHeader); - - return requestMessageType; - - } - - public String writeFileFromResponse(int uploadId, MessageContext response) - throws I2B2Exception { - String localFileName = null; - Attachments attach = response.getAttachmentMap(); // - // String[] ids = attach.getAllContentIDs(); - SOAPBody body = response.getEnvelope().getBody(); - if (attach != null) { - String attachmentName = CRCLoaderUtil.getInstance() - .getFileRepositoryAttachmentName(); - - jakarta.activation.DataHandler dataHandler2 = response - .getAttachment(attachmentName); - String processFolderName = CRCLoaderUtil.getInstance() - .getProcessFolderName(); - localFileName = processFolderName + File.separatorChar + uploadId - + ".xml"; - log.debug("Local file name [" + localFileName + "]"); - // Writing the attachment data to a file - File graphFile = new File(localFileName); - FileOutputStream outputStream; - try { - outputStream = new FileOutputStream(graphFile); - dataHandler2.writeTo(outputStream); - outputStream.flush(); - } catch (FileNotFoundException e) { - throw new I2B2Exception("Error creating local file [" - + localFileName + "] from file repository ", e); - } catch (IOException e) { - throw new I2B2Exception( - "IOException while creating local file [" - + localFileName + "] from file repository", e); - } - } else { - throw new I2B2Exception( - "Unable to create local file using file repository response"); - } - return localFileName; - } - - private MessageContext getResponseSOAPBody(OMElement requestElement) - throws I2B2Exception, AxisFault, JAXBUtilException { - MessageContext response = null; - // call - - - // ServiceClient serviceClient = new ServiceClient(); - - Options options = new Options(); - String frOperationName = CRCLoaderUtil.getInstance() - .getFileRepositoryOperationName(); - if (frOperationName == null) { - throw new I2B2Exception( - "File Repository operation property missing from the property file"); - } - - - response = ServiceClient.getSOAPFile(frUrl + "recvfileRequest", requestElement, frOperationName, CRCLoaderUtil.getInstance().getFileRepositoryTimeout() ); - - OMElement frResponse = (OMElement) response.getEnvelope().getBody() - .getFirstOMChild(); - log.debug("File Repository response body [: " + frResponse + "]"); - // read header status - ResultStatusType resultStatusType = getI2B2ResponseStatus(frResponse); - - // if the status type is error, then throw i2b2exception - if (resultStatusType.getStatus() != null - && resultStatusType.getStatus().getType() != null - && resultStatusType.getStatus().getType().equalsIgnoreCase( - "error")) { - String errorMsg = resultStatusType.getStatus().getValue(); - - throw new I2B2Exception( - "Unable to fetch file from file repository [" - + errorMsg + "]"); - } - - - - /* - log.debug("File Repository operation property value [" - + frOperationName + "]"); - options.setAction(frOperationName); - options.setSoapVersionURI(SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI); - String timeout = CRCLoaderUtil.getInstance().getFileRepositoryTimeout(); - log.debug("File Repository timeout property value [" + timeout + "]"); - // Increase the time out to receive large attachments - options.setTimeOutInMilliSeconds(Integer.parseInt(timeout)); - options.setProperty(Constants.Configuration.ENABLE_SWA, Constants.VALUE_TRUE); - options.setProperty(Constants.Configuration.ENABLE_MTOM, Constants.VALUE_FALSE); - - options.setProperty(Constants.Configuration.CACHE_ATTACHMENTS, - Constants.VALUE_TRUE); - options.setProperty(Constants.Configuration.ATTACHMENT_TEMP_DIR, - CRCLoaderUtil.getInstance().getFileRepositoryTempSpace()); - options.setProperty(Constants.Configuration.FILE_SIZE_THRESHOLD, - CRCLoaderUtil.getInstance().getFileRepositoryThreshold()); - options.setTo(new EndpointReference(frUrl)); - serviceClient.setOptions(options); - - try { - OperationClient mepClient = serviceClient - .createClient(ServiceClient.ANON_OUT_IN_OP); - MessageContext mc = new MessageContext(); - - //SOAPFactory sfac = OMAbstractFactory.getSOAP11Factory(); - SOAPFactory sfac = OMAbstractFactory.getSOAP12Factory(); - - SOAPEnvelope env = sfac.getDefaultEnvelope(); - env.getBody().addChild(requestElement); - - // SOAPEnvelope env = createEnvelope("fileattachment"); - mc.setEnvelope(env); - // mc.addAttachment("contentID",dataHandler); - mc.setDoingSwA(true); - mc.setDoingMTOM(false); - - mepClient.addMessageContext(mc); - mepClient.execute(true); - response = mepClient - .getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE); - log.debug("File Repository response envelope: " - + response.toString() + "]"); - OMElement frResponse = (OMElement) response.getEnvelope().getBody() - .getFirstOMChild(); - log.debug("File Repository response body [: " + frResponse + "]"); - // read header status - ResultStatusType resultStatusType = getI2B2ResponseStatus(frResponse); - - // if the status type is error, then throw i2b2exception - if (resultStatusType.getStatus() != null - && resultStatusType.getStatus().getType() != null - && resultStatusType.getStatus().getType().equalsIgnoreCase( - "error")) { - String errorMsg = resultStatusType.getStatus().getValue(); - - throw new I2B2Exception( - "Unable to fetch file from file repository [" - + errorMsg + "]"); - } - - OperationContext operationContext = mc.getOperationContext(); - MessageContext outMessageContext = operationContext - .getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE); - log - .debug("File Repository response has [" - + outMessageContext.getAttachmentMap() - .getAllContentIDs().length - + "] attachments"); - - - } catch (AxisFault axisFault) { - throw new I2B2Exception( - "Unable to fetch file from file repository :Axisfault [" - + axisFault.getCause().getMessage() + "]"); - } catch (JAXBUtilException jaxbUtilEx) { - throw new I2B2Exception( - "Unable to fetch file from file repository :Axisfault [" - + jaxbUtilEx.getMessage() + "]"); - } catch (Throwable t) { - t.printStackTrace(); - throw new I2B2Exception( - "Unable to fetch file from file repository :Axisfault [" - + t.getMessage() + "]"); - } - */ - return response; - - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.delegate.fr; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.StringReader; +import java.io.StringWriter; + +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import jakarta.xml.bind.JAXBElement; + +import edu.harvard.i2b2.common.util.axis2.ServiceClient; +import org.apache.axiom.om.OMXMLBuilderFactory; + +import org.apache.axiom.attachments.Attachments; +import org.apache.axiom.om.OMElement; +import org.apache.axiom.soap.SOAPBody; +import org.apache.axis2.AxisFault; +import org.apache.axis2.client.Options; +import org.apache.axis2.context.MessageContext; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +//import edu.harvard.i2b2.common.util.axis2.ServiceClient; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.loader.datavo.CRCLoaderJAXBUtil; +import edu.harvard.i2b2.crc.loader.datavo.fr.ObjectFactory; +import edu.harvard.i2b2.crc.loader.datavo.fr.RecvfileRequestType; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2message.FacilityType; +import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResultStatusType; +import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; +import edu.harvard.i2b2.crc.loader.util.CRCLoaderUtil; + +/** + * + * @author rk903 + * + */ +public class CallFileRepositoryUtil { + + /** log **/ + protected final Log log = LogFactory.getLog(getClass()); + + private SecurityType securityType = null; + private String projectId = null; + private String frUrl = null; + + public CallFileRepositoryUtil(String requestXml) throws JAXBUtilException, + I2B2Exception { + JAXBElement responseJaxb = CRCLoaderJAXBUtil.getJAXBUtil() + .unMashallFromString(requestXml); + RequestMessageType request = (RequestMessageType) responseJaxb + .getValue(); + this.securityType = request.getMessageHeader().getSecurity(); + this.projectId = request.getMessageHeader().getProjectId(); + this.frUrl = CRCLoaderUtil.getInstance().getFileManagentCellUrl(); + + } + + public CallFileRepositoryUtil(SecurityType securityType, String projectId) + throws I2B2Exception { + this.securityType = securityType; + this.projectId = projectId; + this.frUrl = CRCLoaderUtil.getInstance().getFileManagentCellUrl(); + log.debug("file repository url " + frUrl); + } + + public CallFileRepositoryUtil(String frUrl, SecurityType securityType, + String projectId) throws I2B2Exception { + this(securityType, projectId); + this.frUrl = frUrl; + } + + public String callFileRepository(int uploadId, String fileRepositoryFileName) + throws I2B2Exception, AxisFault, JAXBUtilException { + String localFileName = null; + RequestMessageType requestMessageType = getI2B2RequestMessage(fileRepositoryFileName); + OMElement requestElement = buildOMElement(requestMessageType); + log.debug("FileRespository request message [" + requestElement + "]"); + MessageContext response = getResponseSOAPBody(requestElement); + localFileName = writeFileFromResponse(uploadId, response); + return localFileName; + } + + private ResultStatusType getI2B2ResponseStatus(OMElement response) + throws JAXBUtilException { + JAXBElement responseJaxb = CRCLoaderJAXBUtil.getJAXBUtil() + .unMashallFromString(response.toString()); + ResponseMessageType r = (ResponseMessageType) responseJaxb.getValue(); + return r.getResponseHeader().getResultStatus(); + } + + private OMElement buildOMElement(RequestMessageType requestMessageType) + throws I2B2Exception { + StringWriter strWriter = new StringWriter(); + edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory hiveof = new edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory(); + OMElement request = null; + try { + CRCLoaderJAXBUtil.getJAXBUtil().marshaller( + hiveof.createRequest(requestMessageType), strWriter); + StringReader strReader = new StringReader(strWriter.toString()); + XMLInputFactory xif = XMLInputFactory.newInstance(); + XMLStreamReader reader = xif.createXMLStreamReader(strReader); + request = OMXMLBuilderFactory.createStAXOMBuilder(reader).getDocumentElement(); + + } catch (XMLStreamException xmlEx) { + throw new I2B2Exception("FileRepository request omelement failed [" + + xmlEx.getMessage() + "]"); + } catch (JAXBUtilException jaxbEx) { + throw new I2B2Exception("FileRepository request omelement failed [" + + jaxbEx.getMessage() + "]"); + } + return request; + } + + private RequestMessageType getI2B2RequestMessage(String recvFileName) { + CRCLoaderUtil queryUtil = CRCLoaderUtil.getInstance(); + MessageHeaderType messageHeaderType = new MessageHeaderType(); + + //(MessageHeaderType) queryUtil + //.getSpringBeanFactory().getBean("message_header"); + messageHeaderType.setSecurity(securityType); + messageHeaderType.setProjectId(projectId); + + messageHeaderType.setReceivingApplication(messageHeaderType + .getSendingApplication()); + FacilityType facilityType = new FacilityType(); + facilityType.setFacilityName("sample"); + messageHeaderType.setSendingFacility(facilityType); + messageHeaderType.setReceivingFacility(facilityType); + // build message body + RecvfileRequestType recvFileRequestType = new RecvfileRequestType(); + recvFileRequestType.setFilename(recvFileName); + + RequestMessageType requestMessageType = new RequestMessageType(); + ObjectFactory of = new ObjectFactory(); + BodyType bodyType = new BodyType(); + bodyType.getAny().add(of.createRecvfileRequest(recvFileRequestType)); + requestMessageType.setMessageBody(bodyType); + + requestMessageType.setMessageHeader(messageHeaderType); + + RequestHeaderType requestHeader = new RequestHeaderType(); + requestHeader.setResultWaittimeMs(180000); + requestMessageType.setRequestHeader(requestHeader); + + return requestMessageType; + + } + + public String writeFileFromResponse(int uploadId, MessageContext response) + throws I2B2Exception { + String localFileName = null; + Attachments attach = response.getAttachmentMap(); // + // String[] ids = attach.getAllContentIDs(); + SOAPBody body = response.getEnvelope().getBody(); + if (attach != null) { + String attachmentName = CRCLoaderUtil.getInstance() + .getFileRepositoryAttachmentName(); + + jakarta.activation.DataHandler dataHandler2 = response + .getAttachment(attachmentName); + String processFolderName = CRCLoaderUtil.getInstance() + .getProcessFolderName(); + localFileName = processFolderName + File.separatorChar + uploadId + + ".xml"; + log.debug("Local file name [" + localFileName + "]"); + // Writing the attachment data to a file + File graphFile = new File(localFileName); + FileOutputStream outputStream; + try { + outputStream = new FileOutputStream(graphFile); + dataHandler2.writeTo(outputStream); + outputStream.flush(); + } catch (FileNotFoundException e) { + throw new I2B2Exception("Error creating local file [" + + localFileName + "] from file repository ", e); + } catch (IOException e) { + throw new I2B2Exception( + "IOException while creating local file [" + + localFileName + "] from file repository", e); + } + } else { + throw new I2B2Exception( + "Unable to create local file using file repository response"); + } + return localFileName; + } + + private MessageContext getResponseSOAPBody(OMElement requestElement) + throws I2B2Exception, AxisFault, JAXBUtilException { + MessageContext response = null; + // call + + + // ServiceClient serviceClient = new ServiceClient(); + + Options options = new Options(); + String frOperationName = CRCLoaderUtil.getInstance() + .getFileRepositoryOperationName(); + if (frOperationName == null) { + throw new I2B2Exception( + "File Repository operation property missing from the property file"); + } + + + response = ServiceClient.getSOAPFile(frUrl + "recvfileRequest", requestElement, frOperationName, CRCLoaderUtil.getInstance().getFileRepositoryTimeout() ); + + OMElement frResponse = (OMElement) response.getEnvelope().getBody() + .getFirstOMChild(); + log.debug("File Repository response body [: " + frResponse + "]"); + // read header status + ResultStatusType resultStatusType = getI2B2ResponseStatus(frResponse); + + // if the status type is error, then throw i2b2exception + if (resultStatusType.getStatus() != null + && resultStatusType.getStatus().getType() != null + && resultStatusType.getStatus().getType().equalsIgnoreCase( + "error")) { + String errorMsg = resultStatusType.getStatus().getValue(); + + throw new I2B2Exception( + "Unable to fetch file from file repository [" + + errorMsg + "]"); + } + + + + /* + log.debug("File Repository operation property value [" + + frOperationName + "]"); + options.setAction(frOperationName); + options.setSoapVersionURI(SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI); + String timeout = CRCLoaderUtil.getInstance().getFileRepositoryTimeout(); + log.debug("File Repository timeout property value [" + timeout + "]"); + // Increase the time out to receive large attachments + options.setTimeOutInMilliSeconds(Integer.parseInt(timeout)); + options.setProperty(Constants.Configuration.ENABLE_SWA, Constants.VALUE_TRUE); + options.setProperty(Constants.Configuration.ENABLE_MTOM, Constants.VALUE_FALSE); + + options.setProperty(Constants.Configuration.CACHE_ATTACHMENTS, + Constants.VALUE_TRUE); + options.setProperty(Constants.Configuration.ATTACHMENT_TEMP_DIR, + CRCLoaderUtil.getInstance().getFileRepositoryTempSpace()); + options.setProperty(Constants.Configuration.FILE_SIZE_THRESHOLD, + CRCLoaderUtil.getInstance().getFileRepositoryThreshold()); + options.setTo(new EndpointReference(frUrl)); + serviceClient.setOptions(options); + + try { + OperationClient mepClient = serviceClient + .createClient(ServiceClient.ANON_OUT_IN_OP); + MessageContext mc = new MessageContext(); + + //SOAPFactory sfac = OMAbstractFactory.getSOAP11Factory(); + SOAPFactory sfac = OMAbstractFactory.getSOAP12Factory(); + + SOAPEnvelope env = sfac.getDefaultEnvelope(); + env.getBody().addChild(requestElement); + + // SOAPEnvelope env = createEnvelope("fileattachment"); + mc.setEnvelope(env); + // mc.addAttachment("contentID",dataHandler); + mc.setDoingSwA(true); + mc.setDoingMTOM(false); + + mepClient.addMessageContext(mc); + mepClient.execute(true); + response = mepClient + .getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE); + log.debug("File Repository response envelope: " + + response.toString() + "]"); + OMElement frResponse = (OMElement) response.getEnvelope().getBody() + .getFirstOMChild(); + log.debug("File Repository response body [: " + frResponse + "]"); + // read header status + ResultStatusType resultStatusType = getI2B2ResponseStatus(frResponse); + + // if the status type is error, then throw i2b2exception + if (resultStatusType.getStatus() != null + && resultStatusType.getStatus().getType() != null + && resultStatusType.getStatus().getType().equalsIgnoreCase( + "error")) { + String errorMsg = resultStatusType.getStatus().getValue(); + + throw new I2B2Exception( + "Unable to fetch file from file repository [" + + errorMsg + "]"); + } + + OperationContext operationContext = mc.getOperationContext(); + MessageContext outMessageContext = operationContext + .getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE); + log + .debug("File Repository response has [" + + outMessageContext.getAttachmentMap() + .getAllContentIDs().length + + "] attachments"); + + + } catch (AxisFault axisFault) { + throw new I2B2Exception( + "Unable to fetch file from file repository :Axisfault [" + + axisFault.getCause().getMessage() + "]"); + } catch (JAXBUtilException jaxbUtilEx) { + throw new I2B2Exception( + "Unable to fetch file from file repository :Axisfault [" + + jaxbUtilEx.getMessage() + "]"); + } catch (Throwable t) { + t.printStackTrace(); + throw new I2B2Exception( + "Unable to fetch file from file repository :Axisfault [" + + t.getMessage() + "]"); + } + */ + return response; + + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/delegate/fr/FileRepositoryServiceClient.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/delegate/fr/FileRepositoryServiceClient.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/delegate/fr/FileRepositoryServiceClient.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/delegate/fr/FileRepositoryServiceClient.java index 361a9900..f6df1a04 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/delegate/fr/FileRepositoryServiceClient.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/delegate/fr/FileRepositoryServiceClient.java @@ -1,37 +1,37 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.loader.delegate.fr; - -import org.apache.axis2.AxisFault; -import org.apache.axis2.client.ServiceClient; - -public class FileRepositoryServiceClient { - private static ServiceClient sender = null; - - private FileRepositoryServiceClient() { - } - - public static ServiceClient getServiceClient() { - if (sender == null) { - try { - sender = new ServiceClient(); - } catch (AxisFault e) { - e.printStackTrace(); - } - } - return sender; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.loader.delegate.fr; + +import org.apache.axis2.AxisFault; +import org.apache.axis2.client.ServiceClient; + +public class FileRepositoryServiceClient { + private static ServiceClient sender = null; + + private FileRepositoryServiceClient() { + } + + public static ServiceClient getServiceClient() { + if (sender == null) { + try { + sender = new ServiceClient(); + } catch (AxisFault e) { + e.printStackTrace(); + } + } + return sender; + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/delegate/pm/GetUserConfigurationRequestMessage.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/delegate/pm/GetUserConfigurationRequestMessage.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/delegate/pm/GetUserConfigurationRequestMessage.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/delegate/pm/GetUserConfigurationRequestMessage.java index 8f2aac7f..e981ba2f --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/delegate/pm/GetUserConfigurationRequestMessage.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/delegate/pm/GetUserConfigurationRequestMessage.java @@ -1,124 +1,124 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.loader.delegate.pm; - -import java.io.StringWriter; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; - -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; -import edu.harvard.i2b2.crc.loader.datavo.CRCLoaderJAXBUtil; -import edu.harvard.i2b2.crc.datavo.pm.GetUserConfigurationType; - -public class GetUserConfigurationRequestMessage extends ProjectManagementRequestData { - - public static final String THIS_CLASS_NAME = GetUserConfigurationRequestMessage.class.getName(); - private Log log = LogFactory.getLog(THIS_CLASS_NAME); - - - public GetUserConfigurationRequestMessage() { - } - - - /** - * Function to build getUserConfiguration body type - * - * @param - * @return BodyType object - */ - - public BodyType getBodyType(GetUserConfigurationType userConfigurationType) { - edu.harvard.i2b2.crc.datavo.pm.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.pm.ObjectFactory(); - - BodyType bodyType = new BodyType(); - bodyType.getAny().add(of.createGetUserConfiguration(userConfigurationType)); - return bodyType; - } - - /** - * Function to build PM Request message type and return it as an XML string - * - * @param GetUserConfigurationType (user config data) - * @return A String data type containing the PM RequestMessage in XML format - */ - public String doBuildXML(GetUserConfigurationType userConfig, SecurityType userSecurity){ - String requestString = null; - try { - MessageHeaderType messageHeader = getMessageHeader(); - messageHeader.setSecurity(userSecurity); - RequestHeaderType reqHeader = getRequestHeader(); - BodyType bodyType = getBodyType(userConfig) ; - RequestMessageType reqMessageType = getRequestMessageType(messageHeader, - reqHeader, bodyType); - requestString = getXMLString(reqMessageType); - - } catch (JAXBUtilException e) { - log.error(e.getMessage()); - } - return requestString; - } - - - /** - * Function to build PM Request message type and return it as an XML string - * - * @param GetUserConfigurationType (user config data) - * MessageHeaderType - * boolean (not used, only to render this method different from the previous one) - * @return A String data type containing the PM RequestMessage in XML format - */ - public String buildXML(GetUserConfigurationType userConfig, MessageHeaderType header) { - String requestString = null; - try { - MessageHeaderType messageHeader = getMessageHeader(); - messageHeader.setSecurity(header.getSecurity()); - messageHeader.setProjectId(header.getProjectId()); - RequestHeaderType reqHeader = getRequestHeader(); - BodyType bodyType = getBodyType(userConfig); - RequestMessageType reqMessageType = getRequestMessageType(messageHeader, reqHeader, bodyType); - requestString = getXMLString(reqMessageType); - } catch (JAXBUtilException e) { - log.error(e.getMessage()); - } - return requestString; - } - - - /** - * Function to convert Ont Request message type to an XML string - * - * @param reqMessageType String containing Ont request message to be converted to string - * @return A String data type containing the Ont RequestMessage in XML format - */ - public String getXMLString(RequestMessageType reqMessageType) throws JAXBUtilException{ - StringWriter strWriter = null; - try { - strWriter = new StringWriter(); - edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory(); - CRCLoaderJAXBUtil.getJAXBUtil().marshaller(of.createRequest(reqMessageType), strWriter); - } catch (JAXBUtilException e) { - log.error("Error marshalling Ont request message"); - throw e; - } - return strWriter.toString(); - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.loader.delegate.pm; + +import java.io.StringWriter; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; + +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; +import edu.harvard.i2b2.crc.loader.datavo.CRCLoaderJAXBUtil; +import edu.harvard.i2b2.crc.datavo.pm.GetUserConfigurationType; + +public class GetUserConfigurationRequestMessage extends ProjectManagementRequestData { + + public static final String THIS_CLASS_NAME = GetUserConfigurationRequestMessage.class.getName(); + private Log log = LogFactory.getLog(THIS_CLASS_NAME); + + + public GetUserConfigurationRequestMessage() { + } + + + /** + * Function to build getUserConfiguration body type + * + * @param + * @return BodyType object + */ + + public BodyType getBodyType(GetUserConfigurationType userConfigurationType) { + edu.harvard.i2b2.crc.datavo.pm.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.pm.ObjectFactory(); + + BodyType bodyType = new BodyType(); + bodyType.getAny().add(of.createGetUserConfiguration(userConfigurationType)); + return bodyType; + } + + /** + * Function to build PM Request message type and return it as an XML string + * + * @param GetUserConfigurationType (user config data) + * @return A String data type containing the PM RequestMessage in XML format + */ + public String doBuildXML(GetUserConfigurationType userConfig, SecurityType userSecurity){ + String requestString = null; + try { + MessageHeaderType messageHeader = getMessageHeader(); + messageHeader.setSecurity(userSecurity); + RequestHeaderType reqHeader = getRequestHeader(); + BodyType bodyType = getBodyType(userConfig) ; + RequestMessageType reqMessageType = getRequestMessageType(messageHeader, + reqHeader, bodyType); + requestString = getXMLString(reqMessageType); + + } catch (JAXBUtilException e) { + log.error(e.getMessage()); + } + return requestString; + } + + + /** + * Function to build PM Request message type and return it as an XML string + * + * @param GetUserConfigurationType (user config data) + * MessageHeaderType + * boolean (not used, only to render this method different from the previous one) + * @return A String data type containing the PM RequestMessage in XML format + */ + public String buildXML(GetUserConfigurationType userConfig, MessageHeaderType header) { + String requestString = null; + try { + MessageHeaderType messageHeader = getMessageHeader(); + messageHeader.setSecurity(header.getSecurity()); + messageHeader.setProjectId(header.getProjectId()); + RequestHeaderType reqHeader = getRequestHeader(); + BodyType bodyType = getBodyType(userConfig); + RequestMessageType reqMessageType = getRequestMessageType(messageHeader, reqHeader, bodyType); + requestString = getXMLString(reqMessageType); + } catch (JAXBUtilException e) { + log.error(e.getMessage()); + } + return requestString; + } + + + /** + * Function to convert Ont Request message type to an XML string + * + * @param reqMessageType String containing Ont request message to be converted to string + * @return A String data type containing the Ont RequestMessage in XML format + */ + public String getXMLString(RequestMessageType reqMessageType) throws JAXBUtilException{ + StringWriter strWriter = null; + try { + strWriter = new StringWriter(); + edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory(); + CRCLoaderJAXBUtil.getJAXBUtil().marshaller(of.createRequest(reqMessageType), strWriter); + } catch (JAXBUtilException e) { + log.error("Error marshalling Ont request message"); + throw e; + } + return strWriter.toString(); + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/delegate/pm/PMResponseMessage.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/delegate/pm/PMResponseMessage.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/delegate/pm/PMResponseMessage.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/delegate/pm/PMResponseMessage.java index 9b0018ec..a609f472 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/delegate/pm/PMResponseMessage.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/delegate/pm/PMResponseMessage.java @@ -1,84 +1,84 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.loader.delegate.pm; - -import jakarta.xml.bind.JAXBElement; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.loader.datavo.CRCLoaderJAXBUtil; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; -import edu.harvard.i2b2.crc.datavo.pm.ConfigureType; -import edu.harvard.i2b2.crc.delegate.pdo.PdoQueryRequestDelegate; - - - - -public class PMResponseMessage { - - public static final String THIS_CLASS_NAME = PMResponseMessage.class.getName(); - private Log log = LogFactory.getLog(THIS_CLASS_NAME); - private ResponseMessageType pmRespMessageType = null; - protected static Log logesapi = LogFactory.getLog(PMResponseMessage.class); - - public PMResponseMessage() {} - - public StatusType processResult(String response) throws JAXBUtilException{ - StatusType status = null; - try { - - JAXBElement jaxbElement = CRCLoaderJAXBUtil.getJAXBUtil().unMashallFromString(response); - pmRespMessageType = (ResponseMessageType) jaxbElement.getValue(); - - // Get response message status - ResponseHeaderType responseHeader = pmRespMessageType.getResponseHeader(); - status = responseHeader.getResultStatus().getStatus(); - String procStatus = status.getType(); - String procMessage = status.getValue(); - - if(procStatus.equals("ERROR")){ - logesapi.info("Error reported by CRC web Service " + procMessage); - } - else if(procStatus.equals("WARNING")){ - logesapi.info("Warning reported by CRC web Service" + procMessage); - } - - } catch (JAXBUtilException e) { - log.error(e); - throw e; - } - return status; - } - - - public ConfigureType readUserInfo() throws JAXBUtilException { - ConfigureType pmResponse = null; - - BodyType bodyType = pmRespMessageType.getMessageBody(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - pmResponse = (ConfigureType)helper.getObjectByClass(bodyType.getAny(), ConfigureType.class); - - return pmResponse; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.loader.delegate.pm; + +import jakarta.xml.bind.JAXBElement; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.loader.datavo.CRCLoaderJAXBUtil; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; +import edu.harvard.i2b2.crc.datavo.pm.ConfigureType; +import edu.harvard.i2b2.crc.delegate.pdo.PdoQueryRequestDelegate; + + + + +public class PMResponseMessage { + + public static final String THIS_CLASS_NAME = PMResponseMessage.class.getName(); + private Log log = LogFactory.getLog(THIS_CLASS_NAME); + private ResponseMessageType pmRespMessageType = null; + protected static Log logesapi = LogFactory.getLog(PMResponseMessage.class); + + public PMResponseMessage() {} + + public StatusType processResult(String response) throws JAXBUtilException{ + StatusType status = null; + try { + + JAXBElement jaxbElement = CRCLoaderJAXBUtil.getJAXBUtil().unMashallFromString(response); + pmRespMessageType = (ResponseMessageType) jaxbElement.getValue(); + + // Get response message status + ResponseHeaderType responseHeader = pmRespMessageType.getResponseHeader(); + status = responseHeader.getResultStatus().getStatus(); + String procStatus = status.getType(); + String procMessage = status.getValue(); + + if(procStatus.equals("ERROR")){ + logesapi.info("Error reported by CRC web Service " + procMessage); + } + else if(procStatus.equals("WARNING")){ + logesapi.info("Warning reported by CRC web Service" + procMessage); + } + + } catch (JAXBUtilException e) { + log.error(e); + throw e; + } + return status; + } + + + public ConfigureType readUserInfo() throws JAXBUtilException { + ConfigureType pmResponse = null; + + BodyType bodyType = pmRespMessageType.getMessageBody(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + pmResponse = (ConfigureType)helper.getObjectByClass(bodyType.getAny(), ConfigureType.class); + + return pmResponse; + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/delegate/pm/PMServiceClient.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/delegate/pm/PMServiceClient.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/delegate/pm/PMServiceClient.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/delegate/pm/PMServiceClient.java index 0b1c9d29..7415c3d6 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/delegate/pm/PMServiceClient.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/delegate/pm/PMServiceClient.java @@ -1,38 +1,38 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.loader.delegate.pm; - -import org.apache.axis2.AxisFault; -import org.apache.axis2.client.ServiceClient; - -public class PMServiceClient { - private static ServiceClient sender = null; - private PMServiceClient() { - } - - - public static ServiceClient getServiceClient() { - if (sender == null) { - try { - sender = new ServiceClient(); - } catch (AxisFault e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - return sender; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.loader.delegate.pm; + +import org.apache.axis2.AxisFault; +import org.apache.axis2.client.ServiceClient; + +public class PMServiceClient { + private static ServiceClient sender = null; + private PMServiceClient() { + } + + + public static ServiceClient getServiceClient() { + if (sender == null) { + try { + sender = new ServiceClient(); + } catch (AxisFault e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + return sender; + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/delegate/pm/PMServiceDriver.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/delegate/pm/PMServiceDriver.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/delegate/pm/PMServiceDriver.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/delegate/pm/PMServiceDriver.java index 38b9d295..c29cd48f --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/delegate/pm/PMServiceDriver.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/delegate/pm/PMServiceDriver.java @@ -1,179 +1,179 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.loader.delegate.pm; - -import java.io.StringReader; -import java.util.List; - -import javax.xml.stream.FactoryConfigurationError; -import javax.xml.stream.XMLInputFactory; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamReader; - -import org.apache.axiom.om.OMAbstractFactory; -import org.apache.axiom.om.OMElement; -import org.apache.axiom.om.OMFactory; -import org.apache.axiom.om.OMXMLBuilderFactory; -import org.apache.axis2.AxisFault; -//import org.apache.axis2.Constants; -//import org.apache.axis2.addressing.EndpointReference; -//import org.apache.axis2.client.Options; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.axis2.ServiceClient; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; -import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; -import edu.harvard.i2b2.crc.datavo.pm.ConfigureType; -import edu.harvard.i2b2.crc.datavo.pm.GetUserConfigurationType; -import edu.harvard.i2b2.crc.datavo.pm.ProjectType; -import edu.harvard.i2b2.crc.loader.util.CRCLoaderUtil; - -public class PMServiceDriver { - private static Log log = LogFactory.getLog(PMServiceDriver.class); - protected static Log logesapi = LogFactory.getLog(PMServiceDriver.class); - - - - /** - * Function to send getRoles request to PM web service - * - * @param GetUserConfigurationType userConfig we wish to get data for - * MessageHeaderType - * @return A String containing the PM web service response - */ - - public String getRoles(GetUserConfigurationType userConfig, MessageHeaderType header) throws I2B2Exception, AxisFault, Exception { - String response = null; - try { - GetUserConfigurationRequestMessage reqMsg = new GetUserConfigurationRequestMessage(); - String getRolesRequestString = reqMsg.buildXML(userConfig, header); -// OMElement getPm = getPmPayLoad(getRolesRequestString); - String pmEPR = CRCLoaderUtil.getInstance().getProjectManagementCellUrl(); - log.debug("project management cell URL " + pmEPR); -// response = ServiceClient.sendREST(pmEPR, getPm); - response = ServiceClient.sendREST(pmEPR, getRolesRequestString); - } catch (I2B2Exception e1) { - e1.printStackTrace(); - log.error("Error reading project management cell URL " + e1.getMessage()); - throw new I2B2Exception("Error reading project management cell URL " + e1.getMessage()); - } catch (AxisFault e2) { - log.error(e2); - throw e2; - } catch (Exception e3) { - log.error(e3.getMessage()); - e3.printStackTrace(); - throw e3; - } - return response; - } - - - /** - * Function to send getRoles request to PM web service - * - * @param GetUserConfigurationType - * userConfig we wish to get data for - * @return A String containing the PM web service response - */ - public String getRoles(SecurityType userSec) throws AxisFault, - I2B2Exception { - String response = null; - try { - GetUserConfigurationRequestMessage reqMsg = new GetUserConfigurationRequestMessage(); - String getRolesRequestString = reqMsg.doBuildXML( - new GetUserConfigurationType(), userSec); - OMElement getPm = ServiceClient.getPayLoad(getRolesRequestString); - String pmEPR = ""; - try { - pmEPR = CRCLoaderUtil.getInstance() - .getProjectManagementCellUrl(); - log.debug("project management cell URL " + pmEPR); - } catch (I2B2Exception e1) { - e1.printStackTrace(); - log.error("Error reading project management cell URL " - + e1.getMessage()); - throw new I2B2Exception( - "Error reading project management cell URL " - + e1.getMessage()); - } - /* - Options options = new Options(); - options.setTo(new EndpointReference(pmEPR)); - options.setTransportInProtocol(Constants.TRANSPORT_HTTP); - options.setProperty(Constants.Configuration.ENABLE_REST, - Constants.VALUE_TRUE); - options.setTimeOutInMilliSeconds(50000); - ServiceClient sender = PMServiceClient.getServiceClient(); - sender.setOptions(options); - OMElement result = sender.sendReceive(getPm); - if (result != null) { - response = result.toString(); - log.debug("PM response message [" + response + "]"); - } - sender.cleanup(); - */ - - response = ServiceClient.sendREST(pmEPR, getPm); - } catch (AxisFault e) { - log.error(e); - throw e; - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - return response; - } - - public ProjectType checkValidUser(SecurityType security, String projectId) - throws I2B2Exception, AxisFault, JAXBUtilException { - ProjectType projectType = null; - - // Are we bypassing the PM cell? Look in properties file. - - String response = null; - - PMResponseMessage msg = new PMResponseMessage(); - response = getRoles(security); - StatusType procStatus = msg.processResult(response); - if (procStatus.getType().equalsIgnoreCase("ERROR")) { - logesapi.debug("PM response error [" + procStatus.getValue() + "]"); - projectType = null; - } else { - ConfigureType pmResponseUserInfo = msg.readUserInfo(); - List projectList = pmResponseUserInfo.getUser() - .getProject(); - for (ProjectType pType : projectList) { - if (pType.getId().equalsIgnoreCase(projectId)) { - projectType = pType; - break; - } - } - if (projectType == null) { - throw new I2B2Exception( - "User not registered to the project[" + projectId - + "]"); - } - - } - - return projectType; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.loader.delegate.pm; + +import java.io.StringReader; +import java.util.List; + +import javax.xml.stream.FactoryConfigurationError; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import org.apache.axiom.om.OMAbstractFactory; +import org.apache.axiom.om.OMElement; +import org.apache.axiom.om.OMFactory; +import org.apache.axiom.om.OMXMLBuilderFactory; +import org.apache.axis2.AxisFault; +//import org.apache.axis2.Constants; +//import org.apache.axis2.addressing.EndpointReference; +//import org.apache.axis2.client.Options; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.axis2.ServiceClient; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; +import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; +import edu.harvard.i2b2.crc.datavo.pm.ConfigureType; +import edu.harvard.i2b2.crc.datavo.pm.GetUserConfigurationType; +import edu.harvard.i2b2.crc.datavo.pm.ProjectType; +import edu.harvard.i2b2.crc.loader.util.CRCLoaderUtil; + +public class PMServiceDriver { + private static Log log = LogFactory.getLog(PMServiceDriver.class); + protected static Log logesapi = LogFactory.getLog(PMServiceDriver.class); + + + + /** + * Function to send getRoles request to PM web service + * + * @param GetUserConfigurationType userConfig we wish to get data for + * MessageHeaderType + * @return A String containing the PM web service response + */ + + public String getRoles(GetUserConfigurationType userConfig, MessageHeaderType header) throws I2B2Exception, AxisFault, Exception { + String response = null; + try { + GetUserConfigurationRequestMessage reqMsg = new GetUserConfigurationRequestMessage(); + String getRolesRequestString = reqMsg.buildXML(userConfig, header); +// OMElement getPm = getPmPayLoad(getRolesRequestString); + String pmEPR = CRCLoaderUtil.getInstance().getProjectManagementCellUrl(); + log.debug("project management cell URL " + pmEPR); +// response = ServiceClient.sendREST(pmEPR, getPm); + response = ServiceClient.sendREST(pmEPR, getRolesRequestString); + } catch (I2B2Exception e1) { + e1.printStackTrace(); + log.error("Error reading project management cell URL " + e1.getMessage()); + throw new I2B2Exception("Error reading project management cell URL " + e1.getMessage()); + } catch (AxisFault e2) { + log.error(e2); + throw e2; + } catch (Exception e3) { + log.error(e3.getMessage()); + e3.printStackTrace(); + throw e3; + } + return response; + } + + + /** + * Function to send getRoles request to PM web service + * + * @param GetUserConfigurationType + * userConfig we wish to get data for + * @return A String containing the PM web service response + */ + public String getRoles(SecurityType userSec) throws AxisFault, + I2B2Exception { + String response = null; + try { + GetUserConfigurationRequestMessage reqMsg = new GetUserConfigurationRequestMessage(); + String getRolesRequestString = reqMsg.doBuildXML( + new GetUserConfigurationType(), userSec); + OMElement getPm = ServiceClient.getPayLoad(getRolesRequestString); + String pmEPR = ""; + try { + pmEPR = CRCLoaderUtil.getInstance() + .getProjectManagementCellUrl(); + log.debug("project management cell URL " + pmEPR); + } catch (I2B2Exception e1) { + e1.printStackTrace(); + log.error("Error reading project management cell URL " + + e1.getMessage()); + throw new I2B2Exception( + "Error reading project management cell URL " + + e1.getMessage()); + } + /* + Options options = new Options(); + options.setTo(new EndpointReference(pmEPR)); + options.setTransportInProtocol(Constants.TRANSPORT_HTTP); + options.setProperty(Constants.Configuration.ENABLE_REST, + Constants.VALUE_TRUE); + options.setTimeOutInMilliSeconds(50000); + ServiceClient sender = PMServiceClient.getServiceClient(); + sender.setOptions(options); + OMElement result = sender.sendReceive(getPm); + if (result != null) { + response = result.toString(); + log.debug("PM response message [" + response + "]"); + } + sender.cleanup(); + */ + + response = ServiceClient.sendREST(pmEPR, getPm); + } catch (AxisFault e) { + log.error(e); + throw e; + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return response; + } + + public ProjectType checkValidUser(SecurityType security, String projectId) + throws I2B2Exception, AxisFault, JAXBUtilException { + ProjectType projectType = null; + + // Are we bypassing the PM cell? Look in properties file. + + String response = null; + + PMResponseMessage msg = new PMResponseMessage(); + response = getRoles(security); + StatusType procStatus = msg.processResult(response); + if (procStatus.getType().equalsIgnoreCase("ERROR")) { + logesapi.debug("PM response error [" + procStatus.getValue() + "]"); + projectType = null; + } else { + ConfigureType pmResponseUserInfo = msg.readUserInfo(); + List projectList = pmResponseUserInfo.getUser() + .getProject(); + for (ProjectType pType : projectList) { + if (pType.getId().equalsIgnoreCase(projectId)) { + projectType = pType; + break; + } + } + if (projectType == null) { + throw new I2B2Exception( + "User not registered to the project[" + projectId + + "]"); + } + + } + + return projectType; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/delegate/pm/ProjectManagementRequestData.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/delegate/pm/ProjectManagementRequestData.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/delegate/pm/ProjectManagementRequestData.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/delegate/pm/ProjectManagementRequestData.java index 7de2121b..08cc8a4b --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/delegate/pm/ProjectManagementRequestData.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/delegate/pm/ProjectManagementRequestData.java @@ -1,174 +1,174 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.loader.delegate.pm; - -import java.io.StringWriter; -import java.math.BigDecimal; -import java.security.SecureRandom; -import java.util.Date; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.util.jaxb.DTOFactory; -import edu.harvard.i2b2.crc.datavo.i2b2message.ApplicationType; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2message.FacilityType; -import edu.harvard.i2b2.crc.datavo.i2b2message.MessageControlIdType; -import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ProcessingIdType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; - -abstract public class ProjectManagementRequestData { - - public static final String THIS_CLASS_NAME = ProjectManagementRequestData.class.getName(); - private Log log = LogFactory.getLog(THIS_CLASS_NAME); - public ProjectManagementRequestData() {} - - - /** - * Function to build i2b2 Request message header - * - * @return RequestHeader object - */ - public RequestHeaderType getRequestHeader() { - RequestHeaderType reqHeader = new RequestHeaderType(); - reqHeader.setResultWaittimeMs(120000); - return reqHeader; - } - - /** - * Function to build i2b2 message header - * - * @return MessageHeader object - */ - public MessageHeaderType getMessageHeader() { - MessageHeaderType messageHeader = new MessageHeaderType(); - - messageHeader.setI2B2VersionCompatible(new BigDecimal("1.0")); - messageHeader.setHl7VersionCompatible(new BigDecimal("2.4")); - - ApplicationType appType = new ApplicationType(); - appType.setApplicationName("i2b2 CRC Cell"); - appType.setApplicationVersion("1.1"); - messageHeader.setSendingApplication(appType); - - FacilityType facility = new FacilityType(); - facility.setFacilityName("i2b2 Hive"); - messageHeader.setSendingFacility(facility); - - ApplicationType appType2 = new ApplicationType(); - appType2.setApplicationVersion("1.1"); - appType2.setApplicationName("Project Management Cell"); - messageHeader.setReceivingApplication(appType2); - - FacilityType facility2 = new FacilityType(); - facility2.setFacilityName("i2b2 Hive"); - messageHeader.setReceivingFacility(facility2); - - - Date currentDate = new Date(); - DTOFactory factory = new DTOFactory(); - messageHeader.setDatetimeOfMessage(factory.getXMLGregorianCalendar(currentDate.getTime())); - - MessageControlIdType mcIdType = new MessageControlIdType(); - mcIdType.setInstanceNum(0); - mcIdType.setMessageNum(generateMessageId()); - messageHeader.setMessageControlId(mcIdType); - - ProcessingIdType proc = new ProcessingIdType(); - proc.setProcessingId("P"); - proc.setProcessingMode("I"); - messageHeader.setProcessingId(proc); - - messageHeader.setAcceptAcknowledgementType("AL"); - messageHeader.setApplicationAcknowledgementType("AL"); - messageHeader.setCountryCode("US"); - - return messageHeader; - } - - /** - * Function to generate i2b2 message header message number - * - * @return String - */ - protected String generateMessageId() { - StringWriter strWriter = new StringWriter(); - for(int i=0; i<20; i++) { - int num = getValidAcsiiValue(); - strWriter.append((char)num); - } - return strWriter.toString(); - } - - /** - * Function to generate random number used in message number - * - * @return int - */ - private int getValidAcsiiValue() { - int number = 48; - while(true) { - SecureRandom random = new SecureRandom(); - - number = 48+(int) Math.round(random.nextDouble() * 74); - if((number > 47 && number < 58) || (number > 64 && number < 91) - || (number > 96 && number < 123)) { - break; - } - } - return number; - } -// /** -// * Function to convert Ont Request message type to an XML string -// * -// * @param reqMessageType String containing Ont request message to be converted to string -// * @return A String data type containing the Ont RequestMessage in XML format -// */ -// public String getXMLString(RequestMessageType reqMessageType) throws JAXBUtilException{ -// StringWriter strWriter = null; -// try { -// strWriter = new StringWriter(); -// edu.harvard.i2b2.ontology.datavo.i2b2message.ObjectFactory of = new edu.harvard.i2b2.ontology.datavo.i2b2message.ObjectFactory(); -// OntologyJAXBUtil.getJAXBUtil().marshaller(of.createRequest(reqMessageType), strWriter); -// } catch (JAXBUtilException e) { -// log.error("Error marshalling PM request message"); -// throw e; -// } -// return strWriter.toString(); -// } - - - - /** - * Function to build Request message type - * - * @param messageHeader MessageHeader object - * @param reqHeader RequestHeader object - * @param bodyType BodyType object - * @return RequestMessageType object - */ - public RequestMessageType getRequestMessageType(MessageHeaderType messageHeader, - RequestHeaderType reqHeader, BodyType bodyType) { - RequestMessageType reqMsgType = new RequestMessageType(); - reqMsgType.setMessageHeader(messageHeader); - reqMsgType.setMessageBody(bodyType); - reqMsgType.setRequestHeader(reqHeader); - return reqMsgType; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.loader.delegate.pm; + +import java.io.StringWriter; +import java.math.BigDecimal; +import java.security.SecureRandom; +import java.util.Date; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.util.jaxb.DTOFactory; +import edu.harvard.i2b2.crc.datavo.i2b2message.ApplicationType; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2message.FacilityType; +import edu.harvard.i2b2.crc.datavo.i2b2message.MessageControlIdType; +import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ProcessingIdType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; + +abstract public class ProjectManagementRequestData { + + public static final String THIS_CLASS_NAME = ProjectManagementRequestData.class.getName(); + private Log log = LogFactory.getLog(THIS_CLASS_NAME); + public ProjectManagementRequestData() {} + + + /** + * Function to build i2b2 Request message header + * + * @return RequestHeader object + */ + public RequestHeaderType getRequestHeader() { + RequestHeaderType reqHeader = new RequestHeaderType(); + reqHeader.setResultWaittimeMs(120000); + return reqHeader; + } + + /** + * Function to build i2b2 message header + * + * @return MessageHeader object + */ + public MessageHeaderType getMessageHeader() { + MessageHeaderType messageHeader = new MessageHeaderType(); + + messageHeader.setI2B2VersionCompatible(new BigDecimal("1.0")); + messageHeader.setHl7VersionCompatible(new BigDecimal("2.4")); + + ApplicationType appType = new ApplicationType(); + appType.setApplicationName("i2b2 CRC Cell"); + appType.setApplicationVersion("1.1"); + messageHeader.setSendingApplication(appType); + + FacilityType facility = new FacilityType(); + facility.setFacilityName("i2b2 Hive"); + messageHeader.setSendingFacility(facility); + + ApplicationType appType2 = new ApplicationType(); + appType2.setApplicationVersion("1.1"); + appType2.setApplicationName("Project Management Cell"); + messageHeader.setReceivingApplication(appType2); + + FacilityType facility2 = new FacilityType(); + facility2.setFacilityName("i2b2 Hive"); + messageHeader.setReceivingFacility(facility2); + + + Date currentDate = new Date(); + DTOFactory factory = new DTOFactory(); + messageHeader.setDatetimeOfMessage(factory.getXMLGregorianCalendar(currentDate.getTime())); + + MessageControlIdType mcIdType = new MessageControlIdType(); + mcIdType.setInstanceNum(0); + mcIdType.setMessageNum(generateMessageId()); + messageHeader.setMessageControlId(mcIdType); + + ProcessingIdType proc = new ProcessingIdType(); + proc.setProcessingId("P"); + proc.setProcessingMode("I"); + messageHeader.setProcessingId(proc); + + messageHeader.setAcceptAcknowledgementType("AL"); + messageHeader.setApplicationAcknowledgementType("AL"); + messageHeader.setCountryCode("US"); + + return messageHeader; + } + + /** + * Function to generate i2b2 message header message number + * + * @return String + */ + protected String generateMessageId() { + StringWriter strWriter = new StringWriter(); + for(int i=0; i<20; i++) { + int num = getValidAcsiiValue(); + strWriter.append((char)num); + } + return strWriter.toString(); + } + + /** + * Function to generate random number used in message number + * + * @return int + */ + private int getValidAcsiiValue() { + int number = 48; + while(true) { + SecureRandom random = new SecureRandom(); + + number = 48+(int) Math.round(random.nextDouble() * 74); + if((number > 47 && number < 58) || (number > 64 && number < 91) + || (number > 96 && number < 123)) { + break; + } + } + return number; + } +// /** +// * Function to convert Ont Request message type to an XML string +// * +// * @param reqMessageType String containing Ont request message to be converted to string +// * @return A String data type containing the Ont RequestMessage in XML format +// */ +// public String getXMLString(RequestMessageType reqMessageType) throws JAXBUtilException{ +// StringWriter strWriter = null; +// try { +// strWriter = new StringWriter(); +// edu.harvard.i2b2.ontology.datavo.i2b2message.ObjectFactory of = new edu.harvard.i2b2.ontology.datavo.i2b2message.ObjectFactory(); +// OntologyJAXBUtil.getJAXBUtil().marshaller(of.createRequest(reqMessageType), strWriter); +// } catch (JAXBUtilException e) { +// log.error("Error marshalling PM request message"); +// throw e; +// } +// return strWriter.toString(); +// } + + + + /** + * Function to build Request message type + * + * @param messageHeader MessageHeader object + * @param reqHeader RequestHeader object + * @param bodyType BodyType object + * @return RequestMessageType object + */ + public RequestMessageType getRequestMessageType(MessageHeaderType messageHeader, + RequestHeaderType reqHeader, BodyType bodyType) { + RequestMessageType reqMsgType = new RequestMessageType(); + reqMsgType.setMessageHeader(messageHeader); + reqMsgType.setMessageBody(bodyType); + reqMsgType.setRequestHeader(reqHeader); + return reqMsgType; + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/AbstractDimensionLoader.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/AbstractDimensionLoader.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/AbstractDimensionLoader.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/AbstractDimensionLoader.java index 25eb9f95..696be09c --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/AbstractDimensionLoader.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/AbstractDimensionLoader.java @@ -1,117 +1,117 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.ejb; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.crc.loader.dao.IUploaderDAOFactory; - -/** - * Abstract loader classs. Individual dimension loader class should implement - * load method. - * - * @author rk903 - * - */ -public abstract class AbstractDimensionLoader { - protected String inputLoadFile = null; - protected String inputLoadFileFormat = null; - protected String outputXmlFileName = null; - protected String stagingTableName = null; - protected String sourceSystemCd = null; - protected String encounterSource = null; - protected IUploaderDAOFactory uploaderDaoFactory = null; - - private int uploadId = 0; - - public void setStagingTableName(String stagingTableName) { - this.stagingTableName = stagingTableName; - } - - public String getStagingTableName() { - return stagingTableName; - } - - public String getOutputXmlFileName() { - return outputXmlFileName; - } - - public void setOutputXmlFileName(String outputXmlFileName) { - this.outputXmlFileName = outputXmlFileName; - } - - public int getUploadId() { - return uploadId; - } - - public void setUploadId(int uploadId) { - this.uploadId = uploadId; - } - - public String getInputLoadFile() { - return inputLoadFile; - } - - public void setInputLoadFile(String inputLoadFile) { - this.inputLoadFile = inputLoadFile; - } - - public String getInputLoadFileFormat() { - return inputLoadFileFormat; - } - - public void setInputLoadFileFormat(String inputLoadFileFormat) { - this.inputLoadFileFormat = inputLoadFileFormat; - } - - public String getSourceSystemCd() { - return sourceSystemCd; - } - - public void setSourceSystemCd(String sourceSystemCd) { - this.sourceSystemCd = sourceSystemCd; - } - - public String getEncounterSource() { - return encounterSource; - } - - public void setEncounterSource(String encounterSource) { - this.encounterSource = encounterSource; - } - - /** - * Implement load method. The values needed for load are set thru instance - * variable. - * - * @throws I2B2Exception - */ - public abstract void load() throws I2B2Exception; - - public abstract void setStartStatus(); - - public abstract void createTempTable() throws I2B2Exception; - - public abstract int loadTempTable() throws I2B2Exception; - - public abstract int mergeTempTable() throws I2B2Exception; - - // public abstract void backupAndClearTable() throws I2B2Exception; - - // public abstract int updateSetStatus(int totalRecords, int updatedRecords, - // Exception exception) throws I2B2Exception; - - public IUploaderDAOFactory getUploaderDaoFactory() { - return uploaderDaoFactory; - } - - public void setUploaderDaoFactory(IUploaderDAOFactory uploaderDaoFactory) { - this.uploaderDaoFactory = uploaderDaoFactory; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.ejb; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.crc.loader.dao.IUploaderDAOFactory; + +/** + * Abstract loader classs. Individual dimension loader class should implement + * load method. + * + * @author rk903 + * + */ +public abstract class AbstractDimensionLoader { + protected String inputLoadFile = null; + protected String inputLoadFileFormat = null; + protected String outputXmlFileName = null; + protected String stagingTableName = null; + protected String sourceSystemCd = null; + protected String encounterSource = null; + protected IUploaderDAOFactory uploaderDaoFactory = null; + + private int uploadId = 0; + + public void setStagingTableName(String stagingTableName) { + this.stagingTableName = stagingTableName; + } + + public String getStagingTableName() { + return stagingTableName; + } + + public String getOutputXmlFileName() { + return outputXmlFileName; + } + + public void setOutputXmlFileName(String outputXmlFileName) { + this.outputXmlFileName = outputXmlFileName; + } + + public int getUploadId() { + return uploadId; + } + + public void setUploadId(int uploadId) { + this.uploadId = uploadId; + } + + public String getInputLoadFile() { + return inputLoadFile; + } + + public void setInputLoadFile(String inputLoadFile) { + this.inputLoadFile = inputLoadFile; + } + + public String getInputLoadFileFormat() { + return inputLoadFileFormat; + } + + public void setInputLoadFileFormat(String inputLoadFileFormat) { + this.inputLoadFileFormat = inputLoadFileFormat; + } + + public String getSourceSystemCd() { + return sourceSystemCd; + } + + public void setSourceSystemCd(String sourceSystemCd) { + this.sourceSystemCd = sourceSystemCd; + } + + public String getEncounterSource() { + return encounterSource; + } + + public void setEncounterSource(String encounterSource) { + this.encounterSource = encounterSource; + } + + /** + * Implement load method. The values needed for load are set thru instance + * variable. + * + * @throws I2B2Exception + */ + public abstract void load() throws I2B2Exception; + + public abstract void setStartStatus(); + + public abstract void createTempTable() throws I2B2Exception; + + public abstract int loadTempTable() throws I2B2Exception; + + public abstract int mergeTempTable() throws I2B2Exception; + + // public abstract void backupAndClearTable() throws I2B2Exception; + + // public abstract int updateSetStatus(int totalRecords, int updatedRecords, + // Exception exception) throws I2B2Exception; + + public IUploaderDAOFactory getUploaderDaoFactory() { + return uploaderDaoFactory; + } + + public void setUploaderDaoFactory(IUploaderDAOFactory uploaderDaoFactory) { + this.uploaderDaoFactory = uploaderDaoFactory; + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/ConceptLoader.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/ConceptLoader.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/ConceptLoader.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/ConceptLoader.java index 3d5dcd56..d506dbb2 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/ConceptLoader.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/ConceptLoader.java @@ -1,189 +1,189 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.ejb; - -import java.io.PrintWriter; -import java.io.StringWriter; -import java.util.Date; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.crc.loader.dao.IConceptDAO; -import edu.harvard.i2b2.crc.loader.dao.IUploaderDAOFactory; -import edu.harvard.i2b2.crc.loader.dao.UploadStatusDAO; -import edu.harvard.i2b2.crc.loader.dao.UploadStatusDAOI; -import edu.harvard.i2b2.crc.loader.datavo.loader.UploadSetStatus; - -/** - * This specific loader class for Visit dimension. This class performs three - * operations, namely. 1.Build PatientData xml file based, if input file is csv - * 2.Load PatientData xml information into staging area in database. 3.Run - * procedure which will merge staging area into Visit dimension. - * - * @author rk903 - * - */ -public class ConceptLoader extends AbstractDimensionLoader { - - private static Log log = LogFactory.getLog(ConceptLoader.class); - IConceptDAO conceptDAO = null; - boolean deleteOldDataFlag = false; - - public ConceptLoader(IUploaderDAOFactory uploaderDaoFactory, - String inputLoadFile, String inputLoadFileFormat, - String encounterSource, String sourceSystemCd, - boolean deleteOldDataFlag, int uploadId) { - setUploaderDaoFactory(uploaderDaoFactory); - setInputLoadFile(inputLoadFile); - setInputLoadFileFormat(inputLoadFileFormat); - setEncounterSource(encounterSource); - setUploadId(uploadId); - setSourceSystemCd(sourceSystemCd); - this.deleteOldDataFlag = deleteOldDataFlag; - conceptDAO = uploaderDaoFactory.getConceptDAO(); - } - - @Override - public void load() throws I2B2Exception { - try { - - // update the status table - UploadStatusDAOI uploadStatusDao = uploaderDaoFactory - .getUploadStatusDAO(); - UploadSetStatus setStatus = new UploadSetStatus(); - setStatus.setUploadId(getUploadId()); - setStatus.setLoadStatus("STARTED"); - setStatus.setSetTypeId(UploadStatusDAO.CONCEPT_SET); - setStatus.setInputFileName(this.getInputLoadFile()); - setStatus.setSourceCd(getSourceSystemCd()); - setStatus.setLoadDate(new Date(System.currentTimeMillis())); - uploadStatusDao.insertUploadSetStatus(setStatus); - - // set pdo xml file - setOutputXmlFileName(getInputLoadFile()); - - String tempConceptTableName = "TEMP_CONCEPT_" + getUploadId(); - setStagingTableName(tempConceptTableName); - - IConceptDAO conceptDAO = uploaderDaoFactory.getConceptDAO(); - conceptDAO.createTempTable(tempConceptTableName); - log.info("Created Visit staging table" + getStagingTableName()); - - ConceptXmlDbLoader conceptDbLoader = new ConceptXmlDbLoader( - uploaderDaoFactory, getOutputXmlFileName(), - getStagingTableName(), getUploadId()); - conceptDbLoader.doUpload(); - log.info("Uploaded " + getOutputXmlFileName() + "to staging table" - + getStagingTableName()); - - conceptDAO.createConceptFromTempTable(getStagingTableName(), - getUploadId()); - log.info("Completed Concept insert operation for staging table" - + getStagingTableName()); - - setStatus = uploadStatusDao.getUploadSetStatus(getUploadId(), - UploadStatusDAO.CONCEPT_SET); - setStatus.setLoadStatus("COMPLETED"); - setStatus.setEndDate(new Date(System.currentTimeMillis())); - setStatus.setLoadedRecord(conceptDAO - .getRecordCountByUploadId(getUploadId())); - // setStatus.setDeletedRecord(deletedRecord); - setStatus.setNoOfRecord(conceptDbLoader.getRowCount()); - uploadStatusDao.updateUploadSetStatus(setStatus); - - } catch (I2B2Exception i2b2Ex) { - // try to write error to set status table, if that fails then simply - // pass the exception to top level - - UploadStatusDAOI uploadStatusDao = uploaderDaoFactory - .getUploadStatusDAO(); - UploadSetStatus setStatus = uploadStatusDao.getUploadSetStatus( - getUploadId(), UploadStatusDAO.CONCEPT_SET); - setStatus.setLoadStatus("ERROR"); - StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw); - i2b2Ex.printStackTrace(pw); - setStatus.setMessage(sw.toString().substring(0, 500)); - uploadStatusDao.updateUploadSetStatus(setStatus); - - throw i2b2Ex; - } - - } - - @Override - public void createTempTable() throws I2B2Exception { - // set pdo xml file - setOutputXmlFileName(getInputLoadFile()); - - String tempConceptTableName = "TEMP_CONCEPT_" + getUploadId(); - setStagingTableName(tempConceptTableName); - - conceptDAO.createTempTable(tempConceptTableName); - log.info("Created Visit staging table" + getStagingTableName()); - - } - - @Override - public int loadTempTable() throws I2B2Exception { - ConceptXmlDbLoader conceptDbLoader = new ConceptXmlDbLoader( - uploaderDaoFactory, getOutputXmlFileName(), - getStagingTableName(), getUploadId()); - conceptDbLoader.doUpload(); - log.info("Uploaded " + getOutputXmlFileName() + "to staging table" - + getStagingTableName()); - return conceptDbLoader.getRowCount(); - } - - @Override - public int mergeTempTable() throws I2B2Exception { - String backupConceptDimensionTableName = "cd_bkup_" + getUploadId(); - if (deleteOldDataFlag) { - conceptDAO.backupAndSyncConceptDimensionTable( - getStagingTableName(), backupConceptDimensionTableName, - getUploadId()); - } else { - conceptDAO.createConceptFromTempTable(getStagingTableName(), - getUploadId()); - } - log.info("Completed Concept insert operation for staging table" - + getStagingTableName()); - UploadStatusDAOI uploadStatusDao = uploaderDaoFactory - .getUploadStatusDAO(); - UploadSetStatus setStatus = uploadStatusDao.getUploadSetStatus( - getUploadId(), UploadStatusDAO.CONCEPT_SET); - setStatus.setLoadStatus("COMPLETED"); - setStatus.setEndDate(new Date(System.currentTimeMillis())); - setStatus.setLoadedRecord(conceptDAO - .getRecordCountByUploadId(getUploadId())); - // setStatus.setDeletedRecord(deletedRecord); - // ssetStatus.setNoOfRecord(conceptDbLoader.getRowCount()); - uploadStatusDao.updateUploadSetStatus(setStatus); - return conceptDAO.getRecordCountByUploadId(getUploadId()); - } - - @Override - public void setStartStatus() { - // update the status table - UploadStatusDAOI uploadStatusDao = uploaderDaoFactory - .getUploadStatusDAO(); - UploadSetStatus setStatus = new UploadSetStatus(); - setStatus.setUploadId(getUploadId()); - setStatus.setLoadStatus("STARTED"); - setStatus.setSetTypeId(UploadStatusDAO.CONCEPT_SET); - setStatus.setInputFileName(this.getInputLoadFile()); - setStatus.setSourceCd(getSourceSystemCd()); - setStatus.setLoadDate(new Date(System.currentTimeMillis())); - uploadStatusDao.insertUploadSetStatus(setStatus); - - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.ejb; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.Date; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.crc.loader.dao.IConceptDAO; +import edu.harvard.i2b2.crc.loader.dao.IUploaderDAOFactory; +import edu.harvard.i2b2.crc.loader.dao.UploadStatusDAO; +import edu.harvard.i2b2.crc.loader.dao.UploadStatusDAOI; +import edu.harvard.i2b2.crc.loader.datavo.loader.UploadSetStatus; + +/** + * This specific loader class for Visit dimension. This class performs three + * operations, namely. 1.Build PatientData xml file based, if input file is csv + * 2.Load PatientData xml information into staging area in database. 3.Run + * procedure which will merge staging area into Visit dimension. + * + * @author rk903 + * + */ +public class ConceptLoader extends AbstractDimensionLoader { + + private static Log log = LogFactory.getLog(ConceptLoader.class); + IConceptDAO conceptDAO = null; + boolean deleteOldDataFlag = false; + + public ConceptLoader(IUploaderDAOFactory uploaderDaoFactory, + String inputLoadFile, String inputLoadFileFormat, + String encounterSource, String sourceSystemCd, + boolean deleteOldDataFlag, int uploadId) { + setUploaderDaoFactory(uploaderDaoFactory); + setInputLoadFile(inputLoadFile); + setInputLoadFileFormat(inputLoadFileFormat); + setEncounterSource(encounterSource); + setUploadId(uploadId); + setSourceSystemCd(sourceSystemCd); + this.deleteOldDataFlag = deleteOldDataFlag; + conceptDAO = uploaderDaoFactory.getConceptDAO(); + } + + @Override + public void load() throws I2B2Exception { + try { + + // update the status table + UploadStatusDAOI uploadStatusDao = uploaderDaoFactory + .getUploadStatusDAO(); + UploadSetStatus setStatus = new UploadSetStatus(); + setStatus.setUploadId(getUploadId()); + setStatus.setLoadStatus("STARTED"); + setStatus.setSetTypeId(UploadStatusDAO.CONCEPT_SET); + setStatus.setInputFileName(this.getInputLoadFile()); + setStatus.setSourceCd(getSourceSystemCd()); + setStatus.setLoadDate(new Date(System.currentTimeMillis())); + uploadStatusDao.insertUploadSetStatus(setStatus); + + // set pdo xml file + setOutputXmlFileName(getInputLoadFile()); + + String tempConceptTableName = "TEMP_CONCEPT_" + getUploadId(); + setStagingTableName(tempConceptTableName); + + IConceptDAO conceptDAO = uploaderDaoFactory.getConceptDAO(); + conceptDAO.createTempTable(tempConceptTableName); + log.info("Created Visit staging table" + getStagingTableName()); + + ConceptXmlDbLoader conceptDbLoader = new ConceptXmlDbLoader( + uploaderDaoFactory, getOutputXmlFileName(), + getStagingTableName(), getUploadId()); + conceptDbLoader.doUpload(); + log.info("Uploaded " + getOutputXmlFileName() + "to staging table" + + getStagingTableName()); + + conceptDAO.createConceptFromTempTable(getStagingTableName(), + getUploadId()); + log.info("Completed Concept insert operation for staging table" + + getStagingTableName()); + + setStatus = uploadStatusDao.getUploadSetStatus(getUploadId(), + UploadStatusDAO.CONCEPT_SET); + setStatus.setLoadStatus("COMPLETED"); + setStatus.setEndDate(new Date(System.currentTimeMillis())); + setStatus.setLoadedRecord(conceptDAO + .getRecordCountByUploadId(getUploadId())); + // setStatus.setDeletedRecord(deletedRecord); + setStatus.setNoOfRecord(conceptDbLoader.getRowCount()); + uploadStatusDao.updateUploadSetStatus(setStatus); + + } catch (I2B2Exception i2b2Ex) { + // try to write error to set status table, if that fails then simply + // pass the exception to top level + + UploadStatusDAOI uploadStatusDao = uploaderDaoFactory + .getUploadStatusDAO(); + UploadSetStatus setStatus = uploadStatusDao.getUploadSetStatus( + getUploadId(), UploadStatusDAO.CONCEPT_SET); + setStatus.setLoadStatus("ERROR"); + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + i2b2Ex.printStackTrace(pw); + setStatus.setMessage(sw.toString().substring(0, 500)); + uploadStatusDao.updateUploadSetStatus(setStatus); + + throw i2b2Ex; + } + + } + + @Override + public void createTempTable() throws I2B2Exception { + // set pdo xml file + setOutputXmlFileName(getInputLoadFile()); + + String tempConceptTableName = "TEMP_CONCEPT_" + getUploadId(); + setStagingTableName(tempConceptTableName); + + conceptDAO.createTempTable(tempConceptTableName); + log.info("Created Visit staging table" + getStagingTableName()); + + } + + @Override + public int loadTempTable() throws I2B2Exception { + ConceptXmlDbLoader conceptDbLoader = new ConceptXmlDbLoader( + uploaderDaoFactory, getOutputXmlFileName(), + getStagingTableName(), getUploadId()); + conceptDbLoader.doUpload(); + log.info("Uploaded " + getOutputXmlFileName() + "to staging table" + + getStagingTableName()); + return conceptDbLoader.getRowCount(); + } + + @Override + public int mergeTempTable() throws I2B2Exception { + String backupConceptDimensionTableName = "cd_bkup_" + getUploadId(); + if (deleteOldDataFlag) { + conceptDAO.backupAndSyncConceptDimensionTable( + getStagingTableName(), backupConceptDimensionTableName, + getUploadId()); + } else { + conceptDAO.createConceptFromTempTable(getStagingTableName(), + getUploadId()); + } + log.info("Completed Concept insert operation for staging table" + + getStagingTableName()); + UploadStatusDAOI uploadStatusDao = uploaderDaoFactory + .getUploadStatusDAO(); + UploadSetStatus setStatus = uploadStatusDao.getUploadSetStatus( + getUploadId(), UploadStatusDAO.CONCEPT_SET); + setStatus.setLoadStatus("COMPLETED"); + setStatus.setEndDate(new Date(System.currentTimeMillis())); + setStatus.setLoadedRecord(conceptDAO + .getRecordCountByUploadId(getUploadId())); + // setStatus.setDeletedRecord(deletedRecord); + // ssetStatus.setNoOfRecord(conceptDbLoader.getRowCount()); + uploadStatusDao.updateUploadSetStatus(setStatus); + return conceptDAO.getRecordCountByUploadId(getUploadId()); + } + + @Override + public void setStartStatus() { + // update the status table + UploadStatusDAOI uploadStatusDao = uploaderDaoFactory + .getUploadStatusDAO(); + UploadSetStatus setStatus = new UploadSetStatus(); + setStatus.setUploadId(getUploadId()); + setStatus.setLoadStatus("STARTED"); + setStatus.setSetTypeId(UploadStatusDAO.CONCEPT_SET); + setStatus.setInputFileName(this.getInputLoadFile()); + setStatus.setSourceCd(getSourceSystemCd()); + setStatus.setLoadDate(new Date(System.currentTimeMillis())); + uploadStatusDao.insertUploadSetStatus(setStatus); + + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/ConceptXmlDbLoader.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/ConceptXmlDbLoader.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/ConceptXmlDbLoader.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/ConceptXmlDbLoader.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/DataMartLoader.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/DataMartLoader.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/DataMartLoader.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/DataMartLoader.java index 404fd19a..f68fe91a --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/DataMartLoader.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/DataMartLoader.java @@ -1,477 +1,477 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.ejb; - -import java.io.File; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.util.Date; - -import jakarta.xml.bind.JAXBElement; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.loader.dao.IUploaderDAOFactory; -import edu.harvard.i2b2.crc.loader.dao.UploadStatusDAO; -import edu.harvard.i2b2.crc.loader.dao.UploadStatusDAOI; -import edu.harvard.i2b2.crc.loader.datavo.loader.UploadSetStatus; -import edu.harvard.i2b2.crc.loader.datavo.loader.query.PublishDataRequestType; - -/** - * Main class for datamart load operation. The Load function delegates load - * operation to appropriate loader class. - * - * @author rk903 - * - */ -public class DataMartLoader implements IDataMartLoaderHelper { - - // if the format is xml, then input file is in PatientData schema. - public final static String INPUT_LOAD_FORMAT_XML = "XML"; - - public final static String INPUT_LOAD_FORMAT_CSV = "CSV"; - - // this is temp holder, later its read thru property file - public static String loaderWorkingDirectory = "/"; - - - // @EJB(mappedName = "service/local") - // private Service service; - - // log - private static Log log = LogFactory.getLog(DataMartLoader.class); - protected static Log logesapi = LogFactory.getLog(DataMartLoader.class); - - /* - * public void load(int uploadId, String inputLoadFile, String - * inputLoadFileFormat, String sourceSystemCd, boolean visitLoadFlag, - * boolean observationFactLoadFlag,boolean pidLoadFlag, boolean - * patientLoadFlag, String encounterSource, String conceptCodePrefix, - * boolean appendFlag, String userId, boolean tempCleanUpFlag) throws - * I2B2Exception { - */ - - /** - * Main function to start upload process. - * - * @param inputLoadFile - * @param inputLoadFileFormat - * @param visitLoadFlag - * @param observationFactLoadFlag - * @param userId - * @param tempCleanUpFlag - * @throws I2B2Exception - */ - @Override - public void load(IUploaderDAOFactory uploaderDaoFactory, String userId, - int uploadId, String localUploadFile, String publishMessage) - throws I2B2Exception { - - try { - - JAXBUtil jaxbUtil = edu.harvard.i2b2.crc.loader.datavo.CRCLoaderJAXBUtil - .getJAXBUtil(); - PublishDataRequestType publishType = null; - try { - JAXBElement jaxbElement = jaxbUtil - .unMashallFromString(publishMessage); - publishType = (PublishDataRequestType) jaxbElement.getValue(); - } catch (JAXBUtilException jaxbEx) { - throw new I2B2Exception("Error proacessing request message " - + jaxbEx.getMessage(), jaxbEx); - } - - String uploadFileName = localUploadFile; - - String inputLoadFileFormat = publishType.getInputList() - .getDataFile().getDataFormatType().toString(); - String sourceSystemCd = publishType.getInputList().getDataFile() - .getSourceSystemCd(); - boolean visitLoadFlag = (publishType.getLoadList() - .getLoadEventSet() != null) ? true : false; - boolean observationFactLoadFlag = (publishType.getLoadList() - .getLoadObservationSet() != null) ? true : false; - boolean appendFlag = false; - if (observationFactLoadFlag) { - appendFlag = publishType.getLoadList().getLoadObservationSet() - .isAppendFlag(); - } - boolean pidLoadFlag = (publishType.getLoadList().getLoadPidSet() != null) ? true - : false; - boolean eidLoadFlag = (publishType.getLoadList().getLoadEidSet() != null) ? true - : false; - boolean patientLoadFlag = (publishType.getLoadList() - .getLoadPatientSet() != null) ? true : false; - boolean conceptLoadFlag = (publishType.getLoadList() - .getLoadConceptSet() != null) ? true : false; - boolean conceptDeleteExistingDataFlag = (publishType.getLoadList() - .getLoadConceptSet() != null) ? publishType.getLoadList() - .getLoadConceptSet().isDeleteExistingData() : false; - boolean modifierLoadFlag = (publishType.getLoadList() - .getLoadModifierSet() != null) ? true : false; - boolean modifierDeleteExistingDataFlag = (publishType.getLoadList() - .getLoadModifierSet() != null) ? publishType.getLoadList() - .getLoadModifierSet().isDeleteExistingData() : false; - boolean observerLoadFlag = (publishType.getLoadList() - .getLoadObserverSet() != null) ? true : false; - boolean observerDeleteExistingDataFlag = (publishType.getLoadList() - .getLoadObserverSet() != null) ? publishType.getLoadList() - .getLoadObserverSet().isDeleteExistingData() : false; - boolean stagingCleanUpFlag = publishType.getLoadList() - .isClearTempLoadTables(); - - String encounterSource = ""; - String conceptCodePrefix = ""; - - doNullCheck(uploadFileName, inputLoadFileFormat, sourceSystemCd, - userId); - - logesapi.info("Starting to process loadfile :" + uploadFileName - + "format " + inputLoadFileFormat + " userid " + userId); - - // create Upload Status - // uploadId = createUploadStatus(inputLoadFile, "STARTED", - // sourceSystemCd, userId); - // log.info("Created Upload Status: uploadId=" + uploadId); - - // check if pid set need to be loaded - UploadStatusDAOI uploadStatusDAO = uploaderDaoFactory - .getUploadStatusDAO(); - if (pidLoadFlag) { - PidLoader pidLoader = new PidLoader(uploaderDaoFactory, - uploadFileName, inputLoadFileFormat, encounterSource, - sourceSystemCd, uploadId); - performLoad(pidLoader, UploadStatusDAO.PID_SET); - log.info("Pid load complete " + uploadFileName + " uploadId" - + uploadId); - if (stagingCleanUpFlag) { - log.info("Droping temp table [" - + pidLoader.getStagingTableName() + "]"); - uploadStatusDAO.dropTempTable(pidLoader - .getStagingTableName()); - - } - } - - // check if eid set need to be loaded - if (eidLoadFlag) { - EidLoader eidLoader = new EidLoader(uploaderDaoFactory, - uploadFileName, inputLoadFileFormat, encounterSource, - sourceSystemCd, uploadId); - performLoad(eidLoader, UploadStatusDAO.EID_SET); - log.info("Eid load complete " + uploadFileName + " uploadId" - + uploadId); - if (stagingCleanUpFlag) { - log.info("Droping temp table [" - + eidLoader.getStagingTableName() + "]"); - uploadStatusDAO.dropTempTable(eidLoader - .getStagingTableName()); - - } - } - - // check if patient set need to be loaded - if (patientLoadFlag) { - PatientLoader patientLoader = new PatientLoader( - uploaderDaoFactory, uploadFileName, - inputLoadFileFormat, encounterSource, sourceSystemCd, - uploadId); - performLoad(patientLoader, UploadStatusDAO.PATIENT_SET); - log.info("Patient load complete " + uploadFileName - + " uploadId" + uploadId); - if (stagingCleanUpFlag) { - log.info("Droping temp table [" - + patientLoader.getStagingTableName() + "]"); - uploadStatusDAO.dropTempTable(patientLoader - .getStagingTableName()); - - } - } - - // check if visit need to be added - if (visitLoadFlag) { - VisitLoader visitLoader = new VisitLoader(uploaderDaoFactory, - uploadFileName, inputLoadFileFormat, encounterSource, - sourceSystemCd, uploadId); - performLoad(visitLoader, UploadStatusDAO.EVENT_SET); - log.info("Visit load complete " + uploadFileName + " uploadId" - + uploadId); - if (stagingCleanUpFlag) { - log.info("Droping temp table [" - + visitLoader.getStagingTableName() + "]"); - uploadStatusDAO.dropTempTable(visitLoader - .getStagingTableName()); - - } - } - - // check if concept set need to be loaded - if (conceptLoadFlag) { - log.info("Concept load started " + uploadFileName + " uploadId" - + uploadId); - - ConceptLoader conceptLoader = new ConceptLoader( - uploaderDaoFactory, uploadFileName, - inputLoadFileFormat, encounterSource, sourceSystemCd, - conceptDeleteExistingDataFlag, uploadId); - performLoad(conceptLoader, UploadStatusDAO.CONCEPT_SET); - log.info("Concept load complete " + uploadFileName - + " uploadId" + uploadId); - if (stagingCleanUpFlag) { - log.info("Droping temp table [" - + conceptLoader.getStagingTableName() + "]"); - uploadStatusDAO.dropTempTable(conceptLoader - .getStagingTableName()); - - } - } - - // check if modifier set need to be loaded - if (modifierLoadFlag) { - log.info("Modifier load started " + uploadFileName + " uploadId" - + uploadId); - - ModifierLoader modifierLoader = new ModifierLoader( - uploaderDaoFactory, uploadFileName, - inputLoadFileFormat, encounterSource, sourceSystemCd, - modifierDeleteExistingDataFlag, uploadId); - performLoad(modifierLoader, UploadStatusDAO.MODIFIER_SET); - log.info("Modifier load complete " + uploadFileName - + " uploadId" + uploadId); - if (stagingCleanUpFlag) { - log.info("Droping temp table [" - + modifierLoader.getStagingTableName() + "]"); - uploadStatusDAO.dropTempTable(modifierLoader - .getStagingTableName()); - - } - } - - // check if observer set need to be loaded - if (observerLoadFlag) { - log.info("Provider load started " + uploadFileName - + " uploadId" + uploadId); - - ProviderLoader providerLoader = new ProviderLoader( - uploaderDaoFactory, uploadFileName, - inputLoadFileFormat, encounterSource, sourceSystemCd, - observerDeleteExistingDataFlag, uploadId); - performLoad(providerLoader, UploadStatusDAO.OBSERVER_SET); - log.info("Provider load complete " + uploadFileName - + " uploadId" + uploadId); - if (stagingCleanUpFlag) { - log.info("Droping temp table [" - + providerLoader.getStagingTableName() + "]"); - uploadStatusDAO.dropTempTable(providerLoader - .getStagingTableName()); - - } - } - - // check if observation fact need to be added - if (observationFactLoadFlag) { - ObservationFactLoader obsFactLoader = new ObservationFactLoader( - uploaderDaoFactory, uploadFileName, - inputLoadFileFormat, encounterSource, - conceptCodePrefix, sourceSystemCd, appendFlag, uploadId); - performLoad(obsFactLoader, UploadStatusDAO.OBSERVATION_SET); - log.info("ObservationFact load complete " + uploadFileName - + " uploadId" + uploadId); - if (stagingCleanUpFlag) { - - log.info("Droping temp table [" - + obsFactLoader.getStagingTableName() + "]"); - uploadStatusDAO.dropTempTable(obsFactLoader - .getStagingTableName()); - - } - - } - - if (stagingCleanUpFlag) { - try { // remove local input file File - File deleteLocalFile = new File(localUploadFile); - deleteLocalFile.delete(); - } catch (Throwable t) { - log.error("Unable to delete the temp file [" - + localUploadFile + " ]"); - } - } - - } catch (Throwable ex) { - ex.printStackTrace(); - log.error("Error in Upload Process ", ex); - /* - try { - if (utx.getStatus() == Status.STATUS_ACTIVE) { - utx.rollback(); - } - } catch (Exception e) { - log.error("unable to rollback transaction [" + e.getMessage() - + "]"); - } - */ - // rethrow exception - throw new I2B2Exception("Error in Upload Process [" - + ex.getMessage() + "]"); - } - } - - public String getLoaderWorkingDirectory() { - return loaderWorkingDirectory; - } - - public void setLoaderWorkingDirectory(String loaderWorkingDirectory) { - DataMartLoader.loaderWorkingDirectory = loaderWorkingDirectory; - } - - private void performLoad(AbstractDimensionLoader dimensionLoader, - int setTypeId) throws I2B2Exception { - - Throwable t = null; - // setstatus started - IUploaderDAOFactory uploadDaoFactory = dimensionLoader - .getUploaderDaoFactory(); - - try { - -// utx.begin(); - UploadStatusDAOI uploadStatusDao = uploadDaoFactory - .getUploadStatusDAO(); - UploadSetStatus setStatus = new UploadSetStatus(); - setStatus.setUploadId(dimensionLoader.getUploadId()); - setStatus.setLoadStatus("PROCESSING"); - setStatus.setSetTypeId(setTypeId); - setStatus.setInputFileName(dimensionLoader.getInputLoadFile()); - setStatus.setSourceCd(dimensionLoader.getSourceSystemCd()); - setStatus.setLoadDate(new Date(System.currentTimeMillis())); - uploadStatusDao.insertUploadSetStatus(setStatus); - // utx.commit(); - - // utx.begin(); - dimensionLoader.createTempTable(); - // utx.commit(); - - // utx.begin(); - int totalRecords = dimensionLoader.loadTempTable(); - // utx.commit(); - - // if (deleteExistingDataFlag) { - // utx.begin(); - // dimensionLoader.backupAndClearTable(); - // utx.commit(); - // } - // utx.begin(); - int loadedRecords = dimensionLoader.mergeTempTable(); - // utx.commit(); - - // utx.begin(); - setStatus = uploadStatusDao.getUploadSetStatus(dimensionLoader - .getUploadId(), setTypeId); - if (loadedRecords == totalRecords) { - setStatus.setLoadStatus("FINISHED"); - } else { - setStatus.setLoadStatus("WARNING"); - } - - setStatus.setLoadedRecord(loadedRecords); - setStatus.setEndDate(new Date(System.currentTimeMillis())); - setStatus.setNoOfRecord(totalRecords); - uploadStatusDao.updateUploadSetStatus(setStatus); - // utx.commit(); - } catch (Throwable e) { - e.printStackTrace(); - t = e; - } finally { - - if (t != null) { - - try { // check if exception thrown after the begin, if so - // rollback - // if (utx.getStatus() == Status.STATUS_ACTIVE) { - // utx.rollback(); - // } // update set status with error status - // utx.begin(); - UploadStatusDAOI uploadStatusDao = uploadDaoFactory - .getUploadStatusDAO(); - UploadSetStatus setStatus = uploadStatusDao - .getUploadSetStatus(dimensionLoader.getUploadId(), - setTypeId); - setStatus.setLoadStatus("ERROR"); - StringWriter stringWriter = new StringWriter(); - t.printStackTrace(new PrintWriter(stringWriter)); - String message = stringWriter.toString(); - if (message != null) { - setStatus.setMessage(message.substring(0, (message - .length() > 3995) ? 3995 : message.length())); - } - setStatus.setEndDate(new Date(System.currentTimeMillis())); - uploadStatusDao.updateUploadSetStatus(setStatus); - // utx.commit(); - // } catch (NotSupportedException e) { - // e.printStackTrace(); - // } catch (SystemException e) { - // e.printStackTrace(); - } catch (SecurityException e) { - e.printStackTrace(); - } catch (IllegalStateException e) { - e.printStackTrace(); - // } catch (RollbackException e) { - // e.printStackTrace(); - // } catch (HeuristicMixedException e) { - // e.printStackTrace(); - // } catch (HeuristicRollbackException e) { - // e.printStackTrace(); - } - throw new I2B2Exception("Error while loading data " - + t.getMessage()); - } - - } - - // setstatus fininshed - } - - @Override - public void deleteUploadData(IUploaderDAOFactory uploaderDaoFactory, - int uploadId) throws I2B2Exception { - UploadStatusDAOI uploadStatusDAO = uploaderDaoFactory - .getUploadStatusDAO(); - // :TODO throw i2b2exception to client. - try { - uploadStatusDAO.deleteUploadData(uploadId); - } catch (I2B2Exception i2b2Ex) { - i2b2Ex.printStackTrace(); - } - } - - private void doNullCheck(String inputLoadFile, String inputLoadFileFormat, - String sourceSystemCd, String userId) throws I2B2Exception { - if (inputLoadFile == null) { - throw new I2B2Exception("Input load file is null"); - } - if (inputLoadFileFormat == null) { - throw new I2B2Exception("Input load file format is null"); - } - if (sourceSystemCd == null) { - throw new I2B2Exception("Input source system code is null"); - } - - if (userId == null) { - throw new I2B2Exception("User id is null"); - } - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.ejb; + +import java.io.File; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.Date; + +import jakarta.xml.bind.JAXBElement; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.loader.dao.IUploaderDAOFactory; +import edu.harvard.i2b2.crc.loader.dao.UploadStatusDAO; +import edu.harvard.i2b2.crc.loader.dao.UploadStatusDAOI; +import edu.harvard.i2b2.crc.loader.datavo.loader.UploadSetStatus; +import edu.harvard.i2b2.crc.loader.datavo.loader.query.PublishDataRequestType; + +/** + * Main class for datamart load operation. The Load function delegates load + * operation to appropriate loader class. + * + * @author rk903 + * + */ +public class DataMartLoader implements IDataMartLoaderHelper { + + // if the format is xml, then input file is in PatientData schema. + public final static String INPUT_LOAD_FORMAT_XML = "XML"; + + public final static String INPUT_LOAD_FORMAT_CSV = "CSV"; + + // this is temp holder, later its read thru property file + public static String loaderWorkingDirectory = "/"; + + + // @EJB(mappedName = "service/local") + // private Service service; + + // log + private static Log log = LogFactory.getLog(DataMartLoader.class); + protected static Log logesapi = LogFactory.getLog(DataMartLoader.class); + + /* + * public void load(int uploadId, String inputLoadFile, String + * inputLoadFileFormat, String sourceSystemCd, boolean visitLoadFlag, + * boolean observationFactLoadFlag,boolean pidLoadFlag, boolean + * patientLoadFlag, String encounterSource, String conceptCodePrefix, + * boolean appendFlag, String userId, boolean tempCleanUpFlag) throws + * I2B2Exception { + */ + + /** + * Main function to start upload process. + * + * @param inputLoadFile + * @param inputLoadFileFormat + * @param visitLoadFlag + * @param observationFactLoadFlag + * @param userId + * @param tempCleanUpFlag + * @throws I2B2Exception + */ + @Override + public void load(IUploaderDAOFactory uploaderDaoFactory, String userId, + int uploadId, String localUploadFile, String publishMessage) + throws I2B2Exception { + + try { + + JAXBUtil jaxbUtil = edu.harvard.i2b2.crc.loader.datavo.CRCLoaderJAXBUtil + .getJAXBUtil(); + PublishDataRequestType publishType = null; + try { + JAXBElement jaxbElement = jaxbUtil + .unMashallFromString(publishMessage); + publishType = (PublishDataRequestType) jaxbElement.getValue(); + } catch (JAXBUtilException jaxbEx) { + throw new I2B2Exception("Error proacessing request message " + + jaxbEx.getMessage(), jaxbEx); + } + + String uploadFileName = localUploadFile; + + String inputLoadFileFormat = publishType.getInputList() + .getDataFile().getDataFormatType().toString(); + String sourceSystemCd = publishType.getInputList().getDataFile() + .getSourceSystemCd(); + boolean visitLoadFlag = (publishType.getLoadList() + .getLoadEventSet() != null) ? true : false; + boolean observationFactLoadFlag = (publishType.getLoadList() + .getLoadObservationSet() != null) ? true : false; + boolean appendFlag = false; + if (observationFactLoadFlag) { + appendFlag = publishType.getLoadList().getLoadObservationSet() + .isAppendFlag(); + } + boolean pidLoadFlag = (publishType.getLoadList().getLoadPidSet() != null) ? true + : false; + boolean eidLoadFlag = (publishType.getLoadList().getLoadEidSet() != null) ? true + : false; + boolean patientLoadFlag = (publishType.getLoadList() + .getLoadPatientSet() != null) ? true : false; + boolean conceptLoadFlag = (publishType.getLoadList() + .getLoadConceptSet() != null) ? true : false; + boolean conceptDeleteExistingDataFlag = (publishType.getLoadList() + .getLoadConceptSet() != null) ? publishType.getLoadList() + .getLoadConceptSet().isDeleteExistingData() : false; + boolean modifierLoadFlag = (publishType.getLoadList() + .getLoadModifierSet() != null) ? true : false; + boolean modifierDeleteExistingDataFlag = (publishType.getLoadList() + .getLoadModifierSet() != null) ? publishType.getLoadList() + .getLoadModifierSet().isDeleteExistingData() : false; + boolean observerLoadFlag = (publishType.getLoadList() + .getLoadObserverSet() != null) ? true : false; + boolean observerDeleteExistingDataFlag = (publishType.getLoadList() + .getLoadObserverSet() != null) ? publishType.getLoadList() + .getLoadObserverSet().isDeleteExistingData() : false; + boolean stagingCleanUpFlag = publishType.getLoadList() + .isClearTempLoadTables(); + + String encounterSource = ""; + String conceptCodePrefix = ""; + + doNullCheck(uploadFileName, inputLoadFileFormat, sourceSystemCd, + userId); + + logesapi.info("Starting to process loadfile :" + uploadFileName + + "format " + inputLoadFileFormat + " userid " + userId); + + // create Upload Status + // uploadId = createUploadStatus(inputLoadFile, "STARTED", + // sourceSystemCd, userId); + // log.info("Created Upload Status: uploadId=" + uploadId); + + // check if pid set need to be loaded + UploadStatusDAOI uploadStatusDAO = uploaderDaoFactory + .getUploadStatusDAO(); + if (pidLoadFlag) { + PidLoader pidLoader = new PidLoader(uploaderDaoFactory, + uploadFileName, inputLoadFileFormat, encounterSource, + sourceSystemCd, uploadId); + performLoad(pidLoader, UploadStatusDAO.PID_SET); + log.info("Pid load complete " + uploadFileName + " uploadId" + + uploadId); + if (stagingCleanUpFlag) { + log.info("Droping temp table [" + + pidLoader.getStagingTableName() + "]"); + uploadStatusDAO.dropTempTable(pidLoader + .getStagingTableName()); + + } + } + + // check if eid set need to be loaded + if (eidLoadFlag) { + EidLoader eidLoader = new EidLoader(uploaderDaoFactory, + uploadFileName, inputLoadFileFormat, encounterSource, + sourceSystemCd, uploadId); + performLoad(eidLoader, UploadStatusDAO.EID_SET); + log.info("Eid load complete " + uploadFileName + " uploadId" + + uploadId); + if (stagingCleanUpFlag) { + log.info("Droping temp table [" + + eidLoader.getStagingTableName() + "]"); + uploadStatusDAO.dropTempTable(eidLoader + .getStagingTableName()); + + } + } + + // check if patient set need to be loaded + if (patientLoadFlag) { + PatientLoader patientLoader = new PatientLoader( + uploaderDaoFactory, uploadFileName, + inputLoadFileFormat, encounterSource, sourceSystemCd, + uploadId); + performLoad(patientLoader, UploadStatusDAO.PATIENT_SET); + log.info("Patient load complete " + uploadFileName + + " uploadId" + uploadId); + if (stagingCleanUpFlag) { + log.info("Droping temp table [" + + patientLoader.getStagingTableName() + "]"); + uploadStatusDAO.dropTempTable(patientLoader + .getStagingTableName()); + + } + } + + // check if visit need to be added + if (visitLoadFlag) { + VisitLoader visitLoader = new VisitLoader(uploaderDaoFactory, + uploadFileName, inputLoadFileFormat, encounterSource, + sourceSystemCd, uploadId); + performLoad(visitLoader, UploadStatusDAO.EVENT_SET); + log.info("Visit load complete " + uploadFileName + " uploadId" + + uploadId); + if (stagingCleanUpFlag) { + log.info("Droping temp table [" + + visitLoader.getStagingTableName() + "]"); + uploadStatusDAO.dropTempTable(visitLoader + .getStagingTableName()); + + } + } + + // check if concept set need to be loaded + if (conceptLoadFlag) { + log.info("Concept load started " + uploadFileName + " uploadId" + + uploadId); + + ConceptLoader conceptLoader = new ConceptLoader( + uploaderDaoFactory, uploadFileName, + inputLoadFileFormat, encounterSource, sourceSystemCd, + conceptDeleteExistingDataFlag, uploadId); + performLoad(conceptLoader, UploadStatusDAO.CONCEPT_SET); + log.info("Concept load complete " + uploadFileName + + " uploadId" + uploadId); + if (stagingCleanUpFlag) { + log.info("Droping temp table [" + + conceptLoader.getStagingTableName() + "]"); + uploadStatusDAO.dropTempTable(conceptLoader + .getStagingTableName()); + + } + } + + // check if modifier set need to be loaded + if (modifierLoadFlag) { + log.info("Modifier load started " + uploadFileName + " uploadId" + + uploadId); + + ModifierLoader modifierLoader = new ModifierLoader( + uploaderDaoFactory, uploadFileName, + inputLoadFileFormat, encounterSource, sourceSystemCd, + modifierDeleteExistingDataFlag, uploadId); + performLoad(modifierLoader, UploadStatusDAO.MODIFIER_SET); + log.info("Modifier load complete " + uploadFileName + + " uploadId" + uploadId); + if (stagingCleanUpFlag) { + log.info("Droping temp table [" + + modifierLoader.getStagingTableName() + "]"); + uploadStatusDAO.dropTempTable(modifierLoader + .getStagingTableName()); + + } + } + + // check if observer set need to be loaded + if (observerLoadFlag) { + log.info("Provider load started " + uploadFileName + + " uploadId" + uploadId); + + ProviderLoader providerLoader = new ProviderLoader( + uploaderDaoFactory, uploadFileName, + inputLoadFileFormat, encounterSource, sourceSystemCd, + observerDeleteExistingDataFlag, uploadId); + performLoad(providerLoader, UploadStatusDAO.OBSERVER_SET); + log.info("Provider load complete " + uploadFileName + + " uploadId" + uploadId); + if (stagingCleanUpFlag) { + log.info("Droping temp table [" + + providerLoader.getStagingTableName() + "]"); + uploadStatusDAO.dropTempTable(providerLoader + .getStagingTableName()); + + } + } + + // check if observation fact need to be added + if (observationFactLoadFlag) { + ObservationFactLoader obsFactLoader = new ObservationFactLoader( + uploaderDaoFactory, uploadFileName, + inputLoadFileFormat, encounterSource, + conceptCodePrefix, sourceSystemCd, appendFlag, uploadId); + performLoad(obsFactLoader, UploadStatusDAO.OBSERVATION_SET); + log.info("ObservationFact load complete " + uploadFileName + + " uploadId" + uploadId); + if (stagingCleanUpFlag) { + + log.info("Droping temp table [" + + obsFactLoader.getStagingTableName() + "]"); + uploadStatusDAO.dropTempTable(obsFactLoader + .getStagingTableName()); + + } + + } + + if (stagingCleanUpFlag) { + try { // remove local input file File + File deleteLocalFile = new File(localUploadFile); + deleteLocalFile.delete(); + } catch (Throwable t) { + log.error("Unable to delete the temp file [" + + localUploadFile + " ]"); + } + } + + } catch (Throwable ex) { + ex.printStackTrace(); + log.error("Error in Upload Process ", ex); + /* + try { + if (utx.getStatus() == Status.STATUS_ACTIVE) { + utx.rollback(); + } + } catch (Exception e) { + log.error("unable to rollback transaction [" + e.getMessage() + + "]"); + } + */ + // rethrow exception + throw new I2B2Exception("Error in Upload Process [" + + ex.getMessage() + "]"); + } + } + + public String getLoaderWorkingDirectory() { + return loaderWorkingDirectory; + } + + public void setLoaderWorkingDirectory(String loaderWorkingDirectory) { + DataMartLoader.loaderWorkingDirectory = loaderWorkingDirectory; + } + + private void performLoad(AbstractDimensionLoader dimensionLoader, + int setTypeId) throws I2B2Exception { + + Throwable t = null; + // setstatus started + IUploaderDAOFactory uploadDaoFactory = dimensionLoader + .getUploaderDaoFactory(); + + try { + +// utx.begin(); + UploadStatusDAOI uploadStatusDao = uploadDaoFactory + .getUploadStatusDAO(); + UploadSetStatus setStatus = new UploadSetStatus(); + setStatus.setUploadId(dimensionLoader.getUploadId()); + setStatus.setLoadStatus("PROCESSING"); + setStatus.setSetTypeId(setTypeId); + setStatus.setInputFileName(dimensionLoader.getInputLoadFile()); + setStatus.setSourceCd(dimensionLoader.getSourceSystemCd()); + setStatus.setLoadDate(new Date(System.currentTimeMillis())); + uploadStatusDao.insertUploadSetStatus(setStatus); + // utx.commit(); + + // utx.begin(); + dimensionLoader.createTempTable(); + // utx.commit(); + + // utx.begin(); + int totalRecords = dimensionLoader.loadTempTable(); + // utx.commit(); + + // if (deleteExistingDataFlag) { + // utx.begin(); + // dimensionLoader.backupAndClearTable(); + // utx.commit(); + // } + // utx.begin(); + int loadedRecords = dimensionLoader.mergeTempTable(); + // utx.commit(); + + // utx.begin(); + setStatus = uploadStatusDao.getUploadSetStatus(dimensionLoader + .getUploadId(), setTypeId); + if (loadedRecords == totalRecords) { + setStatus.setLoadStatus("FINISHED"); + } else { + setStatus.setLoadStatus("WARNING"); + } + + setStatus.setLoadedRecord(loadedRecords); + setStatus.setEndDate(new Date(System.currentTimeMillis())); + setStatus.setNoOfRecord(totalRecords); + uploadStatusDao.updateUploadSetStatus(setStatus); + // utx.commit(); + } catch (Throwable e) { + e.printStackTrace(); + t = e; + } finally { + + if (t != null) { + + try { // check if exception thrown after the begin, if so + // rollback + // if (utx.getStatus() == Status.STATUS_ACTIVE) { + // utx.rollback(); + // } // update set status with error status + // utx.begin(); + UploadStatusDAOI uploadStatusDao = uploadDaoFactory + .getUploadStatusDAO(); + UploadSetStatus setStatus = uploadStatusDao + .getUploadSetStatus(dimensionLoader.getUploadId(), + setTypeId); + setStatus.setLoadStatus("ERROR"); + StringWriter stringWriter = new StringWriter(); + t.printStackTrace(new PrintWriter(stringWriter)); + String message = stringWriter.toString(); + if (message != null) { + setStatus.setMessage(message.substring(0, (message + .length() > 3995) ? 3995 : message.length())); + } + setStatus.setEndDate(new Date(System.currentTimeMillis())); + uploadStatusDao.updateUploadSetStatus(setStatus); + // utx.commit(); + // } catch (NotSupportedException e) { + // e.printStackTrace(); + // } catch (SystemException e) { + // e.printStackTrace(); + } catch (SecurityException e) { + e.printStackTrace(); + } catch (IllegalStateException e) { + e.printStackTrace(); + // } catch (RollbackException e) { + // e.printStackTrace(); + // } catch (HeuristicMixedException e) { + // e.printStackTrace(); + // } catch (HeuristicRollbackException e) { + // e.printStackTrace(); + } + throw new I2B2Exception("Error while loading data " + + t.getMessage()); + } + + } + + // setstatus fininshed + } + + @Override + public void deleteUploadData(IUploaderDAOFactory uploaderDaoFactory, + int uploadId) throws I2B2Exception { + UploadStatusDAOI uploadStatusDAO = uploaderDaoFactory + .getUploadStatusDAO(); + // :TODO throw i2b2exception to client. + try { + uploadStatusDAO.deleteUploadData(uploadId); + } catch (I2B2Exception i2b2Ex) { + i2b2Ex.printStackTrace(); + } + } + + private void doNullCheck(String inputLoadFile, String inputLoadFileFormat, + String sourceSystemCd, String userId) throws I2B2Exception { + if (inputLoadFile == null) { + throw new I2B2Exception("Input load file is null"); + } + if (inputLoadFileFormat == null) { + throw new I2B2Exception("Input load file format is null"); + } + if (sourceSystemCd == null) { + throw new I2B2Exception("Input source system code is null"); + } + + if (userId == null) { + throw new I2B2Exception("User id is null"); + } + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/DataMartLoaderAsyncBean.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/DataMartLoaderAsyncBean.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/DataMartLoaderAsyncBean.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/DataMartLoaderAsyncBean.java index 310b1a32..d1020832 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/DataMartLoaderAsyncBean.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/DataMartLoaderAsyncBean.java @@ -1,635 +1,635 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.ejb; - -import java.io.PrintWriter; -import java.io.StringWriter; -import java.util.Date; -import java.util.Hashtable; -import java.util.List; - -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; -import jakarta.xml.bind.JAXBElement; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.DTOFactory; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.loader.dao.ILoaderDAOFactory; -import edu.harvard.i2b2.crc.loader.dao.IUploaderDAOFactory; -import edu.harvard.i2b2.crc.loader.dao.LoaderDAOFactoryHelper; -import edu.harvard.i2b2.crc.loader.dao.UniqueKeyException; -import edu.harvard.i2b2.crc.loader.dao.UploadStatusDAOI; -import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; -import edu.harvard.i2b2.crc.loader.datavo.loader.DataSourceLookup; -import edu.harvard.i2b2.crc.loader.datavo.loader.UploadSetStatus; -import edu.harvard.i2b2.crc.loader.datavo.loader.UploadStatus; -import edu.harvard.i2b2.crc.loader.datavo.loader.query.BulkLoadRequestType; -import edu.harvard.i2b2.crc.loader.datavo.loader.query.InputOptionListType; -import edu.harvard.i2b2.crc.loader.datavo.loader.query.LoadDataResponseType; -import edu.harvard.i2b2.crc.loader.datavo.loader.query.PublishDataRequestType; -import edu.harvard.i2b2.crc.loader.datavo.loader.query.SetStatusType; -import edu.harvard.i2b2.crc.loader.datavo.loader.query.StatusType; -import edu.harvard.i2b2.crc.loader.datavo.loader.query.LoadDataResponseType.DataFileLocationUri; - -public class DataMartLoaderAsyncBean implements DataMartLoaderAsyncBeanRemote, - DataMartLoaderAsyncBeanLocal { - - DTOFactory dtoFactory = new DTOFactory(); - - // get this - public static final String LOG_REFERENCE_PREFIX = ""; - - protected static Log log = LogFactory.getLog(DataMartLoaderAsyncBean.class); - - /* - * (non-Javadoc) - * - * @see - * edu.harvard.i2b2.crc.loader.ejb.IDataMartLoaderBean#load(java.lang.String - * ) - */ - @Override - public LoadDataResponseType load(DataSourceLookup dataSourceLookup, - String publishMessage, SecurityType i2b2SecurityType, long timeout, - String fileSystemDefaultStorageResource) throws I2B2Exception { - LoadDataResponseType response = null; - String userId = null, password = null; - int uploadId = 0; - Exception exception = null; - - // //String hiveId, String projectId, String ownerId - LoaderDAOFactoryHelper daoHelper = new LoaderDAOFactoryHelper( - dataSourceLookup.getDomainId(), dataSourceLookup - .getProjectPath(), dataSourceLookup.getOwnerId()); - ILoaderDAOFactory loaderDaoFactory = daoHelper.getDAOFactory(); - IUploaderDAOFactory uploaderDaoFactory = loaderDaoFactory - .getUpLoaderDAOFactory(); - log.debug("In Load-1"); - try { - if (i2b2SecurityType == null) { - String errorMsg = "DataMartLoaderAsyncBean.load: input security type is null"; - log.error(errorMsg); - throw new I2B2Exception(errorMsg); - } else { - userId = i2b2SecurityType.getUsername(); - password = i2b2SecurityType.getPassword().getValue(); - - } - PublishDataRequestType publishType = null; - - try { - log.debug("In Load-2"); - - JAXBUtil jaxbUtil = edu.harvard.i2b2.crc.loader.datavo.CRCLoaderJAXBUtil - .getJAXBUtil(); - - JAXBElement jaxbElement = jaxbUtil - .unMashallFromString(publishMessage); - publishType = (PublishDataRequestType) jaxbElement.getValue(); - - } catch (JAXBUtilException jaxbEx) { - - throw new I2B2Exception("Error processing request message " - + jaxbEx.getMessage(), jaxbEx); - } - - // utx.begin(); - log.debug("In Load-3"); - - uploadId = createUploadStatus(uploaderDaoFactory, publishType, - userId); - log.info("Created Upload Status: uploadId=" + uploadId); - // utx.commit(); - - // utx.begin(); - - if ((publishType.getInputList().getDataFile().getTransformName() == null) || - (publishType.getInputList().getDataFile().getTransformName().equals("PDO_IMPORT"))){ - - response = sendAndGetQueueResponse(uploaderDaoFactory, uploadId, - i2b2SecurityType, publishMessage, timeout, - fileSystemDefaultStorageResource); - } - - // Its something other than a PDO import so dont kick off queueing.. - else{ - if(publishType.getInputList().getDataFile().getTransformName().equals("GENOMIC_IMPORT")){ - if(publishType.getInputList().getDataFile().getLoadLabel().equals("BULK_LOAD_OBS_FACT")){ - createSetUploadStatus(uploaderDaoFactory, publishType,uploadId, 5); - } - } - response = buildResponse(uploaderDaoFactory, uploadId); - } - // utx.commit(); - // return processUploadMessage(publishType); - } catch (I2B2Exception e) { - exception = e; - } catch (SecurityException e) { - exception = e; - } catch (IllegalStateException e) { - exception = e; - } finally { - if (exception != null) { - //try { - // if (utx.getStatus() == Status.STATUS_ACTIVE) { - // utx.rollback(); - // } - //} catch (Exception e) { - //} - - try { - // utx.begin(); - // update status - - StringWriter stringWriter = new StringWriter(); - exception.printStackTrace(new PrintWriter(stringWriter)); - updateUploadStatus(uploaderDaoFactory, uploadId, - "INCOMPLETE", stringWriter.toString()); - // build response - response = buildResponse(uploaderDaoFactory, uploadId); - // utx.commit(); - } catch (Exception e) { - // try { - // utx.rollback(); - // } catch (Exception e1) { - // } - } - - String errorMsg = "LoadDataResponseType.load:Error " - + exception.getMessage(); - log.error(errorMsg); - throw new I2B2Exception(errorMsg, exception); - - } - - } - - return response; - - } - - public LoadDataResponseType bulkLoad(DataSourceLookup dataSourceLookup, - String bulkLoadMessage, SecurityType i2b2SecurityType, long timeout) throws I2B2Exception { - LoadDataResponseType response = null; - String userId = null, password = null; - int uploadId = 0; - Exception exception = null; - - // //String hiveId, String projectId, String ownerId - LoaderDAOFactoryHelper daoHelper = new LoaderDAOFactoryHelper( - dataSourceLookup.getDomainId(), dataSourceLookup - .getProjectPath(), dataSourceLookup.getOwnerId()); - ILoaderDAOFactory loaderDaoFactory = daoHelper.getDAOFactory(); - IUploaderDAOFactory uploaderDaoFactory = loaderDaoFactory - .getUpLoaderDAOFactory(); - // log.debug("In BulkLoad-1"); - try { - if (i2b2SecurityType == null) { - String errorMsg = "DataMartLoaderAsyncBean.bulkLoad: input security type is null"; - log.error(errorMsg); - throw new I2B2Exception(errorMsg); - } else { - userId = i2b2SecurityType.getUsername(); - password = i2b2SecurityType.getPassword().getValue(); - - } - BulkLoadRequestType bulkLoadType = null; - - try { - // log.debug("In BulkLoad-2"); - - JAXBUtil jaxbUtil = edu.harvard.i2b2.crc.loader.datavo.CRCLoaderJAXBUtil - .getJAXBUtil(); - - JAXBElement jaxbElement = jaxbUtil - .unMashallFromString(bulkLoadMessage); - bulkLoadType = (BulkLoadRequestType) jaxbElement.getValue(); - - } catch (JAXBUtilException jaxbEx) { - - throw new I2B2Exception("Error processing request message " - + jaxbEx.getMessage(), jaxbEx); - } - - // utx.begin(); - // log.debug("In BulkLoad-3"); - - uploadId = createUploadStatus(uploaderDaoFactory, bulkLoadType, - userId); - // log.info("Created Upload Status: uploadId=" + uploadId); - // utx.commit(); - - // utx.begin(); - response = buildBulkLoadResponse(uploaderDaoFactory, uploadId); - // utx.commit(); - // return processUploadMessage(publishType); - } catch (I2B2Exception e) { - exception = e; - } catch (SecurityException e) { - exception = e; - } catch (IllegalStateException e) { - exception = e; - } finally { - if (exception != null) { - //try { - // if (utx.getStatus() == Status.STATUS_ACTIVE) { - // utx.rollback(); - // } - //} catch (Exception e) { - //} - - try { - // utx.begin(); - // update status - - StringWriter stringWriter = new StringWriter(); - exception.printStackTrace(new PrintWriter(stringWriter)); - updateUploadStatus(uploaderDaoFactory, uploadId, - "INCOMPLETE", stringWriter.toString()); - // build response - response = buildBulkLoadResponse(uploaderDaoFactory, uploadId); - // utx.commit(); - } catch (Exception e) { - // try { - // utx.rollback(); - // } catch (Exception e1) { - // } - } - - String errorMsg = "LoadDataResponseType.bulkLoad:Error " - + exception.getMessage(); - log.error(errorMsg); - throw new I2B2Exception(errorMsg, exception); - - } - - } - - return response; - - } - - - - - - private int createUploadStatus(IUploaderDAOFactory uploaderDaoFactory, - PublishDataRequestType publishType, String userId) - throws I2B2Exception { - InputOptionListType inputOptionType = publishType.getInputList(); - String loadFileName = inputOptionType.getDataFile().getLocationUri() - .getValue(); - String sourceSystemCd = inputOptionType.getDataFile() - .getSourceSystemCd(); - - String status = "QUEUED"; - String uploadLabel = inputOptionType.getDataFile().getLoadLabel(); - UploadStatus uploadStatus = new UploadStatus(); - uploadStatus.setInputFileName(loadFileName); - uploadStatus.setUploadLabel(uploadLabel); - uploadStatus.setSourceCd(sourceSystemCd); - uploadStatus.setLoadStatus(status); - uploadStatus.setUserId(userId); - uploadStatus.setLoadDate(new Date(System.currentTimeMillis())); - uploadStatus.setTransformName(inputOptionType.getDataFile().getTransformName()); - - UploadStatusDAOI uploadStatusDAO = uploaderDaoFactory - .getUploadStatusDAO(); - return uploadStatusDAO.insertUploadStatus(uploadStatus); - - } - - /* - * This method is a way for the non-PDO loads to write the initial entry - * to the set_upload_status table - */ - - private void createSetUploadStatus(IUploaderDAOFactory uploaderDaoFactory, - PublishDataRequestType publishType, int uploadId, int setId) - throws I2B2Exception { - InputOptionListType inputOptionType = publishType.getInputList(); - String loadFileName = inputOptionType.getDataFile().getLocationUri().getValue(); - - //set_upload_status has no load label, so store this info in source system code. - String sourceSystemCd = inputOptionType.getDataFile().getLoadLabel(); - - String status = "QUEUED"; - UploadSetStatus uploadSetStatus = new UploadSetStatus(); - uploadSetStatus.setUploadId(uploadId); - uploadSetStatus.setInputFileName(loadFileName); - uploadSetStatus.setSetTypeId(setId); - uploadSetStatus.setSourceCd(sourceSystemCd); - uploadSetStatus.setLoadStatus(status); - uploadSetStatus.setLoadDate(new Date(System.currentTimeMillis())); - uploadSetStatus.setTransformName(inputOptionType.getDataFile().getTransformName()); - - UploadStatusDAOI uploadStatusDAO = uploaderDaoFactory - .getUploadStatusDAO(); - uploadStatusDAO.insertUploadSetStatus(uploadSetStatus); - - } - - - private int createUploadStatus(IUploaderDAOFactory uploaderDaoFactory, - BulkLoadRequestType bulkLoadType, String userId) - throws I2B2Exception { - String loadFileName = bulkLoadType.getFileName(); - String sourceSystemCd = bulkLoadType.getSourceSystemCd(); - - String status = "READY"; - String uploadLabel = bulkLoadType.getFileType(); - UploadStatus uploadStatus = new UploadStatus(); - uploadStatus.setInputFileName(loadFileName); - uploadStatus.setUploadLabel(uploadLabel); - uploadStatus.setSourceCd(sourceSystemCd); - uploadStatus.setLoadStatus(status); - uploadStatus.setUserId(userId); - uploadStatus.setLoadDate(new Date(System.currentTimeMillis())); - - UploadStatusDAOI uploadStatusDAO = uploaderDaoFactory - .getUploadStatusDAO(); - return uploadStatusDAO.insertUploadStatus(uploadStatus); - - } - - private void updateUploadStatus(IUploaderDAOFactory uploaderDaoFactory, - int uploadId, String status, String message) throws I2B2Exception { - UploadStatusDAOI uploadStatusDAO = uploaderDaoFactory - .getUploadStatusDAO(); - // try { - UploadStatus uploadStatus; - try { - uploadStatus = uploadStatusDAO.findById(uploadId); - uploadStatus.setLoadStatus(status); - if (message != null) { - int length = (message.length() > 3995) ? 3995 : message - .length(); - uploadStatus.setMessage(message.substring(0, length)); - } - uploadStatus.setEndDate(new Date(System.currentTimeMillis())); - uploadStatusDAO.updateUploadStatus(uploadStatus); - // uploadStatusDAO.calculateUploadStatus(uploadId); - - } catch (UniqueKeyException unqEx) { - unqEx.printStackTrace(); - log.error("Error while upload status update", unqEx); - } - } - - private LoadDataResponseType sendAndGetQueueResponse( - IUploaderDAOFactory uploaderDaoFactory, int uploadId, - SecurityType securityType, String publishMessage, long timeout, - String fileSystemDefaultStorageResource) { - /*//mm removed EJB - Session session = null; - MessageProducer producer = null; - MessageConsumer receiver = null; - TextMessage message = null; - */ - LoadDataResponseType response = null; - try { - /*//mm removed EJB - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - producer = session.createProducer(queue); - message = session.createTextMessage(); - - message.setJMSCorrelationID(String.valueOf(uploadId)); - message.setIntProperty(DataMartLoaderBeanMDB.UPLOAD_ID, uploadId); - message.setStringProperty(DataMartLoaderBeanMDB.I2B2_USER_ID, - securityType.getUsername()); - message.setStringProperty(DataMartLoaderBeanMDB.I2B2_PASSWORD, - securityType.getPassword().getValue()); - message.setBooleanProperty(DataMartLoaderBeanMDB.I2B2_PASSWORD_ISTOKEN, - securityType.getPassword().isIsToken()); - - message.setStringProperty( - DataMartLoaderBeanMDB.DS_LOOKUP_DOMAIN_ID, - uploaderDaoFactory.getDataSourceLookup().getDomainId()); - message.setStringProperty(DataMartLoaderBeanMDB.DS_LOOKUP_OWNER_ID, - uploaderDaoFactory.getDataSourceLookup().getOwnerId()); - message.setStringProperty( - DataMartLoaderBeanMDB.DS_LOOKUP_PROJECT_ID, - uploaderDaoFactory.getDataSourceLookup().getProjectPath()); - message.setStringProperty( - DataMartLoaderBeanMDB.IROD_FILESYSTEM_STORAGE_RESOURCE, - fileSystemDefaultStorageResource); - - message.setText(publishMessage); - log.info("DataMartLoaderSync: Sending " + "message text to: " - + message.getText()); - producer.send(message); - - // - String selector = "JMSCorrelationID='" + uploadId + "'"; - receiver = session.createConsumer(responseQueue, selector); - - connection.start(); - - TextMessage inMessage = (TextMessage) receiver.receive(timeout); - if (inMessage != null) { - log.debug("Received text message from response queue" - + inMessage.getText()); - - } - */ - - - - // no longer needed? - // message.put( - // DataMartLoaderBeanMDB.IROD_FILESYSTEM_STORAGE_RESOURCE, - // fileSystemDefaultStorageResource); - - - log.debug("In DatamartLoaderAsync about to run MDB.onMessage"); - - - - - - response = buildResponse(uploaderDaoFactory, uploadId); - } catch (Throwable t) { - // JMSException could be thrown - log.error("DataMartLoaderAsync.sendAndGetQueueResponse: " - + "Exception: " + t.toString()); - - - - StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw); - t.printStackTrace(pw); - - try { - buildResponse(uploaderDaoFactory, uploadId); - } catch (I2B2Exception e) { - StatusType statusType = new StatusType(); - StatusType.Condition condition = new StatusType.Condition(); - condition.setType("ERROR"); - condition.setValue(sw.toString()); - statusType.getCondition().add(condition); - response.setStatus(statusType); - } - } finally { - //mm removed EJB - /* - if (session != null) { - try { - session.close(); - } catch (JMSException e) { - } - } - */ - - } - return response; - - } - - private LoadDataResponseType buildResponse( - IUploaderDAOFactory uploaderDaoFactory, int uploadId) - throws I2B2Exception { - LoadDataResponseType response = new LoadDataResponseType(); - try { - UploadStatusDAOI statusDao = uploaderDaoFactory - .getUploadStatusDAO(); - - UploadStatus uploadStatus = statusDao.findById(uploadId); - // build response - DataFileLocationUri fileLoc = new DataFileLocationUri(); - fileLoc.setValue(uploadStatus.getInputFileName()); - response.setDataFileLocationUri(fileLoc); - response.setLoadStatus(uploadStatus.getLoadStatus()); - response.setUploadId(String.valueOf(uploadStatus.getUploadId())); - response.setUserId(uploadStatus.getUserId()); - response.setMessage(uploadStatus.getMessage()); - response.setTransformerName(uploadStatus.getTransformName()); - response.setStartDate(dtoFactory - .getXMLGregorianCalendar(uploadStatus.getLoadDate() - .getTime())); - if (uploadStatus.getEndDate() != null) { - response.setEndDate(dtoFactory - .getXMLGregorianCalendar(uploadStatus.getEndDate() - .getTime())); - } - - List setStatusList = statusDao - .getUploadSetStatusByLoadId(uploadId); - for (UploadSetStatus setStatus : setStatusList) { - SetStatusType responseSetStatusType = new SetStatusType(); - responseSetStatusType.setIgnoredRecord(setStatus - .getNoOfRecord() - - setStatus.getLoadedRecord()); - responseSetStatusType.setInsertedRecord(setStatus - .getLoadedRecord()); - responseSetStatusType.setMessage(setStatus.getMessage()); - responseSetStatusType.setTotalRecord(setStatus.getNoOfRecord()); - if (setStatus.getSetTypeId() == 1) { - response.setEventSet(responseSetStatusType); - } else if (setStatus.getSetTypeId() == 2) { - response.setPatientSet(responseSetStatusType); - } else if (setStatus.getSetTypeId() == 3) { - response.setConceptSet(responseSetStatusType); - } else if (setStatus.getSetTypeId() == 4) { - response.setObserverSet(responseSetStatusType); - } else if (setStatus.getSetTypeId() == 5) { - response.setObservationSet(responseSetStatusType); - } else if (setStatus.getSetTypeId() == 6) { - response.setPidSet(responseSetStatusType); - } else if (setStatus.getSetTypeId() == 7) { - response.setEventidSet(responseSetStatusType); - } else if (setStatus.getSetTypeId() == 8) { - response.setModifierSet(responseSetStatusType); - } - - } - } catch (I2B2Exception i2b2Ex) { - throw new I2B2Exception( - "DataMartLoaderAsync.buildResponse:Exception" - + i2b2Ex.getMessage(), i2b2Ex); - } - return response; - } - - private LoadDataResponseType buildBulkLoadResponse( - IUploaderDAOFactory uploaderDaoFactory, int uploadId) - throws I2B2Exception { - LoadDataResponseType response = new LoadDataResponseType(); - try { - UploadStatusDAOI statusDao = uploaderDaoFactory - .getUploadStatusDAO(); - - UploadStatus uploadStatus = statusDao.findById(uploadId); - // build response - DataFileLocationUri fileLoc = new DataFileLocationUri(); - fileLoc.setValue(uploadStatus.getInputFileName()); - response.setDataFileLocationUri(fileLoc); - response.setLoadStatus(uploadStatus.getLoadStatus()); - response.setUploadId(String.valueOf(uploadStatus.getUploadId())); - response.setUserId(uploadStatus.getUserId()); - response.setMessage(uploadStatus.getMessage()); - response.setTransformerName(uploadStatus.getTransformName()); - response.setStartDate(dtoFactory - .getXMLGregorianCalendar(uploadStatus.getLoadDate() - .getTime())); - if (uploadStatus.getEndDate() != null) { - response.setEndDate(dtoFactory - .getXMLGregorianCalendar(uploadStatus.getEndDate() - .getTime())); - - } - } catch (I2B2Exception i2b2Ex) { - throw new I2B2Exception( - "DataMartLoaderAsync.buildBulkLoadResponse:Exception" - + i2b2Ex.getMessage(), i2b2Ex); - } - return response; - } - - - - /** - * Creates the connection. - */ - @PostConstruct - public void makeConnection() { - try { - //mm removed EJB - // connection = connectionFactory.createConnection(); - } catch (Throwable t) { - // JMSException could be thrown - log.error("DataMartLoaderAsync.makeConnection:" + "Exception: " - + t.toString()); - } - } - - /** - * Closes the connection. - */ - @PreDestroy - public void endConnection() throws RuntimeException { - //mm removed EJB - /* - if (connection != null) { - try { - connection.close(); - } catch (Exception e) { - e.printStackTrace(); - } - } - */ - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.ejb; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.Date; +import java.util.Hashtable; +import java.util.List; + +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; +import jakarta.xml.bind.JAXBElement; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.DTOFactory; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.loader.dao.ILoaderDAOFactory; +import edu.harvard.i2b2.crc.loader.dao.IUploaderDAOFactory; +import edu.harvard.i2b2.crc.loader.dao.LoaderDAOFactoryHelper; +import edu.harvard.i2b2.crc.loader.dao.UniqueKeyException; +import edu.harvard.i2b2.crc.loader.dao.UploadStatusDAOI; +import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; +import edu.harvard.i2b2.crc.loader.datavo.loader.DataSourceLookup; +import edu.harvard.i2b2.crc.loader.datavo.loader.UploadSetStatus; +import edu.harvard.i2b2.crc.loader.datavo.loader.UploadStatus; +import edu.harvard.i2b2.crc.loader.datavo.loader.query.BulkLoadRequestType; +import edu.harvard.i2b2.crc.loader.datavo.loader.query.InputOptionListType; +import edu.harvard.i2b2.crc.loader.datavo.loader.query.LoadDataResponseType; +import edu.harvard.i2b2.crc.loader.datavo.loader.query.PublishDataRequestType; +import edu.harvard.i2b2.crc.loader.datavo.loader.query.SetStatusType; +import edu.harvard.i2b2.crc.loader.datavo.loader.query.StatusType; +import edu.harvard.i2b2.crc.loader.datavo.loader.query.LoadDataResponseType.DataFileLocationUri; + +public class DataMartLoaderAsyncBean implements DataMartLoaderAsyncBeanRemote, + DataMartLoaderAsyncBeanLocal { + + DTOFactory dtoFactory = new DTOFactory(); + + // get this + public static final String LOG_REFERENCE_PREFIX = ""; + + protected static Log log = LogFactory.getLog(DataMartLoaderAsyncBean.class); + + /* + * (non-Javadoc) + * + * @see + * edu.harvard.i2b2.crc.loader.ejb.IDataMartLoaderBean#load(java.lang.String + * ) + */ + @Override + public LoadDataResponseType load(DataSourceLookup dataSourceLookup, + String publishMessage, SecurityType i2b2SecurityType, long timeout, + String fileSystemDefaultStorageResource) throws I2B2Exception { + LoadDataResponseType response = null; + String userId = null, password = null; + int uploadId = 0; + Exception exception = null; + + // //String hiveId, String projectId, String ownerId + LoaderDAOFactoryHelper daoHelper = new LoaderDAOFactoryHelper( + dataSourceLookup.getDomainId(), dataSourceLookup + .getProjectPath(), dataSourceLookup.getOwnerId()); + ILoaderDAOFactory loaderDaoFactory = daoHelper.getDAOFactory(); + IUploaderDAOFactory uploaderDaoFactory = loaderDaoFactory + .getUpLoaderDAOFactory(); + log.debug("In Load-1"); + try { + if (i2b2SecurityType == null) { + String errorMsg = "DataMartLoaderAsyncBean.load: input security type is null"; + log.error(errorMsg); + throw new I2B2Exception(errorMsg); + } else { + userId = i2b2SecurityType.getUsername(); + password = i2b2SecurityType.getPassword().getValue(); + + } + PublishDataRequestType publishType = null; + + try { + log.debug("In Load-2"); + + JAXBUtil jaxbUtil = edu.harvard.i2b2.crc.loader.datavo.CRCLoaderJAXBUtil + .getJAXBUtil(); + + JAXBElement jaxbElement = jaxbUtil + .unMashallFromString(publishMessage); + publishType = (PublishDataRequestType) jaxbElement.getValue(); + + } catch (JAXBUtilException jaxbEx) { + + throw new I2B2Exception("Error processing request message " + + jaxbEx.getMessage(), jaxbEx); + } + + // utx.begin(); + log.debug("In Load-3"); + + uploadId = createUploadStatus(uploaderDaoFactory, publishType, + userId); + log.info("Created Upload Status: uploadId=" + uploadId); + // utx.commit(); + + // utx.begin(); + + if ((publishType.getInputList().getDataFile().getTransformName() == null) || + (publishType.getInputList().getDataFile().getTransformName().equals("PDO_IMPORT"))){ + + response = sendAndGetQueueResponse(uploaderDaoFactory, uploadId, + i2b2SecurityType, publishMessage, timeout, + fileSystemDefaultStorageResource); + } + + // Its something other than a PDO import so dont kick off queueing.. + else{ + if(publishType.getInputList().getDataFile().getTransformName().equals("GENOMIC_IMPORT")){ + if(publishType.getInputList().getDataFile().getLoadLabel().equals("BULK_LOAD_OBS_FACT")){ + createSetUploadStatus(uploaderDaoFactory, publishType,uploadId, 5); + } + } + response = buildResponse(uploaderDaoFactory, uploadId); + } + // utx.commit(); + // return processUploadMessage(publishType); + } catch (I2B2Exception e) { + exception = e; + } catch (SecurityException e) { + exception = e; + } catch (IllegalStateException e) { + exception = e; + } finally { + if (exception != null) { + //try { + // if (utx.getStatus() == Status.STATUS_ACTIVE) { + // utx.rollback(); + // } + //} catch (Exception e) { + //} + + try { + // utx.begin(); + // update status + + StringWriter stringWriter = new StringWriter(); + exception.printStackTrace(new PrintWriter(stringWriter)); + updateUploadStatus(uploaderDaoFactory, uploadId, + "INCOMPLETE", stringWriter.toString()); + // build response + response = buildResponse(uploaderDaoFactory, uploadId); + // utx.commit(); + } catch (Exception e) { + // try { + // utx.rollback(); + // } catch (Exception e1) { + // } + } + + String errorMsg = "LoadDataResponseType.load:Error " + + exception.getMessage(); + log.error(errorMsg); + throw new I2B2Exception(errorMsg, exception); + + } + + } + + return response; + + } + + public LoadDataResponseType bulkLoad(DataSourceLookup dataSourceLookup, + String bulkLoadMessage, SecurityType i2b2SecurityType, long timeout) throws I2B2Exception { + LoadDataResponseType response = null; + String userId = null, password = null; + int uploadId = 0; + Exception exception = null; + + // //String hiveId, String projectId, String ownerId + LoaderDAOFactoryHelper daoHelper = new LoaderDAOFactoryHelper( + dataSourceLookup.getDomainId(), dataSourceLookup + .getProjectPath(), dataSourceLookup.getOwnerId()); + ILoaderDAOFactory loaderDaoFactory = daoHelper.getDAOFactory(); + IUploaderDAOFactory uploaderDaoFactory = loaderDaoFactory + .getUpLoaderDAOFactory(); + // log.debug("In BulkLoad-1"); + try { + if (i2b2SecurityType == null) { + String errorMsg = "DataMartLoaderAsyncBean.bulkLoad: input security type is null"; + log.error(errorMsg); + throw new I2B2Exception(errorMsg); + } else { + userId = i2b2SecurityType.getUsername(); + password = i2b2SecurityType.getPassword().getValue(); + + } + BulkLoadRequestType bulkLoadType = null; + + try { + // log.debug("In BulkLoad-2"); + + JAXBUtil jaxbUtil = edu.harvard.i2b2.crc.loader.datavo.CRCLoaderJAXBUtil + .getJAXBUtil(); + + JAXBElement jaxbElement = jaxbUtil + .unMashallFromString(bulkLoadMessage); + bulkLoadType = (BulkLoadRequestType) jaxbElement.getValue(); + + } catch (JAXBUtilException jaxbEx) { + + throw new I2B2Exception("Error processing request message " + + jaxbEx.getMessage(), jaxbEx); + } + + // utx.begin(); + // log.debug("In BulkLoad-3"); + + uploadId = createUploadStatus(uploaderDaoFactory, bulkLoadType, + userId); + // log.info("Created Upload Status: uploadId=" + uploadId); + // utx.commit(); + + // utx.begin(); + response = buildBulkLoadResponse(uploaderDaoFactory, uploadId); + // utx.commit(); + // return processUploadMessage(publishType); + } catch (I2B2Exception e) { + exception = e; + } catch (SecurityException e) { + exception = e; + } catch (IllegalStateException e) { + exception = e; + } finally { + if (exception != null) { + //try { + // if (utx.getStatus() == Status.STATUS_ACTIVE) { + // utx.rollback(); + // } + //} catch (Exception e) { + //} + + try { + // utx.begin(); + // update status + + StringWriter stringWriter = new StringWriter(); + exception.printStackTrace(new PrintWriter(stringWriter)); + updateUploadStatus(uploaderDaoFactory, uploadId, + "INCOMPLETE", stringWriter.toString()); + // build response + response = buildBulkLoadResponse(uploaderDaoFactory, uploadId); + // utx.commit(); + } catch (Exception e) { + // try { + // utx.rollback(); + // } catch (Exception e1) { + // } + } + + String errorMsg = "LoadDataResponseType.bulkLoad:Error " + + exception.getMessage(); + log.error(errorMsg); + throw new I2B2Exception(errorMsg, exception); + + } + + } + + return response; + + } + + + + + + private int createUploadStatus(IUploaderDAOFactory uploaderDaoFactory, + PublishDataRequestType publishType, String userId) + throws I2B2Exception { + InputOptionListType inputOptionType = publishType.getInputList(); + String loadFileName = inputOptionType.getDataFile().getLocationUri() + .getValue(); + String sourceSystemCd = inputOptionType.getDataFile() + .getSourceSystemCd(); + + String status = "QUEUED"; + String uploadLabel = inputOptionType.getDataFile().getLoadLabel(); + UploadStatus uploadStatus = new UploadStatus(); + uploadStatus.setInputFileName(loadFileName); + uploadStatus.setUploadLabel(uploadLabel); + uploadStatus.setSourceCd(sourceSystemCd); + uploadStatus.setLoadStatus(status); + uploadStatus.setUserId(userId); + uploadStatus.setLoadDate(new Date(System.currentTimeMillis())); + uploadStatus.setTransformName(inputOptionType.getDataFile().getTransformName()); + + UploadStatusDAOI uploadStatusDAO = uploaderDaoFactory + .getUploadStatusDAO(); + return uploadStatusDAO.insertUploadStatus(uploadStatus); + + } + + /* + * This method is a way for the non-PDO loads to write the initial entry + * to the set_upload_status table + */ + + private void createSetUploadStatus(IUploaderDAOFactory uploaderDaoFactory, + PublishDataRequestType publishType, int uploadId, int setId) + throws I2B2Exception { + InputOptionListType inputOptionType = publishType.getInputList(); + String loadFileName = inputOptionType.getDataFile().getLocationUri().getValue(); + + //set_upload_status has no load label, so store this info in source system code. + String sourceSystemCd = inputOptionType.getDataFile().getLoadLabel(); + + String status = "QUEUED"; + UploadSetStatus uploadSetStatus = new UploadSetStatus(); + uploadSetStatus.setUploadId(uploadId); + uploadSetStatus.setInputFileName(loadFileName); + uploadSetStatus.setSetTypeId(setId); + uploadSetStatus.setSourceCd(sourceSystemCd); + uploadSetStatus.setLoadStatus(status); + uploadSetStatus.setLoadDate(new Date(System.currentTimeMillis())); + uploadSetStatus.setTransformName(inputOptionType.getDataFile().getTransformName()); + + UploadStatusDAOI uploadStatusDAO = uploaderDaoFactory + .getUploadStatusDAO(); + uploadStatusDAO.insertUploadSetStatus(uploadSetStatus); + + } + + + private int createUploadStatus(IUploaderDAOFactory uploaderDaoFactory, + BulkLoadRequestType bulkLoadType, String userId) + throws I2B2Exception { + String loadFileName = bulkLoadType.getFileName(); + String sourceSystemCd = bulkLoadType.getSourceSystemCd(); + + String status = "READY"; + String uploadLabel = bulkLoadType.getFileType(); + UploadStatus uploadStatus = new UploadStatus(); + uploadStatus.setInputFileName(loadFileName); + uploadStatus.setUploadLabel(uploadLabel); + uploadStatus.setSourceCd(sourceSystemCd); + uploadStatus.setLoadStatus(status); + uploadStatus.setUserId(userId); + uploadStatus.setLoadDate(new Date(System.currentTimeMillis())); + + UploadStatusDAOI uploadStatusDAO = uploaderDaoFactory + .getUploadStatusDAO(); + return uploadStatusDAO.insertUploadStatus(uploadStatus); + + } + + private void updateUploadStatus(IUploaderDAOFactory uploaderDaoFactory, + int uploadId, String status, String message) throws I2B2Exception { + UploadStatusDAOI uploadStatusDAO = uploaderDaoFactory + .getUploadStatusDAO(); + // try { + UploadStatus uploadStatus; + try { + uploadStatus = uploadStatusDAO.findById(uploadId); + uploadStatus.setLoadStatus(status); + if (message != null) { + int length = (message.length() > 3995) ? 3995 : message + .length(); + uploadStatus.setMessage(message.substring(0, length)); + } + uploadStatus.setEndDate(new Date(System.currentTimeMillis())); + uploadStatusDAO.updateUploadStatus(uploadStatus); + // uploadStatusDAO.calculateUploadStatus(uploadId); + + } catch (UniqueKeyException unqEx) { + unqEx.printStackTrace(); + log.error("Error while upload status update", unqEx); + } + } + + private LoadDataResponseType sendAndGetQueueResponse( + IUploaderDAOFactory uploaderDaoFactory, int uploadId, + SecurityType securityType, String publishMessage, long timeout, + String fileSystemDefaultStorageResource) { + /*//mm removed EJB + Session session = null; + MessageProducer producer = null; + MessageConsumer receiver = null; + TextMessage message = null; + */ + LoadDataResponseType response = null; + try { + /*//mm removed EJB + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + producer = session.createProducer(queue); + message = session.createTextMessage(); + + message.setJMSCorrelationID(String.valueOf(uploadId)); + message.setIntProperty(DataMartLoaderBeanMDB.UPLOAD_ID, uploadId); + message.setStringProperty(DataMartLoaderBeanMDB.I2B2_USER_ID, + securityType.getUsername()); + message.setStringProperty(DataMartLoaderBeanMDB.I2B2_PASSWORD, + securityType.getPassword().getValue()); + message.setBooleanProperty(DataMartLoaderBeanMDB.I2B2_PASSWORD_ISTOKEN, + securityType.getPassword().isIsToken()); + + message.setStringProperty( + DataMartLoaderBeanMDB.DS_LOOKUP_DOMAIN_ID, + uploaderDaoFactory.getDataSourceLookup().getDomainId()); + message.setStringProperty(DataMartLoaderBeanMDB.DS_LOOKUP_OWNER_ID, + uploaderDaoFactory.getDataSourceLookup().getOwnerId()); + message.setStringProperty( + DataMartLoaderBeanMDB.DS_LOOKUP_PROJECT_ID, + uploaderDaoFactory.getDataSourceLookup().getProjectPath()); + message.setStringProperty( + DataMartLoaderBeanMDB.IROD_FILESYSTEM_STORAGE_RESOURCE, + fileSystemDefaultStorageResource); + + message.setText(publishMessage); + log.info("DataMartLoaderSync: Sending " + "message text to: " + + message.getText()); + producer.send(message); + + // + String selector = "JMSCorrelationID='" + uploadId + "'"; + receiver = session.createConsumer(responseQueue, selector); + + connection.start(); + + TextMessage inMessage = (TextMessage) receiver.receive(timeout); + if (inMessage != null) { + log.debug("Received text message from response queue" + + inMessage.getText()); + + } + */ + + + + // no longer needed? + // message.put( + // DataMartLoaderBeanMDB.IROD_FILESYSTEM_STORAGE_RESOURCE, + // fileSystemDefaultStorageResource); + + + log.debug("In DatamartLoaderAsync about to run MDB.onMessage"); + + + + + + response = buildResponse(uploaderDaoFactory, uploadId); + } catch (Throwable t) { + // JMSException could be thrown + log.error("DataMartLoaderAsync.sendAndGetQueueResponse: " + + "Exception: " + t.toString()); + + + + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + t.printStackTrace(pw); + + try { + buildResponse(uploaderDaoFactory, uploadId); + } catch (I2B2Exception e) { + StatusType statusType = new StatusType(); + StatusType.Condition condition = new StatusType.Condition(); + condition.setType("ERROR"); + condition.setValue(sw.toString()); + statusType.getCondition().add(condition); + response.setStatus(statusType); + } + } finally { + //mm removed EJB + /* + if (session != null) { + try { + session.close(); + } catch (JMSException e) { + } + } + */ + + } + return response; + + } + + private LoadDataResponseType buildResponse( + IUploaderDAOFactory uploaderDaoFactory, int uploadId) + throws I2B2Exception { + LoadDataResponseType response = new LoadDataResponseType(); + try { + UploadStatusDAOI statusDao = uploaderDaoFactory + .getUploadStatusDAO(); + + UploadStatus uploadStatus = statusDao.findById(uploadId); + // build response + DataFileLocationUri fileLoc = new DataFileLocationUri(); + fileLoc.setValue(uploadStatus.getInputFileName()); + response.setDataFileLocationUri(fileLoc); + response.setLoadStatus(uploadStatus.getLoadStatus()); + response.setUploadId(String.valueOf(uploadStatus.getUploadId())); + response.setUserId(uploadStatus.getUserId()); + response.setMessage(uploadStatus.getMessage()); + response.setTransformerName(uploadStatus.getTransformName()); + response.setStartDate(dtoFactory + .getXMLGregorianCalendar(uploadStatus.getLoadDate() + .getTime())); + if (uploadStatus.getEndDate() != null) { + response.setEndDate(dtoFactory + .getXMLGregorianCalendar(uploadStatus.getEndDate() + .getTime())); + } + + List setStatusList = statusDao + .getUploadSetStatusByLoadId(uploadId); + for (UploadSetStatus setStatus : setStatusList) { + SetStatusType responseSetStatusType = new SetStatusType(); + responseSetStatusType.setIgnoredRecord(setStatus + .getNoOfRecord() + - setStatus.getLoadedRecord()); + responseSetStatusType.setInsertedRecord(setStatus + .getLoadedRecord()); + responseSetStatusType.setMessage(setStatus.getMessage()); + responseSetStatusType.setTotalRecord(setStatus.getNoOfRecord()); + if (setStatus.getSetTypeId() == 1) { + response.setEventSet(responseSetStatusType); + } else if (setStatus.getSetTypeId() == 2) { + response.setPatientSet(responseSetStatusType); + } else if (setStatus.getSetTypeId() == 3) { + response.setConceptSet(responseSetStatusType); + } else if (setStatus.getSetTypeId() == 4) { + response.setObserverSet(responseSetStatusType); + } else if (setStatus.getSetTypeId() == 5) { + response.setObservationSet(responseSetStatusType); + } else if (setStatus.getSetTypeId() == 6) { + response.setPidSet(responseSetStatusType); + } else if (setStatus.getSetTypeId() == 7) { + response.setEventidSet(responseSetStatusType); + } else if (setStatus.getSetTypeId() == 8) { + response.setModifierSet(responseSetStatusType); + } + + } + } catch (I2B2Exception i2b2Ex) { + throw new I2B2Exception( + "DataMartLoaderAsync.buildResponse:Exception" + + i2b2Ex.getMessage(), i2b2Ex); + } + return response; + } + + private LoadDataResponseType buildBulkLoadResponse( + IUploaderDAOFactory uploaderDaoFactory, int uploadId) + throws I2B2Exception { + LoadDataResponseType response = new LoadDataResponseType(); + try { + UploadStatusDAOI statusDao = uploaderDaoFactory + .getUploadStatusDAO(); + + UploadStatus uploadStatus = statusDao.findById(uploadId); + // build response + DataFileLocationUri fileLoc = new DataFileLocationUri(); + fileLoc.setValue(uploadStatus.getInputFileName()); + response.setDataFileLocationUri(fileLoc); + response.setLoadStatus(uploadStatus.getLoadStatus()); + response.setUploadId(String.valueOf(uploadStatus.getUploadId())); + response.setUserId(uploadStatus.getUserId()); + response.setMessage(uploadStatus.getMessage()); + response.setTransformerName(uploadStatus.getTransformName()); + response.setStartDate(dtoFactory + .getXMLGregorianCalendar(uploadStatus.getLoadDate() + .getTime())); + if (uploadStatus.getEndDate() != null) { + response.setEndDate(dtoFactory + .getXMLGregorianCalendar(uploadStatus.getEndDate() + .getTime())); + + } + } catch (I2B2Exception i2b2Ex) { + throw new I2B2Exception( + "DataMartLoaderAsync.buildBulkLoadResponse:Exception" + + i2b2Ex.getMessage(), i2b2Ex); + } + return response; + } + + + + /** + * Creates the connection. + */ + @PostConstruct + public void makeConnection() { + try { + //mm removed EJB + // connection = connectionFactory.createConnection(); + } catch (Throwable t) { + // JMSException could be thrown + log.error("DataMartLoaderAsync.makeConnection:" + "Exception: " + + t.toString()); + } + } + + /** + * Closes the connection. + */ + @PreDestroy + public void endConnection() throws RuntimeException { + //mm removed EJB + /* + if (connection != null) { + try { + connection.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } + */ + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/DataMartLoaderAsyncBeanLocal.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/DataMartLoaderAsyncBeanLocal.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/DataMartLoaderAsyncBeanLocal.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/DataMartLoaderAsyncBeanLocal.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/DataMartLoaderAsyncBeanRemote.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/DataMartLoaderAsyncBeanRemote.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/DataMartLoaderAsyncBeanRemote.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/DataMartLoaderAsyncBeanRemote.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/DataMartLoaderBeanMDB.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/DataMartLoaderBeanMDB.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/DataMartLoaderBeanMDB.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/DataMartLoaderBeanMDB.java index 961213b7..f8de068c --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/DataMartLoaderBeanMDB.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/DataMartLoaderBeanMDB.java @@ -1,350 +1,350 @@ - - - -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ - - - - -package edu.harvard.i2b2.crc.loader.ejb; - -import java.io.PrintWriter; -import java.io.StringWriter; -import java.util.Date; -import java.util.Hashtable; -import java.util.logging.Logger; - -import jakarta.xml.bind.JAXBElement; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.loader.dao.IUploaderDAOFactory; -import edu.harvard.i2b2.crc.loader.dao.LoaderDAOFactoryHelper; -import edu.harvard.i2b2.crc.loader.dao.UniqueKeyException; -import edu.harvard.i2b2.crc.loader.dao.UploadStatusDAOI; -import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; -import edu.harvard.i2b2.crc.loader.datavo.loader.UploadStatus; -import edu.harvard.i2b2.crc.loader.datavo.loader.query.DataListType; -import edu.harvard.i2b2.crc.loader.datavo.loader.query.PublishDataRequestType; -import edu.harvard.i2b2.crc.loader.ejb.fr.FRBean; - -/** - * The MessageBean class is a message-driven bean. It implements the - * javax.jms.MessageListener interface. It is defined as public (but not final - * or abstract). - */ - -public class DataMartLoaderBeanMDB { - - public final static String UPLOAD_ID = "UPLOAD_ID"; - public final static String DS_LOOKUP_DOMAIN_ID = "DS_LOOKUP_DOMAIN_ID"; - public final static String DS_LOOKUP_PROJECT_ID = "DS_LOOKUP_PROJECT_ID"; - public final static String DS_LOOKUP_OWNER_ID = "DS_LOOKUP_OWNER_ID"; - public final static String I2B2_USER_ID = "I2B2_USER_ID"; - public final static String I2B2_REQUEST_MSG = "I2B2_REQUEST_MSG"; - public final static String IROD_FILESYSTEM_STORAGE_RESOURCE = "IROD_FILESYSTEM_STORAGE_RESOURCE"; - - IDataMartLoaderHelper dmLoader = new DataMartLoader(); - - // @ActivationConfigProperty(propertyName = "transactionTimeout", - // propertyValue = "0"), - - /* - * @ActivationConfigProperty(propertyName="useDLQ", propertyValue="false"), - * - * @ActivationConfigProperty(propertyName="DLQMaxResent", - * propertyValue="1"), - * - * @ActivationConfigProperty(propertyName = "subscriptionDurability", - * propertyValue = "Durable"), - */ - private static Log log = LogFactory.getLog(DataMartLoaderBeanMDB.class); - - // get this - public static final String LOG_REFERENCE_PREFIX = ""; - - static final Logger logger = Logger.getLogger("DataMartLoaderBeanMDB"); - - /** - * Constructor, which is public and takes no arguments. - */ - public DataMartLoaderBeanMDB() { - } - - /** - * onMessage method, declared as public (but not final or static), with a - * return type of void, and with one argument of type javax.jms.Message. - * - * Casts the incoming Message to a TextMessage and displays the text. - * - * @param inMessage - * the incoming message - */ - //mm removed EJB - - public String onMessage(Hashtable msg) { - // TextMessage msg = null; - String sessionId = null, publishMessage = null; - int uploadId = 0; - IUploaderDAOFactory uploaderDaoFactory = null; - Throwable throwable = null; - try { - //if (inMessage instanceof TextMessage) { - // msg = (TextMessage) inMessage; - //publishMessage = msg.getText(); - - - String userId = (String) msg.get(I2B2_USER_ID); -// String password = (String) msg.get(I2B2_PASSWORD); -// boolean password_istoken = (Boolean) msg.get(I2B2_PASSWORD_ISTOKEN); - uploadId = (Integer) msg.get(UPLOAD_ID); - -// String fileSystemDefaultStorageResource = (String) msg -// .get(IROD_FILESYSTEM_STORAGE_RESOURCE); - - String dsLookupDomainId = (String) msg - .get(DS_LOOKUP_DOMAIN_ID); - String dsLookupProjectId = (String) msg - .get(DS_LOOKUP_PROJECT_ID); - String dsLookupOwnerId = (String) msg - .get(DS_LOOKUP_OWNER_ID); - LoaderDAOFactoryHelper daoFactoryHelper = new LoaderDAOFactoryHelper( - dsLookupDomainId, dsLookupProjectId, dsLookupOwnerId); - uploaderDaoFactory = daoFactoryHelper.getDAOFactory() - .getUpLoaderDAOFactory(); - - publishMessage = (String)msg.get(I2B2_REQUEST_MSG); - - - if(publishMessage == null) - log.debug("MDB publishMessage is NULL"); - - - PublishDataRequestType publishDataReqType = getPublishDataRequestType(publishMessage); - DataListType dataListType = publishDataReqType.getInputList() - .getDataFile(); - // use the file in the FRC dir. - String localUploadFile = dataListType.getLocationUri().getValue(); - - if(localUploadFile == null) - log.debug("MDB localUploadFile is NULL"); - - - updateUploadStatus(uploaderDaoFactory, uploadId, "PROCESSING", - ""); - processUploadMessage(uploaderDaoFactory, userId, uploadId, - localUploadFile, publishMessage); - // utx.commit(); - - // write completed status to upload status - log.info("Update Upload Status with Completed Status"); - // utx.begin(); - updateUploadStatus(uploaderDaoFactory, uploadId, "COMPLETED", - ""); - // utx.commit(); - - // } else { - // logger.warning("Message of wrong type: " - // + inMessage.getClass().getName()); - // } - - } catch (Exception e) { - logger.severe("MessageBean.onMessage: JMSException: " - + e.toString()); - e.printStackTrace(); - /* - try { - if (utx.getStatus() == Status.STATUS_ACTIVE) { - utx.rollback(); - } - } catch (IllegalStateException e1) { - e1.printStackTrace(); - } catch (SecurityException e1) { - e1.printStackTrace(); - } catch (SystemException e1) { - e1.printStackTrace(); - }*/ - - } catch (Throwable te) { - throwable = te; - logger.severe("MessageBean.onMessage: Exception: " + te.toString()); - te.printStackTrace(); - /* - try { - if (utx.getStatus() == Status.STATUS_ACTIVE) { - utx.rollback(); - } - } catch (IllegalStateException e) { - e.printStackTrace(); - } catch (SecurityException e) { - e.printStackTrace(); - } catch (SystemException e) { - e.printStackTrace(); - } - */ - - } finally { - if (throwable != null) { - // try to write error status to upload status - log.info("Update Upload Status with Completed Status"); - StringWriter stringWriter = new StringWriter(); - throwable.printStackTrace(new PrintWriter(stringWriter)); - try { - // utx.begin(); - updateUploadStatus(uploaderDaoFactory, uploadId, "ERROR", - stringWriter.toString()); - // utx.commit(); - } catch (Exception e) { - log.error( - "Failed to update 'error' status to upload status", - e); - } - } - try { - sendResponse(uploadId, sessionId, publishMessage); - } catch (Throwable t) { - t.printStackTrace(); - log - .error("Error sending response ack [" + t.getMessage() - + "]"); - } - } - return publishMessage; - - } - - private String createLocalFile(int uploadId, String publishMessage, - SecurityType i2b2SecurityType, String projectId, - String fileSystemDefaultStorageResource) throws I2B2Exception { - String localUploadFile = null; - try { - PublishDataRequestType pubishDataReqType = getPublishDataRequestType(publishMessage); - DataListType dataListType = pubishDataReqType.getInputList() - .getDataFile(); - //TODO removed EJB - - //FRLocal testLocal = CRCLoaderUtil.getInstance() - // .getFRBeanLocalHome().create(); - FRBean testLocal = new FRBean(); - - localUploadFile = testLocal.createClient(uploadId, dataListType, - i2b2SecurityType, projectId, - fileSystemDefaultStorageResource); - log.debug("localUploadFile :" + localUploadFile); - - } catch (Exception e) { - e.printStackTrace(); - throw new I2B2Exception("Failed to create CRCFR-EJB :[" - + e.getMessage() + "]"); - } - return localUploadFile; - } - - /* - * @throws Throwable - */ - private void sendResponse(int uploadId, String sessionId, - String publishMessage) throws Throwable { - //mm removed EJB - /* - Session session = null; - MessageProducer publisher = null; - TextMessage message = null; - try { - - connection = connectionFactory.createConnection(); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - publisher = session.createProducer(responseQueue); - message = session.createTextMessage(); - message.setJMSCorrelationID(sessionId); - message.setText(publishMessage); - message.setIntProperty(UPLOAD_ID, uploadId); - publisher.send(message); - - } catch (Throwable t) { - throw t; - } finally { - if (session != null) { - try { - session.close(); - } catch (JMSException e) { - } - - } - if (connection != null) { - try { - connection.close(); - } catch (JMSException e) { - - } - } - } - */ - } - - /** - * - */ - public int processUploadMessage(IUploaderDAOFactory uploaderDaoFactory, - String userId, int uploadId, String localUploadFile, - String publishMessage) throws I2B2Exception { - - dmLoader.load(uploaderDaoFactory, userId, uploadId, localUploadFile, - publishMessage); - return uploadId; - - } - - private void updateUploadStatus(IUploaderDAOFactory uploaderDaoFactory, - int uploadId, String status, String message) throws I2B2Exception { - UploadStatusDAOI uploadStatusDAO = uploaderDaoFactory - .getUploadStatusDAO(); - // try { - UploadStatus uploadStatus; - try { - uploadStatus = uploadStatusDAO.findById(uploadId); - uploadStatus.setLoadStatus(status); - if (message != null) { - int length = (message.length() > 3995) ? 3995 : message - .length(); - uploadStatus.setMessage(message.substring(0, length)); - } - uploadStatus.setEndDate(new Date(System.currentTimeMillis())); - uploadStatusDAO.updateUploadStatus(uploadStatus); - // uploadStatusDAO.calculateUploadStatus(uploadId); - - } catch (UniqueKeyException unqEx) { - unqEx.printStackTrace(); - log.error("Error while upload status update", unqEx); - } - } - - private PublishDataRequestType getPublishDataRequestType( - String publishMessage) throws I2B2Exception { - JAXBUtil jaxbUtil = edu.harvard.i2b2.crc.loader.datavo.CRCLoaderJAXBUtil - .getJAXBUtil(); - PublishDataRequestType publishType = null; - try { - JAXBElement jaxbElement = jaxbUtil - .unMashallFromString(publishMessage); - publishType = (PublishDataRequestType) jaxbElement.getValue(); - } catch (JAXBUtilException jaxbEx) { - throw new I2B2Exception("Error processing request message " - + jaxbEx.getMessage(), jaxbEx); - } - return publishType; - } - -} + + + +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ + + + + +package edu.harvard.i2b2.crc.loader.ejb; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.Date; +import java.util.Hashtable; +import java.util.logging.Logger; + +import jakarta.xml.bind.JAXBElement; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.loader.dao.IUploaderDAOFactory; +import edu.harvard.i2b2.crc.loader.dao.LoaderDAOFactoryHelper; +import edu.harvard.i2b2.crc.loader.dao.UniqueKeyException; +import edu.harvard.i2b2.crc.loader.dao.UploadStatusDAOI; +import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; +import edu.harvard.i2b2.crc.loader.datavo.loader.UploadStatus; +import edu.harvard.i2b2.crc.loader.datavo.loader.query.DataListType; +import edu.harvard.i2b2.crc.loader.datavo.loader.query.PublishDataRequestType; +import edu.harvard.i2b2.crc.loader.ejb.fr.FRBean; + +/** + * The MessageBean class is a message-driven bean. It implements the + * javax.jms.MessageListener interface. It is defined as public (but not final + * or abstract). + */ + +public class DataMartLoaderBeanMDB { + + public final static String UPLOAD_ID = "UPLOAD_ID"; + public final static String DS_LOOKUP_DOMAIN_ID = "DS_LOOKUP_DOMAIN_ID"; + public final static String DS_LOOKUP_PROJECT_ID = "DS_LOOKUP_PROJECT_ID"; + public final static String DS_LOOKUP_OWNER_ID = "DS_LOOKUP_OWNER_ID"; + public final static String I2B2_USER_ID = "I2B2_USER_ID"; + public final static String I2B2_REQUEST_MSG = "I2B2_REQUEST_MSG"; + public final static String IROD_FILESYSTEM_STORAGE_RESOURCE = "IROD_FILESYSTEM_STORAGE_RESOURCE"; + + IDataMartLoaderHelper dmLoader = new DataMartLoader(); + + // @ActivationConfigProperty(propertyName = "transactionTimeout", + // propertyValue = "0"), + + /* + * @ActivationConfigProperty(propertyName="useDLQ", propertyValue="false"), + * + * @ActivationConfigProperty(propertyName="DLQMaxResent", + * propertyValue="1"), + * + * @ActivationConfigProperty(propertyName = "subscriptionDurability", + * propertyValue = "Durable"), + */ + private static Log log = LogFactory.getLog(DataMartLoaderBeanMDB.class); + + // get this + public static final String LOG_REFERENCE_PREFIX = ""; + + static final Logger logger = Logger.getLogger("DataMartLoaderBeanMDB"); + + /** + * Constructor, which is public and takes no arguments. + */ + public DataMartLoaderBeanMDB() { + } + + /** + * onMessage method, declared as public (but not final or static), with a + * return type of void, and with one argument of type javax.jms.Message. + * + * Casts the incoming Message to a TextMessage and displays the text. + * + * @param inMessage + * the incoming message + */ + //mm removed EJB + + public String onMessage(Hashtable msg) { + // TextMessage msg = null; + String sessionId = null, publishMessage = null; + int uploadId = 0; + IUploaderDAOFactory uploaderDaoFactory = null; + Throwable throwable = null; + try { + //if (inMessage instanceof TextMessage) { + // msg = (TextMessage) inMessage; + //publishMessage = msg.getText(); + + + String userId = (String) msg.get(I2B2_USER_ID); +// String password = (String) msg.get(I2B2_PASSWORD); +// boolean password_istoken = (Boolean) msg.get(I2B2_PASSWORD_ISTOKEN); + uploadId = (Integer) msg.get(UPLOAD_ID); + +// String fileSystemDefaultStorageResource = (String) msg +// .get(IROD_FILESYSTEM_STORAGE_RESOURCE); + + String dsLookupDomainId = (String) msg + .get(DS_LOOKUP_DOMAIN_ID); + String dsLookupProjectId = (String) msg + .get(DS_LOOKUP_PROJECT_ID); + String dsLookupOwnerId = (String) msg + .get(DS_LOOKUP_OWNER_ID); + LoaderDAOFactoryHelper daoFactoryHelper = new LoaderDAOFactoryHelper( + dsLookupDomainId, dsLookupProjectId, dsLookupOwnerId); + uploaderDaoFactory = daoFactoryHelper.getDAOFactory() + .getUpLoaderDAOFactory(); + + publishMessage = (String)msg.get(I2B2_REQUEST_MSG); + + + if(publishMessage == null) + log.debug("MDB publishMessage is NULL"); + + + PublishDataRequestType publishDataReqType = getPublishDataRequestType(publishMessage); + DataListType dataListType = publishDataReqType.getInputList() + .getDataFile(); + // use the file in the FRC dir. + String localUploadFile = dataListType.getLocationUri().getValue(); + + if(localUploadFile == null) + log.debug("MDB localUploadFile is NULL"); + + + updateUploadStatus(uploaderDaoFactory, uploadId, "PROCESSING", + ""); + processUploadMessage(uploaderDaoFactory, userId, uploadId, + localUploadFile, publishMessage); + // utx.commit(); + + // write completed status to upload status + log.info("Update Upload Status with Completed Status"); + // utx.begin(); + updateUploadStatus(uploaderDaoFactory, uploadId, "COMPLETED", + ""); + // utx.commit(); + + // } else { + // logger.warning("Message of wrong type: " + // + inMessage.getClass().getName()); + // } + + } catch (Exception e) { + logger.severe("MessageBean.onMessage: JMSException: " + + e.toString()); + e.printStackTrace(); + /* + try { + if (utx.getStatus() == Status.STATUS_ACTIVE) { + utx.rollback(); + } + } catch (IllegalStateException e1) { + e1.printStackTrace(); + } catch (SecurityException e1) { + e1.printStackTrace(); + } catch (SystemException e1) { + e1.printStackTrace(); + }*/ + + } catch (Throwable te) { + throwable = te; + logger.severe("MessageBean.onMessage: Exception: " + te.toString()); + te.printStackTrace(); + /* + try { + if (utx.getStatus() == Status.STATUS_ACTIVE) { + utx.rollback(); + } + } catch (IllegalStateException e) { + e.printStackTrace(); + } catch (SecurityException e) { + e.printStackTrace(); + } catch (SystemException e) { + e.printStackTrace(); + } + */ + + } finally { + if (throwable != null) { + // try to write error status to upload status + log.info("Update Upload Status with Completed Status"); + StringWriter stringWriter = new StringWriter(); + throwable.printStackTrace(new PrintWriter(stringWriter)); + try { + // utx.begin(); + updateUploadStatus(uploaderDaoFactory, uploadId, "ERROR", + stringWriter.toString()); + // utx.commit(); + } catch (Exception e) { + log.error( + "Failed to update 'error' status to upload status", + e); + } + } + try { + sendResponse(uploadId, sessionId, publishMessage); + } catch (Throwable t) { + t.printStackTrace(); + log + .error("Error sending response ack [" + t.getMessage() + + "]"); + } + } + return publishMessage; + + } + + private String createLocalFile(int uploadId, String publishMessage, + SecurityType i2b2SecurityType, String projectId, + String fileSystemDefaultStorageResource) throws I2B2Exception { + String localUploadFile = null; + try { + PublishDataRequestType pubishDataReqType = getPublishDataRequestType(publishMessage); + DataListType dataListType = pubishDataReqType.getInputList() + .getDataFile(); + //TODO removed EJB + + //FRLocal testLocal = CRCLoaderUtil.getInstance() + // .getFRBeanLocalHome().create(); + FRBean testLocal = new FRBean(); + + localUploadFile = testLocal.createClient(uploadId, dataListType, + i2b2SecurityType, projectId, + fileSystemDefaultStorageResource); + log.debug("localUploadFile :" + localUploadFile); + + } catch (Exception e) { + e.printStackTrace(); + throw new I2B2Exception("Failed to create CRCFR-EJB :[" + + e.getMessage() + "]"); + } + return localUploadFile; + } + + /* + * @throws Throwable + */ + private void sendResponse(int uploadId, String sessionId, + String publishMessage) throws Throwable { + //mm removed EJB + /* + Session session = null; + MessageProducer publisher = null; + TextMessage message = null; + try { + + connection = connectionFactory.createConnection(); + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + + publisher = session.createProducer(responseQueue); + message = session.createTextMessage(); + message.setJMSCorrelationID(sessionId); + message.setText(publishMessage); + message.setIntProperty(UPLOAD_ID, uploadId); + publisher.send(message); + + } catch (Throwable t) { + throw t; + } finally { + if (session != null) { + try { + session.close(); + } catch (JMSException e) { + } + + } + if (connection != null) { + try { + connection.close(); + } catch (JMSException e) { + + } + } + } + */ + } + + /** + * + */ + public int processUploadMessage(IUploaderDAOFactory uploaderDaoFactory, + String userId, int uploadId, String localUploadFile, + String publishMessage) throws I2B2Exception { + + dmLoader.load(uploaderDaoFactory, userId, uploadId, localUploadFile, + publishMessage); + return uploadId; + + } + + private void updateUploadStatus(IUploaderDAOFactory uploaderDaoFactory, + int uploadId, String status, String message) throws I2B2Exception { + UploadStatusDAOI uploadStatusDAO = uploaderDaoFactory + .getUploadStatusDAO(); + // try { + UploadStatus uploadStatus; + try { + uploadStatus = uploadStatusDAO.findById(uploadId); + uploadStatus.setLoadStatus(status); + if (message != null) { + int length = (message.length() > 3995) ? 3995 : message + .length(); + uploadStatus.setMessage(message.substring(0, length)); + } + uploadStatus.setEndDate(new Date(System.currentTimeMillis())); + uploadStatusDAO.updateUploadStatus(uploadStatus); + // uploadStatusDAO.calculateUploadStatus(uploadId); + + } catch (UniqueKeyException unqEx) { + unqEx.printStackTrace(); + log.error("Error while upload status update", unqEx); + } + } + + private PublishDataRequestType getPublishDataRequestType( + String publishMessage) throws I2B2Exception { + JAXBUtil jaxbUtil = edu.harvard.i2b2.crc.loader.datavo.CRCLoaderJAXBUtil + .getJAXBUtil(); + PublishDataRequestType publishType = null; + try { + JAXBElement jaxbElement = jaxbUtil + .unMashallFromString(publishMessage); + publishType = (PublishDataRequestType) jaxbElement.getValue(); + } catch (JAXBUtilException jaxbEx) { + throw new I2B2Exception("Error processing request message " + + jaxbEx.getMessage(), jaxbEx); + } + return publishType; + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/EidLoader.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/EidLoader.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/EidLoader.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/EidLoader.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/EidXmlDbLoader.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/EidXmlDbLoader.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/EidXmlDbLoader.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/EidXmlDbLoader.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/IDataMartLoaderBean.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/IDataMartLoaderBean.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/IDataMartLoaderBean.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/IDataMartLoaderBean.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/IDataMartLoaderHelper.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/IDataMartLoaderHelper.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/IDataMartLoaderHelper.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/IDataMartLoaderHelper.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/ILoaderStatusBean.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/ILoaderStatusBean.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/ILoaderStatusBean.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/ILoaderStatusBean.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/IMissingTermReportBean.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/IMissingTermReportBean.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/IMissingTermReportBean.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/IMissingTermReportBean.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/LoaderStatusBean.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/LoaderStatusBean.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/LoaderStatusBean.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/LoaderStatusBean.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/LoaderStatusBeanLocal.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/LoaderStatusBeanLocal.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/LoaderStatusBeanLocal.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/LoaderStatusBeanLocal.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/LoaderStatusBeanRemote.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/LoaderStatusBeanRemote.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/LoaderStatusBeanRemote.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/LoaderStatusBeanRemote.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/MissingTermReportBean.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/MissingTermReportBean.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/MissingTermReportBean.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/MissingTermReportBean.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/MissingTermReportBeanLocal.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/MissingTermReportBeanLocal.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/MissingTermReportBeanLocal.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/MissingTermReportBeanLocal.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/MissingTermReportBeanRemote.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/MissingTermReportBeanRemote.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/MissingTermReportBeanRemote.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/MissingTermReportBeanRemote.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/ModifierLoader.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/ModifierLoader.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/ModifierLoader.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/ModifierLoader.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/ModifierXmlDbLoader.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/ModifierXmlDbLoader.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/ModifierXmlDbLoader.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/ModifierXmlDbLoader.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/ObservationFactLoader.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/ObservationFactLoader.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/ObservationFactLoader.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/ObservationFactLoader.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/ObservationFactXmlDbLoader.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/ObservationFactXmlDbLoader.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/ObservationFactXmlDbLoader.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/ObservationFactXmlDbLoader.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/PatientLoader.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/PatientLoader.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/PatientLoader.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/PatientLoader.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/PatientXmlDbLoader.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/PatientXmlDbLoader.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/PatientXmlDbLoader.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/PatientXmlDbLoader.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/PidLoader.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/PidLoader.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/PidLoader.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/PidLoader.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/PidXmlDbLoader.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/PidXmlDbLoader.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/PidXmlDbLoader.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/PidXmlDbLoader.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/ProviderLoader.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/ProviderLoader.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/ProviderLoader.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/ProviderLoader.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/ProviderXmlDbLoader.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/ProviderXmlDbLoader.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/ProviderXmlDbLoader.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/ProviderXmlDbLoader.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/VisitLoader.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/VisitLoader.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/VisitLoader.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/VisitLoader.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/VisitXmlDbLoader.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/VisitXmlDbLoader.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/VisitXmlDbLoader.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/VisitXmlDbLoader.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/fr/FRBean.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/fr/FRBean.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ejb/fr/FRBean.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ejb/fr/FRBean.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/util/Base64.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/util/Base64.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/util/Base64.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/util/Base64.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/util/CRCLoaderUtil.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/util/CRCLoaderUtil.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/util/CRCLoaderUtil.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/util/CRCLoaderUtil.java index eccff5c3..9e596334 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/util/CRCLoaderUtil.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/util/CRCLoaderUtil.java @@ -1,426 +1,426 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.loader.util; - -import java.io.IOException; -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.List; -import java.util.Properties; - -import javax.naming.InitialContext; -import javax.naming.NamingException; -import javax.sql.DataSource; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import org.springframework.context.support.FileSystemXmlApplicationContext; -import org.springframework.dao.DataAccessException; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.RowMapper; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.ServiceLocator; -import edu.harvard.i2b2.common.util.axis2.ServiceClient; -import edu.harvard.i2b2.common.util.jaxb.DTOFactory; -import edu.harvard.i2b2.crc.datavo.pm.ParamType; -import edu.harvard.i2b2.crc.loader.ejb.DataMartLoaderAsyncBeanLocal; -import edu.harvard.i2b2.crc.loader.ejb.LoaderStatusBeanLocal; -import edu.harvard.i2b2.crc.loader.ejb.MissingTermReportBeanLocal; -//import edu.harvard.i2b2.crc.loader.ejb.fr.FRLocalHome; - -/** - * This is the CRC application's main utility class This utility class provides - * support for fetching resources like datasouce, to read application - * properties, to get ejb home,etc. $Id: CRCLoaderUtil.java,v 1.7 2007/04/25 - * 15:05:11 rk903 Exp $ - * - * @author rkuttan - */ -public class CRCLoaderUtil { - - /** log **/ - protected final static Log log = LogFactory.getLog(CRCLoaderUtil.class); - - /** property name for datasource present in app property file* */ - private static final String DATASOURCE_JNDI_PROPERTIES = "queryprocessor.jndi.datasource_name"; - - /** property name for metadata schema name* */ - private static final String PMCELL_WS_URL_PROPERTIES = "queryprocessor.ws.pm.url"; - - - /** property name for metadata schema name* */ - private static final String DS_LOOKUP_DATASOURCE_PROPERTIES = "edu.harvard.i2b2.crc.loader.ds.lookup.datasource"; - - /** property name for metadata schema name* */ - private static final String DS_LOOKUP_SCHEMANAME_PROPERTIES = "edu.harvard.i2b2.crc.loader.ds.lookup.schemaname"; - - /** property name for metadata schema name* */ - private static final String DS_LOOKUP_SERVERTYPE_PROPERTIES = "edu.harvard.i2b2.crc.loader.ds.lookup.servertype"; - - /** property name for metadata schema name* */ - private static final String FRCELL_WS_URL_PROPERTIES = "edu.harvard.i2b2.crc.loader.ws.fr.url"; - - /** property name for metadata schema name* */ - private static final String PROCESS_FOLDER_PROPERTIES = "edu.harvard.i2b2.crc.loader.process.foldername"; - - private static final String PROCESS_TRANSACTIONTIMEOUT_PROPERTIES = "edu.harvard.i2b2.crc.loader.process.transactiontimeout"; - - private static final String FRCELL_WS_TEMPSPACE_PROPERTIES = "edu.harvard.i2b2.crc.loader.ws.fr.tempspace"; - - private static final String FRCELL_WS_TIMEOUT_PROPERTIES = "edu.harvard.i2b2.crc.loader.ws.fr.timeout"; - - private static final String FRCELL_WS_FILETHRESHOLD_PROPERTIES = "edu.harvard.i2b2.crc.loader.ws.fr.filethreshold"; - - private static final String FRCELL_WS_ATTACHMENTNAME_PROPERTIES = "edu.harvard.i2b2.crc.loader.ws.fr.attachmentname"; - - private static final String FRCELL_WS_OPERATIONNAME_PROPERTIES = "edu.harvard.i2b2.crc.loader.ws.fr.operation"; - - /** class instance field* */ - private static CRCLoaderUtil thisInstance = null; - - /** service locator field* */ - private static ServiceLocator serviceLocator = null; - - /** field to store application properties * */ - private static List appProperties = null; - - private static Properties loadProperties = null; - - /** field to store app datasource* */ - private DataSource dataSource = null; - - - /** - * Private constructor to make the class singleton - */ - private CRCLoaderUtil() { - } - - /** - * Return this class instance - * - * @return QueryProcessorUtil - */ - public static CRCLoaderUtil getInstance() { - if (thisInstance == null) { - thisInstance = new CRCLoaderUtil(); - serviceLocator = ServiceLocator.getInstance(); - } - return thisInstance; - } - - /** - * Function to get ejb local home for query manager - * - * @return QueryManagerLocalHome - * @throws I2B2Exception - * @throws ServiceLocatorException - */ - /* //mm removed EJB - public FRLocalHome getFRBeanLocalHome() throws I2B2Exception, - ServiceLocatorException { - return (FRLocalHome) serviceLocator - .getLocalHome("ejb.crc.loader.FRBeanLocal"); - } - */ - - - /** - * Return app server datasource - * - * @return datasource - * @throws I2B2Exception - * @throws SQLException - */ - public DataSource getDataSource(String dataSourceName) - throws I2B2Exception { - - dataSource = serviceLocator - .getAppServerDataSource(dataSourceName); - // DataSource dataSource = (DataSource) getSpringBeanFactory().getBean( - // dataSourceName); - - return dataSource; - - } - /** - * Function to create spring bean factory - * - * @return BeanFactory - */ - /* - public BeanFactory getSpringBeanFactory() { - if (beanFactory == null) { - String appDir = null; - try { - // read application directory property file via classpath - loadProperties = ServiceLocator - .getProperties(APPLICATION_DIRECTORY_PROPERTIES_FILENAME); - // read directory property - appDir = loadProperties.getProperty(APPLICATIONDIR_PROPERTIES); - - } catch (I2B2Exception e) { - log.error(APPLICATION_DIRECTORY_PROPERTIES_FILENAME - + "could not be located from classpath "); - } - - if (appDir != null && !appDir.equals("")) { - FileSystemXmlApplicationContext ctx = new FileSystemXmlApplicationContext( - "file:" + appDir + "/" - + "CRCLoaderApplicationContext.xml"); - beanFactory = ctx.getBeanFactory(); - } else { - - FileSystemXmlApplicationContext ctx = new FileSystemXmlApplicationContext( - "standalone/configuration/crcapp/CRCLoaderApplicationContext.xml"); - beanFactory = ctx.getBeanFactory(); - } - - } - return beanFactory; - } - */ - - public DataMartLoaderAsyncBeanLocal getDataMartLoaderBean() - throws I2B2Exception { - InitialContext ctx; - try { - ctx = new InitialContext(); - return (DataMartLoaderAsyncBeanLocal) ctx - .lookup("DataMartLoaderAsyncBean/local"); - } catch (NamingException e) { - throw new I2B2Exception("Bean lookup error ", e); - } - - } - - /** - * Get Project managment cell's service url - * - * @return - * @throws I2B2Exception - */ - public String getProjectManagementCellUrl() throws I2B2Exception { - return getPropertyValue(PMCELL_WS_URL_PROPERTIES); - } - - /** - * Get Project managment cell's service url - * - * @return - * @throws I2B2Exception - */ - public String getFileManagentCellUrl() throws I2B2Exception { - return getPropertyValue(FRCELL_WS_URL_PROPERTIES); - } - - /** - * Get Project management bypass flag - * - * @return - * @throws I2B2Exception - */ - - - public String getCRCDBLookupDataSource() throws I2B2Exception { - return getPropertyValue(DS_LOOKUP_DATASOURCE_PROPERTIES); - } - - public String getCRCDBLookupServerType() throws I2B2Exception { - return getPropertyValue(DS_LOOKUP_SERVERTYPE_PROPERTIES); - } - - public String getCRCDBLookupSchemaName() throws I2B2Exception { - return getPropertyValue(DS_LOOKUP_SCHEMANAME_PROPERTIES); - } - - public String getProcessFolderName() throws I2B2Exception { - return getPropertyValue(PROCESS_FOLDER_PROPERTIES); - } - - public String getProcessTransactionTimeout() throws I2B2Exception { - return getPropertyValue(PROCESS_TRANSACTIONTIMEOUT_PROPERTIES); - } - - public String getFileRepositoryTempSpace() throws I2B2Exception { - return getPropertyValue(FRCELL_WS_TEMPSPACE_PROPERTIES); - } - - public String getFileRepositoryTimeout() throws I2B2Exception { - return getPropertyValue(FRCELL_WS_TIMEOUT_PROPERTIES); - } - - public String getFileRepositoryThreshold() throws I2B2Exception { - return getPropertyValue(FRCELL_WS_FILETHRESHOLD_PROPERTIES); - } - - public String getFileRepositoryAttachmentName() throws I2B2Exception { - return getPropertyValue(FRCELL_WS_ATTACHMENTNAME_PROPERTIES); - } - - public String getFileRepositoryOperationName() throws I2B2Exception { - return getPropertyValue(FRCELL_WS_OPERATIONNAME_PROPERTIES); - } - - public LoaderStatusBeanLocal getLoaderStatusBean() throws I2B2Exception { - InitialContext ctx; - try { - ctx = new InitialContext(); - return (LoaderStatusBeanLocal) ctx.lookup("LoaderStatusBean/local"); - } catch (NamingException e) { - throw new I2B2Exception("Bean lookup error ", e); - } - - } - - public MissingTermReportBeanLocal getMissingTermReportBean() throws I2B2Exception { - InitialContext ctx; - try { - ctx = new InitialContext(); - return (MissingTermReportBeanLocal) ctx.lookup("MissingTermReportBean/local"); - } catch (NamingException e) { - throw new I2B2Exception("Bean lookup error ", e); - } - - } - - /** - * Return app server datasource - * - * @return datasource - * @throws I2B2Exception - * @throws SQLException - */ - /* - public DataSource getSpringDataSource(String dataSourceName) - throws I2B2Exception { - DataSource dataSource = (DataSource) getSpringBeanFactory().getBean( - dataSourceName); - - return dataSource; - - } - */ - - // --------------------- - // private methods here - // --------------------- - - /** - * Load application property file into memory - */ - - - /** - * Load application property file into memory - */ - private String getPropertyValue(String propertyName) throws I2B2Exception { - if (appProperties == null) { - - - - // log.info(sql + domainId + projectId + ownerId); - // List queryResult = null; - try { - DataSource ds = this.getDataSource("java:/CRCBootStrapDS"); - - JdbcTemplate jt = new JdbcTemplate(ds); - Connection conn = ds.getConnection(); - - String metadataSchema = conn.getSchema(); - conn.close(); - String sql = "select * from " + metadataSchema + ".hive_cell_params where status_cd <> 'D' and cell_id = 'CRC'"; - - log.debug("Start query"); - appProperties = jt.query(sql, new getHiveCellParam()); - log.debug("End query"); - - - } catch (DataAccessException e) { - log.error(e.getMessage()); - e.printStackTrace(); - throw new I2B2DAOException("Database error"); - } - //return queryResult; - catch (SQLException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - } - - String propertyValue = null;//appProperties.getProperty(propertyName); - for (int i=0; i < appProperties.size(); i++) - { - if (appProperties.get(i).getName() != null) - { - if (appProperties.get(i).getName().equalsIgnoreCase(propertyName)) - - if (appProperties.get(i).getDatatype().equalsIgnoreCase("U")) - try { - propertyValue = ServiceClient.getContextRoot() + appProperties.get(i).getValue(); - - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - else - propertyValue = appProperties.get(i).getValue(); - } - } - - if ((propertyValue == null) && (propertyValue.trim().length() == 0)) { - throw new I2B2Exception("Application property file(" - // + APPLICATION_PROPERTIES_FILENAME + ") missing " - + propertyName + " entry"); - } - - return propertyValue; - } - - /* - - public class HiveCellParamMapper void getHiveCellParam() implements RowMapper { - - public ParamType mapRow(ResultSet rs, int rowNum) throws SQLException { - ParamType param = new ParamType(); - param.setId(rs.getInt("id")); - param.setName(rs.getString("param_name_cd")); - param.setValue(rs.getString("value")); - param.setDatatype(rs.getString("datatype_cd")); - return param; - } - } - */ -} - -class getHiveCellParam implements RowMapper { - @Override - public ParamType mapRow(ResultSet rs, int rowNum) throws SQLException { - - ParamType param = new ParamType(); - param.setId(rs.getInt("id")); - param.setName(rs.getString("param_name_cd")); - param.setValue(rs.getString("value")); - param.setDatatype(rs.getString("datatype_cd")); - return param; - } -} - - +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.loader.util; + +import java.io.IOException; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.List; +import java.util.Properties; + +import javax.naming.InitialContext; +import javax.naming.NamingException; +import javax.sql.DataSource; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.springframework.context.support.FileSystemXmlApplicationContext; +import org.springframework.dao.DataAccessException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.RowMapper; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.ServiceLocator; +import edu.harvard.i2b2.common.util.axis2.ServiceClient; +import edu.harvard.i2b2.common.util.jaxb.DTOFactory; +import edu.harvard.i2b2.crc.datavo.pm.ParamType; +import edu.harvard.i2b2.crc.loader.ejb.DataMartLoaderAsyncBeanLocal; +import edu.harvard.i2b2.crc.loader.ejb.LoaderStatusBeanLocal; +import edu.harvard.i2b2.crc.loader.ejb.MissingTermReportBeanLocal; +//import edu.harvard.i2b2.crc.loader.ejb.fr.FRLocalHome; + +/** + * This is the CRC application's main utility class This utility class provides + * support for fetching resources like datasouce, to read application + * properties, to get ejb home,etc. $Id: CRCLoaderUtil.java,v 1.7 2007/04/25 + * 15:05:11 rk903 Exp $ + * + * @author rkuttan + */ +public class CRCLoaderUtil { + + /** log **/ + protected final static Log log = LogFactory.getLog(CRCLoaderUtil.class); + + /** property name for datasource present in app property file* */ + private static final String DATASOURCE_JNDI_PROPERTIES = "queryprocessor.jndi.datasource_name"; + + /** property name for metadata schema name* */ + private static final String PMCELL_WS_URL_PROPERTIES = "queryprocessor.ws.pm.url"; + + + /** property name for metadata schema name* */ + private static final String DS_LOOKUP_DATASOURCE_PROPERTIES = "edu.harvard.i2b2.crc.loader.ds.lookup.datasource"; + + /** property name for metadata schema name* */ + private static final String DS_LOOKUP_SCHEMANAME_PROPERTIES = "edu.harvard.i2b2.crc.loader.ds.lookup.schemaname"; + + /** property name for metadata schema name* */ + private static final String DS_LOOKUP_SERVERTYPE_PROPERTIES = "edu.harvard.i2b2.crc.loader.ds.lookup.servertype"; + + /** property name for metadata schema name* */ + private static final String FRCELL_WS_URL_PROPERTIES = "edu.harvard.i2b2.crc.loader.ws.fr.url"; + + /** property name for metadata schema name* */ + private static final String PROCESS_FOLDER_PROPERTIES = "edu.harvard.i2b2.crc.loader.process.foldername"; + + private static final String PROCESS_TRANSACTIONTIMEOUT_PROPERTIES = "edu.harvard.i2b2.crc.loader.process.transactiontimeout"; + + private static final String FRCELL_WS_TEMPSPACE_PROPERTIES = "edu.harvard.i2b2.crc.loader.ws.fr.tempspace"; + + private static final String FRCELL_WS_TIMEOUT_PROPERTIES = "edu.harvard.i2b2.crc.loader.ws.fr.timeout"; + + private static final String FRCELL_WS_FILETHRESHOLD_PROPERTIES = "edu.harvard.i2b2.crc.loader.ws.fr.filethreshold"; + + private static final String FRCELL_WS_ATTACHMENTNAME_PROPERTIES = "edu.harvard.i2b2.crc.loader.ws.fr.attachmentname"; + + private static final String FRCELL_WS_OPERATIONNAME_PROPERTIES = "edu.harvard.i2b2.crc.loader.ws.fr.operation"; + + /** class instance field* */ + private static CRCLoaderUtil thisInstance = null; + + /** service locator field* */ + private static ServiceLocator serviceLocator = null; + + /** field to store application properties * */ + private static List appProperties = null; + + private static Properties loadProperties = null; + + /** field to store app datasource* */ + private DataSource dataSource = null; + + + /** + * Private constructor to make the class singleton + */ + private CRCLoaderUtil() { + } + + /** + * Return this class instance + * + * @return QueryProcessorUtil + */ + public static CRCLoaderUtil getInstance() { + if (thisInstance == null) { + thisInstance = new CRCLoaderUtil(); + serviceLocator = ServiceLocator.getInstance(); + } + return thisInstance; + } + + /** + * Function to get ejb local home for query manager + * + * @return QueryManagerLocalHome + * @throws I2B2Exception + * @throws ServiceLocatorException + */ + /* //mm removed EJB + public FRLocalHome getFRBeanLocalHome() throws I2B2Exception, + ServiceLocatorException { + return (FRLocalHome) serviceLocator + .getLocalHome("ejb.crc.loader.FRBeanLocal"); + } + */ + + + /** + * Return app server datasource + * + * @return datasource + * @throws I2B2Exception + * @throws SQLException + */ + public DataSource getDataSource(String dataSourceName) + throws I2B2Exception { + + dataSource = serviceLocator + .getAppServerDataSource(dataSourceName); + // DataSource dataSource = (DataSource) getSpringBeanFactory().getBean( + // dataSourceName); + + return dataSource; + + } + /** + * Function to create spring bean factory + * + * @return BeanFactory + */ + /* + public BeanFactory getSpringBeanFactory() { + if (beanFactory == null) { + String appDir = null; + try { + // read application directory property file via classpath + loadProperties = ServiceLocator + .getProperties(APPLICATION_DIRECTORY_PROPERTIES_FILENAME); + // read directory property + appDir = loadProperties.getProperty(APPLICATIONDIR_PROPERTIES); + + } catch (I2B2Exception e) { + log.error(APPLICATION_DIRECTORY_PROPERTIES_FILENAME + + "could not be located from classpath "); + } + + if (appDir != null && !appDir.equals("")) { + FileSystemXmlApplicationContext ctx = new FileSystemXmlApplicationContext( + "file:" + appDir + "/" + + "CRCLoaderApplicationContext.xml"); + beanFactory = ctx.getBeanFactory(); + } else { + + FileSystemXmlApplicationContext ctx = new FileSystemXmlApplicationContext( + "standalone/configuration/crcapp/CRCLoaderApplicationContext.xml"); + beanFactory = ctx.getBeanFactory(); + } + + } + return beanFactory; + } + */ + + public DataMartLoaderAsyncBeanLocal getDataMartLoaderBean() + throws I2B2Exception { + InitialContext ctx; + try { + ctx = new InitialContext(); + return (DataMartLoaderAsyncBeanLocal) ctx + .lookup("DataMartLoaderAsyncBean/local"); + } catch (NamingException e) { + throw new I2B2Exception("Bean lookup error ", e); + } + + } + + /** + * Get Project managment cell's service url + * + * @return + * @throws I2B2Exception + */ + public String getProjectManagementCellUrl() throws I2B2Exception { + return getPropertyValue(PMCELL_WS_URL_PROPERTIES); + } + + /** + * Get Project managment cell's service url + * + * @return + * @throws I2B2Exception + */ + public String getFileManagentCellUrl() throws I2B2Exception { + return getPropertyValue(FRCELL_WS_URL_PROPERTIES); + } + + /** + * Get Project management bypass flag + * + * @return + * @throws I2B2Exception + */ + + + public String getCRCDBLookupDataSource() throws I2B2Exception { + return getPropertyValue(DS_LOOKUP_DATASOURCE_PROPERTIES); + } + + public String getCRCDBLookupServerType() throws I2B2Exception { + return getPropertyValue(DS_LOOKUP_SERVERTYPE_PROPERTIES); + } + + public String getCRCDBLookupSchemaName() throws I2B2Exception { + return getPropertyValue(DS_LOOKUP_SCHEMANAME_PROPERTIES); + } + + public String getProcessFolderName() throws I2B2Exception { + return getPropertyValue(PROCESS_FOLDER_PROPERTIES); + } + + public String getProcessTransactionTimeout() throws I2B2Exception { + return getPropertyValue(PROCESS_TRANSACTIONTIMEOUT_PROPERTIES); + } + + public String getFileRepositoryTempSpace() throws I2B2Exception { + return getPropertyValue(FRCELL_WS_TEMPSPACE_PROPERTIES); + } + + public String getFileRepositoryTimeout() throws I2B2Exception { + return getPropertyValue(FRCELL_WS_TIMEOUT_PROPERTIES); + } + + public String getFileRepositoryThreshold() throws I2B2Exception { + return getPropertyValue(FRCELL_WS_FILETHRESHOLD_PROPERTIES); + } + + public String getFileRepositoryAttachmentName() throws I2B2Exception { + return getPropertyValue(FRCELL_WS_ATTACHMENTNAME_PROPERTIES); + } + + public String getFileRepositoryOperationName() throws I2B2Exception { + return getPropertyValue(FRCELL_WS_OPERATIONNAME_PROPERTIES); + } + + public LoaderStatusBeanLocal getLoaderStatusBean() throws I2B2Exception { + InitialContext ctx; + try { + ctx = new InitialContext(); + return (LoaderStatusBeanLocal) ctx.lookup("LoaderStatusBean/local"); + } catch (NamingException e) { + throw new I2B2Exception("Bean lookup error ", e); + } + + } + + public MissingTermReportBeanLocal getMissingTermReportBean() throws I2B2Exception { + InitialContext ctx; + try { + ctx = new InitialContext(); + return (MissingTermReportBeanLocal) ctx.lookup("MissingTermReportBean/local"); + } catch (NamingException e) { + throw new I2B2Exception("Bean lookup error ", e); + } + + } + + /** + * Return app server datasource + * + * @return datasource + * @throws I2B2Exception + * @throws SQLException + */ + /* + public DataSource getSpringDataSource(String dataSourceName) + throws I2B2Exception { + DataSource dataSource = (DataSource) getSpringBeanFactory().getBean( + dataSourceName); + + return dataSource; + + } + */ + + // --------------------- + // private methods here + // --------------------- + + /** + * Load application property file into memory + */ + + + /** + * Load application property file into memory + */ + private String getPropertyValue(String propertyName) throws I2B2Exception { + if (appProperties == null) { + + + + // log.info(sql + domainId + projectId + ownerId); + // List queryResult = null; + try { + DataSource ds = this.getDataSource("java:/CRCBootStrapDS"); + + JdbcTemplate jt = new JdbcTemplate(ds); + Connection conn = ds.getConnection(); + + String metadataSchema = conn.getSchema(); + conn.close(); + String sql = "select * from " + metadataSchema + ".hive_cell_params where status_cd <> 'D' and cell_id = 'CRC'"; + + log.debug("Start query"); + appProperties = jt.query(sql, new getHiveCellParam()); + log.debug("End query"); + + + } catch (DataAccessException e) { + log.error(e.getMessage()); + e.printStackTrace(); + throw new I2B2DAOException("Database error"); + } + //return queryResult; + catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + + String propertyValue = null;//appProperties.getProperty(propertyName); + for (int i=0; i < appProperties.size(); i++) + { + if (appProperties.get(i).getName() != null) + { + if (appProperties.get(i).getName().equalsIgnoreCase(propertyName)) + + if (appProperties.get(i).getDatatype().equalsIgnoreCase("U")) + try { + propertyValue = ServiceClient.getContextRoot() + appProperties.get(i).getValue(); + + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + else + propertyValue = appProperties.get(i).getValue(); + } + } + + if ((propertyValue == null) && (propertyValue.trim().length() == 0)) { + throw new I2B2Exception("Application property file(" + // + APPLICATION_PROPERTIES_FILENAME + ") missing " + + propertyName + " entry"); + } + + return propertyValue; + } + + /* + + public class HiveCellParamMapper void getHiveCellParam() implements RowMapper { + + public ParamType mapRow(ResultSet rs, int rowNum) throws SQLException { + ParamType param = new ParamType(); + param.setId(rs.getInt("id")); + param.setName(rs.getString("param_name_cd")); + param.setValue(rs.getString("value")); + param.setDatatype(rs.getString("datatype_cd")); + return param; + } + } + */ +} + +class getHiveCellParam implements RowMapper { + @Override + public ParamType mapRow(ResultSet rs, int rowNum) throws SQLException { + + ParamType param = new ParamType(); + param.setId(rs.getInt("id")); + param.setName(rs.getString("param_name_cd")); + param.setValue(rs.getString("value")); + param.setDatatype(rs.getString("datatype_cd")); + return param; + } +} + + diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/util/ConstantUtil.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/util/ConstantUtil.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/util/ConstantUtil.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/util/ConstantUtil.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/util/CryptUtil.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/util/CryptUtil.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/util/CryptUtil.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/util/CryptUtil.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/util/ExecUtil.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/util/ExecUtil.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/util/ExecUtil.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/util/ExecUtil.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/util/FileTransferUtil.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/util/FileTransferUtil.java old mode 100755 new mode 100644 similarity index 92% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/util/FileTransferUtil.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/util/FileTransferUtil.java index 80355e18..50d768e0 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/util/FileTransferUtil.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/util/FileTransferUtil.java @@ -10,13 +10,6 @@ import edu.harvard.i2b2.common.exception.I2B2Exception; import edu.harvard.i2b2.crc.datavo.i2b2message.PasswordType; -/* -import edu.sdsc.grid.io.GeneralFile; -import edu.sdsc.grid.io.irods.IRODSAccount; -import edu.sdsc.grid.io.irods.IRODSFile; -import edu.sdsc.grid.io.irods.IRODSFileSystem; -import edu.sdsc.grid.io.local.LocalFile; -*/ public class FileTransferUtil { private final static String STORAGE_RESOURCE = "demoResc"; diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/util/KeyReaderUtil.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/util/KeyReaderUtil.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/util/KeyReaderUtil.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/util/KeyReaderUtil.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/util/NoKeyException.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/util/NoKeyException.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/util/NoKeyException.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/util/NoKeyException.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/util/csv/CSVFile.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/util/csv/CSVFile.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/util/csv/CSVFile.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/util/csv/CSVFile.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/util/csv/CSVFileReader.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/util/csv/CSVFileReader.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/util/csv/CSVFileReader.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/util/csv/CSVFileReader.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/util/csv/ObservationFactCSV2XmlBuilder.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/util/csv/ObservationFactCSV2XmlBuilder.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/util/csv/ObservationFactCSV2XmlBuilder.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/util/csv/ObservationFactCSV2XmlBuilder.java index 4c284f99..b25a1647 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/util/csv/ObservationFactCSV2XmlBuilder.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/util/csv/ObservationFactCSV2XmlBuilder.java @@ -1,275 +1,275 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.util.csv; - -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.io.StringWriter; -import java.util.Date; -import java.util.Hashtable; - -import jakarta.xml.bind.JAXBElement; -//import javax.xml.namespace.QName; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.DTOFactory; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.loader.datavo.CRCLoaderJAXBUtil; -import edu.harvard.i2b2.crc.datavo.pdo.ObservationSet; -import edu.harvard.i2b2.crc.datavo.pdo.ObservationType; -import edu.harvard.i2b2.crc.datavo.pdo.PatientIdType; - -/** - * This program creates ObservationFact portion of PatientData XML file, from - * given input csv file. - * - * Sample column heading : "Record_Id," "Report_Id," 1 "EMPI," 2 "MRN_Type," 3 - * "MRN," "LMRNote_Date_Time," 5 "Status," "Author," "COD," "Institution," 9 - * "Author_MRN," 10 "Subject," 11 "Classification," "Timestamp," 13 - * "Software_Version" - * - * The above numbered columns are currently used. - * - * @author rk903 - * - */ -public class ObservationFactCSV2XmlBuilder { - - private String inputFileName = null; - - private String outputXmlFileName = null; - - private static Log log = LogFactory - .getLog(ObservationFactCSV2XmlBuilder.class); - - private static Hashtable csvHeaderMap = null; - - private Hashtable csvHeaderColumnPosition = null; - - private JAXBUtil jaxbUtil = null; - - private DTOFactory dtoFactory = new DTOFactory(); - - private edu.harvard.i2b2.crc.datavo.pdo.ObjectFactory pdoObjectFactory = new edu.harvard.i2b2.crc.datavo.pdo.ObjectFactory(); - static { - csvHeaderMap = new Hashtable(); - csvHeaderMap.put("encounter_ide", new String[] { "encounter_id" }); - csvHeaderMap.put("patient_ide", new String[] { "patient_id" }); - // csvHeaderMap.put("encounter_ide_source",new - // String[]{"MRN_TYPE","MRN_Type"}); - csvHeaderMap.put("encounter_ide_source", - new String[] { "sourcesytem_cd" }); - csvHeaderMap.put("start_date", new String[] { "start_date" }); - csvHeaderMap.put("sourcesystem_cd", new String[] { "sourcesystem_cd" }); - csvHeaderMap.put("provider_id", new String[] { "provider_id" }); - csvHeaderMap.put("concept_cd", new String[] { "concept_cd" }); - csvHeaderMap.put("update_date", new String[] { "Timestamp", - "Extraction_Timestamp" }); - csvHeaderMap.put("Negation", new String[] { "Negation" }); - csvHeaderMap.put("end_date", new String[] { "end_date" }); - } - - /** - * constructor - * - * @param inputFileName - * @param outputXmlFileName - */ - public ObservationFactCSV2XmlBuilder(String inputFileName, - String outputXmlFileName) { - this.inputFileName = inputFileName; - this.outputXmlFileName = outputXmlFileName; - - jaxbUtil = CRCLoaderJAXBUtil.getJAXBUtil(); - } - - /** - * Read csv file and create ObservationFact xml file. - * - * @throws I2B2Exception - */ - public void buildXml() throws I2B2Exception { - - BufferedReader inputReader = null; - BufferedWriter observationFactWriter = null; - log.info("Before building ObservationFact xml: " + outputXmlFileName - + " for " + inputFileName); - try { - // read file and return buffered reader - inputReader = new BufferedReader(new InputStreamReader( - new FileInputStream(inputFileName))); - observationFactWriter = new BufferedWriter(new OutputStreamWriter( - new FileOutputStream(outputXmlFileName))); - writeHeader(observationFactWriter); - observationFactWriter.write("\n"); - CSVFileReader csvReader = new CSVFileReader(inputFileName, ',', - '\"'); - - // read header and map header column position with element name - java.util.Vector headerFields = csvReader.readFields(); - int headerFieldCount = headerFields.size(); - csvHeaderColumnPosition = PatientDataXmlBuilder - .getCsvHeaderColumnPosition(csvHeaderMap, headerFields); - - java.util.Vector fields = null; - int i = 0; - ObservationSet observationSet = new ObservationSet(); - while ((fields = csvReader.readFields()) != null) { - // skip line which have less columns, compared to header column - if (headerFieldCount > fields.size()) { - continue; - } - String col[] = fields.toArray(new String[] {}); - - observationSet.getObservation().add(getObservationFact(col)); - i++; - if (i % 100 == 0) { - i = 0; - StringWriter strWriter = new StringWriter(); - try { - //MM Changed for Java 11 - //jaxbUtil.marshaller(new JAXBElement(new QName("", - // "observation_set"), ObservationSet.class, - // observationSet), strWriter); - } catch (Exception e) { - e.printStackTrace(); - } - String xml = strWriter.toString(); - String observationStr = xml.substring(xml.indexOf('>', xml - .indexOf("observation_set")) + 1, xml - .indexOf(" 0) { - StringWriter strWriter = new StringWriter(); - try { - //MM Changed for Java 11 - //jaxbUtil.marshaller(new JAXBElement(new QName("", - // "observation_set"), ObservationSet.class, - // observationSet), strWriter); - } catch (Exception e) { - e.printStackTrace(); - } - String xml = strWriter.toString(); - String observationStr = xml.substring(xml.indexOf('>', xml - .indexOf("observation_set")) + 1, xml - .indexOf("\n"); - writeEndDocument(observationFactWriter); - } catch (Exception ex) { - ex.printStackTrace(); - throw new I2B2Exception("Build XML failed ", ex); - } finally { - try { - if (inputReader != null) { - inputReader.close(); - } - - if (observationFactWriter != null) { - observationFactWriter.close(); - } - } catch (IOException closeEx) { - closeEx.printStackTrace(); - } - } - log.info("Finished building ObservationFact xml: " + outputXmlFileName - + " for " + inputFileName); - } - - private String getColumnValue(String col[], String elementName) { - String elementValue = PatientDataXmlBuilder.getColumnValue( - csvHeaderColumnPosition, col, elementName); - return elementValue; - } - - private String getNegationPrefix(String col[]) { - // check if negation present in this file. - if (csvHeaderColumnPosition.get("Negation") == null) { - return ""; - } - - String negation = getColumnValue(col, "Negation"); - if (negation != null) { - if (negation.equals("negated")) { - return "-NEG"; - } else { - return ""; - } - } - return ""; - } - - private String getProviderId(String col[]) { - if (csvHeaderColumnPosition.get("provider_id") == null) { - return "@"; - } else { - return getColumnValue(col, "provider_id"); - } - } - - private String getEndDate(String col[]) { - String endDate = getColumnValue(col, "end_date"); - if (endDate == null) { - endDate = ""; - } - return endDate; - } - - private ObservationType getObservationFact(String col[]) { - ObservationType observation = new ObservationType(); - ObservationType.EventId eventId = new ObservationType.EventId(); - eventId.setSource(getColumnValue(col, "sourcesystem_cd")); - eventId.setValue(getColumnValue(col, "encounter_ide")); - observation.setEventId(eventId); - PatientIdType patientId = new PatientIdType(); - patientId.setSource("EMPI"); - patientId.setValue(getColumnValue(col, "patient_ide")); - observation.setPatientId(patientId); - ObservationType.ConceptCd conceptCd = new ObservationType.ConceptCd(); - conceptCd.setValue(getColumnValue(col, "concept_cd").toLowerCase()); - observation.setConceptCd(conceptCd); - ObservationType.ObserverCd observerCd = new ObservationType.ObserverCd(); - observerCd.setValue(getProviderId(col)); - observation.setObserverCd(observerCd); - Date date = PatientDataXmlBuilder.getDate(getColumnValue(col, - "start_date")); - observation.setStartDate(dtoFactory.getXMLGregorianCalendar(date - .getTime())); - date = PatientDataXmlBuilder.getDate(getEndDate(col)); - observation.setEndDate((date != null) ? dtoFactory - .getXMLGregorianCalendar(date.getTime()) : null); - return observation; - - } - - private void writeHeader(BufferedWriter observationFactWriter) - throws IOException { - observationFactWriter.write(PatientDataXmlBuilder.getDocumentHeader()); - } - - private void writeEndDocument(BufferedWriter observationFactWriter) - throws IOException { - observationFactWriter.write(PatientDataXmlBuilder.getEndDocument()); - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.util.csv; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.io.StringWriter; +import java.util.Date; +import java.util.Hashtable; + +import jakarta.xml.bind.JAXBElement; +//import javax.xml.namespace.QName; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.DTOFactory; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.loader.datavo.CRCLoaderJAXBUtil; +import edu.harvard.i2b2.crc.datavo.pdo.ObservationSet; +import edu.harvard.i2b2.crc.datavo.pdo.ObservationType; +import edu.harvard.i2b2.crc.datavo.pdo.PatientIdType; + +/** + * This program creates ObservationFact portion of PatientData XML file, from + * given input csv file. + * + * Sample column heading : "Record_Id," "Report_Id," 1 "EMPI," 2 "MRN_Type," 3 + * "MRN," "LMRNote_Date_Time," 5 "Status," "Author," "COD," "Institution," 9 + * "Author_MRN," 10 "Subject," 11 "Classification," "Timestamp," 13 + * "Software_Version" + * + * The above numbered columns are currently used. + * + * @author rk903 + * + */ +public class ObservationFactCSV2XmlBuilder { + + private String inputFileName = null; + + private String outputXmlFileName = null; + + private static Log log = LogFactory + .getLog(ObservationFactCSV2XmlBuilder.class); + + private static Hashtable csvHeaderMap = null; + + private Hashtable csvHeaderColumnPosition = null; + + private JAXBUtil jaxbUtil = null; + + private DTOFactory dtoFactory = new DTOFactory(); + + private edu.harvard.i2b2.crc.datavo.pdo.ObjectFactory pdoObjectFactory = new edu.harvard.i2b2.crc.datavo.pdo.ObjectFactory(); + static { + csvHeaderMap = new Hashtable(); + csvHeaderMap.put("encounter_ide", new String[] { "encounter_id" }); + csvHeaderMap.put("patient_ide", new String[] { "patient_id" }); + // csvHeaderMap.put("encounter_ide_source",new + // String[]{"MRN_TYPE","MRN_Type"}); + csvHeaderMap.put("encounter_ide_source", + new String[] { "sourcesytem_cd" }); + csvHeaderMap.put("start_date", new String[] { "start_date" }); + csvHeaderMap.put("sourcesystem_cd", new String[] { "sourcesystem_cd" }); + csvHeaderMap.put("provider_id", new String[] { "provider_id" }); + csvHeaderMap.put("concept_cd", new String[] { "concept_cd" }); + csvHeaderMap.put("update_date", new String[] { "Timestamp", + "Extraction_Timestamp" }); + csvHeaderMap.put("Negation", new String[] { "Negation" }); + csvHeaderMap.put("end_date", new String[] { "end_date" }); + } + + /** + * constructor + * + * @param inputFileName + * @param outputXmlFileName + */ + public ObservationFactCSV2XmlBuilder(String inputFileName, + String outputXmlFileName) { + this.inputFileName = inputFileName; + this.outputXmlFileName = outputXmlFileName; + + jaxbUtil = CRCLoaderJAXBUtil.getJAXBUtil(); + } + + /** + * Read csv file and create ObservationFact xml file. + * + * @throws I2B2Exception + */ + public void buildXml() throws I2B2Exception { + + BufferedReader inputReader = null; + BufferedWriter observationFactWriter = null; + log.info("Before building ObservationFact xml: " + outputXmlFileName + + " for " + inputFileName); + try { + // read file and return buffered reader + inputReader = new BufferedReader(new InputStreamReader( + new FileInputStream(inputFileName))); + observationFactWriter = new BufferedWriter(new OutputStreamWriter( + new FileOutputStream(outputXmlFileName))); + writeHeader(observationFactWriter); + observationFactWriter.write("\n"); + CSVFileReader csvReader = new CSVFileReader(inputFileName, ',', + '\"'); + + // read header and map header column position with element name + java.util.Vector headerFields = csvReader.readFields(); + int headerFieldCount = headerFields.size(); + csvHeaderColumnPosition = PatientDataXmlBuilder + .getCsvHeaderColumnPosition(csvHeaderMap, headerFields); + + java.util.Vector fields = null; + int i = 0; + ObservationSet observationSet = new ObservationSet(); + while ((fields = csvReader.readFields()) != null) { + // skip line which have less columns, compared to header column + if (headerFieldCount > fields.size()) { + continue; + } + String col[] = fields.toArray(new String[] {}); + + observationSet.getObservation().add(getObservationFact(col)); + i++; + if (i % 100 == 0) { + i = 0; + StringWriter strWriter = new StringWriter(); + try { + //MM Changed for Java 11 + //jaxbUtil.marshaller(new JAXBElement(new QName("", + // "observation_set"), ObservationSet.class, + // observationSet), strWriter); + } catch (Exception e) { + e.printStackTrace(); + } + String xml = strWriter.toString(); + String observationStr = xml.substring(xml.indexOf('>', xml + .indexOf("observation_set")) + 1, xml + .indexOf(" 0) { + StringWriter strWriter = new StringWriter(); + try { + //MM Changed for Java 11 + //jaxbUtil.marshaller(new JAXBElement(new QName("", + // "observation_set"), ObservationSet.class, + // observationSet), strWriter); + } catch (Exception e) { + e.printStackTrace(); + } + String xml = strWriter.toString(); + String observationStr = xml.substring(xml.indexOf('>', xml + .indexOf("observation_set")) + 1, xml + .indexOf("\n"); + writeEndDocument(observationFactWriter); + } catch (Exception ex) { + ex.printStackTrace(); + throw new I2B2Exception("Build XML failed ", ex); + } finally { + try { + if (inputReader != null) { + inputReader.close(); + } + + if (observationFactWriter != null) { + observationFactWriter.close(); + } + } catch (IOException closeEx) { + closeEx.printStackTrace(); + } + } + log.info("Finished building ObservationFact xml: " + outputXmlFileName + + " for " + inputFileName); + } + + private String getColumnValue(String col[], String elementName) { + String elementValue = PatientDataXmlBuilder.getColumnValue( + csvHeaderColumnPosition, col, elementName); + return elementValue; + } + + private String getNegationPrefix(String col[]) { + // check if negation present in this file. + if (csvHeaderColumnPosition.get("Negation") == null) { + return ""; + } + + String negation = getColumnValue(col, "Negation"); + if (negation != null) { + if (negation.equals("negated")) { + return "-NEG"; + } else { + return ""; + } + } + return ""; + } + + private String getProviderId(String col[]) { + if (csvHeaderColumnPosition.get("provider_id") == null) { + return "@"; + } else { + return getColumnValue(col, "provider_id"); + } + } + + private String getEndDate(String col[]) { + String endDate = getColumnValue(col, "end_date"); + if (endDate == null) { + endDate = ""; + } + return endDate; + } + + private ObservationType getObservationFact(String col[]) { + ObservationType observation = new ObservationType(); + ObservationType.EventId eventId = new ObservationType.EventId(); + eventId.setSource(getColumnValue(col, "sourcesystem_cd")); + eventId.setValue(getColumnValue(col, "encounter_ide")); + observation.setEventId(eventId); + PatientIdType patientId = new PatientIdType(); + patientId.setSource("EMPI"); + patientId.setValue(getColumnValue(col, "patient_ide")); + observation.setPatientId(patientId); + ObservationType.ConceptCd conceptCd = new ObservationType.ConceptCd(); + conceptCd.setValue(getColumnValue(col, "concept_cd").toLowerCase()); + observation.setConceptCd(conceptCd); + ObservationType.ObserverCd observerCd = new ObservationType.ObserverCd(); + observerCd.setValue(getProviderId(col)); + observation.setObserverCd(observerCd); + Date date = PatientDataXmlBuilder.getDate(getColumnValue(col, + "start_date")); + observation.setStartDate(dtoFactory.getXMLGregorianCalendar(date + .getTime())); + date = PatientDataXmlBuilder.getDate(getEndDate(col)); + observation.setEndDate((date != null) ? dtoFactory + .getXMLGregorianCalendar(date.getTime()) : null); + return observation; + + } + + private void writeHeader(BufferedWriter observationFactWriter) + throws IOException { + observationFactWriter.write(PatientDataXmlBuilder.getDocumentHeader()); + } + + private void writeEndDocument(BufferedWriter observationFactWriter) + throws IOException { + observationFactWriter.write(PatientDataXmlBuilder.getEndDocument()); + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/util/csv/PatientDataXmlBuilder.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/util/csv/PatientDataXmlBuilder.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/util/csv/PatientDataXmlBuilder.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/util/csv/PatientDataXmlBuilder.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/util/csv/VisitCSV2XmlBuilder.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/util/csv/VisitCSV2XmlBuilder.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/util/csv/VisitCSV2XmlBuilder.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/util/csv/VisitCSV2XmlBuilder.java index 9b3a7dc2..468ccdb2 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/util/csv/VisitCSV2XmlBuilder.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/util/csv/VisitCSV2XmlBuilder.java @@ -1,224 +1,224 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.util.csv; - -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStreamWriter; -import java.io.StringWriter; -import java.util.Date; -import java.util.Hashtable; - -import jakarta.xml.bind.JAXBElement; -//import javax.xml.namespace.QName; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.DTOFactory; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.loader.datavo.CRCLoaderJAXBUtil; -import edu.harvard.i2b2.crc.datavo.pdo.EventSet; -import edu.harvard.i2b2.crc.datavo.pdo.EventType; -import edu.harvard.i2b2.crc.datavo.pdo.PatientIdType; - -/** - * Build's patient data xml with visit information, from input csv file. - * - * CSV Header information: "Record_Id," "Report_Id," "EMPI," "MRN_Type," "MRN," - * "LMRNote_Date_Time," "Status," "Author," "COD," "Institution," "Author_MRN," - * "Subject," "Classification," "Timestamp," "Software_Version" - * - * @author rk903 - * - */ -public class VisitCSV2XmlBuilder { - - private String inputFileName = null; - private String outputXmlFileName = null; - - private static Hashtable csvHeaderMap = null; - private Hashtable csvHeaderColumnPosition = null; - private DTOFactory dtoFactory = new DTOFactory(); - private JAXBUtil jaxbUtil = null; - - static { - csvHeaderMap = new Hashtable(); - csvHeaderMap.put("encounter_ide", new String[] { "encounter_id" }); - csvHeaderMap.put("patient_ide", new String[] { "patient_id" }); - // csvHeaderMap.put("encounter_ide_source",new - // String[]{"MRN_TYPE","MRN_Type"}); - csvHeaderMap.put("encounter_ide_source", - new String[] { "sourcesystem_cd" }); - csvHeaderMap.put("start_date", new String[] { "start_date" }); - csvHeaderMap.put("sourcesystem_cd", new String[] { "sourcesystem_cd" }); - csvHeaderMap.put("update_date", new String[] { "Timestamp", - "Extraction_Timestamp" }); - csvHeaderMap.put("end_date", new String[] { "Dis_Date_Time" }); - } - - /** - * Constructor - * - * @param inputFileName - * input csv file name - * @param outputXmlFileName - * output xml file name - */ - public VisitCSV2XmlBuilder(String inputFileName, String outputXmlFileName) { - this.inputFileName = inputFileName; - this.outputXmlFileName = outputXmlFileName; - - jaxbUtil = CRCLoaderJAXBUtil.getJAXBUtil(); - } - - public EventType getVisitDimension(String col[]) { - EventType event = new EventType(); - EventType.EventId eventId = new EventType.EventId(); - eventId.setValue(getColumnValue(col, "encounter_ide")); - eventId.setSource(getColumnValue(col, "encounter_ide_source")); - event.setEventId(eventId); - PatientIdType patientId = new PatientIdType(); - patientId.setSource("EMPI"); - patientId.setValue(getColumnValue(col, "patient_ide")); - event.setPatientId(patientId); - - // event.setPatientId(patientIdType); - Date date = PatientDataXmlBuilder.getDate(getColumnValue(col, - "start_date")); - event.setStartDate(dtoFactory.getXMLGregorianCalendar(date.getTime())); - date = PatientDataXmlBuilder.getDate(getEndDate(col)); - event.setEndDate((date != null) ? dtoFactory - .getXMLGregorianCalendar(date.getTime()) : null); - event.setSourcesystemCd(getColumnValue(col, "sourcesystem_cd")); - // date = - // PatientDataXmlBuilder.formatIntDate(getColumnValue(col,"update_date" - // ); - event.setUpdateDate(null); - return event; - } - - private void writeHeader(BufferedWriter visitWriter) throws IOException { - visitWriter.write(PatientDataXmlBuilder.getDocumentHeader()); - } - - private void writeEndDocument(BufferedWriter visitWriter) - throws IOException { - visitWriter.write(PatientDataXmlBuilder.getEndDocument()); - } - - /** - * Parse csv file and generate xml file. - * - * @throws I2B2Exception - */ - @SuppressWarnings("unchecked") - public void buildXml() throws I2B2Exception { - - BufferedReader inputReader = null; - BufferedWriter visitWriter = null; - - try { - // read file and return buffered reader - visitWriter = new BufferedWriter(new OutputStreamWriter( - new FileOutputStream(outputXmlFileName))); - writeHeader(visitWriter); - visitWriter.write(""); - CSVFileReader csvReader = new CSVFileReader(inputFileName, ',', - '\"'); - // read header and map header column position with element name - java.util.Vector headerFields = csvReader.readFields(); - int headerFieldCount = headerFields.size(); - csvHeaderColumnPosition = PatientDataXmlBuilder - .getCsvHeaderColumnPosition(csvHeaderMap, headerFields); - - java.util.Vector fields = null; - int i = 0; - EventSet eventSet = new EventSet(); - while ((fields = csvReader.readFields()) != null) { - // skip line which have less columns, compared to header column - if (headerFieldCount > fields.size()) { - continue; - } - i++; - - String col[] = fields.toArray(new String[] {}); - eventSet.getEvent().add(getVisitDimension(col)); - if (i % 1000 == 0) { - i = 0; - StringWriter strWriter = new StringWriter(); - try { - //MM Changed for Java 11 - //jaxbUtil.marshaller(new JAXBElement(new QName("", - // "eventset"), EventSet.class, eventSet), - // strWriter); - } catch (Exception e) { - e.printStackTrace(); - } - String xml = strWriter.toString(); - String observationStr = xml.substring(xml.indexOf('>', xml - .indexOf("eventset")) + 1, xml - .indexOf(" 0) { - StringWriter strWriter = new StringWriter(); - try { - //MM Changed for Java 11 - //jaxbUtil.marshaller(new JAXBElement(new QName("", - // "eventset"), EventSet.class, eventSet), strWriter); - } catch (Exception e) { - e.printStackTrace(); - } - String xml = strWriter.toString(); - String observationStr = xml.substring(xml.indexOf('>', xml - .indexOf("eventset")) + 1, xml.indexOf(""); - } - - writeEndDocument(visitWriter); - } catch (Exception ex) { - ex.printStackTrace(); - throw new I2B2Exception("Error building Visit xml", ex); - } finally { - try { - if (inputReader != null) { - inputReader.close(); - } - if (visitWriter != null) { - visitWriter.close(); - } - - } catch (IOException closeEx) { - closeEx.printStackTrace(); - } - } - - } - - private String getColumnValue(String col[], String elementName) { - String elementValue = PatientDataXmlBuilder.getColumnValue( - csvHeaderColumnPosition, col, elementName); - return elementValue; - } - - private String getEndDate(String col[]) { - String endDate = getColumnValue(col, "end_date"); - if (endDate == null) { - endDate = ""; - } - return endDate; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.util.csv; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.StringWriter; +import java.util.Date; +import java.util.Hashtable; + +import jakarta.xml.bind.JAXBElement; +//import javax.xml.namespace.QName; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.DTOFactory; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.loader.datavo.CRCLoaderJAXBUtil; +import edu.harvard.i2b2.crc.datavo.pdo.EventSet; +import edu.harvard.i2b2.crc.datavo.pdo.EventType; +import edu.harvard.i2b2.crc.datavo.pdo.PatientIdType; + +/** + * Build's patient data xml with visit information, from input csv file. + * + * CSV Header information: "Record_Id," "Report_Id," "EMPI," "MRN_Type," "MRN," + * "LMRNote_Date_Time," "Status," "Author," "COD," "Institution," "Author_MRN," + * "Subject," "Classification," "Timestamp," "Software_Version" + * + * @author rk903 + * + */ +public class VisitCSV2XmlBuilder { + + private String inputFileName = null; + private String outputXmlFileName = null; + + private static Hashtable csvHeaderMap = null; + private Hashtable csvHeaderColumnPosition = null; + private DTOFactory dtoFactory = new DTOFactory(); + private JAXBUtil jaxbUtil = null; + + static { + csvHeaderMap = new Hashtable(); + csvHeaderMap.put("encounter_ide", new String[] { "encounter_id" }); + csvHeaderMap.put("patient_ide", new String[] { "patient_id" }); + // csvHeaderMap.put("encounter_ide_source",new + // String[]{"MRN_TYPE","MRN_Type"}); + csvHeaderMap.put("encounter_ide_source", + new String[] { "sourcesystem_cd" }); + csvHeaderMap.put("start_date", new String[] { "start_date" }); + csvHeaderMap.put("sourcesystem_cd", new String[] { "sourcesystem_cd" }); + csvHeaderMap.put("update_date", new String[] { "Timestamp", + "Extraction_Timestamp" }); + csvHeaderMap.put("end_date", new String[] { "Dis_Date_Time" }); + } + + /** + * Constructor + * + * @param inputFileName + * input csv file name + * @param outputXmlFileName + * output xml file name + */ + public VisitCSV2XmlBuilder(String inputFileName, String outputXmlFileName) { + this.inputFileName = inputFileName; + this.outputXmlFileName = outputXmlFileName; + + jaxbUtil = CRCLoaderJAXBUtil.getJAXBUtil(); + } + + public EventType getVisitDimension(String col[]) { + EventType event = new EventType(); + EventType.EventId eventId = new EventType.EventId(); + eventId.setValue(getColumnValue(col, "encounter_ide")); + eventId.setSource(getColumnValue(col, "encounter_ide_source")); + event.setEventId(eventId); + PatientIdType patientId = new PatientIdType(); + patientId.setSource("EMPI"); + patientId.setValue(getColumnValue(col, "patient_ide")); + event.setPatientId(patientId); + + // event.setPatientId(patientIdType); + Date date = PatientDataXmlBuilder.getDate(getColumnValue(col, + "start_date")); + event.setStartDate(dtoFactory.getXMLGregorianCalendar(date.getTime())); + date = PatientDataXmlBuilder.getDate(getEndDate(col)); + event.setEndDate((date != null) ? dtoFactory + .getXMLGregorianCalendar(date.getTime()) : null); + event.setSourcesystemCd(getColumnValue(col, "sourcesystem_cd")); + // date = + // PatientDataXmlBuilder.formatIntDate(getColumnValue(col,"update_date" + // ); + event.setUpdateDate(null); + return event; + } + + private void writeHeader(BufferedWriter visitWriter) throws IOException { + visitWriter.write(PatientDataXmlBuilder.getDocumentHeader()); + } + + private void writeEndDocument(BufferedWriter visitWriter) + throws IOException { + visitWriter.write(PatientDataXmlBuilder.getEndDocument()); + } + + /** + * Parse csv file and generate xml file. + * + * @throws I2B2Exception + */ + @SuppressWarnings("unchecked") + public void buildXml() throws I2B2Exception { + + BufferedReader inputReader = null; + BufferedWriter visitWriter = null; + + try { + // read file and return buffered reader + visitWriter = new BufferedWriter(new OutputStreamWriter( + new FileOutputStream(outputXmlFileName))); + writeHeader(visitWriter); + visitWriter.write(""); + CSVFileReader csvReader = new CSVFileReader(inputFileName, ',', + '\"'); + // read header and map header column position with element name + java.util.Vector headerFields = csvReader.readFields(); + int headerFieldCount = headerFields.size(); + csvHeaderColumnPosition = PatientDataXmlBuilder + .getCsvHeaderColumnPosition(csvHeaderMap, headerFields); + + java.util.Vector fields = null; + int i = 0; + EventSet eventSet = new EventSet(); + while ((fields = csvReader.readFields()) != null) { + // skip line which have less columns, compared to header column + if (headerFieldCount > fields.size()) { + continue; + } + i++; + + String col[] = fields.toArray(new String[] {}); + eventSet.getEvent().add(getVisitDimension(col)); + if (i % 1000 == 0) { + i = 0; + StringWriter strWriter = new StringWriter(); + try { + //MM Changed for Java 11 + //jaxbUtil.marshaller(new JAXBElement(new QName("", + // "eventset"), EventSet.class, eventSet), + // strWriter); + } catch (Exception e) { + e.printStackTrace(); + } + String xml = strWriter.toString(); + String observationStr = xml.substring(xml.indexOf('>', xml + .indexOf("eventset")) + 1, xml + .indexOf(" 0) { + StringWriter strWriter = new StringWriter(); + try { + //MM Changed for Java 11 + //jaxbUtil.marshaller(new JAXBElement(new QName("", + // "eventset"), EventSet.class, eventSet), strWriter); + } catch (Exception e) { + e.printStackTrace(); + } + String xml = strWriter.toString(); + String observationStr = xml.substring(xml.indexOf('>', xml + .indexOf("eventset")) + 1, xml.indexOf(""); + } + + writeEndDocument(visitWriter); + } catch (Exception ex) { + ex.printStackTrace(); + throw new I2B2Exception("Error building Visit xml", ex); + } finally { + try { + if (inputReader != null) { + inputReader.close(); + } + if (visitWriter != null) { + visitWriter.close(); + } + + } catch (IOException closeEx) { + closeEx.printStackTrace(); + } + } + + } + + private String getColumnValue(String col[], String elementName) { + String elementValue = PatientDataXmlBuilder.getColumnValue( + csvHeaderColumnPosition, col, elementName); + return elementValue; + } + + private String getEndDate(String col[]) { + String endDate = getColumnValue(col, "end_date"); + if (endDate == null) { + endDate = ""; + } + return endDate; + } + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/util/security/Cipher.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/util/security/Cipher.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/util/security/Cipher.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/util/security/Cipher.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/util/security/HighEncryption.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/util/security/HighEncryption.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/util/security/HighEncryption.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/util/security/HighEncryption.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/util/security/RijndaelAlgorithm.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/util/security/RijndaelAlgorithm.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/util/security/RijndaelAlgorithm.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/util/security/RijndaelAlgorithm.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/util/security/UInt.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/util/security/UInt.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/util/security/UInt.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/util/security/UInt.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/util/security/UInt64.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/util/security/UInt64.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/util/security/UInt64.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/util/security/UInt64.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ws/ProviderRestService.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ws/ProviderRestService.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ws/ProviderRestService.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ws/ProviderRestService.java index cae23cfa..d0ec73ed --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/ws/ProviderRestService.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/ws/ProviderRestService.java @@ -1,174 +1,174 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.ws; - -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileWriter; -import java.io.InputStreamReader; -import java.io.PrintWriter; -import java.io.StringReader; - -import jakarta.activation.DataHandler; -import jakarta.activation.FileDataSource; -import javax.xml.stream.XMLInputFactory; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamReader; -import org.apache.axiom.om.OMElement; -import org.apache.axiom.om.OMText; -import org.apache.axiom.om.OMXMLBuilderFactory; -import org.apache.axis2.context.MessageContext; -import org.apache.axis2.context.OperationContext; -import org.apache.axis2.wsdl.WSDLConstants; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.axis2.ServiceClient; -import edu.harvard.i2b2.crc.loader.delegate.GetLoadStatusRequestHandler; -import edu.harvard.i2b2.crc.loader.delegate.GetMissingTermRequestHandler; -import edu.harvard.i2b2.crc.loader.delegate.LoaderQueryRequestDelegate; -import edu.harvard.i2b2.crc.loader.delegate.PublishDataRequestHandler; - -/** - * Test a Provider - * - * @see - * @author rkuttan - * - */ - -//@WebServiceProvider(serviceName = "ProviderService", portName = "ProviderPort", targetNamespace = "http://org.jboss.ws/provider", wsdlLocation = "WEB-INF/wsdl/Provider.wsdl") -//@ServiceMode(value = Service.Mode.PAYLOAD) - -// - PAYLOAD is implicit -public class ProviderRestService { - /** log **/ - protected final Log log = LogFactory.getLog(getClass()); - - public OMElement publishDataRequest(OMElement request) { - LoaderQueryRequestDelegate queryDelegate = new LoaderQueryRequestDelegate(); - OMElement responseElement = null; - try { - String requestXml = request.toString(); - PublishDataRequestHandler handler = new PublishDataRequestHandler( - requestXml); - String response = queryDelegate.handleRequest(requestXml, handler); - responseElement = ServiceClient.buildOMElementFromString(response); - - } catch (XMLStreamException e) { - log.error("xml stream exception", e); - } catch (I2B2Exception e) { - log.error("i2b2 exception", e); - } catch (Throwable e) { - log.error("Throwable", e); - } - return responseElement; - } - - public OMElement getLoadDataStatusRequest(OMElement request) { - LoaderQueryRequestDelegate queryDelegate = new LoaderQueryRequestDelegate(); - OMElement responseElement = null; - try { - String requestXml = request.toString(); - GetLoadStatusRequestHandler handler = new GetLoadStatusRequestHandler( - requestXml); - String response = queryDelegate.handleRequest(requestXml, handler); - responseElement = ServiceClient.buildOMElementFromString(response); - - } catch (XMLStreamException e) { - log.error("xml stream exception", e); - } catch (I2B2Exception e) { - log.error("i2b2 exception", e); - } catch (Throwable e) { - log.error("Throwable", e); - } - return responseElement; - } - - - public OMElement getMissingTermRequest(OMElement request) { - LoaderQueryRequestDelegate queryDelegate = new LoaderQueryRequestDelegate(); - OMElement responseElement = null; - try { - String requestXml = request.toString(); - - - GetMissingTermRequestHandler handler = new GetMissingTermRequestHandler( - requestXml); - String response = queryDelegate.handleRequest(requestXml, handler); - responseElement = ServiceClient.buildOMElementFromString(response); - - } catch (XMLStreamException e) { - log.error("xml stream exception", e); - } catch (I2B2Exception e) { - log.error("i2b2 exception", e); - } catch (Throwable e) { - log.error("Throwable", e); - } - return responseElement; - } - - public OMElement mtomSample(OMElement element) throws Exception { - OMElement _fileNameEle = null; - OMElement _imageElement = null; - - - MessageContext inMessageContext = MessageContext - .getCurrentMessageContext(); - OperationContext operationContext = inMessageContext - .getOperationContext(); - - DataHandler dataHandler = inMessageContext - .getAttachment("fileattachment"); - - // OMText firstText = (OMText) element.getFirstOMChild(); - // System.out.println(firstText); - - OMText binaryNode = (OMText) (element.getFirstElement()) - .getFirstOMChild(); - - // OMText binaryNode = firstText; - binaryNode.setOptimize(true); - DataHandler actualDH; - // actualDH = (DataHandler) binaryNode.getDataHandler(); - actualDH = dataHandler; - ByteArrayInputStream is = (ByteArrayInputStream) actualDH - .getDataSource().getInputStream(); - BufferedReader br = new BufferedReader(new InputStreamReader(is, - "UTF-8")); - String fileSaveName = "FileAttachment"; - File file = new File(fileSaveName); - PrintWriter filetmp = new PrintWriter(new BufferedWriter( - new FileWriter(file, true))); - String ligne = null; - while ((ligne = br.readLine()) != null) - filetmp.println(ligne); - filetmp.flush(); - filetmp.close(); - - // setting response - - MessageContext outMessageContext = operationContext - .getMessageContext(WSDLConstants.MESSAGE_LABEL_OUT_VALUE); - String attachmentfilename = "/crcapp/jdbc.properties"; - jakarta.activation.DataHandler outDataHandler = new jakarta.activation.DataHandler( - new FileDataSource(attachmentfilename)); - - outMessageContext.addAttachment(outDataHandler); - outMessageContext.addAttachment("f2", outDataHandler); - - return element; - } - - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.ws; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileWriter; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.io.StringReader; + +import jakarta.activation.DataHandler; +import jakarta.activation.FileDataSource; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import org.apache.axiom.om.OMElement; +import org.apache.axiom.om.OMText; +import org.apache.axiom.om.OMXMLBuilderFactory; +import org.apache.axis2.context.MessageContext; +import org.apache.axis2.context.OperationContext; +import org.apache.axis2.wsdl.WSDLConstants; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.axis2.ServiceClient; +import edu.harvard.i2b2.crc.loader.delegate.GetLoadStatusRequestHandler; +import edu.harvard.i2b2.crc.loader.delegate.GetMissingTermRequestHandler; +import edu.harvard.i2b2.crc.loader.delegate.LoaderQueryRequestDelegate; +import edu.harvard.i2b2.crc.loader.delegate.PublishDataRequestHandler; + +/** + * Test a Provider + * + * @see + * @author rkuttan + * + */ + +//@WebServiceProvider(serviceName = "ProviderService", portName = "ProviderPort", targetNamespace = "http://org.jboss.ws/provider", wsdlLocation = "WEB-INF/wsdl/Provider.wsdl") +//@ServiceMode(value = Service.Mode.PAYLOAD) + +// - PAYLOAD is implicit +public class ProviderRestService { + /** log **/ + protected final Log log = LogFactory.getLog(getClass()); + + public OMElement publishDataRequest(OMElement request) { + LoaderQueryRequestDelegate queryDelegate = new LoaderQueryRequestDelegate(); + OMElement responseElement = null; + try { + String requestXml = request.toString(); + PublishDataRequestHandler handler = new PublishDataRequestHandler( + requestXml); + String response = queryDelegate.handleRequest(requestXml, handler); + responseElement = ServiceClient.buildOMElementFromString(response); + + } catch (XMLStreamException e) { + log.error("xml stream exception", e); + } catch (I2B2Exception e) { + log.error("i2b2 exception", e); + } catch (Throwable e) { + log.error("Throwable", e); + } + return responseElement; + } + + public OMElement getLoadDataStatusRequest(OMElement request) { + LoaderQueryRequestDelegate queryDelegate = new LoaderQueryRequestDelegate(); + OMElement responseElement = null; + try { + String requestXml = request.toString(); + GetLoadStatusRequestHandler handler = new GetLoadStatusRequestHandler( + requestXml); + String response = queryDelegate.handleRequest(requestXml, handler); + responseElement = ServiceClient.buildOMElementFromString(response); + + } catch (XMLStreamException e) { + log.error("xml stream exception", e); + } catch (I2B2Exception e) { + log.error("i2b2 exception", e); + } catch (Throwable e) { + log.error("Throwable", e); + } + return responseElement; + } + + + public OMElement getMissingTermRequest(OMElement request) { + LoaderQueryRequestDelegate queryDelegate = new LoaderQueryRequestDelegate(); + OMElement responseElement = null; + try { + String requestXml = request.toString(); + + + GetMissingTermRequestHandler handler = new GetMissingTermRequestHandler( + requestXml); + String response = queryDelegate.handleRequest(requestXml, handler); + responseElement = ServiceClient.buildOMElementFromString(response); + + } catch (XMLStreamException e) { + log.error("xml stream exception", e); + } catch (I2B2Exception e) { + log.error("i2b2 exception", e); + } catch (Throwable e) { + log.error("Throwable", e); + } + return responseElement; + } + + public OMElement mtomSample(OMElement element) throws Exception { + OMElement _fileNameEle = null; + OMElement _imageElement = null; + + + MessageContext inMessageContext = MessageContext + .getCurrentMessageContext(); + OperationContext operationContext = inMessageContext + .getOperationContext(); + + DataHandler dataHandler = inMessageContext + .getAttachment("fileattachment"); + + // OMText firstText = (OMText) element.getFirstOMChild(); + // System.out.println(firstText); + + OMText binaryNode = (OMText) (element.getFirstElement()) + .getFirstOMChild(); + + // OMText binaryNode = firstText; + binaryNode.setOptimize(true); + DataHandler actualDH; + // actualDH = (DataHandler) binaryNode.getDataHandler(); + actualDH = dataHandler; + ByteArrayInputStream is = (ByteArrayInputStream) actualDH + .getDataSource().getInputStream(); + BufferedReader br = new BufferedReader(new InputStreamReader(is, + "UTF-8")); + String fileSaveName = "FileAttachment"; + File file = new File(fileSaveName); + PrintWriter filetmp = new PrintWriter(new BufferedWriter( + new FileWriter(file, true))); + String ligne = null; + while ((ligne = br.readLine()) != null) + filetmp.println(ligne); + filetmp.flush(); + filetmp.close(); + + // setting response + + MessageContext outMessageContext = operationContext + .getMessageContext(WSDLConstants.MESSAGE_LABEL_OUT_VALUE); + String attachmentfilename = "/crcapp/jdbc.properties"; + jakarta.activation.DataHandler outDataHandler = new jakarta.activation.DataHandler( + new FileDataSource(attachmentfilename)); + + outMessageContext.addAttachment(outDataHandler); + outMessageContext.addAttachment("f2", outDataHandler); + + return element; + } + + + +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/xml/StartElementListener.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/xml/StartElementListener.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/xml/StartElementListener.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/xml/StartElementListener.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/xml/TypePullParser.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/xml/TypePullParser.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/xml/TypePullParser.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/xml/TypePullParser.java index d37a4a5f..3cf923c2 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/xml/TypePullParser.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/loader/xml/TypePullParser.java @@ -1,104 +1,104 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.xml; - -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; - -import jakarta.xml.bind.JAXBContext; -import jakarta.xml.bind.JAXBElement; -import jakarta.xml.bind.JAXBException; -import jakarta.xml.bind.Marshaller; -import jakarta.xml.bind.Unmarshaller; -import javax.xml.stream.EventFilter; -import javax.xml.stream.XMLEventReader; -import javax.xml.stream.XMLInputFactory; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.events.StartElement; -import javax.xml.stream.events.XMLEvent; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.crc.datavo.pdo.ObservationType; - -public class TypePullParser { - StartElementListener listener = null; - String filename = null; - String typeName = null; - Class jaxbClass = null; - - public TypePullParser(StartElementListener listener, String typeName, - Class jaxbClass, String filename) { - this.listener = listener; - this.typeName = typeName; - this.jaxbClass = jaxbClass; - this.filename = filename; - } - - public void doParsing() throws I2B2Exception { - - XMLInputFactory xmlif = XMLInputFactory.newInstance(); - FileReader fr = null; - try { - fr = new FileReader(filename); - XMLEventReader xmler = xmlif.createXMLEventReader(fr); - EventFilter filter = new EventFilter() { - @Override - public boolean accept(XMLEvent event) { - return event.isStartElement(); - } - }; - XMLEventReader xmlfer = xmlif.createFilteredReader(xmler, filter); - - // Jump to the first element in the document, the enclosing - // BugCollection - StartElement e = (StartElement) xmlfer.nextEvent(); - // System.out.println(e.getName().getLocalPart()); - - JAXBContext ctx = JAXBContext - .newInstance("edu.harvard.i2b2.crc.datavo.i2b2message:edu.harvard.i2b2.crc.datavo.pdo"); - Unmarshaller um = ctx.createUnmarshaller(); - Marshaller ma = ctx.createMarshaller(); - int bugs = 0; - - while (xmlfer.hasNext()) { - - StartElement startElement = (StartElement) xmlfer.peek(); - if (startElement == null) { - break; - } - - if (startElement.getName().getLocalPart().trim().equals( - typeName)) { - - JAXBElement element = um.unmarshal(xmler, - jaxbClass); - listener.process(element.getValue()); - } else { - xmlfer.nextEvent(); - } - - } - } catch (JAXBException jaxEx) { - throw new I2B2Exception("<" + typeName + "> parsing failed", jaxEx); - } catch (XMLStreamException streamEx) { - throw new I2B2Exception("<" + typeName + "> parsing failed", - streamEx); - } catch (FileNotFoundException fileEx) { - throw new I2B2Exception("<" + typeName + "> parsing failed", fileEx); - } finally { - try { - fr.close(); - } catch (IOException ioe) { - ; - } - } - - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.xml; + +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; + +import jakarta.xml.bind.JAXBContext; +import jakarta.xml.bind.JAXBElement; +import jakarta.xml.bind.JAXBException; +import jakarta.xml.bind.Marshaller; +import jakarta.xml.bind.Unmarshaller; +import javax.xml.stream.EventFilter; +import javax.xml.stream.XMLEventReader; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.events.StartElement; +import javax.xml.stream.events.XMLEvent; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.crc.datavo.pdo.ObservationType; + +public class TypePullParser { + StartElementListener listener = null; + String filename = null; + String typeName = null; + Class jaxbClass = null; + + public TypePullParser(StartElementListener listener, String typeName, + Class jaxbClass, String filename) { + this.listener = listener; + this.typeName = typeName; + this.jaxbClass = jaxbClass; + this.filename = filename; + } + + public void doParsing() throws I2B2Exception { + + XMLInputFactory xmlif = XMLInputFactory.newInstance(); + FileReader fr = null; + try { + fr = new FileReader(filename); + XMLEventReader xmler = xmlif.createXMLEventReader(fr); + EventFilter filter = new EventFilter() { + @Override + public boolean accept(XMLEvent event) { + return event.isStartElement(); + } + }; + XMLEventReader xmlfer = xmlif.createFilteredReader(xmler, filter); + + // Jump to the first element in the document, the enclosing + // BugCollection + StartElement e = (StartElement) xmlfer.nextEvent(); + // System.out.println(e.getName().getLocalPart()); + + JAXBContext ctx = JAXBContext + .newInstance("edu.harvard.i2b2.crc.datavo.i2b2message:edu.harvard.i2b2.crc.datavo.pdo"); + Unmarshaller um = ctx.createUnmarshaller(); + Marshaller ma = ctx.createMarshaller(); + int bugs = 0; + + while (xmlfer.hasNext()) { + + StartElement startElement = (StartElement) xmlfer.peek(); + if (startElement == null) { + break; + } + + if (startElement.getName().getLocalPart().trim().equals( + typeName)) { + + JAXBElement element = um.unmarshal(xmler, + jaxbClass); + listener.process(element.getValue()); + } else { + xmlfer.nextEvent(); + } + + } + } catch (JAXBException jaxEx) { + throw new I2B2Exception("<" + typeName + "> parsing failed", jaxEx); + } catch (XMLStreamException streamEx) { + throw new I2B2Exception("<" + typeName + "> parsing failed", + streamEx); + } catch (FileNotFoundException fileEx) { + throw new I2B2Exception("<" + typeName + "> parsing failed", fileEx); + } finally { + try { + fr.close(); + } catch (IOException ioe) { + ; + } + } + + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/mbean/CronStartService.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/mbean/CronStartService.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/mbean/CronStartService.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/mbean/CronStartService.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/mbean/META-INF/jboss-service.xml b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/mbean/META-INF/jboss-service.xml old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/mbean/META-INF/jboss-service.xml rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/mbean/META-INF/jboss-service.xml diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/CSVIterator.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/CSVIterator.java similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/CSVIterator.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/CSVIterator.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/CSVParser.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/CSVParser.java similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/CSVParser.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/CSVParser.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/CSVParserBuilder.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/CSVParserBuilder.java similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/CSVParserBuilder.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/CSVParserBuilder.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/CSVReader.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/CSVReader.java similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/CSVReader.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/CSVReader.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/CSVReaderBuilder.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/CSVReaderBuilder.java similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/CSVReaderBuilder.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/CSVReaderBuilder.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/CSVWriter.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/CSVWriter.java similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/CSVWriter.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/CSVWriter.java index 046b47a4..76546912 100644 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/CSVWriter.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/CSVWriter.java @@ -1,510 +1,510 @@ -package edu.harvard.i2b2.crc.opencsv; - -/** - * Copyright 2005 Bytecode Pty Ltd. - *

    - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - *

    - * http://www.apache.org/licenses/LICENSE-2.0 - *

    - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import java.io.*; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.sql.SQLException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.HashMap; -import java.util.List; - -import org.springframework.util.DigestUtils; - -import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; - -/** - * A very simple CSV writer released under a commercial-friendly license. - * - * @author Glen Smith - */ -public class CSVWriter implements Closeable { - public static final String RFC4180_LINE_END = "\r\n"; - /** - * The character used for escaping quotes. - */ - public static char DEFAULT_ESCAPE_CHARACTER = '"'; - /** - * The quote constant to use when you wish to suppress all quoting. - */ - public static char NO_QUOTE_CHARACTER = '\u0000'; - /** - * The escape constant to use when you wish to suppress all escaping. - */ - public static char NO_ESCAPE_CHARACTER = '\u0000'; - /** - * Default line terminator uses platform encoding. - */ - public static String DEFAULT_LINE_END = "\n"; - public static int INITIAL_BUFFER_SIZE = 8 << 20; //8 MB - protected char separator; - protected char quotechar; - protected char escapechar; - protected int lineWidth; - protected int totalRows; - protected int recordCount; - protected int incrRows; - //protected Boolean isZip = false; - protected String lineEnd; - protected PrintWriter logWriter; - protected String CSVFileName; - protected ResultSetHelperService resultService; - protected FileBuffer buffer; - protected boolean asyncMode = false; - protected HashMap excludes = new HashMap<>(); - protected HashMap remaps = new HashMap(); - protected String[] titles; - protected String msg = ""; -// protected SetFinderDAOFactory sfDAOFactory; - - /** - * Constructs CSVWriter using a comma for the separator. - * - * @param writer the writer to an underlying CSV source. - */ - public CSVWriter(Writer writer) { - this(writer, CSVParser.DEFAULT_SEPARATOR); - } - - public CSVWriter(String fileName, char separator, char quotechar, char escapechar, String lineEnd, int recordCount) throws Exception { - this(new FileWriter(fileName), separator, quotechar, escapechar, lineEnd); - this.CSVFileName = fileName; - this.recordCount = recordCount; - //this.sfDAOFactory = sfDAOFactory; - String extensionName = "csv"; - if (quotechar == '\'' && escapechar == quotechar) extensionName = "sql"; - - buffer = new FileBuffer(INITIAL_BUFFER_SIZE, fileName, extensionName); - //logWriter = new PrintWriter(buffer.file.getParentFile().getAbsolutePath() + File.separator + buffer.fileName + ".log"); - logWriter = new PrintWriter(new FileOutputStream( - new File(buffer.file.getParentFile().getAbsolutePath() + File.separator + "Log.txt"), true)); - writeLogHeader(fileName); - //logWriter = new PrintWriter(System.err); - } - -// public CSVWriter(String fileName) throws Exception { -// this(fileName, CSVParser.DEFAULT_SEPARATOR, CSVParser.DEFAULT_QUOTE_CHARACTER, DEFAULT_ESCAPE_CHARACTER, DEFAULT_LINE_END); -// } - - /** - * Constructs CSVWriter with supplied separator. - * - * @param writer the writer to an underlying CSV source. - * @param separator the delimiter to use for separating entries. - */ - public CSVWriter(Writer writer, char separator) { - this(writer, separator, CSVParser.DEFAULT_QUOTE_CHARACTER); - } - - /** - * Constructs CSVWriter with supplied separator and quote char. - * - * @param writer the writer to an underlying CSV source. - * @param separator the delimiter to use for separating entries - * @param quotechar the character to use for quoted elements - */ - public CSVWriter(Writer writer, char separator, char quotechar) { - this(writer, separator, quotechar, DEFAULT_ESCAPE_CHARACTER); - } - - /** - * Constructs CSVWriter with supplied separator and quote char. - * - * @param writer the writer to an underlying CSV source. - * @param separator the delimiter to use for separating entries - * @param quotechar the character to use for quoted elements - * @param escapechar the character to use for escaping quotechars or escapechars - */ - public CSVWriter(Writer writer, char separator, char quotechar, char escapechar) { - this(writer, separator, quotechar, escapechar, DEFAULT_LINE_END); - } - - /** - * Constructs CSVWriter with supplied separator and quote char. - * - * @param writer the writer to an underlying CSV source. - * @param separator the delimiter to use for separating entries - * @param quotechar the character to use for quoted elements - * @param lineEnd the line feed terminator to use - */ - public CSVWriter(Writer writer, char separator, char quotechar, String lineEnd) { - this(writer, separator, quotechar, DEFAULT_ESCAPE_CHARACTER, lineEnd); - } - - /** - * Constructs CSVWriter with supplied separator, quote char, escape char and line ending. - * - * @param writer the writer to an underlying CSV source. - * @param separator the delimiter to use for separating entries - * @param quotechar the character to use for quoted elements - * @param escapechar the character to use for escaping quotechars or escapechars - * @param lineEnd the line feed terminator to use - */ - public CSVWriter(Writer writer, char separator, char quotechar, char escapechar, String lineEnd) { - this.separator = separator; - this.quotechar = quotechar; - this.escapechar = escapechar; - this.lineEnd = lineEnd; - } - - public void setExclude(String columnName, boolean exclude) { - if (columnName == null) return; - excludes.put(columnName.toUpperCase().trim(), exclude); - } - - public void setRemap(String columnName, String value) { - if (columnName == null) return; - remaps.put(columnName.toUpperCase().trim(), value.trim()); - } - - public void setAsyncMode(boolean mode) { - asyncMode = mode; - } - - public void setBufferSize(int bytes) { - INITIAL_BUFFER_SIZE = bytes; - } - - protected CSVWriter add(char str) throws IOException { - buffer.write(str); - ++lineWidth; - return this; - } - - protected CSVWriter add(String str) throws IOException { - buffer.write(str); - int len = str.length(); - lineWidth += len; - return this; - } - - protected CSVWriter add(StringBuilder sbf) throws IOException { - return add(sbf.toString()); - } - - protected void writeLogHeader(String fileName) { - //String msg = String.format("%s: %d rows extracted, total: %d rows, %.2f MB, %.3f secs on fetching.", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()), rows - incrRows, rows, (float) buffer.position / 1024 / 1024, resultService == null ? 0f : (float) resultService.cost / 1e9); - - //String msg; - try { - - String md5 = ""; - try (InputStream is = Files.newInputStream(Paths.get(fileName))) { - //MM Fix md5 = md5Hex(is); - } - - msg += "Environment Settings:---------------------------------------------------------------------------\n" - + " \n" - + " Machine name: "+ InetAddress.getLocalHost().getHostName() + "\n" - + " Operating system: " + System.getProperty("os.name") + " " + System.getProperty("os.version") + "\n" - + " Login user: "+System.getProperty("user.name") + "\n" - + " Version number: [6.3.2.1]\n" - + " Config title: 2. PRODUCTION \n" - + " Run directory: " + this.CSVFileName + "\n" - + " File Name: " + fileName + "\n" - + " md5 hash: " + md5 + "\n" - + "" - // + "Data Sources:\n" - // + " --CRC Name: " + sfDAOFactory.getDataSourceLookup().getNiceName() + "\n" - // + " --CRC Vendor: " + sfDAOFactory.getDataSource().getConnection().getMetaData().getDatabaseProductName() + "\n" //sfDAOFactory.getDataSourceLookup().getServerType() + "\n" - // + " --CRC URL: " + sfDAOFactory.getDataSource().getConnection().getMetaData().getURL() + "\n" - // + " --CRC Username: " + sfDAOFactory.getDataSource().getConnection().getMetaData().getUserName() + "\n" - + ""; - - logWriter.write(msg + "\n"); - } catch ( Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - logWriter.flush(); - } - - public String getLog() - { - return msg; - } - - protected void writeLog(int rows) { - String msg = String.format("%s: %d rows extracted, total: %d rows, %.2f MB, %.3f secs on fetching.", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()), rows - incrRows, rows, (float) buffer.position / 1024 / 1024, resultService == null ? 0f : (float) resultService.cost / 1e9); - - logWriter.write(msg + "\n"); - - logWriter.flush(); - incrRows = rows; - } - - /** - * Writes the entire list to a CSV file. The list is assumed to be a - * String[] - * - * @param allLines a List of String[], with each String[] representing a line of - * the file. - * @param applyQuotesToAll true if all values are to be quoted. false if quotes only - * to be applied to values which contain the separator, escape, - * quote or new line characters. - */ - public int writeAll(List allLines, boolean applyQuotesToAll) throws IOException { - try (CSVWriter c = this) { - for (String[] line : allLines) { - writeNext(line, applyQuotesToAll); - } - return totalRows; - } - } - - /** - * Writes the entire list to a CSV file. The list is assumed to be a - * String[] - * - * @param allLines a List of String[], with each String[] representing a line of - * the file. - */ - public int writeAll(List allLines) throws IOException { - return writeAll(allLines, false); - } - - /** - * Writes the column names. - * - * @throws SQLException - thrown by ResultSet::getColumnNames - */ - protected void writeColumnNames() throws SQLException, IOException { - writeNext(resultService.columnNames); - } - - /** - * Writes the entire ResultSet to a CSV file. - *

    - * The caller is responsible for closing the ResultSet. - * - * @param rs the result set to write - * @param includeColumnNames true if you want column names in the output, false otherwise - * @throws java.io.IOException thrown by getColumnValue - * @throws java.sql.SQLException thrown by getColumnValue - */ - public int writeAll(java.sql.ResultSet rs, boolean includeColumnNames) throws Exception { - return writeAll(rs, includeColumnNames, false); - } - - /** - * Writes the entire ResultSet to a CSV file. - *

    - * The caller is responsible for closing the ResultSet. - * - * @param rs the Result set to write. - * @param includeColumnNames include the column names in the output. - * @param trim remove spaces from the data before writing. - * @throws java.io.IOException thrown by getColumnValue - * @throws java.sql.SQLException thrown by getColumnValue - */ - public int writeAll(java.sql.ResultSet rs, boolean includeColumnNames, boolean trim) throws Exception { - try (CSVWriter c = this; ResultSetHelperService resultService = new ResultSetHelperService(rs)) { - this.resultService = resultService; - titles = new String[resultService.columnNames.length]; - for (int i = 0; i < titles.length; i++) titles[i] = resultService.columnNames[i].trim().toUpperCase(); - if (includeColumnNames) { - writeColumnNames(); - // if (CSVFileName != null) - // createOracleCtlFileFromHeaders(CSVFileName, resultService.columnNames, resultService.columnTypes, quotechar, separator, null); - } - - if (asyncMode) { - resultService.startAsyncFetch(new RowCallback() { - @Override - public void execute(Object[] row) throws Exception { - writeNext(row); - } - }); - } else { - Object[] values; - while ((values = resultService.getColumnValues(true)) != null) writeNext(values); - } - return totalRows; - } - } - - public void flush(boolean force) throws IOException { - if (buffer.currentBytes == 0) return; - if (buffer.flush(force)) - writeLog(totalRows); - } - - /** - * Writes the next line to the file. - * - * @param nextLine a string array with each comma-separated element as a separate - * entry. - * @param applyQuotesToAll true if all values are to be quoted. false applies quotes only - * to values which contain the separator, escape, quote or new line characters. - */ - public void writeNext(Object[] nextLine, boolean applyQuotesToAll) throws IOException { - if (nextLine == null) { - return; - } - if (totalRows == 0) writeLog(0); - lineWidth = 0; - int counter = 0; - String nextElement; - Boolean stringContainsSpecialCharacters; - for (int i = 0; i < nextLine.length; i++) { - if (titles != null && remaps.containsKey(titles[i])) nextElement = remaps.get(titles[i]); - else nextElement = nextLine[i] == null ? "" : nextLine[i].toString(); - if (resultService != null && excludes.containsKey(resultService.columnNames[i].toUpperCase()) && excludes.get(resultService.columnNames[i].toUpperCase())) - continue; - if (++counter > 1) add(separator); - stringContainsSpecialCharacters = stringContainsSpecialCharacters(nextElement); - if ((applyQuotesToAll || stringContainsSpecialCharacters) && quotechar != NO_QUOTE_CHARACTER) { - add(quotechar); - } - - if (stringContainsSpecialCharacters) { - processLine(nextElement); - } else { - add(nextElement); - } - - if ((applyQuotesToAll || stringContainsSpecialCharacters) && quotechar != NO_QUOTE_CHARACTER) { - add(quotechar); - } - } - add(lineEnd); - ++totalRows; - flush(false); - } - - /** - * Writes the next line to the file. - * - * @param nextLine a string array with each comma-separated element as a separate - * entry. - */ - public void writeNext(Object[] nextLine) throws IOException { - writeNext(nextLine, false); - } - - /** - * checks to see if the line contains special characters. - * - * @param line - element of data to check for special characters. - * @return true if the line contains the quote, escape, separator, newline or return. - */ - protected boolean stringContainsSpecialCharacters(String line) { - return line.indexOf(quotechar) != -1 || line.indexOf(escapechar) != -1 || line.indexOf(separator) != -1 || line.contains(DEFAULT_LINE_END) || line.contains("\r"); - } - - /** - * Processes all the characters in a line. - * - * @param nextElement - element to process. - * @return a StringBuilder with the elements data. - */ - protected void processLine(String nextElement) throws IOException { - for (int j = 0; j < nextElement.length(); j++) { - char nextChar = nextElement.charAt(j); - if (escapechar != NO_ESCAPE_CHARACTER && (nextChar == quotechar || nextChar == escapechar)) { - add(escapechar).add(nextChar); - } else { - add(nextChar); - } - } - } - - /** - * Flush underlying stream to writer. - * - * @throws IOException if bad things happen - */ - /** - * Close the underlying stream writer flushing any buffered content. - * - * @throws IOException if bad things happen - */ - public void close() throws IOException { - flush(true); - writeLog(totalRows); - logWriter.close(); - buffer.close(); - resultService = null; - System.gc(); - System.runFinalization(); - } - - private String toHexIfInvisible(char c) { - String str = Integer.toHexString(c); - return c >= 32 ? "'" + c + "'" : "X'" + (str.length() == 1 ? "0" + str : str) + "'"; - } - - /* - public void createOracleCtlFileFromHeaders(String CSVFileName, String[] titles, String[] types, char encloser, char seperator, String rowSep) throws IOException { - File file = new File(CSVFileName); - String FileName = file.getParentFile().getAbsolutePath() + File.separator + buffer.fileName + ".ctl"; - String ColName, str; - FileWriter writer = new FileWriter(FileName); - StringBuilder b = new StringBuilder(CSVParser.READ_BUFFER_SIZE); - b.append("OPTIONS (SKIP=1, ROWS=3000, BINDSIZE=16777216, STREAMSIZE=33554432, ERRORS=1000, READSIZE=16777216, DIRECT=FALSE)\nLOAD DATA\n"); - b.append("INFILE ").append(buffer.fileName).append(".csv"); - if (rowSep != null) b.append(" \"STR '" + rowSep + "'\""); - b.append("\n"); - b.append("BADFILE ").append(buffer.fileName).append(".bad\n"); - b.append("DISCARDFILE ").append(buffer.fileName).append(".dsc\n"); - b.append("APPEND INTO TABLE ").append(buffer.fileName).append("\n"); - b.append("FIELDS CSV TERMINATED BY ").append(toHexIfInvisible(separator)); - b.append(" OPTIONALLY ENCLOSED BY ").append(toHexIfInvisible(encloser)).append(" AND ").append(toHexIfInvisible(encloser)).append(" TRAILING NULLCOLS\n(\n"); - for (int i = 0; i < titles.length; i++) { - if (excludes.containsKey(titles[i].toUpperCase()) && excludes.get(titles[i].toUpperCase())) continue; - if (i > 0) b.append(",\n"); - ColName = '"' + titles[i] + '"'; - b.append(" ").append(String.format("%-32s", ColName)); - if (types[i] == null) b.append("FILLER"); - else { - if (types[i].equalsIgnoreCase("date")) b.append("DATE \"YYYY-MM-DD HH24:MI:SS\" "); - else if (types[i].equalsIgnoreCase("timestamp")) b.append("TIMESTAMP \"YYYY-MM-DD HH24:MI:SSXFF\" "); - else if (types[i].equalsIgnoreCase("timestamptz")) - b.append("TIMESTAMP WITH TIME ZONE \"YYYY-MM-DD HH24:MI:SSXFF TZH\" "); - b.append(String.format("NULLIF %s=BLANKS", ColName)); - } - } - b.append("\n)"); - writer.write(b.toString()); - writer.flush(); - writer.close(); - } - */ - /** - * Checks to see if the there has been an error in the printstream. - * - * @return true if the print stream has encountered an error, - * either on the underlying output stream or during a format - * conversion. - */ - /** - * Sets the result service. - * - * @param resultService - the ResultSetHelper - */ - public void setResultService(ResultSetHelperService resultService) { - this.resultService = resultService; - } - - /** - * flushes the writer without throwing any exceptions. - */ -} +package edu.harvard.i2b2.crc.opencsv; + +/** + * Copyright 2005 Bytecode Pty Ltd. + *

    + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

    + * http://www.apache.org/licenses/LICENSE-2.0 + *

    + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.*; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.sql.SQLException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.List; + +import org.springframework.util.DigestUtils; + +import edu.harvard.i2b2.crc.dao.SetFinderDAOFactory; + +/** + * A very simple CSV writer released under a commercial-friendly license. + * + * @author Glen Smith + */ +public class CSVWriter implements Closeable { + public static final String RFC4180_LINE_END = "\r\n"; + /** + * The character used for escaping quotes. + */ + public static char DEFAULT_ESCAPE_CHARACTER = '"'; + /** + * The quote constant to use when you wish to suppress all quoting. + */ + public static char NO_QUOTE_CHARACTER = '\u0000'; + /** + * The escape constant to use when you wish to suppress all escaping. + */ + public static char NO_ESCAPE_CHARACTER = '\u0000'; + /** + * Default line terminator uses platform encoding. + */ + public static String DEFAULT_LINE_END = "\n"; + public static int INITIAL_BUFFER_SIZE = 8 << 20; //8 MB + protected char separator; + protected char quotechar; + protected char escapechar; + protected int lineWidth; + protected int totalRows; + protected int recordCount; + protected int incrRows; + //protected Boolean isZip = false; + protected String lineEnd; + protected PrintWriter logWriter; + protected String CSVFileName; + protected ResultSetHelperService resultService; + protected FileBuffer buffer; + protected boolean asyncMode = false; + protected HashMap excludes = new HashMap<>(); + protected HashMap remaps = new HashMap(); + protected String[] titles; + protected String msg = ""; +// protected SetFinderDAOFactory sfDAOFactory; + + /** + * Constructs CSVWriter using a comma for the separator. + * + * @param writer the writer to an underlying CSV source. + */ + public CSVWriter(Writer writer) { + this(writer, CSVParser.DEFAULT_SEPARATOR); + } + + public CSVWriter(String fileName, char separator, char quotechar, char escapechar, String lineEnd, int recordCount) throws Exception { + this(new FileWriter(fileName), separator, quotechar, escapechar, lineEnd); + this.CSVFileName = fileName; + this.recordCount = recordCount; + //this.sfDAOFactory = sfDAOFactory; + String extensionName = "csv"; + if (quotechar == '\'' && escapechar == quotechar) extensionName = "sql"; + + buffer = new FileBuffer(INITIAL_BUFFER_SIZE, fileName, extensionName); + //logWriter = new PrintWriter(buffer.file.getParentFile().getAbsolutePath() + File.separator + buffer.fileName + ".log"); + logWriter = new PrintWriter(new FileOutputStream( + new File(buffer.file.getParentFile().getAbsolutePath() + File.separator + "Log.txt"), true)); + writeLogHeader(fileName); + //logWriter = new PrintWriter(System.err); + } + +// public CSVWriter(String fileName) throws Exception { +// this(fileName, CSVParser.DEFAULT_SEPARATOR, CSVParser.DEFAULT_QUOTE_CHARACTER, DEFAULT_ESCAPE_CHARACTER, DEFAULT_LINE_END); +// } + + /** + * Constructs CSVWriter with supplied separator. + * + * @param writer the writer to an underlying CSV source. + * @param separator the delimiter to use for separating entries. + */ + public CSVWriter(Writer writer, char separator) { + this(writer, separator, CSVParser.DEFAULT_QUOTE_CHARACTER); + } + + /** + * Constructs CSVWriter with supplied separator and quote char. + * + * @param writer the writer to an underlying CSV source. + * @param separator the delimiter to use for separating entries + * @param quotechar the character to use for quoted elements + */ + public CSVWriter(Writer writer, char separator, char quotechar) { + this(writer, separator, quotechar, DEFAULT_ESCAPE_CHARACTER); + } + + /** + * Constructs CSVWriter with supplied separator and quote char. + * + * @param writer the writer to an underlying CSV source. + * @param separator the delimiter to use for separating entries + * @param quotechar the character to use for quoted elements + * @param escapechar the character to use for escaping quotechars or escapechars + */ + public CSVWriter(Writer writer, char separator, char quotechar, char escapechar) { + this(writer, separator, quotechar, escapechar, DEFAULT_LINE_END); + } + + /** + * Constructs CSVWriter with supplied separator and quote char. + * + * @param writer the writer to an underlying CSV source. + * @param separator the delimiter to use for separating entries + * @param quotechar the character to use for quoted elements + * @param lineEnd the line feed terminator to use + */ + public CSVWriter(Writer writer, char separator, char quotechar, String lineEnd) { + this(writer, separator, quotechar, DEFAULT_ESCAPE_CHARACTER, lineEnd); + } + + /** + * Constructs CSVWriter with supplied separator, quote char, escape char and line ending. + * + * @param writer the writer to an underlying CSV source. + * @param separator the delimiter to use for separating entries + * @param quotechar the character to use for quoted elements + * @param escapechar the character to use for escaping quotechars or escapechars + * @param lineEnd the line feed terminator to use + */ + public CSVWriter(Writer writer, char separator, char quotechar, char escapechar, String lineEnd) { + this.separator = separator; + this.quotechar = quotechar; + this.escapechar = escapechar; + this.lineEnd = lineEnd; + } + + public void setExclude(String columnName, boolean exclude) { + if (columnName == null) return; + excludes.put(columnName.toUpperCase().trim(), exclude); + } + + public void setRemap(String columnName, String value) { + if (columnName == null) return; + remaps.put(columnName.toUpperCase().trim(), value.trim()); + } + + public void setAsyncMode(boolean mode) { + asyncMode = mode; + } + + public void setBufferSize(int bytes) { + INITIAL_BUFFER_SIZE = bytes; + } + + protected CSVWriter add(char str) throws IOException { + buffer.write(str); + ++lineWidth; + return this; + } + + protected CSVWriter add(String str) throws IOException { + buffer.write(str); + int len = str.length(); + lineWidth += len; + return this; + } + + protected CSVWriter add(StringBuilder sbf) throws IOException { + return add(sbf.toString()); + } + + protected void writeLogHeader(String fileName) { + //String msg = String.format("%s: %d rows extracted, total: %d rows, %.2f MB, %.3f secs on fetching.", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()), rows - incrRows, rows, (float) buffer.position / 1024 / 1024, resultService == null ? 0f : (float) resultService.cost / 1e9); + + //String msg; + try { + + String md5 = ""; + try (InputStream is = Files.newInputStream(Paths.get(fileName))) { + //MM Fix md5 = md5Hex(is); + } + + msg += "Environment Settings:---------------------------------------------------------------------------\n" + + " \n" + + " Machine name: "+ InetAddress.getLocalHost().getHostName() + "\n" + + " Operating system: " + System.getProperty("os.name") + " " + System.getProperty("os.version") + "\n" + + " Login user: "+System.getProperty("user.name") + "\n" + + " Version number: [6.3.2.1]\n" + + " Config title: 2. PRODUCTION \n" + + " Run directory: " + this.CSVFileName + "\n" + + " File Name: " + fileName + "\n" + + " md5 hash: " + md5 + "\n" + + "" + // + "Data Sources:\n" + // + " --CRC Name: " + sfDAOFactory.getDataSourceLookup().getNiceName() + "\n" + // + " --CRC Vendor: " + sfDAOFactory.getDataSource().getConnection().getMetaData().getDatabaseProductName() + "\n" //sfDAOFactory.getDataSourceLookup().getServerType() + "\n" + // + " --CRC URL: " + sfDAOFactory.getDataSource().getConnection().getMetaData().getURL() + "\n" + // + " --CRC Username: " + sfDAOFactory.getDataSource().getConnection().getMetaData().getUserName() + "\n" + + ""; + + logWriter.write(msg + "\n"); + } catch ( Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + logWriter.flush(); + } + + public String getLog() + { + return msg; + } + + protected void writeLog(int rows) { + String msg = String.format("%s: %d rows extracted, total: %d rows, %.2f MB, %.3f secs on fetching.", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()), rows - incrRows, rows, (float) buffer.position / 1024 / 1024, resultService == null ? 0f : (float) resultService.cost / 1e9); + + logWriter.write(msg + "\n"); + + logWriter.flush(); + incrRows = rows; + } + + /** + * Writes the entire list to a CSV file. The list is assumed to be a + * String[] + * + * @param allLines a List of String[], with each String[] representing a line of + * the file. + * @param applyQuotesToAll true if all values are to be quoted. false if quotes only + * to be applied to values which contain the separator, escape, + * quote or new line characters. + */ + public int writeAll(List allLines, boolean applyQuotesToAll) throws IOException { + try (CSVWriter c = this) { + for (String[] line : allLines) { + writeNext(line, applyQuotesToAll); + } + return totalRows; + } + } + + /** + * Writes the entire list to a CSV file. The list is assumed to be a + * String[] + * + * @param allLines a List of String[], with each String[] representing a line of + * the file. + */ + public int writeAll(List allLines) throws IOException { + return writeAll(allLines, false); + } + + /** + * Writes the column names. + * + * @throws SQLException - thrown by ResultSet::getColumnNames + */ + protected void writeColumnNames() throws SQLException, IOException { + writeNext(resultService.columnNames); + } + + /** + * Writes the entire ResultSet to a CSV file. + *

    + * The caller is responsible for closing the ResultSet. + * + * @param rs the result set to write + * @param includeColumnNames true if you want column names in the output, false otherwise + * @throws java.io.IOException thrown by getColumnValue + * @throws java.sql.SQLException thrown by getColumnValue + */ + public int writeAll(java.sql.ResultSet rs, boolean includeColumnNames) throws Exception { + return writeAll(rs, includeColumnNames, false); + } + + /** + * Writes the entire ResultSet to a CSV file. + *

    + * The caller is responsible for closing the ResultSet. + * + * @param rs the Result set to write. + * @param includeColumnNames include the column names in the output. + * @param trim remove spaces from the data before writing. + * @throws java.io.IOException thrown by getColumnValue + * @throws java.sql.SQLException thrown by getColumnValue + */ + public int writeAll(java.sql.ResultSet rs, boolean includeColumnNames, boolean trim) throws Exception { + try (CSVWriter c = this; ResultSetHelperService resultService = new ResultSetHelperService(rs)) { + this.resultService = resultService; + titles = new String[resultService.columnNames.length]; + for (int i = 0; i < titles.length; i++) titles[i] = resultService.columnNames[i].trim().toUpperCase(); + if (includeColumnNames) { + writeColumnNames(); + // if (CSVFileName != null) + // createOracleCtlFileFromHeaders(CSVFileName, resultService.columnNames, resultService.columnTypes, quotechar, separator, null); + } + + if (asyncMode) { + resultService.startAsyncFetch(new RowCallback() { + @Override + public void execute(Object[] row) throws Exception { + writeNext(row); + } + }); + } else { + Object[] values; + while ((values = resultService.getColumnValues(true)) != null) writeNext(values); + } + return totalRows; + } + } + + public void flush(boolean force) throws IOException { + if (buffer.currentBytes == 0) return; + if (buffer.flush(force)) + writeLog(totalRows); + } + + /** + * Writes the next line to the file. + * + * @param nextLine a string array with each comma-separated element as a separate + * entry. + * @param applyQuotesToAll true if all values are to be quoted. false applies quotes only + * to values which contain the separator, escape, quote or new line characters. + */ + public void writeNext(Object[] nextLine, boolean applyQuotesToAll) throws IOException { + if (nextLine == null) { + return; + } + if (totalRows == 0) writeLog(0); + lineWidth = 0; + int counter = 0; + String nextElement; + Boolean stringContainsSpecialCharacters; + for (int i = 0; i < nextLine.length; i++) { + if (titles != null && remaps.containsKey(titles[i])) nextElement = remaps.get(titles[i]); + else nextElement = nextLine[i] == null ? "" : nextLine[i].toString(); + if (resultService != null && excludes.containsKey(resultService.columnNames[i].toUpperCase()) && excludes.get(resultService.columnNames[i].toUpperCase())) + continue; + if (++counter > 1) add(separator); + stringContainsSpecialCharacters = stringContainsSpecialCharacters(nextElement); + if ((applyQuotesToAll || stringContainsSpecialCharacters) && quotechar != NO_QUOTE_CHARACTER) { + add(quotechar); + } + + if (stringContainsSpecialCharacters) { + processLine(nextElement); + } else { + add(nextElement); + } + + if ((applyQuotesToAll || stringContainsSpecialCharacters) && quotechar != NO_QUOTE_CHARACTER) { + add(quotechar); + } + } + add(lineEnd); + ++totalRows; + flush(false); + } + + /** + * Writes the next line to the file. + * + * @param nextLine a string array with each comma-separated element as a separate + * entry. + */ + public void writeNext(Object[] nextLine) throws IOException { + writeNext(nextLine, false); + } + + /** + * checks to see if the line contains special characters. + * + * @param line - element of data to check for special characters. + * @return true if the line contains the quote, escape, separator, newline or return. + */ + protected boolean stringContainsSpecialCharacters(String line) { + return line.indexOf(quotechar) != -1 || line.indexOf(escapechar) != -1 || line.indexOf(separator) != -1 || line.contains(DEFAULT_LINE_END) || line.contains("\r"); + } + + /** + * Processes all the characters in a line. + * + * @param nextElement - element to process. + * @return a StringBuilder with the elements data. + */ + protected void processLine(String nextElement) throws IOException { + for (int j = 0; j < nextElement.length(); j++) { + char nextChar = nextElement.charAt(j); + if (escapechar != NO_ESCAPE_CHARACTER && (nextChar == quotechar || nextChar == escapechar)) { + add(escapechar).add(nextChar); + } else { + add(nextChar); + } + } + } + + /** + * Flush underlying stream to writer. + * + * @throws IOException if bad things happen + */ + /** + * Close the underlying stream writer flushing any buffered content. + * + * @throws IOException if bad things happen + */ + public void close() throws IOException { + flush(true); + writeLog(totalRows); + logWriter.close(); + buffer.close(); + resultService = null; + System.gc(); + System.runFinalization(); + } + + private String toHexIfInvisible(char c) { + String str = Integer.toHexString(c); + return c >= 32 ? "'" + c + "'" : "X'" + (str.length() == 1 ? "0" + str : str) + "'"; + } + + /* + public void createOracleCtlFileFromHeaders(String CSVFileName, String[] titles, String[] types, char encloser, char seperator, String rowSep) throws IOException { + File file = new File(CSVFileName); + String FileName = file.getParentFile().getAbsolutePath() + File.separator + buffer.fileName + ".ctl"; + String ColName, str; + FileWriter writer = new FileWriter(FileName); + StringBuilder b = new StringBuilder(CSVParser.READ_BUFFER_SIZE); + b.append("OPTIONS (SKIP=1, ROWS=3000, BINDSIZE=16777216, STREAMSIZE=33554432, ERRORS=1000, READSIZE=16777216, DIRECT=FALSE)\nLOAD DATA\n"); + b.append("INFILE ").append(buffer.fileName).append(".csv"); + if (rowSep != null) b.append(" \"STR '" + rowSep + "'\""); + b.append("\n"); + b.append("BADFILE ").append(buffer.fileName).append(".bad\n"); + b.append("DISCARDFILE ").append(buffer.fileName).append(".dsc\n"); + b.append("APPEND INTO TABLE ").append(buffer.fileName).append("\n"); + b.append("FIELDS CSV TERMINATED BY ").append(toHexIfInvisible(separator)); + b.append(" OPTIONALLY ENCLOSED BY ").append(toHexIfInvisible(encloser)).append(" AND ").append(toHexIfInvisible(encloser)).append(" TRAILING NULLCOLS\n(\n"); + for (int i = 0; i < titles.length; i++) { + if (excludes.containsKey(titles[i].toUpperCase()) && excludes.get(titles[i].toUpperCase())) continue; + if (i > 0) b.append(",\n"); + ColName = '"' + titles[i] + '"'; + b.append(" ").append(String.format("%-32s", ColName)); + if (types[i] == null) b.append("FILLER"); + else { + if (types[i].equalsIgnoreCase("date")) b.append("DATE \"YYYY-MM-DD HH24:MI:SS\" "); + else if (types[i].equalsIgnoreCase("timestamp")) b.append("TIMESTAMP \"YYYY-MM-DD HH24:MI:SSXFF\" "); + else if (types[i].equalsIgnoreCase("timestamptz")) + b.append("TIMESTAMP WITH TIME ZONE \"YYYY-MM-DD HH24:MI:SSXFF TZH\" "); + b.append(String.format("NULLIF %s=BLANKS", ColName)); + } + } + b.append("\n)"); + writer.write(b.toString()); + writer.flush(); + writer.close(); + } + */ + /** + * Checks to see if the there has been an error in the printstream. + * + * @return true if the print stream has encountered an error, + * either on the underlying output stream or during a format + * conversion. + */ + /** + * Sets the result service. + * + * @param resultService - the ResultSetHelper + */ + public void setResultService(ResultSetHelperService resultService) { + this.resultService = resultService; + } + + /** + * flushes the writer without throwing any exceptions. + */ +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/FileBuffer.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/FileBuffer.java similarity index 96% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/FileBuffer.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/FileBuffer.java index 50398b6a..a8075a64 100644 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/FileBuffer.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/FileBuffer.java @@ -1,215 +1,215 @@ -package edu.harvard.i2b2.crc.opencsv; - -//import sun.nio.ch.DirectBuffer; - -import java.io.*; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.nio.channels.Channels; -import java.nio.channels.FileChannel; -import java.nio.charset.Charset; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - - -public class FileBuffer implements Closeable { - public static int BUFFER_RESERVED_SIZE = 1 << 20; - public String fileName; - public String extName; - public File file; - public int bufferSize; - public ByteBuffer buffer; - public long position = 0; - protected RandomAccessFile out; - protected String zipType = ""; - protected FileChannel channel; - protected int currentBytes = 0; - protected Charset charset; - protected byte[] bList = new byte[BUFFER_RESERVED_SIZE]; - protected int bLen = 0; - protected String workFoler; - protected String encryptMethod; - protected String zipPassword; - - - public FileBuffer(int bufferSize, String path, String default_ext, String charset, boolean doEncrypt) throws Exception { - try { - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - - String workFolerStr = qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.workfolder"); - if (workFolerStr != null) { - workFoler = workFolerStr; - } - String encryptMethodStr = qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.zipencryptmethod"); - if (encryptMethodStr != null) { - encryptMethod = encryptMethodStr.toUpperCase(); - } - - file = new File(path); - fileName = file.getName(); - int index = fileName.lastIndexOf("."); - //Boolean isZip = false; - if (index > -1) { - extName = fileName.substring(index + 1); - fileName = fileName.substring(0, index); - - /*if (extName.equalsIgnoreCase("zip") || extName.equalsIgnoreCase("gz")) { - zipType = extName.toLowerCase(); - isZip = true; - index = fileName.lastIndexOf("."); - if (default_ext != null && index > -1 && fileName.substring(index + 1).equalsIgnoreCase(default_ext)) { - extName = default_ext; - fileName = fileName.substring(0, index); - } - } - */ - } else if (default_ext != null) { - extName = default_ext; - file = new File(path + "." + extName); - } else extName = ""; - - - out = new RandomAccessFile(file, "rw"); - channel = out.getChannel(); - this.bufferSize = bufferSize; - - // if (isZip) { - // BufferedOutputStream buff = new BufferedOutputStream(Channels.newOutputStream(channel)); - - // if (zipType.equals("zip")) { - - - - //zipfile.addStream(null, zipParameters); - - - // ZipOutputStream zip = new ZipOutputStream(buff); - // zip.putNextEntry(new ZipEntry(fileName + (extName.equals(null) ? "" : "." + default_ext))); - // zipStream = zip; - // } - //else zipStream = new GZIPOutputStream(buff, true); - - - //zipFile.addFile(new File("aFile.txt"), zipParameters); - /* - BufferedOutputStream buff = new BufferedOutputStream(Channels.newOutputStream(channel)); - if (zipType.equals("zip")) { - ZipOutputStream zip = new ZipOutputStream(buff); - zip.putNextEntry(new ZipEntry(fileName + (extName.equals(null) ? "" : "." + default_ext))); - zipStream = zip; - } else zipStream = new GZIPOutputStream(buff, true); - */ - //} else { - - zipType = null; - buffer = ByteBuffer.allocateDirect(bufferSize + BUFFER_RESERVED_SIZE); - buffer.order(ByteOrder.nativeOrder()); - //} - if (charset != null) this.charset = Charset.forName(charset); - } catch (IOException | I2B2Exception e) { - close(); - throw new I2B2DAOException("Error while init FileBuffer", e); - } - } - - public FileBuffer(int bufferSize, String path, String default_ext) throws Exception { - this(bufferSize, path, default_ext, null, false); - } - - public FileBuffer(int bufferSize, String path) throws Exception { - this(bufferSize, path, null); - } - - protected void fill(boolean force) throws IOException { - if ((!force && bLen < BUFFER_RESERVED_SIZE) || bLen == 0) return; // || channel == null || !channel.isOpen()) return; - try { - //if (zipType != null) zipStream.write(bList, 0, bLen); - //else - buffer.put(bList, 0, bLen); - currentBytes += bLen; - bLen = 0; - } catch (Exception e) { - bLen = 0; - currentBytes = 0; - close(); - throw e; - } - } - - public FileBuffer write(byte[] bytes, int startPos) throws IOException { - for (byte b : bytes) { - if (bList == null) return this; - bList[bLen++] = b; - fill(false); - } - return this; - } - - public FileBuffer write(byte[] bytes) throws IOException { - return write(bytes, 0); - } - - public FileBuffer write(char c) throws IOException { - if (bList == null) return this; - bList[bLen++] = (byte) c; - fill(false); - return this; - } - - public FileBuffer write(String str) throws IOException { - return write(str.getBytes()); - } - - public boolean flush(boolean force) throws IOException { - try { - fill(force); - if (currentBytes > 0 && (force || currentBytes >= bufferSize - 1024)) { - position += currentBytes; - if (zipType == null) { - buffer.flip(); - channel.write(buffer); - buffer.clear(); - } - currentBytes = 0; - return true; - } - return false; - } catch (IOException e) { - currentBytes = 0; - close(); - throw e; - } - } - - public boolean flush() throws IOException { - return flush(false); - } - - public void close() { - try { - flush(true); - if (channel != null && channel.isOpen()) { - //if (zipStream != null) { - //zipStream..finish(); - - // zipStream.closeEntry(); - // zipStream.flush(); - // zipStream.close(); - //} - channel.close(); - } - //MM if (buffer != null && buffer.isDirect()) ((DirectBuffer) buffer).cleaner().clean(); - if (out != null) out.close(); - channel = null; - out = null; - buffer = null; - //zipStream = null; - bList = null; - } catch (IOException e) { - //e.printStackTrace(); - } - } -} - +package edu.harvard.i2b2.crc.opencsv; + +//import sun.nio.ch.DirectBuffer; + +import java.io.*; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.channels.Channels; +import java.nio.channels.FileChannel; +import java.nio.charset.Charset; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + + +public class FileBuffer implements Closeable { + public static int BUFFER_RESERVED_SIZE = 1 << 20; + public String fileName; + public String extName; + public File file; + public int bufferSize; + public ByteBuffer buffer; + public long position = 0; + protected RandomAccessFile out; + protected String zipType = ""; + protected FileChannel channel; + protected int currentBytes = 0; + protected Charset charset; + protected byte[] bList = new byte[BUFFER_RESERVED_SIZE]; + protected int bLen = 0; + protected String workFoler; + protected String encryptMethod; + protected String zipPassword; + + + public FileBuffer(int bufferSize, String path, String default_ext, String charset, boolean doEncrypt) throws Exception { + try { + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + + String workFolerStr = qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.workfolder"); + if (workFolerStr != null) { + workFoler = workFolerStr; + } + String encryptMethodStr = qpUtil.getCRCPropertyValue("edu.harvard.i2b2.crc.exportcsv.zipencryptmethod"); + if (encryptMethodStr != null) { + encryptMethod = encryptMethodStr.toUpperCase(); + } + + file = new File(path); + fileName = file.getName(); + int index = fileName.lastIndexOf("."); + //Boolean isZip = false; + if (index > -1) { + extName = fileName.substring(index + 1); + fileName = fileName.substring(0, index); + + /*if (extName.equalsIgnoreCase("zip") || extName.equalsIgnoreCase("gz")) { + zipType = extName.toLowerCase(); + isZip = true; + index = fileName.lastIndexOf("."); + if (default_ext != null && index > -1 && fileName.substring(index + 1).equalsIgnoreCase(default_ext)) { + extName = default_ext; + fileName = fileName.substring(0, index); + } + } + */ + } else if (default_ext != null) { + extName = default_ext; + file = new File(path + "." + extName); + } else extName = ""; + + + out = new RandomAccessFile(file, "rw"); + channel = out.getChannel(); + this.bufferSize = bufferSize; + + // if (isZip) { + // BufferedOutputStream buff = new BufferedOutputStream(Channels.newOutputStream(channel)); + + // if (zipType.equals("zip")) { + + + + //zipfile.addStream(null, zipParameters); + + + // ZipOutputStream zip = new ZipOutputStream(buff); + // zip.putNextEntry(new ZipEntry(fileName + (extName.equals(null) ? "" : "." + default_ext))); + // zipStream = zip; + // } + //else zipStream = new GZIPOutputStream(buff, true); + + + //zipFile.addFile(new File("aFile.txt"), zipParameters); + /* + BufferedOutputStream buff = new BufferedOutputStream(Channels.newOutputStream(channel)); + if (zipType.equals("zip")) { + ZipOutputStream zip = new ZipOutputStream(buff); + zip.putNextEntry(new ZipEntry(fileName + (extName.equals(null) ? "" : "." + default_ext))); + zipStream = zip; + } else zipStream = new GZIPOutputStream(buff, true); + */ + //} else { + + zipType = null; + buffer = ByteBuffer.allocateDirect(bufferSize + BUFFER_RESERVED_SIZE); + buffer.order(ByteOrder.nativeOrder()); + //} + if (charset != null) this.charset = Charset.forName(charset); + } catch (IOException | I2B2Exception e) { + close(); + throw new I2B2DAOException("Error while init FileBuffer", e); + } + } + + public FileBuffer(int bufferSize, String path, String default_ext) throws Exception { + this(bufferSize, path, default_ext, null, false); + } + + public FileBuffer(int bufferSize, String path) throws Exception { + this(bufferSize, path, null); + } + + protected void fill(boolean force) throws IOException { + if ((!force && bLen < BUFFER_RESERVED_SIZE) || bLen == 0) return; // || channel == null || !channel.isOpen()) return; + try { + //if (zipType != null) zipStream.write(bList, 0, bLen); + //else + buffer.put(bList, 0, bLen); + currentBytes += bLen; + bLen = 0; + } catch (Exception e) { + bLen = 0; + currentBytes = 0; + close(); + throw e; + } + } + + public FileBuffer write(byte[] bytes, int startPos) throws IOException { + for (byte b : bytes) { + if (bList == null) return this; + bList[bLen++] = b; + fill(false); + } + return this; + } + + public FileBuffer write(byte[] bytes) throws IOException { + return write(bytes, 0); + } + + public FileBuffer write(char c) throws IOException { + if (bList == null) return this; + bList[bLen++] = (byte) c; + fill(false); + return this; + } + + public FileBuffer write(String str) throws IOException { + return write(str.getBytes()); + } + + public boolean flush(boolean force) throws IOException { + try { + fill(force); + if (currentBytes > 0 && (force || currentBytes >= bufferSize - 1024)) { + position += currentBytes; + if (zipType == null) { + buffer.flip(); + channel.write(buffer); + buffer.clear(); + } + currentBytes = 0; + return true; + } + return false; + } catch (IOException e) { + currentBytes = 0; + close(); + throw e; + } + } + + public boolean flush() throws IOException { + return flush(false); + } + + public void close() { + try { + flush(true); + if (channel != null && channel.isOpen()) { + //if (zipStream != null) { + //zipStream..finish(); + + // zipStream.closeEntry(); + // zipStream.flush(); + // zipStream.close(); + //} + channel.close(); + } + //MM if (buffer != null && buffer.isDirect()) ((DirectBuffer) buffer).cleaner().clean(); + if (out != null) out.close(); + channel = null; + out = null; + buffer = null; + //zipStream = null; + bList = null; + } catch (IOException e) { + //e.printStackTrace(); + } + } +} + diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/ResultSetHelperService.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/ResultSetHelperService.java similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/ResultSetHelperService.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/ResultSetHelperService.java index 9639af00..7970770f 100644 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/ResultSetHelperService.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/ResultSetHelperService.java @@ -1,460 +1,460 @@ -package edu.harvard.i2b2.crc.opencsv; - -import jakarta.xml.bind.DatatypeConverter; -import java.io.Closeable; -import java.io.IOException; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.sql.*; -import java.text.SimpleDateFormat; -import java.time.OffsetDateTime; -import java.time.ZonedDateTime; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.concurrent.ArrayBlockingQueue; - -/** - * Created by Tyler on 30/12/2016. - */ -public class ResultSetHelperService implements Closeable { - // note: we want to maintain compatibility with Java 5 VM's - // These types don't exist in Java 5 - public static int RESULT_FETCH_SIZE = 10000; - public static int MAX_FETCH_ROWS = -1; - public static boolean IS_TRIM = false; - public static String DEFAULT_DATE_FORMAT = "yyyy-MM-dd"; - public static String DEFAULT_TIMESTAMP_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS"; - public int columnCount; - public String[] columnNames; - public String[] columnTypes; - public String[] columnClassName; - public int[] columnTypesI; - public Object[] rowObject; - public long cost = 0; - private SimpleDateFormat dateFormat; - private SimpleDateFormat timeFormat; - private SimpleDateFormat TimeTZFormat1; - private DateTimeFormatter timeTZFormat; - private ResultSet rs; - private Object[] EOF = new Object[1]; - private ArrayBlockingQueue queue; - private boolean isFinished = false; - private static volatile boolean isAborted = false; - - /** - * Default Constructor. - */ - public ResultSetHelperService(ResultSet res, int fetchSize) throws SQLException { - long sec = System.nanoTime(); - rs = res; - rs.setFetchSize(fetchSize); - - RESULT_FETCH_SIZE = fetchSize; - isAborted = false; - try { - rs.setFetchDirection(ResultSet.FETCH_FORWARD); - } catch (Exception e) { - } - ResultSetMetaData metadata = rs.getMetaData(); - columnCount = metadata.getColumnCount(); - columnNames = new String[columnCount]; - columnTypes = new String[columnCount]; - columnClassName = new String[columnCount]; - columnTypesI = new int[columnCount]; - for (int i = 0; i < metadata.getColumnCount(); i++) { - int type = metadata.getColumnType(i + 1); - String value; - switch (type) { - case Types.JAVA_OBJECT: - value = "object"; - break; - case Types.BIT: - case Types.BOOLEAN: - value = "boolean"; - break; - case Types.DECIMAL: - case Types.DOUBLE: - case Types.FLOAT: - case Types.REAL: - case Types.NUMERIC: - value = "double"; - break; - case Types.BIGINT: - value = "long"; - break; -// case Types.BIT: - case Types.INTEGER: - case Types.TINYINT: - case Types.SMALLINT: - value = "int"; - break; - case Types.TIME: - value = "date"; - break; - case Types.DATE: - value = "date"; - break; - case Types.TIMESTAMP: - case -100: - value = "timestamp"; - break; - case -101: - case -102: - //case Types.TIME_WITH_TIMEZONE: - //case Types.TIMESTAMP_WITH_TIMEZONE: - value = "timestamptz"; - break; - case Types.BINARY: - case Types.VARBINARY: - case Types.LONGVARBINARY: - value = "raw"; - break; - case Types.CLOB: - case Types.NCLOB: - value = "clob"; - break; - case Types.BLOB: - value = "blob"; - break; - case Types.SQLXML: - value = "xml"; - break; - case Types.LONGVARCHAR: - case Types.LONGNVARCHAR: - value = "longtext"; - break; - default: - value = "string"; - } - columnTypesI[i] = type; - columnTypes[i] = value.intern(); - final String name=metadata.getColumnName(i + 1); - columnNames[i] = (name==null?"":name).intern(); - } - cost += System.nanoTime() - sec; - } - - public static void abort() { - isAborted = true; - } - - public ResultSetHelperService(ResultSet res) throws SQLException { - this(res, RESULT_FETCH_SIZE); - } - - /** - * Get all the column values from the result set. - * - * @return - String array containing all the column values. - * @throws SQLException - thrown by the result set. - * @throws IOException - thrown by the result set. - */ - public Object[] getColumnValues() throws SQLException, IOException { - return this.getColumnValues(IS_TRIM, DEFAULT_DATE_FORMAT, DEFAULT_TIMESTAMP_FORMAT); - } - - /** - * Get all the column values from the result set. - * - * @param trim - values should have white spaces trimmed. - * @return - String array containing all the column values. - * @throws SQLException - thrown by the result set. - * @throws IOException - thrown by the result set. - */ - public Object[] getColumnValues(boolean trim) throws SQLException, IOException { - return this.getColumnValues(trim, DEFAULT_DATE_FORMAT, DEFAULT_TIMESTAMP_FORMAT); - } - - /** - * Get all the column values from the result set. - * - * @param trim - values should have white spaces trimmed. - * @param dateFormatString - format String for dates. - * @param timeFormatString - format String for timestamps. - * @return - String array containing all the column values. - * @throws SQLException - thrown by the result set. - * @throws IOException - thrown by the result set. - */ - public Object[] getColumnValues(boolean trim, String dateFormatString, String timeFormatString) throws SQLException, IOException { - long sec = System.nanoTime(); - if (isAborted) { - if (rs != null) rs.close(); - throw new IOException("Processing is aborted!"); - } - if (rs == null || rs.isClosed() || !rs.next()) { - if (rs != null) rs.close(); - cost += System.nanoTime() - sec; - isFinished = true; - return null; - } - if (rowObject == null) rowObject = new Object[columnCount]; - Object o = null; - boolean isFetched; - for (int i = 0; i < columnCount; i++) { - isFetched = false; - if (columnClassName[i] == null) { - try { - o = rs.getObject(i + 1); - } catch (SQLException e) { - o = null; - } - if (o != null) columnClassName[i] = o.getClass().getName(); - isFetched = true; - } - switch (columnTypes[i]) { - case "timestamptz": - try { - o = rs.getObject(i + 1, ZonedDateTime.class); - } catch (AbstractMethodError ex2) { - o = rs.getTimestamp(i + 1); - } catch (Exception ex) { - try { - o = rs.getObject(i + 1, OffsetDateTime.class); - } catch (Exception ex1) { - o = rs.getTimestamp(i + 1); - } - } - break; - case "timestamp": - o = rs.getTimestamp(i + 1); - break; - case "raw": - o = rs.getString(i + 1); - break; - case "blob": - Blob bl = rs.getBlob(i + 1); - if (bl != null) { - o = DatatypeConverter.printHexBinary(bl.getBytes(1, (int) bl.length())); - try { - bl.free(); - } catch (Exception e) { - } - } else o = null; - break; - case "clob": - Clob c = rs.getClob(i + 1); - if (c != null) { - o = c.getSubString(1, (int) c.length()); - try { - c.free(); - } catch (Exception e) { - } - } else o = null; - break; - case "xml": - SQLXML x = rs.getSQLXML(i + 1); - try { - if (x != null) o = x.getString(); - else o = null; - } catch (Exception e) { - o = isFetched ? o : rs.getObject(i + 1); - } - break; - default: - try { - o = isFetched ? o : rs.getObject(i + 1); - } catch (SQLException e) { - o = null; - } - } - if (o != null && rs.wasNull()) o = null; - if (queue == null) rowObject[i] = getColumnValue(o, i, trim, dateFormatString, timeFormatString); - else rowObject[i] = o; - } - cost += System.nanoTime() - sec; - return rowObject; - } - - @Override - public void close() { - try { - if (rs != null && !rs.isClosed()) rs.close(); - } catch (Exception e) { - } - queue = null; - } - - /** - * changes an object to a String. - * - * @param obj - Object to format. - * @return - String value of an object or empty string if the object is null. - */ - protected String handleObject(Object obj) { - return obj == null ? "" : String.valueOf(obj); - } - - protected String handleDate(Date date, String dateFormatString) { - if (dateFormat == null) { - DEFAULT_DATE_FORMAT = dateFormatString; - dateFormat = new SimpleDateFormat(dateFormatString); - } - return date == null ? null : dateFormat.format(date); - } - - protected String handleTimestamp(Timestamp timestamp, String timestampFormatString) { - String result = null; - if (timeFormat == null) { - DEFAULT_TIMESTAMP_FORMAT = timestampFormatString; - timeFormat = new SimpleDateFormat(timestampFormatString); - } - if (timestamp != null) { - result = timeFormat.format(timestamp); - if (result.endsWith(".0")) result = result.substring(0, result.length() - 2); - else if (result.endsWith(".000")) result = result.substring(0, result.length() - 4); - } - return result; - } - - protected String handleTimestampTZ(Object timestamp, String timestampFormatString) { - if (timeTZFormat == null) { - timeTZFormat = DateTimeFormatter.ofPattern(timestampFormatString + " X"); - TimeTZFormat1 = new SimpleDateFormat(timestampFormatString + " X"); - } - if (timestamp == null) return null; - if (timestamp instanceof OffsetDateTime) return ((OffsetDateTime) timestamp).format(timeTZFormat); - else if (timestamp instanceof Timestamp) return TimeTZFormat1.format((Timestamp) timestamp); - return ((ZonedDateTime) timestamp).format(timeTZFormat); - } - - private Object getColumnValue(Object o, int colIndex, boolean trim, String dateFormatString, String timestampFormatString) throws SQLException, IOException { - if (o == null) return null; - String str; - final double d; - switch (columnTypes[colIndex]) { - case "object": - str = handleObject(o); - break; - case "boolean": - return o; - case "int": - return ((Number) o).intValue(); - case "double": - case "long": - str = o.getClass().getSimpleName(); - if (str.equals(columnTypes[colIndex])) str = Character.toUpperCase(str.charAt(0)) + str.substring(1); - columnTypes[colIndex] = str; - return getColumnValue(o, colIndex, trim, dateFormatString, timestampFormatString); - case "Double": - d = ((Number) o).doubleValue(); - return d == (long) d ? (long) d : d; - case "Float": - return Double.valueOf(o.toString()); - case "Integer": - return ((Number) o).intValue(); - case "Long": - return ((Number) o).longValue(); - case "BigInteger": - d = ((Number) o).doubleValue(); - if (o.toString().equals(new BigInteger(String.valueOf((long) d)))) return (long) d; - return o; - case "BigDecimal": - d = ((Number) o).doubleValue(); - final long l = (long) d; - if (d == l && o.toString().equals(BigInteger.valueOf(l))) return l; - if (o.toString().equals(BigDecimal.valueOf(d).toString())) return d; - return o.toString(); - case "date": - case "time": - str = handleDate((Date) o, dateFormatString); - break; - case "timestamp": - try { - str = handleTimestamp((Timestamp) o, timestampFormatString); - if (columnClassName[colIndex].startsWith("oracle.sql.DATE")) { - int pos = str.lastIndexOf('.'); - if (pos > 0) str = str.substring(0, pos - 1); - } - } catch (Exception e) { - System.out.println(o + ":" + colIndex + ":" + columnClassName[colIndex] + ":" + columnNames[colIndex]); - throw e; - } - break; - case "timestamptz": - str = handleTimestampTZ(o, timestampFormatString); - break; - case "longraw": - str = DatatypeConverter.printHexBinary((byte[]) o); - break; - default: - if (o instanceof Number) { - d = ((Number) o).doubleValue(); - return d == (long) d ? (long) d : d; - } - str = o.toString(); - } - return trim ? str.trim() : str; - } - - private volatile Exception exception = null; - - public void startAsyncFetch(final RowCallback callback, final boolean trim, final String dateFormatString, final String timeFormatString, int fetchRows) throws Exception { - if (fetchRows == -1) queue = new ArrayBlockingQueue<>(RESULT_FETCH_SIZE * 2 + 10); - else if (fetchRows > 0) { - int size = Math.max(256, Math.min(fetchRows, RESULT_FETCH_SIZE)); - rs.getStatement().setMaxRows(fetchRows); - if (size >= fetchRows / 2 && size < fetchRows) rs.setFetchSize(fetchRows / 2 + 1); - else rs.setFetchSize(size); - queue = new ArrayBlockingQueue<>(rs.getFetchSize() * 2 + 10); - } else queue = new ArrayBlockingQueue<>(256); - exception = null; - Thread t = new Thread(new Runnable() { - @Override - public void run() { - try { - while (queue != null && !isFinished && (rowObject = new Object[columnCount]) != null) - queue.put(getColumnValues() == null ? EOF : rowObject); - } catch (NullPointerException e0) { - } catch (Exception e) { - try { - if (queue != null) queue.put(EOF); - } catch (Exception e1) { - } - exception = e; - } - } - }); - t.setDaemon(true); - t.start(); - - Object[] values; - int count = 0; - while ((values = queue.take()) != EOF && (fetchRows < 0 || ++count < fetchRows)) { - for (int i = 0; i < columnCount; i++) - values[i] = getColumnValue(values[i], i, trim, dateFormatString, timeFormatString); - callback.execute(values); - } - queue = null; - t.join(); - if (exception != null) throw exception; - } - - public void startAsyncFetch(final RowCallback c, boolean trim) throws Exception { - startAsyncFetch(c, trim, DEFAULT_DATE_FORMAT, DEFAULT_TIMESTAMP_FORMAT, MAX_FETCH_ROWS); - } - - public void startAsyncFetch(final RowCallback c) throws Exception { - startAsyncFetch(c, IS_TRIM); - } - - public Object[][] fetchRowsAsync(int rows) throws Exception { - final ArrayList ary = new ArrayList(); - //ary.add(columnNames); - startAsyncFetch(row -> ary.add(row.clone()), false, DEFAULT_DATE_FORMAT, DEFAULT_TIMESTAMP_FORMAT, rows); - return ary.toArray(new Object[][]{}); - } - - public Object[][] fetchRows(int rows) throws Exception { - queue = null; - final ArrayList ary = new ArrayList(); - Object[] row; - int counter = 0; - if (rows > 0) rs.setFetchSize(rows <= 1000 ? rows : rows / 2); - while (rows < 0 || ++counter <= rows) { - row = getColumnValues(); - if (row == null) break; - ary.add(row.clone()); - } - return ary.toArray(new Object[][]{}); - } +package edu.harvard.i2b2.crc.opencsv; + +import jakarta.xml.bind.DatatypeConverter; +import java.io.Closeable; +import java.io.IOException; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.sql.*; +import java.text.SimpleDateFormat; +import java.time.OffsetDateTime; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.concurrent.ArrayBlockingQueue; + +/** + * Created by Tyler on 30/12/2016. + */ +public class ResultSetHelperService implements Closeable { + // note: we want to maintain compatibility with Java 5 VM's + // These types don't exist in Java 5 + public static int RESULT_FETCH_SIZE = 10000; + public static int MAX_FETCH_ROWS = -1; + public static boolean IS_TRIM = false; + public static String DEFAULT_DATE_FORMAT = "yyyy-MM-dd"; + public static String DEFAULT_TIMESTAMP_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS"; + public int columnCount; + public String[] columnNames; + public String[] columnTypes; + public String[] columnClassName; + public int[] columnTypesI; + public Object[] rowObject; + public long cost = 0; + private SimpleDateFormat dateFormat; + private SimpleDateFormat timeFormat; + private SimpleDateFormat TimeTZFormat1; + private DateTimeFormatter timeTZFormat; + private ResultSet rs; + private Object[] EOF = new Object[1]; + private ArrayBlockingQueue queue; + private boolean isFinished = false; + private static volatile boolean isAborted = false; + + /** + * Default Constructor. + */ + public ResultSetHelperService(ResultSet res, int fetchSize) throws SQLException { + long sec = System.nanoTime(); + rs = res; + rs.setFetchSize(fetchSize); + + RESULT_FETCH_SIZE = fetchSize; + isAborted = false; + try { + rs.setFetchDirection(ResultSet.FETCH_FORWARD); + } catch (Exception e) { + } + ResultSetMetaData metadata = rs.getMetaData(); + columnCount = metadata.getColumnCount(); + columnNames = new String[columnCount]; + columnTypes = new String[columnCount]; + columnClassName = new String[columnCount]; + columnTypesI = new int[columnCount]; + for (int i = 0; i < metadata.getColumnCount(); i++) { + int type = metadata.getColumnType(i + 1); + String value; + switch (type) { + case Types.JAVA_OBJECT: + value = "object"; + break; + case Types.BIT: + case Types.BOOLEAN: + value = "boolean"; + break; + case Types.DECIMAL: + case Types.DOUBLE: + case Types.FLOAT: + case Types.REAL: + case Types.NUMERIC: + value = "double"; + break; + case Types.BIGINT: + value = "long"; + break; +// case Types.BIT: + case Types.INTEGER: + case Types.TINYINT: + case Types.SMALLINT: + value = "int"; + break; + case Types.TIME: + value = "date"; + break; + case Types.DATE: + value = "date"; + break; + case Types.TIMESTAMP: + case -100: + value = "timestamp"; + break; + case -101: + case -102: + //case Types.TIME_WITH_TIMEZONE: + //case Types.TIMESTAMP_WITH_TIMEZONE: + value = "timestamptz"; + break; + case Types.BINARY: + case Types.VARBINARY: + case Types.LONGVARBINARY: + value = "raw"; + break; + case Types.CLOB: + case Types.NCLOB: + value = "clob"; + break; + case Types.BLOB: + value = "blob"; + break; + case Types.SQLXML: + value = "xml"; + break; + case Types.LONGVARCHAR: + case Types.LONGNVARCHAR: + value = "longtext"; + break; + default: + value = "string"; + } + columnTypesI[i] = type; + columnTypes[i] = value.intern(); + final String name=metadata.getColumnName(i + 1); + columnNames[i] = (name==null?"":name).intern(); + } + cost += System.nanoTime() - sec; + } + + public static void abort() { + isAborted = true; + } + + public ResultSetHelperService(ResultSet res) throws SQLException { + this(res, RESULT_FETCH_SIZE); + } + + /** + * Get all the column values from the result set. + * + * @return - String array containing all the column values. + * @throws SQLException - thrown by the result set. + * @throws IOException - thrown by the result set. + */ + public Object[] getColumnValues() throws SQLException, IOException { + return this.getColumnValues(IS_TRIM, DEFAULT_DATE_FORMAT, DEFAULT_TIMESTAMP_FORMAT); + } + + /** + * Get all the column values from the result set. + * + * @param trim - values should have white spaces trimmed. + * @return - String array containing all the column values. + * @throws SQLException - thrown by the result set. + * @throws IOException - thrown by the result set. + */ + public Object[] getColumnValues(boolean trim) throws SQLException, IOException { + return this.getColumnValues(trim, DEFAULT_DATE_FORMAT, DEFAULT_TIMESTAMP_FORMAT); + } + + /** + * Get all the column values from the result set. + * + * @param trim - values should have white spaces trimmed. + * @param dateFormatString - format String for dates. + * @param timeFormatString - format String for timestamps. + * @return - String array containing all the column values. + * @throws SQLException - thrown by the result set. + * @throws IOException - thrown by the result set. + */ + public Object[] getColumnValues(boolean trim, String dateFormatString, String timeFormatString) throws SQLException, IOException { + long sec = System.nanoTime(); + if (isAborted) { + if (rs != null) rs.close(); + throw new IOException("Processing is aborted!"); + } + if (rs == null || rs.isClosed() || !rs.next()) { + if (rs != null) rs.close(); + cost += System.nanoTime() - sec; + isFinished = true; + return null; + } + if (rowObject == null) rowObject = new Object[columnCount]; + Object o = null; + boolean isFetched; + for (int i = 0; i < columnCount; i++) { + isFetched = false; + if (columnClassName[i] == null) { + try { + o = rs.getObject(i + 1); + } catch (SQLException e) { + o = null; + } + if (o != null) columnClassName[i] = o.getClass().getName(); + isFetched = true; + } + switch (columnTypes[i]) { + case "timestamptz": + try { + o = rs.getObject(i + 1, ZonedDateTime.class); + } catch (AbstractMethodError ex2) { + o = rs.getTimestamp(i + 1); + } catch (Exception ex) { + try { + o = rs.getObject(i + 1, OffsetDateTime.class); + } catch (Exception ex1) { + o = rs.getTimestamp(i + 1); + } + } + break; + case "timestamp": + o = rs.getTimestamp(i + 1); + break; + case "raw": + o = rs.getString(i + 1); + break; + case "blob": + Blob bl = rs.getBlob(i + 1); + if (bl != null) { + o = DatatypeConverter.printHexBinary(bl.getBytes(1, (int) bl.length())); + try { + bl.free(); + } catch (Exception e) { + } + } else o = null; + break; + case "clob": + Clob c = rs.getClob(i + 1); + if (c != null) { + o = c.getSubString(1, (int) c.length()); + try { + c.free(); + } catch (Exception e) { + } + } else o = null; + break; + case "xml": + SQLXML x = rs.getSQLXML(i + 1); + try { + if (x != null) o = x.getString(); + else o = null; + } catch (Exception e) { + o = isFetched ? o : rs.getObject(i + 1); + } + break; + default: + try { + o = isFetched ? o : rs.getObject(i + 1); + } catch (SQLException e) { + o = null; + } + } + if (o != null && rs.wasNull()) o = null; + if (queue == null) rowObject[i] = getColumnValue(o, i, trim, dateFormatString, timeFormatString); + else rowObject[i] = o; + } + cost += System.nanoTime() - sec; + return rowObject; + } + + @Override + public void close() { + try { + if (rs != null && !rs.isClosed()) rs.close(); + } catch (Exception e) { + } + queue = null; + } + + /** + * changes an object to a String. + * + * @param obj - Object to format. + * @return - String value of an object or empty string if the object is null. + */ + protected String handleObject(Object obj) { + return obj == null ? "" : String.valueOf(obj); + } + + protected String handleDate(Date date, String dateFormatString) { + if (dateFormat == null) { + DEFAULT_DATE_FORMAT = dateFormatString; + dateFormat = new SimpleDateFormat(dateFormatString); + } + return date == null ? null : dateFormat.format(date); + } + + protected String handleTimestamp(Timestamp timestamp, String timestampFormatString) { + String result = null; + if (timeFormat == null) { + DEFAULT_TIMESTAMP_FORMAT = timestampFormatString; + timeFormat = new SimpleDateFormat(timestampFormatString); + } + if (timestamp != null) { + result = timeFormat.format(timestamp); + if (result.endsWith(".0")) result = result.substring(0, result.length() - 2); + else if (result.endsWith(".000")) result = result.substring(0, result.length() - 4); + } + return result; + } + + protected String handleTimestampTZ(Object timestamp, String timestampFormatString) { + if (timeTZFormat == null) { + timeTZFormat = DateTimeFormatter.ofPattern(timestampFormatString + " X"); + TimeTZFormat1 = new SimpleDateFormat(timestampFormatString + " X"); + } + if (timestamp == null) return null; + if (timestamp instanceof OffsetDateTime) return ((OffsetDateTime) timestamp).format(timeTZFormat); + else if (timestamp instanceof Timestamp) return TimeTZFormat1.format((Timestamp) timestamp); + return ((ZonedDateTime) timestamp).format(timeTZFormat); + } + + private Object getColumnValue(Object o, int colIndex, boolean trim, String dateFormatString, String timestampFormatString) throws SQLException, IOException { + if (o == null) return null; + String str; + final double d; + switch (columnTypes[colIndex]) { + case "object": + str = handleObject(o); + break; + case "boolean": + return o; + case "int": + return ((Number) o).intValue(); + case "double": + case "long": + str = o.getClass().getSimpleName(); + if (str.equals(columnTypes[colIndex])) str = Character.toUpperCase(str.charAt(0)) + str.substring(1); + columnTypes[colIndex] = str; + return getColumnValue(o, colIndex, trim, dateFormatString, timestampFormatString); + case "Double": + d = ((Number) o).doubleValue(); + return d == (long) d ? (long) d : d; + case "Float": + return Double.valueOf(o.toString()); + case "Integer": + return ((Number) o).intValue(); + case "Long": + return ((Number) o).longValue(); + case "BigInteger": + d = ((Number) o).doubleValue(); + if (o.toString().equals(new BigInteger(String.valueOf((long) d)))) return (long) d; + return o; + case "BigDecimal": + d = ((Number) o).doubleValue(); + final long l = (long) d; + if (d == l && o.toString().equals(BigInteger.valueOf(l))) return l; + if (o.toString().equals(BigDecimal.valueOf(d).toString())) return d; + return o.toString(); + case "date": + case "time": + str = handleDate((Date) o, dateFormatString); + break; + case "timestamp": + try { + str = handleTimestamp((Timestamp) o, timestampFormatString); + if (columnClassName[colIndex].startsWith("oracle.sql.DATE")) { + int pos = str.lastIndexOf('.'); + if (pos > 0) str = str.substring(0, pos - 1); + } + } catch (Exception e) { + System.out.println(o + ":" + colIndex + ":" + columnClassName[colIndex] + ":" + columnNames[colIndex]); + throw e; + } + break; + case "timestamptz": + str = handleTimestampTZ(o, timestampFormatString); + break; + case "longraw": + str = DatatypeConverter.printHexBinary((byte[]) o); + break; + default: + if (o instanceof Number) { + d = ((Number) o).doubleValue(); + return d == (long) d ? (long) d : d; + } + str = o.toString(); + } + return trim ? str.trim() : str; + } + + private volatile Exception exception = null; + + public void startAsyncFetch(final RowCallback callback, final boolean trim, final String dateFormatString, final String timeFormatString, int fetchRows) throws Exception { + if (fetchRows == -1) queue = new ArrayBlockingQueue<>(RESULT_FETCH_SIZE * 2 + 10); + else if (fetchRows > 0) { + int size = Math.max(256, Math.min(fetchRows, RESULT_FETCH_SIZE)); + rs.getStatement().setMaxRows(fetchRows); + if (size >= fetchRows / 2 && size < fetchRows) rs.setFetchSize(fetchRows / 2 + 1); + else rs.setFetchSize(size); + queue = new ArrayBlockingQueue<>(rs.getFetchSize() * 2 + 10); + } else queue = new ArrayBlockingQueue<>(256); + exception = null; + Thread t = new Thread(new Runnable() { + @Override + public void run() { + try { + while (queue != null && !isFinished && (rowObject = new Object[columnCount]) != null) + queue.put(getColumnValues() == null ? EOF : rowObject); + } catch (NullPointerException e0) { + } catch (Exception e) { + try { + if (queue != null) queue.put(EOF); + } catch (Exception e1) { + } + exception = e; + } + } + }); + t.setDaemon(true); + t.start(); + + Object[] values; + int count = 0; + while ((values = queue.take()) != EOF && (fetchRows < 0 || ++count < fetchRows)) { + for (int i = 0; i < columnCount; i++) + values[i] = getColumnValue(values[i], i, trim, dateFormatString, timeFormatString); + callback.execute(values); + } + queue = null; + t.join(); + if (exception != null) throw exception; + } + + public void startAsyncFetch(final RowCallback c, boolean trim) throws Exception { + startAsyncFetch(c, trim, DEFAULT_DATE_FORMAT, DEFAULT_TIMESTAMP_FORMAT, MAX_FETCH_ROWS); + } + + public void startAsyncFetch(final RowCallback c) throws Exception { + startAsyncFetch(c, IS_TRIM); + } + + public Object[][] fetchRowsAsync(int rows) throws Exception { + final ArrayList ary = new ArrayList(); + //ary.add(columnNames); + startAsyncFetch(row -> ary.add(row.clone()), false, DEFAULT_DATE_FORMAT, DEFAULT_TIMESTAMP_FORMAT, rows); + return ary.toArray(new Object[][]{}); + } + + public Object[][] fetchRows(int rows) throws Exception { + queue = null; + final ArrayList ary = new ArrayList(); + Object[] row; + int counter = 0; + if (rows > 0) rs.setFetchSize(rows <= 1000 ? rows : rows / 2); + while (rows < 0 || ++counter <= rows) { + row = getColumnValues(); + if (row == null) break; + ary.add(row.clone()); + } + return ary.toArray(new Object[][]{}); + } } \ No newline at end of file diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/RowCallback.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/RowCallback.java similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/RowCallback.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/RowCallback.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/bean/AbstractCSVToBean.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/bean/AbstractCSVToBean.java similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/bean/AbstractCSVToBean.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/bean/AbstractCSVToBean.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/bean/BeanField.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/bean/BeanField.java similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/bean/BeanField.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/bean/BeanField.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/bean/BeanToCsv.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/bean/BeanToCsv.java similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/bean/BeanToCsv.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/bean/BeanToCsv.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/bean/ColumnPositionMappingStrategy.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/bean/ColumnPositionMappingStrategy.java similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/bean/ColumnPositionMappingStrategy.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/bean/ColumnPositionMappingStrategy.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/bean/CsvBind.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/bean/CsvBind.java similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/bean/CsvBind.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/bean/CsvBind.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/bean/CsvBindByName.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/bean/CsvBindByName.java similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/bean/CsvBindByName.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/bean/CsvBindByName.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/bean/CsvBindByPosition.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/bean/CsvBindByPosition.java similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/bean/CsvBindByPosition.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/bean/CsvBindByPosition.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/bean/CsvDate.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/bean/CsvDate.java similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/bean/CsvDate.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/bean/CsvDate.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/bean/CsvToBean.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/bean/CsvToBean.java similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/bean/CsvToBean.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/bean/CsvToBean.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/bean/CsvToBeanFilter.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/bean/CsvToBeanFilter.java similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/bean/CsvToBeanFilter.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/bean/CsvToBeanFilter.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/bean/HeaderColumnNameMappingStrategy.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/bean/HeaderColumnNameMappingStrategy.java similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/bean/HeaderColumnNameMappingStrategy.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/bean/HeaderColumnNameMappingStrategy.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/bean/HeaderColumnNameTranslateMappingStrategy.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/bean/HeaderColumnNameTranslateMappingStrategy.java similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/bean/HeaderColumnNameTranslateMappingStrategy.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/bean/HeaderColumnNameTranslateMappingStrategy.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/bean/IterableCSVToBean.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/bean/IterableCSVToBean.java similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/bean/IterableCSVToBean.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/bean/IterableCSVToBean.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/bean/IterableCSVToBeanBuilder.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/bean/IterableCSVToBeanBuilder.java similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/bean/IterableCSVToBeanBuilder.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/bean/IterableCSVToBeanBuilder.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/bean/MappingStrategy.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/bean/MappingStrategy.java similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/bean/MappingStrategy.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/bean/MappingStrategy.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/bean/package-info.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/bean/package-info.java similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/bean/package-info.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/bean/package-info.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/bean/package.html b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/bean/package.html similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/bean/package.html rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/bean/package.html diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/enums/CSVReaderNullFieldIndicator.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/enums/CSVReaderNullFieldIndicator.java similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/enums/CSVReaderNullFieldIndicator.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/enums/CSVReaderNullFieldIndicator.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/enums/package-info.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/enums/package-info.java similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/enums/package-info.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/enums/package-info.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/exceptions/CsvBadConverterException.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/exceptions/CsvBadConverterException.java similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/exceptions/CsvBadConverterException.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/exceptions/CsvBadConverterException.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/exceptions/CsvConstraintViolationException.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/exceptions/CsvConstraintViolationException.java similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/exceptions/CsvConstraintViolationException.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/exceptions/CsvConstraintViolationException.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/exceptions/CsvDataTypeMismatchException.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/exceptions/CsvDataTypeMismatchException.java similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/exceptions/CsvDataTypeMismatchException.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/exceptions/CsvDataTypeMismatchException.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/exceptions/CsvException.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/exceptions/CsvException.java similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/exceptions/CsvException.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/exceptions/CsvException.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/exceptions/CsvRequiredFieldEmptyException.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/exceptions/CsvRequiredFieldEmptyException.java similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/exceptions/CsvRequiredFieldEmptyException.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/exceptions/CsvRequiredFieldEmptyException.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/exceptions/package-info.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/exceptions/package-info.java similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/exceptions/package-info.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/exceptions/package-info.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/stream/reader/LineReader.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/stream/reader/LineReader.java similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/stream/reader/LineReader.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/stream/reader/LineReader.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/stream/reader/package-info.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/stream/reader/package-info.java similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/stream/reader/package-info.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/stream/reader/package-info.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/util/NumberUtils.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/util/NumberUtils.java similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/util/NumberUtils.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/util/NumberUtils.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/util/StringUtils.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/util/StringUtils.java similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/opencsv/util/StringUtils.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/opencsv/util/StringUtils.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/quartz/AnalysisJobStarter.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/quartz/AnalysisJobStarter.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/quartz/AnalysisJobStarter.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/quartz/AnalysisJobStarter.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/quartz/AnalysisQueue.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/quartz/AnalysisQueue.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/quartz/AnalysisQueue.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/quartz/AnalysisQueue.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/quartz/CronJob.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/quartz/CronJob.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/quartz/CronJob.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/quartz/CronJob.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/quartz/FirstJob.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/quartz/FirstJob.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/quartz/FirstJob.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/quartz/FirstJob.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/quartz/Job1Listener.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/quartz/Job1Listener.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/quartz/Job1Listener.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/quartz/Job1Listener.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/quartz/JobParamName.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/quartz/JobParamName.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/quartz/JobParamName.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/quartz/JobParamName.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/quartz/QuartzFactory.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/quartz/QuartzFactory.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/quartz/QuartzFactory.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/quartz/QuartzFactory.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/quartz/StartJobHandler.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/quartz/StartJobHandler.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/quartz/StartJobHandler.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/quartz/StartJobHandler.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/role/AuthrizationHelper.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/role/AuthrizationHelper.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/role/AuthrizationHelper.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/role/AuthrizationHelper.java index 797283ea..806f40f8 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/role/AuthrizationHelper.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/role/AuthrizationHelper.java @@ -1,119 +1,119 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.role; - -import java.util.List; - - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.crc.dao.IDAOFactory; -import edu.harvard.i2b2.crc.ejb.role.PriviledgeLocal; -import edu.harvard.i2b2.crc.util.CacheUtil; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - -public class AuthrizationHelper { - - protected final Log log = LogFactory.getLog(AuthrizationHelper.class); - private String domainId = null, projectId = null, userId = null; - private IDAOFactory daoFactory = null; - - public AuthrizationHelper(String domainId, String projectId, String userId, - IDAOFactory daoFactory) { - this.domainId = domainId; - this.projectId = projectId; - this.userId = userId; - this.daoFactory = daoFactory; - } - - /** - * - * @param protectionLabel - * @param roles - * @throws I2B2Exception - */ - public void checkRoleForProtectionLabel(String protectionLabel, - List roles) throws I2B2Exception { - PriviledgeLocal privilegeLocal = QueryProcessorUtil.getInstance() - .getPriviledgeLocal(); - privilegeLocal.checkPriviledge(daoFactory, protectionLabel, roles); - } - - /** - * - * @param protectionLabel - * @param roles - * @throws I2B2Exception - */ - public void checkRoleForPluginId(String pluginId, List roles) - throws I2B2Exception { - PriviledgeLocal privilegeLocal = QueryProcessorUtil.getInstance() - .getPriviledgeLocal(); - privilegeLocal.checkPluginPrivilege(daoFactory, pluginId, roles); - } - - /** - * Read the user role from the cache and check for protection lable with the - * priviledge table - * - * @param protectionLabel - * @throws I2B2Exception - */ - public void checkRoleForProtectionLabel(String protectionLabel) - throws I2B2Exception { - List roles = getRolesFromCache(); - checkRoleForProtectionLabel(protectionLabel, roles); - - } - - public void checkRoleForPluginId(String pluginId) throws I2B2Exception { - List roles = getRolesFromCache(); - checkRoleForPluginId(pluginId, roles); - } - - public List getRolesFromCache() throws I2B2Exception { - //TODO removed cache - /* - Cache cache = null; - try { - cache = CacheUtil.getCache(); - } catch (MalformedObjectNameException e) { - log.error("Unable to get cache object " - + StackTraceUtil.getStackTrace(e)); - throw new I2B2Exception("Unable to get cache object " - + StackTraceUtil.getStackTrace(e)); - } catch (NullPointerException e) { - log.error("Unable to get cache object " - + StackTraceUtil.getStackTrace(e)); - throw new I2B2Exception("Unable to get cache object " - + StackTraceUtil.getStackTrace(e)); - } - */ - // domainId + "/" + projectId + "/" + userId; - String rolePath = domainId + "/" + projectId + "/" + userId; - //List roles = (List) cache.getRoot().get(rolePath); - List roles = (List) CacheUtil.get(rolePath); - - log.debug("Roles from get " + rolePath); - if (roles != null) { - log.debug("Roles from size " + roles.size()); - } else { - log.error( "Could not find the Roles from the cache for [" - + rolePath + "]"); - throw new I2B2Exception( - "Could not find the Roles from the cache for [" + rolePath - + "]"); - } - return roles; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.role; + +import java.util.List; + + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.crc.dao.IDAOFactory; +import edu.harvard.i2b2.crc.ejb.role.PriviledgeLocal; +import edu.harvard.i2b2.crc.util.CacheUtil; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + +public class AuthrizationHelper { + + protected final Log log = LogFactory.getLog(AuthrizationHelper.class); + private String domainId = null, projectId = null, userId = null; + private IDAOFactory daoFactory = null; + + public AuthrizationHelper(String domainId, String projectId, String userId, + IDAOFactory daoFactory) { + this.domainId = domainId; + this.projectId = projectId; + this.userId = userId; + this.daoFactory = daoFactory; + } + + /** + * + * @param protectionLabel + * @param roles + * @throws I2B2Exception + */ + public void checkRoleForProtectionLabel(String protectionLabel, + List roles) throws I2B2Exception { + PriviledgeLocal privilegeLocal = QueryProcessorUtil.getInstance() + .getPriviledgeLocal(); + privilegeLocal.checkPriviledge(daoFactory, protectionLabel, roles); + } + + /** + * + * @param protectionLabel + * @param roles + * @throws I2B2Exception + */ + public void checkRoleForPluginId(String pluginId, List roles) + throws I2B2Exception { + PriviledgeLocal privilegeLocal = QueryProcessorUtil.getInstance() + .getPriviledgeLocal(); + privilegeLocal.checkPluginPrivilege(daoFactory, pluginId, roles); + } + + /** + * Read the user role from the cache and check for protection lable with the + * priviledge table + * + * @param protectionLabel + * @throws I2B2Exception + */ + public void checkRoleForProtectionLabel(String protectionLabel) + throws I2B2Exception { + List roles = getRolesFromCache(); + checkRoleForProtectionLabel(protectionLabel, roles); + + } + + public void checkRoleForPluginId(String pluginId) throws I2B2Exception { + List roles = getRolesFromCache(); + checkRoleForPluginId(pluginId, roles); + } + + public List getRolesFromCache() throws I2B2Exception { + //TODO removed cache + /* + Cache cache = null; + try { + cache = CacheUtil.getCache(); + } catch (MalformedObjectNameException e) { + log.error("Unable to get cache object " + + StackTraceUtil.getStackTrace(e)); + throw new I2B2Exception("Unable to get cache object " + + StackTraceUtil.getStackTrace(e)); + } catch (NullPointerException e) { + log.error("Unable to get cache object " + + StackTraceUtil.getStackTrace(e)); + throw new I2B2Exception("Unable to get cache object " + + StackTraceUtil.getStackTrace(e)); + } + */ + // domainId + "/" + projectId + "/" + userId; + String rolePath = domainId + "/" + projectId + "/" + userId; + //List roles = (List) cache.getRoot().get(rolePath); + List roles = (List) CacheUtil.get(rolePath); + + log.debug("Roles from get " + rolePath); + if (roles != null) { + log.debug("Roles from size " + roles.size()); + } else { + log.error( "Could not find the Roles from the cache for [" + + rolePath + "]"); + throw new I2B2Exception( + "Could not find the Roles from the cache for [" + rolePath + + "]"); + } + return roles; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/util/AnalysisPropertyUtil.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/util/AnalysisPropertyUtil.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/util/AnalysisPropertyUtil.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/util/AnalysisPropertyUtil.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/util/Base64.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/util/Base64.java similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/util/Base64.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/util/Base64.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/util/CacheUtil.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/util/CacheUtil.java old mode 100755 new mode 100644 similarity index 82% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/util/CacheUtil.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/util/CacheUtil.java index eecf0f57..553a4a5d --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/util/CacheUtil.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/util/CacheUtil.java @@ -10,18 +10,6 @@ import java.util.Hashtable; -/* -import javax.management.MBeanServer; -import javax.management.MBeanServerInvocationHandler; -import javax.management.MalformedObjectNameException; -import javax.management.ObjectName; - -import org.jboss.cache.Cache; -import org.jboss.cache.jmx.CacheJmxWrapperMBean; -import org.jboss.mx.util.MBeanServerLocator; -*/ - - public class CacheUtil { static Hashtable rootNode = new Hashtable(); diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/util/ContainsUtil.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/util/ContainsUtil.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/util/ContainsUtil.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/util/ContainsUtil.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/util/I2B2RequestMessageHelper.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/util/I2B2RequestMessageHelper.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/util/I2B2RequestMessageHelper.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/util/I2B2RequestMessageHelper.java index 8dd96196..2c0bed29 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/util/I2B2RequestMessageHelper.java +++ b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/util/I2B2RequestMessageHelper.java @@ -1,201 +1,201 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.util; - -import java.io.StringWriter; - -import jakarta.xml.bind.JAXBElement; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.AnalysisDefinitionRequestType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.AnalysisDefinitionType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.AnalysisResultOptionListType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.AnalysisResultOptionType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionRequestType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultOutputOptionListType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultOutputOptionType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.UserType; -import edu.harvard.i2b2.crc.delegate.getnameinfo.GetNameInfoRequestDelegate; - -public class I2B2RequestMessageHelper { - - private static Log log = LogFactory.getLog(I2B2RequestMessageHelper.class); - protected static Log logesapi = LogFactory.getLog(I2B2RequestMessageHelper.class); - - String requestXml = null; - JAXBUnWrapHelper unWrapHelper = null; - JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); - JAXBElement jaxbElement = null; - RequestMessageType requestMessageType = null; - - public I2B2RequestMessageHelper(String requestXml) throws I2B2Exception { - this.requestXml = requestXml; - unWrapHelper = new JAXBUnWrapHelper(); - try { - jaxbElement = jaxbUtil.unMashallFromString(requestXml); - - if (jaxbElement == null) { - throw new I2B2Exception( - "null value in after unmarshalling request string "); - } - requestMessageType = (RequestMessageType) jaxbElement - .getValue(); - } catch (JAXBUtilException jaxbUtilEx) { - logesapi.error("Error processing request xml [" + requestXml + "]", - jaxbUtilEx); - throw new I2B2Exception(jaxbUtilEx.getMessage()); - } - } - - public RequestMessageType getI2B2RequestMessageType() { - return this.requestMessageType; - } - - private BodyType getBodyType() { - return requestMessageType.getMessageBody(); - } - - public QueryDefinitionType getQueryDefinition() throws JAXBUtilException { - BodyType bodyType = getBodyType(); - - QueryDefinitionRequestType queryDefReqType = (QueryDefinitionRequestType) unWrapHelper - .getObjectByClass(bodyType.getAny(), - QueryDefinitionRequestType.class); - - QueryDefinitionType queryDef = null; - if (queryDefReqType != null) { - queryDef = queryDefReqType.getQueryDefinition(); - } - return queryDef; - } - - public AnalysisDefinitionType getAnalysisDefinition() - throws JAXBUtilException { - BodyType bodyType = getBodyType(); - - AnalysisDefinitionRequestType analysisDefReqType = (AnalysisDefinitionRequestType) unWrapHelper - .getObjectByClass(bodyType.getAny(), - AnalysisDefinitionRequestType.class); - AnalysisDefinitionType analysisDef = null; - if (analysisDefReqType != null) { - analysisDef = analysisDefReqType.getAnalysisDefinition(); - } - return analysisDef; - - } - - public UserType getUserType() { - - RequestMessageType requestMessageType = (RequestMessageType) jaxbElement - .getValue(); - - UserType userType = new UserType(); - userType.setLogin(requestMessageType.getMessageHeader().getSecurity() - .getUsername()); - userType.setGroup(requestMessageType.getMessageHeader().getSecurity() - .getDomain()); - - return userType; - } - - public SecurityType getSecurityType() { - RequestMessageType requestMessageType = (RequestMessageType) jaxbElement - .getValue(); - return requestMessageType.getMessageHeader().getSecurity(); - } - - public String getProjectId() { - String projectId = null; - RequestMessageType requestMessageType = (RequestMessageType) jaxbElement - .getValue(); - projectId = requestMessageType.getMessageHeader().getProjectId(); - return projectId; - } - - public long getTimeout() { - RequestMessageType requestMessageType = (RequestMessageType) jaxbElement - .getValue(); - - RequestHeaderType requestHeader = requestMessageType.getRequestHeader(); - long timeOut = 1; - if (requestHeader != null && requestHeader.getResultWaittimeMs() > -1) { - timeOut = requestHeader.getResultWaittimeMs(); - } - return timeOut; - - } - - public String getVersion() { - RequestMessageType requestMessageType = (RequestMessageType) jaxbElement - .getValue(); - String version = ""; - if (requestMessageType.getMessageHeader().getSendingApplication() != null) { - version = requestMessageType.getMessageHeader().getSendingApplication().getApplicationVersion(); - if (version == null) { - version = ""; - } else { - version = version.trim(); - } - } - - return version; - } - - public static String getAnalysisDefinitionXml( - AnalysisDefinitionType analysisDefinition) throws JAXBUtilException { - StringWriter queryDefWriter = new StringWriter(); - edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); - JAXBUtil jaxbUtil = CRCJAXBUtil.getAnalysisDefJAXBUtil(); - jaxbUtil.marshaller(of.createAnalysisDefinition(analysisDefinition), - queryDefWriter); - - return queryDefWriter.toString(); - } - - public static AnalysisDefinitionType getAnalysisDefinitionFromXml( - String defXml) throws JAXBUtilException { - JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); - JAXBElement analysisDef = jaxbUtil.unMashallFromString(defXml); - return (AnalysisDefinitionType) analysisDef.getValue(); - } - - public static ResultOutputOptionListType buildResultOptionListFromAnalysisResultList( - AnalysisResultOptionListType analysisResultListType) { - ResultOutputOptionListType resultOutputOptionList = new ResultOutputOptionListType(); - if (analysisResultListType == null) { - return resultOutputOptionList; - } - for (AnalysisResultOptionType analysisResultType : analysisResultListType - .getResultOutput()) { - ResultOutputOptionType resultOuputOptionType = new ResultOutputOptionType(); - resultOuputOptionType.setName(analysisResultType.getName()); - resultOuputOptionType.setFullName(analysisResultType.getFullName()); - resultOuputOptionType.setDisplayType(analysisResultType - .getDisplayType()); - resultOuputOptionType.setPriorityIndex(analysisResultType - .getPriorityIndex()); - resultOutputOptionList.getResultOutput().add(resultOuputOptionType); - } - return resultOutputOptionList; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.util; + +import java.io.StringWriter; + +import jakarta.xml.bind.JAXBElement; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.SecurityType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.AnalysisDefinitionRequestType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.AnalysisDefinitionType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.AnalysisResultOptionListType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.AnalysisResultOptionType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionRequestType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultOutputOptionListType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultOutputOptionType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.UserType; +import edu.harvard.i2b2.crc.delegate.getnameinfo.GetNameInfoRequestDelegate; + +public class I2B2RequestMessageHelper { + + private static Log log = LogFactory.getLog(I2B2RequestMessageHelper.class); + protected static Log logesapi = LogFactory.getLog(I2B2RequestMessageHelper.class); + + String requestXml = null; + JAXBUnWrapHelper unWrapHelper = null; + JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); + JAXBElement jaxbElement = null; + RequestMessageType requestMessageType = null; + + public I2B2RequestMessageHelper(String requestXml) throws I2B2Exception { + this.requestXml = requestXml; + unWrapHelper = new JAXBUnWrapHelper(); + try { + jaxbElement = jaxbUtil.unMashallFromString(requestXml); + + if (jaxbElement == null) { + throw new I2B2Exception( + "null value in after unmarshalling request string "); + } + requestMessageType = (RequestMessageType) jaxbElement + .getValue(); + } catch (JAXBUtilException jaxbUtilEx) { + logesapi.error("Error processing request xml [" + requestXml + "]", + jaxbUtilEx); + throw new I2B2Exception(jaxbUtilEx.getMessage()); + } + } + + public RequestMessageType getI2B2RequestMessageType() { + return this.requestMessageType; + } + + private BodyType getBodyType() { + return requestMessageType.getMessageBody(); + } + + public QueryDefinitionType getQueryDefinition() throws JAXBUtilException { + BodyType bodyType = getBodyType(); + + QueryDefinitionRequestType queryDefReqType = (QueryDefinitionRequestType) unWrapHelper + .getObjectByClass(bodyType.getAny(), + QueryDefinitionRequestType.class); + + QueryDefinitionType queryDef = null; + if (queryDefReqType != null) { + queryDef = queryDefReqType.getQueryDefinition(); + } + return queryDef; + } + + public AnalysisDefinitionType getAnalysisDefinition() + throws JAXBUtilException { + BodyType bodyType = getBodyType(); + + AnalysisDefinitionRequestType analysisDefReqType = (AnalysisDefinitionRequestType) unWrapHelper + .getObjectByClass(bodyType.getAny(), + AnalysisDefinitionRequestType.class); + AnalysisDefinitionType analysisDef = null; + if (analysisDefReqType != null) { + analysisDef = analysisDefReqType.getAnalysisDefinition(); + } + return analysisDef; + + } + + public UserType getUserType() { + + RequestMessageType requestMessageType = (RequestMessageType) jaxbElement + .getValue(); + + UserType userType = new UserType(); + userType.setLogin(requestMessageType.getMessageHeader().getSecurity() + .getUsername()); + userType.setGroup(requestMessageType.getMessageHeader().getSecurity() + .getDomain()); + + return userType; + } + + public SecurityType getSecurityType() { + RequestMessageType requestMessageType = (RequestMessageType) jaxbElement + .getValue(); + return requestMessageType.getMessageHeader().getSecurity(); + } + + public String getProjectId() { + String projectId = null; + RequestMessageType requestMessageType = (RequestMessageType) jaxbElement + .getValue(); + projectId = requestMessageType.getMessageHeader().getProjectId(); + return projectId; + } + + public long getTimeout() { + RequestMessageType requestMessageType = (RequestMessageType) jaxbElement + .getValue(); + + RequestHeaderType requestHeader = requestMessageType.getRequestHeader(); + long timeOut = 1; + if (requestHeader != null && requestHeader.getResultWaittimeMs() > -1) { + timeOut = requestHeader.getResultWaittimeMs(); + } + return timeOut; + + } + + public String getVersion() { + RequestMessageType requestMessageType = (RequestMessageType) jaxbElement + .getValue(); + String version = ""; + if (requestMessageType.getMessageHeader().getSendingApplication() != null) { + version = requestMessageType.getMessageHeader().getSendingApplication().getApplicationVersion(); + if (version == null) { + version = ""; + } else { + version = version.trim(); + } + } + + return version; + } + + public static String getAnalysisDefinitionXml( + AnalysisDefinitionType analysisDefinition) throws JAXBUtilException { + StringWriter queryDefWriter = new StringWriter(); + edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory(); + JAXBUtil jaxbUtil = CRCJAXBUtil.getAnalysisDefJAXBUtil(); + jaxbUtil.marshaller(of.createAnalysisDefinition(analysisDefinition), + queryDefWriter); + + return queryDefWriter.toString(); + } + + public static AnalysisDefinitionType getAnalysisDefinitionFromXml( + String defXml) throws JAXBUtilException { + JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); + JAXBElement analysisDef = jaxbUtil.unMashallFromString(defXml); + return (AnalysisDefinitionType) analysisDef.getValue(); + } + + public static ResultOutputOptionListType buildResultOptionListFromAnalysisResultList( + AnalysisResultOptionListType analysisResultListType) { + ResultOutputOptionListType resultOutputOptionList = new ResultOutputOptionListType(); + if (analysisResultListType == null) { + return resultOutputOptionList; + } + for (AnalysisResultOptionType analysisResultType : analysisResultListType + .getResultOutput()) { + ResultOutputOptionType resultOuputOptionType = new ResultOutputOptionType(); + resultOuputOptionType.setName(analysisResultType.getName()); + resultOuputOptionType.setFullName(analysisResultType.getFullName()); + resultOuputOptionType.setDisplayType(analysisResultType + .getDisplayType()); + resultOuputOptionType.setPriorityIndex(analysisResultType + .getPriorityIndex()); + resultOutputOptionList.getResultOutput().add(resultOuputOptionType); + } + return resultOutputOptionList; + } +} diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/util/I2B2ResponseMessageHelper.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/util/I2B2ResponseMessageHelper.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/util/I2B2ResponseMessageHelper.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/util/I2B2ResponseMessageHelper.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/util/ItemKeyUtil.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/util/ItemKeyUtil.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/util/ItemKeyUtil.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/util/ItemKeyUtil.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/util/JAXBConstant.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/util/JAXBConstant.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/util/JAXBConstant.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/util/JAXBConstant.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/util/LogTimingUtil.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/util/LogTimingUtil.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/util/LogTimingUtil.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/util/LogTimingUtil.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/util/PMServiceAccountUtil.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/util/PMServiceAccountUtil.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/util/PMServiceAccountUtil.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/util/PMServiceAccountUtil.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/util/ParamUtil.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/util/ParamUtil.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/util/ParamUtil.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/util/ParamUtil.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/util/QueryProcessorUtil.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/util/QueryProcessorUtil.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/util/QueryProcessorUtil.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/util/QueryProcessorUtil.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/util/RegExUtil.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/util/RegExUtil.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/util/RegExUtil.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/util/RegExUtil.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/util/SqlClauseUtil.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/util/SqlClauseUtil.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/util/SqlClauseUtil.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/util/SqlClauseUtil.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/util/StringUtil.java b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/util/StringUtil.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/util/StringUtil.java rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/crc/util/StringUtil.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/querytool/axis2/META-INF/QueryProcessor.wsdl b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/querytool/axis2/META-INF/QueryProcessor.wsdl old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/querytool/axis2/META-INF/QueryProcessor.wsdl rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/querytool/axis2/META-INF/QueryProcessor.wsdl diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/querytool/axis2/META-INF/services.xml b/edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/querytool/axis2/META-INF/services.xml old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/querytool/axis2/META-INF/services.xml rename to edu.harvard.i2b2.crc/src/main/java/edu/harvard/i2b2/querytool/axis2/META-INF/services.xml diff --git a/edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/dao/pdo/input/OutPutOptionHelperTest.java b/edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/dao/pdo/input/OutPutOptionHelperTest.java deleted file mode 100755 index aa66c72a..00000000 --- a/edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/dao/pdo/input/OutPutOptionHelperTest.java +++ /dev/null @@ -1,31 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.pdo.input; - -import org.junit.Test; - -import edu.harvard.i2b2.crc.datavo.pdo.query.OutputOptionListType; -import edu.harvard.i2b2.crc.datavo.pdo.query.OutputOptionSelectType; -import edu.harvard.i2b2.crc.datavo.pdo.query.OutputOptionType; - -public class OutPutOptionHelperTest { - - @Test - public void testA() { - OutputOptionListType opOptionList = new OutputOptionListType(); - OutputOptionType ooType = new OutputOptionType(); - - ooType.setSelect(OutputOptionSelectType.USING_INPUT_LIST); - opOptionList.setPatientSet(ooType); - OutputOptionFactRelatedHelper OutputOptionFactRelatedHelper = new OutputOptionFactRelatedHelper( - opOptionList); - System.out.println(" " + OutputOptionFactRelatedHelper.isFactRelated()); - - } -} diff --git a/edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/dao/pdo/input/PagingHandlerTest.java b/edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/dao/pdo/input/PagingHandlerTest.java deleted file mode 100755 index b28315fc..00000000 --- a/edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/dao/pdo/input/PagingHandlerTest.java +++ /dev/null @@ -1,135 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.pdo.input; - -import static org.junit.Assert.assertNotNull; - -import java.util.HashMap; - -import javax.sql.DataSource; - -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; - -import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.crc.axis2.CRCAxisAbstract; -import edu.harvard.i2b2.crc.dao.DAOFactoryHelper; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.crc.datavo.pdo.query.GetPDOFromInputListRequestType; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - -public class PagingHandlerTest { - private static String testFileDir = null; - private static GetPDOFromInputListRequestType pdoRequestType = null; - private static DataSourceLookup dataSourceLookup = null; - private static String pageMethod = null; - - @BeforeClass - public static void setUp() throws Exception { - testFileDir = System.getProperty("testfiledir"); - System.out.println("test file dir " + testFileDir); - - if (!((testFileDir != null) && (testFileDir.trim().length() > 0))) { - throw new Exception( - "please provide test file directory info -Dtestfiledir"); - } - - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - // dataSourceLookup = (DataSourceLookup) qpUtil.getSpringBeanFactory() - // .getBean("TestDataSourceLookup"); - - String filename = testFileDir - + "/edu.harvard.i2b2.crc.dao.pdo/pdo_query.xml"; - - // String filename = testFileDir + "/mikeincrement.xml"; - String xml = CRCAxisAbstract.getQueryString(filename); - JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); - RequestMessageType reqMsgType = (RequestMessageType) jaxbUtil - .unMashallFromString(xml).getValue(); - System.out.println(reqMsgType.getMessageHeader().getMessageControlId()); - JAXBUnWrapHelper unWrapHelper = new JAXBUnWrapHelper(); - pdoRequestType = (GetPDOFromInputListRequestType) unWrapHelper - .getObjectByClass(reqMsgType.getMessageBody().getAny(), - GetPDOFromInputListRequestType.class); - - IFactRelatedQueryHandler pdoQueryHandler = null; - if (dataSourceLookup.getServerType().equalsIgnoreCase( - DAOFactoryHelper.ORACLE)) { - pdoQueryHandler = new FactRelatedQueryHandler(dataSourceLookup, - pdoRequestType.getInputList(), pdoRequestType - .getFilterList(), pdoRequestType.getOutputOption()); - } - pageMethod = qpUtil.getPagingMethod(); - - } - - @Ignore - @Test - public void buildSql() throws Exception { - DataSource dataSource = null; - DAOFactoryHelper daoHelper = new DAOFactoryHelper(dataSourceLookup, - dataSource); - assertNotNull(dataSourceLookup); - - PagingHandler ph = new PagingHandler(daoHelper, pdoRequestType - .getInputList(), pdoRequestType.getFilterList(), pageMethod); - - System.out.println("Total for the panel " + ph.getTotal(10)); - - } - - @Ignore - @Test - public void buildMinSql() throws Exception { - - QueryProcessorUtil queryProcessorUtil = QueryProcessorUtil - .getInstance(); - DataSource dataSource = queryProcessorUtil - .getSpringDataSource("java:CRC_ASTHMADS_ORACLE"); - DAOFactoryHelper daoHelper = new DAOFactoryHelper(dataSourceLookup, - dataSource); - assertNotNull(dataSourceLookup); - - PagingHandler ph = new PagingHandler(daoHelper, pdoRequestType - .getInputList(), pdoRequestType.getFilterList(), pageMethod); - - HashMap map = ph.getMinPatientIndexAndTheTotal(10); - System.out.println("min index" + map.get("MIN_INDEX")); - System.out.println("min index total " + map.get("MIN_INDEX_TOTAL")); - // System.out.println("Min index " + - // ph.getMinPatientIndexAndTheTotal(10)); - - } - - @Test - public void calculateMaxPageInputList() throws Exception { - - QueryProcessorUtil queryProcessorUtil = QueryProcessorUtil - .getInstance(); - DataSource dataSource = queryProcessorUtil - .getSpringDataSource("java:CRC_ASTHMADS_ORACLE"); - - DAOFactoryHelper daoHelper = new DAOFactoryHelper(dataSourceLookup, - dataSource); - - assertNotNull(dataSourceLookup); - assertNotNull(dataSource); - - PagingHandler ph = new PagingHandler(daoHelper, pdoRequestType - .getInputList(), pdoRequestType.getFilterList(), pageMethod); - HashMap map = ph.calculateMaxPageInputList(); - System.out.println("Patients list size of [" - + map.get(PagingHandler.MAX_INPUT_LIST) + "] fits the page "); - - } -} diff --git a/edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/axis2/CRCAxisAbstract.java b/edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/axis2/CRCAxisAbstract.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/axis2/CRCAxisAbstract.java rename to edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/axis2/CRCAxisAbstract.java diff --git a/edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/axis2/CRCDBlookupTests.java b/edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/axis2/CRCDBlookupTests.java similarity index 97% rename from edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/axis2/CRCDBlookupTests.java rename to edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/axis2/CRCDBlookupTests.java index 08c5f07d..1802ee8b 100644 --- a/edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/axis2/CRCDBlookupTests.java +++ b/edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/axis2/CRCDBlookupTests.java @@ -1,246 +1,246 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * S.W.Chan - */ -package edu.harvard.i2b2.crc.axis2; - -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; -import jakarta.xml.bind.JAXBElement; -import junit.framework.JUnit4TestAdapter; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import org.junit.BeforeClass; -import org.junit.Test; -import org.apache.axiom.om.OMElement; - -/** - * Class to test different CRC DBLookup request's - * @author S.W. Chan - */ -public class CRCDBlookupTests extends CRCAxisAbstract { - private static String testFileDir = ""; - private static String crcTargetEPR = "http://localhost:9090/i2b2/services/QueryToolService/"; - private static String getAllDBlookups = crcTargetEPR + "getAllDblookups"; - private static String setDBlookup = crcTargetEPR + "setDblookup"; - private static String getDBlookup = crcTargetEPR + "getDblookup"; - private static String deleteDBlookup = crcTargetEPR + "deleteDblookup"; - - @BeforeClass - public static void setUp() throws Exception { - testFileDir = "testfiles/DBlookup"; //System.getProperty("testfiledir"); - System.out.println("test file dir " + testFileDir); - if (testFileDir == null || 0 == testFileDir.trim().length()) { - throw new Exception("please provide test file directory info -Dtestfiledir"); - } - } - - public static junit.framework.Test suite() { - return new JUnit4TestAdapter(CRCDBlookupTests.class); - } - - @Test - public void GetAllDBlookups_admin() throws Exception { //swc20160722 - String filename = testFileDir + "/getAllDBlookups_admin.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(getAllDBlookups).sendReceive(requestElement); - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - String msg = r.getResponseHeader().getResultStatus().getStatus().getType(); - assertEquals("DONE", msg); - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void GetAllDBlookups_non_admin() throws Exception { //swc20160722 - String filename = testFileDir + "/getAllDBlookups_non_admin.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(getAllDBlookups).sendReceive(requestElement); - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - String msg = r.getResponseHeader().getResultStatus().getStatus().getType(); - assertEquals("ERROR", msg); - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void SetDBlookup_admin() throws Exception { //swc20160722 - String filename = testFileDir + "/setDBlookup_admin.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setDBlookup).sendReceive(requestElement); - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - String msg = r.getResponseHeader().getResultStatus().getStatus().getType(); - assertEquals("DONE", msg); - DeleteDBlookup_admin(); //clean it up (in case this gets run after the DeleteDBlookup_admin() - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void SetDBlookup_non_admin() throws Exception { //swc20160722 - String filename = testFileDir + "/setDBlookup_non_admin.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setDBlookup).sendReceive(requestElement); - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - String msg = r.getResponseHeader().getResultStatus().getStatus().getType(); - assertEquals("ERROR", msg); - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void GetDBlookup_admin() throws Exception { //swc20160722 - String filename = testFileDir + "/getDBlookup_admin.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(getDBlookup).sendReceive(requestElement); - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - String msg = r.getResponseHeader().getResultStatus().getStatus().getType(); - assertEquals("DONE", msg); - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void GetDBlookup_schema_admin() throws Exception { //swc20160722 - String filename = testFileDir + "/getDBlookup_schema_admin.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(getDBlookup).sendReceive(requestElement); - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - String msg = r.getResponseHeader().getResultStatus().getStatus().getType(); - assertEquals("DONE", msg); - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void GetDBlookup_non_admin() throws Exception { //swc20160722 - String filename = testFileDir + "/getDBlookup_non_admin.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(getDBlookup).sendReceive(requestElement); - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - String msg = r.getResponseHeader().getResultStatus().getStatus().getType(); - assertEquals("ERROR", msg); - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void DeleteDBlookup_admin() throws Exception { //swc20160722 - String filename = testFileDir + "/deleteDBlookup_admin.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(deleteDBlookup).sendReceive(requestElement); - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - String msg = r.getResponseHeader().getResultStatus().getStatus().getType(); - assertEquals("DONE", msg); - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void DeleteDBlookup_non_admin() throws Exception { //swc20160722 - String filename = testFileDir + "/deleteDBlookup_non_admin.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(deleteDBlookup).sendReceive(requestElement); - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - String msg = r.getResponseHeader().getResultStatus().getStatus().getType(); - assertEquals("ERROR", msg); - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void DeleteDBlookup_nonexist_admin() throws Exception { //swc20160722 - String filename = testFileDir + "/deleteDBlookup_nonexist_admin.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(deleteDBlookup).sendReceive(requestElement); - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - StatusType st = r.getResponseHeader().getResultStatus().getStatus(); - assertEquals("DONE", st.getType()); - if (st.getValue().contains("no dblookup row was deleted (could be due to no target row found)!")) { - assertTrue(true); - } else { - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void DeleteDBlookup_missingAttrib_admin() throws Exception { //swc20160722 - String filename = testFileDir + "/deleteDBlookup_missing_attrib_admin.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(deleteDBlookup).sendReceive(requestElement); - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - String msg = r.getResponseHeader().getResultStatus().getStatus().getType(); - assertEquals("ERROR", msg); - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * S.W.Chan + */ +package edu.harvard.i2b2.crc.axis2; + +import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; +import jakarta.xml.bind.JAXBElement; +import junit.framework.JUnit4TestAdapter; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import org.junit.BeforeClass; +import org.junit.Test; +import org.apache.axiom.om.OMElement; + +/** + * Class to test different CRC DBLookup request's + * @author S.W. Chan + */ +public class CRCDBlookupTests extends CRCAxisAbstract { + private static String testFileDir = ""; + private static String crcTargetEPR = "http://localhost:9090/i2b2/services/QueryToolService/"; + private static String getAllDBlookups = crcTargetEPR + "getAllDblookups"; + private static String setDBlookup = crcTargetEPR + "setDblookup"; + private static String getDBlookup = crcTargetEPR + "getDblookup"; + private static String deleteDBlookup = crcTargetEPR + "deleteDblookup"; + + @BeforeClass + public static void setUp() throws Exception { + testFileDir = "testfiles/DBlookup"; //System.getProperty("testfiledir"); + System.out.println("test file dir " + testFileDir); + if (testFileDir == null || 0 == testFileDir.trim().length()) { + throw new Exception("please provide test file directory info -Dtestfiledir"); + } + } + + public static junit.framework.Test suite() { + return new JUnit4TestAdapter(CRCDBlookupTests.class); + } + + @Test + public void GetAllDBlookups_admin() throws Exception { //swc20160722 + String filename = testFileDir + "/getAllDBlookups_admin.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(getAllDBlookups).sendReceive(requestElement); + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + String msg = r.getResponseHeader().getResultStatus().getStatus().getType(); + assertEquals("DONE", msg); + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void GetAllDBlookups_non_admin() throws Exception { //swc20160722 + String filename = testFileDir + "/getAllDBlookups_non_admin.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(getAllDBlookups).sendReceive(requestElement); + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + String msg = r.getResponseHeader().getResultStatus().getStatus().getType(); + assertEquals("ERROR", msg); + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void SetDBlookup_admin() throws Exception { //swc20160722 + String filename = testFileDir + "/setDBlookup_admin.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setDBlookup).sendReceive(requestElement); + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + String msg = r.getResponseHeader().getResultStatus().getStatus().getType(); + assertEquals("DONE", msg); + DeleteDBlookup_admin(); //clean it up (in case this gets run after the DeleteDBlookup_admin() + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void SetDBlookup_non_admin() throws Exception { //swc20160722 + String filename = testFileDir + "/setDBlookup_non_admin.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setDBlookup).sendReceive(requestElement); + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + String msg = r.getResponseHeader().getResultStatus().getStatus().getType(); + assertEquals("ERROR", msg); + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void GetDBlookup_admin() throws Exception { //swc20160722 + String filename = testFileDir + "/getDBlookup_admin.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(getDBlookup).sendReceive(requestElement); + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + String msg = r.getResponseHeader().getResultStatus().getStatus().getType(); + assertEquals("DONE", msg); + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void GetDBlookup_schema_admin() throws Exception { //swc20160722 + String filename = testFileDir + "/getDBlookup_schema_admin.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(getDBlookup).sendReceive(requestElement); + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + String msg = r.getResponseHeader().getResultStatus().getStatus().getType(); + assertEquals("DONE", msg); + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void GetDBlookup_non_admin() throws Exception { //swc20160722 + String filename = testFileDir + "/getDBlookup_non_admin.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(getDBlookup).sendReceive(requestElement); + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + String msg = r.getResponseHeader().getResultStatus().getStatus().getType(); + assertEquals("ERROR", msg); + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void DeleteDBlookup_admin() throws Exception { //swc20160722 + String filename = testFileDir + "/deleteDBlookup_admin.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(deleteDBlookup).sendReceive(requestElement); + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + String msg = r.getResponseHeader().getResultStatus().getStatus().getType(); + assertEquals("DONE", msg); + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void DeleteDBlookup_non_admin() throws Exception { //swc20160722 + String filename = testFileDir + "/deleteDBlookup_non_admin.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(deleteDBlookup).sendReceive(requestElement); + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + String msg = r.getResponseHeader().getResultStatus().getStatus().getType(); + assertEquals("ERROR", msg); + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void DeleteDBlookup_nonexist_admin() throws Exception { //swc20160722 + String filename = testFileDir + "/deleteDBlookup_nonexist_admin.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(deleteDBlookup).sendReceive(requestElement); + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + StatusType st = r.getResponseHeader().getResultStatus().getStatus(); + assertEquals("DONE", st.getType()); + if (st.getValue().contains("no dblookup row was deleted (could be due to no target row found)!")) { + assertTrue(true); + } else { + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void DeleteDBlookup_missingAttrib_admin() throws Exception { //swc20160722 + String filename = testFileDir + "/deleteDBlookup_missing_attrib_admin.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(deleteDBlookup).sendReceive(requestElement); + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + String msg = r.getResponseHeader().getResultStatus().getStatus().getType(); + assertEquals("ERROR", msg); + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + +} diff --git a/edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/axis2/CRCLoaderTest.java b/edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/axis2/CRCLoaderTest.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/axis2/CRCLoaderTest.java rename to edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/axis2/CRCLoaderTest.java index b80e03eb..bb444e94 --- a/edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/axis2/CRCLoaderTest.java +++ b/edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/axis2/CRCLoaderTest.java @@ -1,317 +1,317 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.axis2; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.DataInputStream; -import java.io.FileInputStream; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.StringReader; -import java.util.ArrayList; - -import org.apache.axiom.attachments.Attachments; -import org.apache.axiom.om.OMAbstractFactory; -import org.apache.axiom.om.OMElement; -import org.apache.axiom.soap.SOAP11Constants; -import org.apache.axiom.soap.SOAPEnvelope; -import org.apache.axiom.soap.SOAPFactory; - -import org.apache.axis2.AxisFault; -import org.apache.axis2.Constants; -import org.apache.axis2.addressing.EndpointReference; -import org.apache.axis2.client.OperationClient; -import org.apache.axis2.client.Options; -import org.apache.axis2.client.ServiceClient; -import org.apache.axis2.context.MessageContext; - -import java.io.BufferedReader; -import java.io.DataInputStream; -import java.io.FileInputStream; -import java.io.InputStreamReader; -import java.io.StringReader; - -import jakarta.xml.bind.JAXBElement; -import javax.xml.stream.FactoryConfigurationError; -import javax.xml.stream.XMLInputFactory; -import javax.xml.stream.XMLStreamReader; - -import junit.framework.JUnit4TestAdapter; - -import org.apache.axiom.om.OMElement; -import org.junit.BeforeClass; -import org.junit.Test; - -import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterInstanceResultResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory; -import edu.harvard.i2b2.crc.datavo.setfinder.query.PsmQryHeaderType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryInstanceType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryMasterType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryResultInstanceType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.RequestType; - - - -/** - * Class to test different CRC Loader request's - * @author Mike Mendis - */ -public class CRCLoaderTest extends CRCAxisAbstract { - - private static QueryMasterType queryMaster = null; - private static QueryInstanceType queryInstance = null; - private static String masterInstanceResult = null; - private static String testFileDir = null; - private static EndpointReference frUrl = null; - - - private static String requestXml = ""; - - @BeforeClass - public static void setUp() throws Exception { - - String host = (System.getProperty("testhost") == null ? "http://127.0.0.1:9090/i2b2/services" : System.getProperty("testhost") ) ; - frUrl = - new EndpointReference(host + "/FRService"); -; - - testFileDir = "testfiles"; //System.getProperty("testfiledir"); - System.out.println("test file dir " + testFileDir); - - if (!((testFileDir != null) && (testFileDir.trim().length() > 0))) { - throw new Exception( - "please provide test file directory info -Dtestfiledir"); - } - - } - - - - - - public static junit.framework.Test suite() { - return new JUnit4TestAdapter(CRCLoaderTest.class); - } - - public static RequestHeaderType generateRequestHeader() { - RequestHeaderType reqHeaderType = new RequestHeaderType(); - reqHeaderType.setResultWaittimeMs(90000); - return reqHeaderType; - } - - public static String getRequestString() throws Exception { - StringBuffer queryStr = new StringBuffer(); - DataInputStream dataStream = new DataInputStream(new FileInputStream( - requestXml)); - BufferedReader reader = new BufferedReader(new InputStreamReader( - dataStream)); - String singleLine = null; - - while ((singleLine = reader.readLine()) != null) { - queryStr.append(singleLine + "\n"); - } - -// System.out.println("queryStr " + queryStr); - - return queryStr.toString(); - } - - - - @Test - public void UploadPatientSet() throws Exception { - requestXml = testFileDir + "/import_ptMap.xml"; - try { - - - - - OMElement getRequestElmt = edu.harvard.i2b2.common.util.axis2.ServiceClient.getPayLoad(getRequestString()); - Options options = new Options(); - options.setTo(frUrl); - - options.setTransportInProtocol(Constants.TRANSPORT_HTTP); -// options.setProperty(Constants.Configuration.ENABLE_REST, Constants.VALUE_TRUE); - options.setProperty(Constants.Configuration.ENABLE_SWA, Constants.VALUE_TRUE); - options.setSoapVersionURI(SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI); - options.setTimeOutInMilliSeconds(50000); - options.setAction("urn:sendfileRequest"); - ServiceClient sender = new ServiceClient(); - sender.setOptions(options); - - OperationClient mepClient = sender.createClient(ServiceClient.ANON_OUT_IN_OP); - - SOAPFactory sfac = OMAbstractFactory.getSOAP11Factory(); - SOAPEnvelope env = sfac.getDefaultEnvelope(); - env.getBody().addChild(getRequestElmt); - MessageContext mc = new MessageContext(); - mc.setEnvelope(env); - - // FileDataSource fileDataSource = new FileDataSource( testFileDir + "/ptMap_8-15-2012.csv"); - // DataHandler dataHandler = new DataHandler(fileDataSource); - // mc.addAttachment(fileDataSource.getName(), dataHandler); - - // fileDataSource = new FileDataSource(testFileDir + "ptMap_8-15-2012.csv"); - // dataHandler = new DataHandler(fileDataSource); - // mc.addAttachment(fileDataSource.getName(), dataHandler); - - Attachments attachments = mc.getAttachmentMap(); - System.out.println("# of attachments: " + attachments.getAllContentIDs().length); - - mepClient.addMessageContext(mc); - mepClient.execute(true); - - - MessageContext inMsgtCtx = mepClient.getMessageContext("In"); - SOAPEnvelope responseEnv = inMsgtCtx.getEnvelope(); - - OMElement soapResponse = responseEnv.getBody().getFirstElement(); - - OMElement soapResult = soapResponse.getFirstElement(); - - String i2b2Response = soapResponse.toString(); - - - - System.out.println(i2b2Response); - - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(i2b2Response); - - - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - masterInstanceResult = (String)helper.getObjectByClass(r.getMessageBody().getAny(),String.class); - assertNotNull(masterInstanceResult); - - - - - - - - - - - - - - - - - /* - - - - - - - DataInputStream dataStream = new DataInputStream(new FileInputStream( - filename)); - OMElement requestElement = convertStringToOMElement(dataStream); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - String queryMasterId = masterInstanceResult.getQueryMaster().getQueryMasterId(); - - // First Query In Query - String requestString = getQueryString(testFileDir + "/QIQ_4Q_MALE_[28].xml"); - requestString = requestString.replace("masterid:431", "masterid:"+queryMasterId); - - requestElement = convertStringToOMElement(requestString); - responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - r = (ResponseMessageType)responseJaxb.getValue(); - helper = new JAXBUnWrapHelper(); - - masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 28); - else - assertTrue(false); - } - - - // Second Query In Query - requestString = getQueryString(testFileDir + "/QIQ_4Q_FEMALE_[10].xml"); - requestString = requestString.replace("masterid:431", "masterid:"+queryMasterId); - - requestElement = convertStringToOMElement(requestString); - responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - r = (ResponseMessageType)responseJaxb.getValue(); - helper = new JAXBUnWrapHelper(); - - masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 10); - else - assertTrue(false); - } - - */ - - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - public static RequestMessageType buildRequestMessage(PsmQryHeaderType requestHeaderType, RequestType requestType) { - //create body type - BodyType bodyType = new BodyType(); - ObjectFactory of = new ObjectFactory(); - bodyType.getAny().add(of.createPsmheader(requestHeaderType)); - bodyType.getAny().add(of.createRequest(requestType)); - RequestMessageType requestMessageType = new RequestMessageType(); - requestMessageType.setMessageHeader(generateMessageHeader()); - requestMessageType.setMessageBody(bodyType); - requestMessageType.setRequestHeader(generateRequestHeader()); - return requestMessageType; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.axis2; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.DataInputStream; +import java.io.FileInputStream; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.StringReader; +import java.util.ArrayList; + +import org.apache.axiom.attachments.Attachments; +import org.apache.axiom.om.OMAbstractFactory; +import org.apache.axiom.om.OMElement; +import org.apache.axiom.soap.SOAP11Constants; +import org.apache.axiom.soap.SOAPEnvelope; +import org.apache.axiom.soap.SOAPFactory; + +import org.apache.axis2.AxisFault; +import org.apache.axis2.Constants; +import org.apache.axis2.addressing.EndpointReference; +import org.apache.axis2.client.OperationClient; +import org.apache.axis2.client.Options; +import org.apache.axis2.client.ServiceClient; +import org.apache.axis2.context.MessageContext; + +import java.io.BufferedReader; +import java.io.DataInputStream; +import java.io.FileInputStream; +import java.io.InputStreamReader; +import java.io.StringReader; + +import jakarta.xml.bind.JAXBElement; +import javax.xml.stream.FactoryConfigurationError; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamReader; + +import junit.framework.JUnit4TestAdapter; + +import org.apache.axiom.om.OMElement; +import org.junit.BeforeClass; +import org.junit.Test; + +import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; +import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterInstanceResultResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory; +import edu.harvard.i2b2.crc.datavo.setfinder.query.PsmQryHeaderType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryInstanceType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryMasterType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryResultInstanceType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.RequestType; + + + +/** + * Class to test different CRC Loader request's + * @author Mike Mendis + */ +public class CRCLoaderTest extends CRCAxisAbstract { + + private static QueryMasterType queryMaster = null; + private static QueryInstanceType queryInstance = null; + private static String masterInstanceResult = null; + private static String testFileDir = null; + private static EndpointReference frUrl = null; + + + private static String requestXml = ""; + + @BeforeClass + public static void setUp() throws Exception { + + String host = (System.getProperty("testhost") == null ? "http://127.0.0.1:9090/i2b2/services" : System.getProperty("testhost") ) ; + frUrl = + new EndpointReference(host + "/FRService"); +; + + testFileDir = "testfiles"; //System.getProperty("testfiledir"); + System.out.println("test file dir " + testFileDir); + + if (!((testFileDir != null) && (testFileDir.trim().length() > 0))) { + throw new Exception( + "please provide test file directory info -Dtestfiledir"); + } + + } + + + + + + public static junit.framework.Test suite() { + return new JUnit4TestAdapter(CRCLoaderTest.class); + } + + public static RequestHeaderType generateRequestHeader() { + RequestHeaderType reqHeaderType = new RequestHeaderType(); + reqHeaderType.setResultWaittimeMs(90000); + return reqHeaderType; + } + + public static String getRequestString() throws Exception { + StringBuffer queryStr = new StringBuffer(); + DataInputStream dataStream = new DataInputStream(new FileInputStream( + requestXml)); + BufferedReader reader = new BufferedReader(new InputStreamReader( + dataStream)); + String singleLine = null; + + while ((singleLine = reader.readLine()) != null) { + queryStr.append(singleLine + "\n"); + } + +// System.out.println("queryStr " + queryStr); + + return queryStr.toString(); + } + + + + @Test + public void UploadPatientSet() throws Exception { + requestXml = testFileDir + "/import_ptMap.xml"; + try { + + + + + OMElement getRequestElmt = edu.harvard.i2b2.common.util.axis2.ServiceClient.getPayLoad(getRequestString()); + Options options = new Options(); + options.setTo(frUrl); + + options.setTransportInProtocol(Constants.TRANSPORT_HTTP); +// options.setProperty(Constants.Configuration.ENABLE_REST, Constants.VALUE_TRUE); + options.setProperty(Constants.Configuration.ENABLE_SWA, Constants.VALUE_TRUE); + options.setSoapVersionURI(SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI); + options.setTimeOutInMilliSeconds(50000); + options.setAction("urn:sendfileRequest"); + ServiceClient sender = new ServiceClient(); + sender.setOptions(options); + + OperationClient mepClient = sender.createClient(ServiceClient.ANON_OUT_IN_OP); + + SOAPFactory sfac = OMAbstractFactory.getSOAP11Factory(); + SOAPEnvelope env = sfac.getDefaultEnvelope(); + env.getBody().addChild(getRequestElmt); + MessageContext mc = new MessageContext(); + mc.setEnvelope(env); + + // FileDataSource fileDataSource = new FileDataSource( testFileDir + "/ptMap_8-15-2012.csv"); + // DataHandler dataHandler = new DataHandler(fileDataSource); + // mc.addAttachment(fileDataSource.getName(), dataHandler); + + // fileDataSource = new FileDataSource(testFileDir + "ptMap_8-15-2012.csv"); + // dataHandler = new DataHandler(fileDataSource); + // mc.addAttachment(fileDataSource.getName(), dataHandler); + + Attachments attachments = mc.getAttachmentMap(); + System.out.println("# of attachments: " + attachments.getAllContentIDs().length); + + mepClient.addMessageContext(mc); + mepClient.execute(true); + + + MessageContext inMsgtCtx = mepClient.getMessageContext("In"); + SOAPEnvelope responseEnv = inMsgtCtx.getEnvelope(); + + OMElement soapResponse = responseEnv.getBody().getFirstElement(); + + OMElement soapResult = soapResponse.getFirstElement(); + + String i2b2Response = soapResponse.toString(); + + + + System.out.println(i2b2Response); + + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(i2b2Response); + + + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + masterInstanceResult = (String)helper.getObjectByClass(r.getMessageBody().getAny(),String.class); + assertNotNull(masterInstanceResult); + + + + + + + + + + + + + + + + + /* + + + + + + + DataInputStream dataStream = new DataInputStream(new FileInputStream( + filename)); + OMElement requestElement = convertStringToOMElement(dataStream); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + String queryMasterId = masterInstanceResult.getQueryMaster().getQueryMasterId(); + + // First Query In Query + String requestString = getQueryString(testFileDir + "/QIQ_4Q_MALE_[28].xml"); + requestString = requestString.replace("masterid:431", "masterid:"+queryMasterId); + + requestElement = convertStringToOMElement(requestString); + responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + r = (ResponseMessageType)responseJaxb.getValue(); + helper = new JAXBUnWrapHelper(); + + masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 28); + else + assertTrue(false); + } + + + // Second Query In Query + requestString = getQueryString(testFileDir + "/QIQ_4Q_FEMALE_[10].xml"); + requestString = requestString.replace("masterid:431", "masterid:"+queryMasterId); + + requestElement = convertStringToOMElement(requestString); + responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + r = (ResponseMessageType)responseJaxb.getValue(); + helper = new JAXBUnWrapHelper(); + + masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 10); + else + assertTrue(false); + } + + */ + + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + public static RequestMessageType buildRequestMessage(PsmQryHeaderType requestHeaderType, RequestType requestType) { + //create body type + BodyType bodyType = new BodyType(); + ObjectFactory of = new ObjectFactory(); + bodyType.getAny().add(of.createPsmheader(requestHeaderType)); + bodyType.getAny().add(of.createRequest(requestType)); + RequestMessageType requestMessageType = new RequestMessageType(); + requestMessageType.setMessageHeader(generateMessageHeader()); + requestMessageType.setMessageBody(bodyType); + requestMessageType.setRequestHeader(generateRequestHeader()); + return requestMessageType; + } + +} diff --git a/edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/axis2/CRCQueryClientTest.java b/edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/axis2/CRCQueryClientTest.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/axis2/CRCQueryClientTest.java rename to edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/axis2/CRCQueryClientTest.java index b8df3e9f..6d021389 --- a/edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/axis2/CRCQueryClientTest.java +++ b/edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/axis2/CRCQueryClientTest.java @@ -1,168 +1,168 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.axis2; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import jakarta.xml.bind.JAXBElement; - -import junit.framework.JUnit4TestAdapter; - -import org.apache.axiom.om.OMElement; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; - -import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.crc.datavo.ontology.ConceptsType; -import edu.harvard.i2b2.crc.datavo.pdo.query.PatientDataResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterInstanceResultResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryResultInstanceType; - -/** - * This class test pdo/timeline requests. - * - * @author rk903 - */ -public class CRCQueryClientTest { - private static String setfinderUrl = "http://localhost:8080/i2b2/rest/QueryToolService/request"; - private static String pdoUrl = "http://localhost:8080/i2b2/rest/QueryToolService/pdorequest"; - private static String ontologyUrl = "http://localhost:8080/i2b2/rest/OntologyService/getTermInfo"; - private static String testFileDir = null; - - @BeforeClass - public static void init() throws Exception { - testFileDir = System.getProperty("testfiledir"); - System.out.println("test file dir " + testFileDir); - - if (!((testFileDir != null) && (testFileDir.trim().length() > 0))) { - throw new Exception( - "please provide test file directory info -Dtestfiledir"); - } - } - - @Test - // (timeout = 180000) - public void testSetfinderMessage() throws Exception { - // read test file and store query master; - String filename = testFileDir + "/setfinder_query.xml"; - - String requestString = PdoQueryTest.getQueryString(filename); - System.out.println("test file dir " + testFileDir); - - OMElement requestElement = PdoQueryTest - .convertStringToOMElement(requestString); - OMElement responseElement = PdoQueryTest.getServiceClient(setfinderUrl) - .sendReceive(requestElement); - - System.out.println(responseElement); - // read test file and store query instance ; - // unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil() - .unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType) responseJaxb.getValue(); - assertEquals("checking i2b2 message status 'DONE'", "DONE", r - .getResponseHeader().getResultStatus().getStatus().getType()); - - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType) helper - .getObjectByClass(r.getMessageBody().getAny(), - MasterInstanceResultResponseType.class); - QueryResultInstanceType queryResultInstance = masterInstanceResult - .getQueryResultInstance().get(0); - assertNotNull(queryResultInstance); - } - - @Ignore - @Test - public void testPDOMessage() throws Exception { - String filename = testFileDir + "/pdo_query1.xml"; - - String requestString = PdoQueryTest.getQueryString(filename); - System.out.println("test file dir " + testFileDir); - - OMElement requestElement = PdoQueryTest - .convertStringToOMElement(requestString); - OMElement responseElement = PdoQueryTest.getServiceClient(pdoUrl) - .sendReceive(requestElement); - - System.out.println(responseElement); - - // read test file and store query instance ; - // unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil() - .unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType) responseJaxb.getValue(); - assertEquals("checking i2b2 message status 'DONE'", "DONE", r - .getResponseHeader().getResultStatus().getStatus().getType()); - - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - PatientDataResponseType patientDataResponseType = (PatientDataResponseType) helper - .getObjectByClass(r.getMessageBody().getAny(), - PatientDataResponseType.class); - assertTrue("checking patient set size > 0 ", patientDataResponseType - .getPatientData().getPatientSet().getPatient().size() > 0); - assertTrue("checking observation set size > 0", patientDataResponseType - .getPatientData().getObservationSet().get(0).getObservation() - .size() > 0); - } - - @Ignore - @Test - public void testOntologyGetChildren() throws Exception { - - String filename = testFileDir + "/get_term_info_query.xml"; - String requestString = PdoQueryTest.getQueryString(filename); - System.out.println("test file dir " + testFileDir); - - OMElement requestElement = PdoQueryTest - .convertStringToOMElement(requestString); - OMElement responseElement = PdoQueryTest.getServiceClient(ontologyUrl) - .sendReceive(requestElement); - System.out.println(responseElement); - String responseString = responseElement.toString(); - - System.out.println(responseString); - // unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil() - .unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType) responseJaxb.getValue(); - - for (Object object : r.getMessageBody().getAny()) { - - System.out.println("name " + object.getClass().getName()); - } - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - ConceptsType conceptsType = (ConceptsType) helper.getObjectByClass(r - .getMessageBody().getAny(), ConceptsType.class); - - assertNotNull("checking concepts for not null", conceptsType); - // helper.getObjectByClass(r.getMessageBody().getAny(), requestClass) - assertTrue("checking patient set size > 0 ", conceptsType.getConcept() - .size() > 0); - assertNotNull("checking concept for not null", conceptsType - .getConcept().get(0)); - - } - - public static junit.framework.Test suite() { - return new JUnit4TestAdapter(CRCQueryClientTest.class); - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.axis2; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import jakarta.xml.bind.JAXBElement; + +import junit.framework.JUnit4TestAdapter; + +import org.apache.axiom.om.OMElement; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; + +import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; +import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.crc.datavo.ontology.ConceptsType; +import edu.harvard.i2b2.crc.datavo.pdo.query.PatientDataResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterInstanceResultResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryResultInstanceType; + +/** + * This class test pdo/timeline requests. + * + * @author rk903 + */ +public class CRCQueryClientTest { + private static String setfinderUrl = "http://localhost:8080/i2b2/rest/QueryToolService/request"; + private static String pdoUrl = "http://localhost:8080/i2b2/rest/QueryToolService/pdorequest"; + private static String ontologyUrl = "http://localhost:8080/i2b2/rest/OntologyService/getTermInfo"; + private static String testFileDir = null; + + @BeforeClass + public static void init() throws Exception { + testFileDir = System.getProperty("testfiledir"); + System.out.println("test file dir " + testFileDir); + + if (!((testFileDir != null) && (testFileDir.trim().length() > 0))) { + throw new Exception( + "please provide test file directory info -Dtestfiledir"); + } + } + + @Test + // (timeout = 180000) + public void testSetfinderMessage() throws Exception { + // read test file and store query master; + String filename = testFileDir + "/setfinder_query.xml"; + + String requestString = PdoQueryTest.getQueryString(filename); + System.out.println("test file dir " + testFileDir); + + OMElement requestElement = PdoQueryTest + .convertStringToOMElement(requestString); + OMElement responseElement = PdoQueryTest.getServiceClient(setfinderUrl) + .sendReceive(requestElement); + + System.out.println(responseElement); + // read test file and store query instance ; + // unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil() + .unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType) responseJaxb.getValue(); + assertEquals("checking i2b2 message status 'DONE'", "DONE", r + .getResponseHeader().getResultStatus().getStatus().getType()); + + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType) helper + .getObjectByClass(r.getMessageBody().getAny(), + MasterInstanceResultResponseType.class); + QueryResultInstanceType queryResultInstance = masterInstanceResult + .getQueryResultInstance().get(0); + assertNotNull(queryResultInstance); + } + + @Ignore + @Test + public void testPDOMessage() throws Exception { + String filename = testFileDir + "/pdo_query1.xml"; + + String requestString = PdoQueryTest.getQueryString(filename); + System.out.println("test file dir " + testFileDir); + + OMElement requestElement = PdoQueryTest + .convertStringToOMElement(requestString); + OMElement responseElement = PdoQueryTest.getServiceClient(pdoUrl) + .sendReceive(requestElement); + + System.out.println(responseElement); + + // read test file and store query instance ; + // unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil() + .unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType) responseJaxb.getValue(); + assertEquals("checking i2b2 message status 'DONE'", "DONE", r + .getResponseHeader().getResultStatus().getStatus().getType()); + + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + PatientDataResponseType patientDataResponseType = (PatientDataResponseType) helper + .getObjectByClass(r.getMessageBody().getAny(), + PatientDataResponseType.class); + assertTrue("checking patient set size > 0 ", patientDataResponseType + .getPatientData().getPatientSet().getPatient().size() > 0); + assertTrue("checking observation set size > 0", patientDataResponseType + .getPatientData().getObservationSet().get(0).getObservation() + .size() > 0); + } + + @Ignore + @Test + public void testOntologyGetChildren() throws Exception { + + String filename = testFileDir + "/get_term_info_query.xml"; + String requestString = PdoQueryTest.getQueryString(filename); + System.out.println("test file dir " + testFileDir); + + OMElement requestElement = PdoQueryTest + .convertStringToOMElement(requestString); + OMElement responseElement = PdoQueryTest.getServiceClient(ontologyUrl) + .sendReceive(requestElement); + System.out.println(responseElement); + String responseString = responseElement.toString(); + + System.out.println(responseString); + // unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil() + .unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType) responseJaxb.getValue(); + + for (Object object : r.getMessageBody().getAny()) { + + System.out.println("name " + object.getClass().getName()); + } + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + ConceptsType conceptsType = (ConceptsType) helper.getObjectByClass(r + .getMessageBody().getAny(), ConceptsType.class); + + assertNotNull("checking concepts for not null", conceptsType); + // helper.getObjectByClass(r.getMessageBody().getAny(), requestClass) + assertTrue("checking patient set size > 0 ", conceptsType.getConcept() + .size() > 0); + assertNotNull("checking concept for not null", conceptsType + .getConcept().get(0)); + + } + + public static junit.framework.Test suite() { + return new JUnit4TestAdapter(CRCQueryClientTest.class); + } + +} diff --git a/edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/axis2/JunitRunA.java b/edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/axis2/JunitRunA.java similarity index 97% rename from edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/axis2/JunitRunA.java rename to edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/axis2/JunitRunA.java index 9c1f13e0..9814b6e8 100644 --- a/edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/axis2/JunitRunA.java +++ b/edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/axis2/JunitRunA.java @@ -1,137 +1,137 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.axis2; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import org.junit.runner.JUnitCore; -import org.junit.experimental.ParallelComputer; - -import java.io.ByteArrayInputStream; -import java.io.DataInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Arrays; - -import jakarta.xml.bind.JAXBElement; - -import junit.framework.JUnit4TestAdapter; - -import org.apache.axiom.om.OMElement; -import org.junit.BeforeClass; -import org.junit.Test; - -import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.CrcXmlResultResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterInstanceResultResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory; -import edu.harvard.i2b2.crc.datavo.setfinder.query.PsmQryHeaderType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryInstanceType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryMasterType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryResultInstanceType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.RequestType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.XmlResultType; - -/** - * Class to test different setfinder request's - * @author rkuttan - */ -public class JunitRunA extends CRCAxisAbstract { - - private static QueryMasterType queryMaster = null; - private static QueryInstanceType queryInstance = null; - private static MasterInstanceResultResponseType masterInstanceResult = null; - private static String testFileDir = null; - - private static String setfinderUrl = "http://127.0.0.1:9090/i2b2/services/QueryToolService/request"; - - - @BeforeClass - public static void setUp() throws Exception { - testFileDir = "testfiles"; //System.getProperty("testfiledir"); - System.out.println("test file dir " + testFileDir); - - if (!((testFileDir != null) && (testFileDir.trim().length() > 0))) { - throw new Exception( - "please provide test file directory info -Dtestfiledir"); - } - - } - - public static junit.framework.Test suite() { - return new JUnit4TestAdapter(JunitRunA.class); - } - - public static RequestHeaderType generateRequestHeader() { - RequestHeaderType reqHeaderType = new RequestHeaderType(); - reqHeaderType.setResultWaittimeMs(90000); - return reqHeaderType; - } - - @Test - public void ExcludeOccurancesMultiplePanelsSame() throws Exception { - String filename = testFileDir + "/setfinder_exclude_and_occurances_same_[63]_1432ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 99); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - public static RequestMessageType buildRequestMessage(PsmQryHeaderType requestHeaderType, RequestType requestType) { - //create body type - BodyType bodyType = new BodyType(); - ObjectFactory of = new ObjectFactory(); - bodyType.getAny().add(of.createPsmheader(requestHeaderType)); - bodyType.getAny().add(of.createRequest(requestType)); - RequestMessageType requestMessageType = new RequestMessageType(); - requestMessageType.setMessageHeader(generateMessageHeader()); - requestMessageType.setMessageBody(bodyType); - requestMessageType.setRequestHeader(generateRequestHeader()); - return requestMessageType; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.axis2; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import org.junit.runner.JUnitCore; +import org.junit.experimental.ParallelComputer; + +import java.io.ByteArrayInputStream; +import java.io.DataInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Arrays; + +import jakarta.xml.bind.JAXBElement; + +import junit.framework.JUnit4TestAdapter; + +import org.apache.axiom.om.OMElement; +import org.junit.BeforeClass; +import org.junit.Test; + +import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; +import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.CrcXmlResultResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterInstanceResultResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory; +import edu.harvard.i2b2.crc.datavo.setfinder.query.PsmQryHeaderType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryInstanceType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryMasterType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryResultInstanceType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.RequestType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.XmlResultType; + +/** + * Class to test different setfinder request's + * @author rkuttan + */ +public class JunitRunA extends CRCAxisAbstract { + + private static QueryMasterType queryMaster = null; + private static QueryInstanceType queryInstance = null; + private static MasterInstanceResultResponseType masterInstanceResult = null; + private static String testFileDir = null; + + private static String setfinderUrl = "http://127.0.0.1:9090/i2b2/services/QueryToolService/request"; + + + @BeforeClass + public static void setUp() throws Exception { + testFileDir = "testfiles"; //System.getProperty("testfiledir"); + System.out.println("test file dir " + testFileDir); + + if (!((testFileDir != null) && (testFileDir.trim().length() > 0))) { + throw new Exception( + "please provide test file directory info -Dtestfiledir"); + } + + } + + public static junit.framework.Test suite() { + return new JUnit4TestAdapter(JunitRunA.class); + } + + public static RequestHeaderType generateRequestHeader() { + RequestHeaderType reqHeaderType = new RequestHeaderType(); + reqHeaderType.setResultWaittimeMs(90000); + return reqHeaderType; + } + + @Test + public void ExcludeOccurancesMultiplePanelsSame() throws Exception { + String filename = testFileDir + "/setfinder_exclude_and_occurances_same_[63]_1432ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 99); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + public static RequestMessageType buildRequestMessage(PsmQryHeaderType requestHeaderType, RequestType requestType) { + //create body type + BodyType bodyType = new BodyType(); + ObjectFactory of = new ObjectFactory(); + bodyType.getAny().add(of.createPsmheader(requestHeaderType)); + bodyType.getAny().add(of.createRequest(requestType)); + RequestMessageType requestMessageType = new RequestMessageType(); + requestMessageType.setMessageHeader(generateMessageHeader()); + requestMessageType.setMessageBody(bodyType); + requestMessageType.setRequestHeader(generateRequestHeader()); + return requestMessageType; + } + +} diff --git a/edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/axis2/JunitRunB.java b/edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/axis2/JunitRunB.java similarity index 97% rename from edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/axis2/JunitRunB.java rename to edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/axis2/JunitRunB.java index e2fb9f50..ea4d3b90 100644 --- a/edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/axis2/JunitRunB.java +++ b/edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/axis2/JunitRunB.java @@ -1,137 +1,137 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.axis2; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import org.junit.runner.JUnitCore; -import org.junit.experimental.ParallelComputer; - -import java.io.ByteArrayInputStream; -import java.io.DataInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Arrays; - -import jakarta.xml.bind.JAXBElement; - -import junit.framework.JUnit4TestAdapter; - -import org.apache.axiom.om.OMElement; -import org.junit.BeforeClass; -import org.junit.Test; - -import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.CrcXmlResultResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterInstanceResultResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory; -import edu.harvard.i2b2.crc.datavo.setfinder.query.PsmQryHeaderType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryInstanceType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryMasterType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryResultInstanceType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.RequestType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.XmlResultType; - -/** - * Class to test different setfinder request's - * @author rkuttan - */ -public class JunitRunB extends CRCAxisAbstract { - - private static QueryMasterType queryMaster = null; - private static QueryInstanceType queryInstance = null; - private static MasterInstanceResultResponseType masterInstanceResult = null; - private static String testFileDir = null; - - private static String setfinderUrl = "http://127.0.0.1:9090/i2b2/services/QueryToolService/request"; - - - @BeforeClass - public static void setUp() throws Exception { - testFileDir = "testfiles"; //System.getProperty("testfiledir"); - System.out.println("test file dir " + testFileDir); - - if (!((testFileDir != null) && (testFileDir.trim().length() > 0))) { - throw new Exception( - "please provide test file directory info -Dtestfiledir"); - } - - } - - public static junit.framework.Test suite() { - return new JUnit4TestAdapter(JunitRunB.class); - } - - public static RequestHeaderType generateRequestHeader() { - RequestHeaderType reqHeaderType = new RequestHeaderType(); - reqHeaderType.setResultWaittimeMs(90000); - return reqHeaderType; - } - - @Test - public void ExcludeOccurancesMultiplePanelsSame() throws Exception { - String filename = testFileDir + "/setfinder_exclude_and_occurances_same_[63]_1432ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 99); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - public static RequestMessageType buildRequestMessage(PsmQryHeaderType requestHeaderType, RequestType requestType) { - //create body type - BodyType bodyType = new BodyType(); - ObjectFactory of = new ObjectFactory(); - bodyType.getAny().add(of.createPsmheader(requestHeaderType)); - bodyType.getAny().add(of.createRequest(requestType)); - RequestMessageType requestMessageType = new RequestMessageType(); - requestMessageType.setMessageHeader(generateMessageHeader()); - requestMessageType.setMessageBody(bodyType); - requestMessageType.setRequestHeader(generateRequestHeader()); - return requestMessageType; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.axis2; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import org.junit.runner.JUnitCore; +import org.junit.experimental.ParallelComputer; + +import java.io.ByteArrayInputStream; +import java.io.DataInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Arrays; + +import jakarta.xml.bind.JAXBElement; + +import junit.framework.JUnit4TestAdapter; + +import org.apache.axiom.om.OMElement; +import org.junit.BeforeClass; +import org.junit.Test; + +import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; +import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.CrcXmlResultResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterInstanceResultResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory; +import edu.harvard.i2b2.crc.datavo.setfinder.query.PsmQryHeaderType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryInstanceType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryMasterType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryResultInstanceType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.RequestType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.XmlResultType; + +/** + * Class to test different setfinder request's + * @author rkuttan + */ +public class JunitRunB extends CRCAxisAbstract { + + private static QueryMasterType queryMaster = null; + private static QueryInstanceType queryInstance = null; + private static MasterInstanceResultResponseType masterInstanceResult = null; + private static String testFileDir = null; + + private static String setfinderUrl = "http://127.0.0.1:9090/i2b2/services/QueryToolService/request"; + + + @BeforeClass + public static void setUp() throws Exception { + testFileDir = "testfiles"; //System.getProperty("testfiledir"); + System.out.println("test file dir " + testFileDir); + + if (!((testFileDir != null) && (testFileDir.trim().length() > 0))) { + throw new Exception( + "please provide test file directory info -Dtestfiledir"); + } + + } + + public static junit.framework.Test suite() { + return new JUnit4TestAdapter(JunitRunB.class); + } + + public static RequestHeaderType generateRequestHeader() { + RequestHeaderType reqHeaderType = new RequestHeaderType(); + reqHeaderType.setResultWaittimeMs(90000); + return reqHeaderType; + } + + @Test + public void ExcludeOccurancesMultiplePanelsSame() throws Exception { + String filename = testFileDir + "/setfinder_exclude_and_occurances_same_[63]_1432ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 99); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + public static RequestMessageType buildRequestMessage(PsmQryHeaderType requestHeaderType, RequestType requestType) { + //create body type + BodyType bodyType = new BodyType(); + ObjectFactory of = new ObjectFactory(); + bodyType.getAny().add(of.createPsmheader(requestHeaderType)); + bodyType.getAny().add(of.createRequest(requestType)); + RequestMessageType requestMessageType = new RequestMessageType(); + requestMessageType.setMessageHeader(generateMessageHeader()); + requestMessageType.setMessageBody(bodyType); + requestMessageType.setRequestHeader(generateRequestHeader()); + return requestMessageType; + } + +} diff --git a/edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/axis2/JunitRunC.java b/edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/axis2/JunitRunC.java similarity index 97% rename from edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/axis2/JunitRunC.java rename to edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/axis2/JunitRunC.java index f51b27d5..d675e7c2 100644 --- a/edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/axis2/JunitRunC.java +++ b/edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/axis2/JunitRunC.java @@ -1,137 +1,137 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.axis2; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import org.junit.runner.JUnitCore; -import org.junit.experimental.ParallelComputer; - -import java.io.ByteArrayInputStream; -import java.io.DataInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Arrays; - -import jakarta.xml.bind.JAXBElement; - -import junit.framework.JUnit4TestAdapter; - -import org.apache.axiom.om.OMElement; -import org.junit.BeforeClass; -import org.junit.Test; - -import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.CrcXmlResultResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterInstanceResultResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory; -import edu.harvard.i2b2.crc.datavo.setfinder.query.PsmQryHeaderType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryInstanceType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryMasterType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryResultInstanceType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.RequestType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.XmlResultType; - -/** - * Class to test different setfinder request's - * @author rkuttan - */ -public class JunitRunC extends CRCAxisAbstract { - - private static QueryMasterType queryMaster = null; - private static QueryInstanceType queryInstance = null; - private static MasterInstanceResultResponseType masterInstanceResult = null; - private static String testFileDir = null; - - private static String setfinderUrl = "http://127.0.0.1:9090/i2b2/services/QueryToolService/request"; - - - @BeforeClass - public static void setUp() throws Exception { - testFileDir = "testfiles"; //System.getProperty("testfiledir"); - System.out.println("test file dir " + testFileDir); - - if (!((testFileDir != null) && (testFileDir.trim().length() > 0))) { - throw new Exception( - "please provide test file directory info -Dtestfiledir"); - } - - } - - public static junit.framework.Test suite() { - return new JUnit4TestAdapter(JunitRunC.class); - } - - public static RequestHeaderType generateRequestHeader() { - RequestHeaderType reqHeaderType = new RequestHeaderType(); - reqHeaderType.setResultWaittimeMs(90000); - return reqHeaderType; - } - - @Test - public void ExcludeOccurancesMultiplePanelsSame() throws Exception { - String filename = testFileDir + "/setfinder_exclude_and_occurances_same_[63]_1432ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 99); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - public static RequestMessageType buildRequestMessage(PsmQryHeaderType requestHeaderType, RequestType requestType) { - //create body type - BodyType bodyType = new BodyType(); - ObjectFactory of = new ObjectFactory(); - bodyType.getAny().add(of.createPsmheader(requestHeaderType)); - bodyType.getAny().add(of.createRequest(requestType)); - RequestMessageType requestMessageType = new RequestMessageType(); - requestMessageType.setMessageHeader(generateMessageHeader()); - requestMessageType.setMessageBody(bodyType); - requestMessageType.setRequestHeader(generateRequestHeader()); - return requestMessageType; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.axis2; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import org.junit.runner.JUnitCore; +import org.junit.experimental.ParallelComputer; + +import java.io.ByteArrayInputStream; +import java.io.DataInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Arrays; + +import jakarta.xml.bind.JAXBElement; + +import junit.framework.JUnit4TestAdapter; + +import org.apache.axiom.om.OMElement; +import org.junit.BeforeClass; +import org.junit.Test; + +import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; +import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.CrcXmlResultResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterInstanceResultResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory; +import edu.harvard.i2b2.crc.datavo.setfinder.query.PsmQryHeaderType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryInstanceType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryMasterType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryResultInstanceType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.RequestType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.XmlResultType; + +/** + * Class to test different setfinder request's + * @author rkuttan + */ +public class JunitRunC extends CRCAxisAbstract { + + private static QueryMasterType queryMaster = null; + private static QueryInstanceType queryInstance = null; + private static MasterInstanceResultResponseType masterInstanceResult = null; + private static String testFileDir = null; + + private static String setfinderUrl = "http://127.0.0.1:9090/i2b2/services/QueryToolService/request"; + + + @BeforeClass + public static void setUp() throws Exception { + testFileDir = "testfiles"; //System.getProperty("testfiledir"); + System.out.println("test file dir " + testFileDir); + + if (!((testFileDir != null) && (testFileDir.trim().length() > 0))) { + throw new Exception( + "please provide test file directory info -Dtestfiledir"); + } + + } + + public static junit.framework.Test suite() { + return new JUnit4TestAdapter(JunitRunC.class); + } + + public static RequestHeaderType generateRequestHeader() { + RequestHeaderType reqHeaderType = new RequestHeaderType(); + reqHeaderType.setResultWaittimeMs(90000); + return reqHeaderType; + } + + @Test + public void ExcludeOccurancesMultiplePanelsSame() throws Exception { + String filename = testFileDir + "/setfinder_exclude_and_occurances_same_[63]_1432ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 99); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + public static RequestMessageType buildRequestMessage(PsmQryHeaderType requestHeaderType, RequestType requestType) { + //create body type + BodyType bodyType = new BodyType(); + ObjectFactory of = new ObjectFactory(); + bodyType.getAny().add(of.createPsmheader(requestHeaderType)); + bodyType.getAny().add(of.createRequest(requestType)); + RequestMessageType requestMessageType = new RequestMessageType(); + requestMessageType.setMessageHeader(generateMessageHeader()); + requestMessageType.setMessageBody(bodyType); + requestMessageType.setRequestHeader(generateRequestHeader()); + return requestMessageType; + } + +} diff --git a/edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/axis2/JunitRunD.java b/edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/axis2/JunitRunD.java similarity index 97% rename from edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/axis2/JunitRunD.java rename to edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/axis2/JunitRunD.java index 1be05e6a..d6c3b3c8 100644 --- a/edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/axis2/JunitRunD.java +++ b/edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/axis2/JunitRunD.java @@ -1,137 +1,137 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.axis2; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import org.junit.runner.JUnitCore; -import org.junit.experimental.ParallelComputer; - -import java.io.ByteArrayInputStream; -import java.io.DataInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Arrays; - -import jakarta.xml.bind.JAXBElement; - -import junit.framework.JUnit4TestAdapter; - -import org.apache.axiom.om.OMElement; -import org.junit.BeforeClass; -import org.junit.Test; - -import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.CrcXmlResultResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterInstanceResultResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory; -import edu.harvard.i2b2.crc.datavo.setfinder.query.PsmQryHeaderType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryInstanceType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryMasterType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryResultInstanceType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.RequestType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.XmlResultType; - -/** - * Class to test different setfinder request's - * @author rkuttan - */ -public class JunitRunD extends CRCAxisAbstract { - - private static QueryMasterType queryMaster = null; - private static QueryInstanceType queryInstance = null; - private static MasterInstanceResultResponseType masterInstanceResult = null; - private static String testFileDir = null; - - private static String setfinderUrl = "http://127.0.0.1:9090/i2b2/services/QueryToolService/request"; - - - @BeforeClass - public static void setUp() throws Exception { - testFileDir = "testfiles"; //System.getProperty("testfiledir"); - System.out.println("test file dir " + testFileDir); - - if (!((testFileDir != null) && (testFileDir.trim().length() > 0))) { - throw new Exception( - "please provide test file directory info -Dtestfiledir"); - } - - } - - public static junit.framework.Test suite() { - return new JUnit4TestAdapter(JunitRunD.class); - } - - public static RequestHeaderType generateRequestHeader() { - RequestHeaderType reqHeaderType = new RequestHeaderType(); - reqHeaderType.setResultWaittimeMs(90000); - return reqHeaderType; - } - - @Test - public void ExcludeOccurancesMultiplePanelsSame() throws Exception { - String filename = testFileDir + "/setfinder_exclude_and_occurances_same_[63]_1432ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 99); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - public static RequestMessageType buildRequestMessage(PsmQryHeaderType requestHeaderType, RequestType requestType) { - //create body type - BodyType bodyType = new BodyType(); - ObjectFactory of = new ObjectFactory(); - bodyType.getAny().add(of.createPsmheader(requestHeaderType)); - bodyType.getAny().add(of.createRequest(requestType)); - RequestMessageType requestMessageType = new RequestMessageType(); - requestMessageType.setMessageHeader(generateMessageHeader()); - requestMessageType.setMessageBody(bodyType); - requestMessageType.setRequestHeader(generateRequestHeader()); - return requestMessageType; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.axis2; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import org.junit.runner.JUnitCore; +import org.junit.experimental.ParallelComputer; + +import java.io.ByteArrayInputStream; +import java.io.DataInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Arrays; + +import jakarta.xml.bind.JAXBElement; + +import junit.framework.JUnit4TestAdapter; + +import org.apache.axiom.om.OMElement; +import org.junit.BeforeClass; +import org.junit.Test; + +import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; +import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.CrcXmlResultResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterInstanceResultResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory; +import edu.harvard.i2b2.crc.datavo.setfinder.query.PsmQryHeaderType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryInstanceType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryMasterType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryResultInstanceType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.RequestType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.XmlResultType; + +/** + * Class to test different setfinder request's + * @author rkuttan + */ +public class JunitRunD extends CRCAxisAbstract { + + private static QueryMasterType queryMaster = null; + private static QueryInstanceType queryInstance = null; + private static MasterInstanceResultResponseType masterInstanceResult = null; + private static String testFileDir = null; + + private static String setfinderUrl = "http://127.0.0.1:9090/i2b2/services/QueryToolService/request"; + + + @BeforeClass + public static void setUp() throws Exception { + testFileDir = "testfiles"; //System.getProperty("testfiledir"); + System.out.println("test file dir " + testFileDir); + + if (!((testFileDir != null) && (testFileDir.trim().length() > 0))) { + throw new Exception( + "please provide test file directory info -Dtestfiledir"); + } + + } + + public static junit.framework.Test suite() { + return new JUnit4TestAdapter(JunitRunD.class); + } + + public static RequestHeaderType generateRequestHeader() { + RequestHeaderType reqHeaderType = new RequestHeaderType(); + reqHeaderType.setResultWaittimeMs(90000); + return reqHeaderType; + } + + @Test + public void ExcludeOccurancesMultiplePanelsSame() throws Exception { + String filename = testFileDir + "/setfinder_exclude_and_occurances_same_[63]_1432ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 99); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + public static RequestMessageType buildRequestMessage(PsmQryHeaderType requestHeaderType, RequestType requestType) { + //create body type + BodyType bodyType = new BodyType(); + ObjectFactory of = new ObjectFactory(); + bodyType.getAny().add(of.createPsmheader(requestHeaderType)); + bodyType.getAny().add(of.createRequest(requestType)); + RequestMessageType requestMessageType = new RequestMessageType(); + requestMessageType.setMessageHeader(generateMessageHeader()); + requestMessageType.setMessageBody(bodyType); + requestMessageType.setRequestHeader(generateRequestHeader()); + return requestMessageType; + } + +} diff --git a/edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/axis2/JunitRunE.java b/edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/axis2/JunitRunE.java similarity index 97% rename from edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/axis2/JunitRunE.java rename to edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/axis2/JunitRunE.java index 5b6802cb..e2bb890c 100644 --- a/edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/axis2/JunitRunE.java +++ b/edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/axis2/JunitRunE.java @@ -1,137 +1,137 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.axis2; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import org.junit.runner.JUnitCore; -import org.junit.experimental.ParallelComputer; - -import java.io.ByteArrayInputStream; -import java.io.DataInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Arrays; - -import jakarta.xml.bind.JAXBElement; - -import junit.framework.JUnit4TestAdapter; - -import org.apache.axiom.om.OMElement; -import org.junit.BeforeClass; -import org.junit.Test; - -import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.CrcXmlResultResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterInstanceResultResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory; -import edu.harvard.i2b2.crc.datavo.setfinder.query.PsmQryHeaderType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryInstanceType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryMasterType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryResultInstanceType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.RequestType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.XmlResultType; - -/** - * Class to test different setfinder request's - * @author rkuttan - */ -public class JunitRunE extends CRCAxisAbstract { - - private static QueryMasterType queryMaster = null; - private static QueryInstanceType queryInstance = null; - private static MasterInstanceResultResponseType masterInstanceResult = null; - private static String testFileDir = null; - - private static String setfinderUrl = "http://127.0.0.1:9090/i2b2/services/QueryToolService/request"; - - - @BeforeClass - public static void setUp() throws Exception { - testFileDir = "testfiles"; //System.getProperty("testfiledir"); - System.out.println("test file dir " + testFileDir); - - if (!((testFileDir != null) && (testFileDir.trim().length() > 0))) { - throw new Exception( - "please provide test file directory info -Dtestfiledir"); - } - - } - - public static junit.framework.Test suite() { - return new JUnit4TestAdapter(JunitRunE.class); - } - - public static RequestHeaderType generateRequestHeader() { - RequestHeaderType reqHeaderType = new RequestHeaderType(); - reqHeaderType.setResultWaittimeMs(90000); - return reqHeaderType; - } - - @Test - public void ExcludeOccurancesMultiplePanelsSame() throws Exception { - String filename = testFileDir + "/setfinder_exclude_and_occurances_same_[63]_1432ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 99); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - public static RequestMessageType buildRequestMessage(PsmQryHeaderType requestHeaderType, RequestType requestType) { - //create body type - BodyType bodyType = new BodyType(); - ObjectFactory of = new ObjectFactory(); - bodyType.getAny().add(of.createPsmheader(requestHeaderType)); - bodyType.getAny().add(of.createRequest(requestType)); - RequestMessageType requestMessageType = new RequestMessageType(); - requestMessageType.setMessageHeader(generateMessageHeader()); - requestMessageType.setMessageBody(bodyType); - requestMessageType.setRequestHeader(generateRequestHeader()); - return requestMessageType; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.axis2; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import org.junit.runner.JUnitCore; +import org.junit.experimental.ParallelComputer; + +import java.io.ByteArrayInputStream; +import java.io.DataInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Arrays; + +import jakarta.xml.bind.JAXBElement; + +import junit.framework.JUnit4TestAdapter; + +import org.apache.axiom.om.OMElement; +import org.junit.BeforeClass; +import org.junit.Test; + +import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; +import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.CrcXmlResultResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterInstanceResultResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory; +import edu.harvard.i2b2.crc.datavo.setfinder.query.PsmQryHeaderType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryInstanceType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryMasterType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryResultInstanceType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.RequestType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.XmlResultType; + +/** + * Class to test different setfinder request's + * @author rkuttan + */ +public class JunitRunE extends CRCAxisAbstract { + + private static QueryMasterType queryMaster = null; + private static QueryInstanceType queryInstance = null; + private static MasterInstanceResultResponseType masterInstanceResult = null; + private static String testFileDir = null; + + private static String setfinderUrl = "http://127.0.0.1:9090/i2b2/services/QueryToolService/request"; + + + @BeforeClass + public static void setUp() throws Exception { + testFileDir = "testfiles"; //System.getProperty("testfiledir"); + System.out.println("test file dir " + testFileDir); + + if (!((testFileDir != null) && (testFileDir.trim().length() > 0))) { + throw new Exception( + "please provide test file directory info -Dtestfiledir"); + } + + } + + public static junit.framework.Test suite() { + return new JUnit4TestAdapter(JunitRunE.class); + } + + public static RequestHeaderType generateRequestHeader() { + RequestHeaderType reqHeaderType = new RequestHeaderType(); + reqHeaderType.setResultWaittimeMs(90000); + return reqHeaderType; + } + + @Test + public void ExcludeOccurancesMultiplePanelsSame() throws Exception { + String filename = testFileDir + "/setfinder_exclude_and_occurances_same_[63]_1432ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 99); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + public static RequestMessageType buildRequestMessage(PsmQryHeaderType requestHeaderType, RequestType requestType) { + //create body type + BodyType bodyType = new BodyType(); + ObjectFactory of = new ObjectFactory(); + bodyType.getAny().add(of.createPsmheader(requestHeaderType)); + bodyType.getAny().add(of.createRequest(requestType)); + RequestMessageType requestMessageType = new RequestMessageType(); + requestMessageType.setMessageHeader(generateMessageHeader()); + requestMessageType.setMessageBody(bodyType); + requestMessageType.setRequestHeader(generateRequestHeader()); + return requestMessageType; + } + +} diff --git a/edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/axis2/OMOPSetfinderQueryTest.java b/edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/axis2/OMOPSetfinderQueryTest.java similarity index 97% rename from edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/axis2/OMOPSetfinderQueryTest.java rename to edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/axis2/OMOPSetfinderQueryTest.java index 00c88000..a57655bb 100644 --- a/edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/axis2/OMOPSetfinderQueryTest.java +++ b/edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/axis2/OMOPSetfinderQueryTest.java @@ -1,315 +1,315 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * S.W.Chan - */ -package edu.harvard.i2b2.crc.axis2; - -import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterInstanceResultResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryResultInstanceType; - -import jakarta.xml.bind.JAXBElement; -import junit.framework.JUnit4TestAdapter; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import org.junit.BeforeClass; -import org.junit.Test; -import org.apache.axiom.om.OMElement; - -/** - * Class to test different CRC DBLookup request's - * @author S.W. Chan - */ -public class OMOPSetfinderQueryTest extends CRCAxisAbstract { - private static String testFileDir = ""; - private static String crcTargetEPR = "http://services.i2b2.org/i2b2/services/QueryToolService/request"; - - - @BeforeClass - public static void setUp() throws Exception { - testFileDir = "testfiles/omop/setfinder"; //System.getProperty("testfiledir"); - System.out.println("test file dir " + testFileDir); - if (testFileDir == null || 0 == testFileDir.trim().length()) { - throw new Exception("please provide test file directory info -Dtestfiledir"); - } - } - - public static junit.framework.Test suite() { - return new JUnit4TestAdapter(OMOPSetfinderQueryTest.class); - } - - @Test - public void TwoPanelAND() throws Exception { //swc20160722 - String filename = testFileDir + "/HYP_and_ISCH_[609].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(crcTargetEPR).sendReceive(requestElement); - String response = responseElement.toString(); - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 609); - else - assertTrue(false); - } - - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void TwoPanelOR() throws Exception { //swc20160722 - String filename = testFileDir + "/HYP_or_ISCH_[770].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(crcTargetEPR).sendReceive(requestElement); - String response = responseElement.toString(); - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 770); - else - assertTrue(false); - } - - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void TwoPanelAND_2Domains() throws Exception { //swc20160722 - String filename = testFileDir + "/HYP_and_Cardio_[635].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(crcTargetEPR).sendReceive(requestElement); - String response = responseElement.toString(); - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 635); - else - assertTrue(false); - } - - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void TwoPanelOR_2Domains() throws Exception { //swc20160722 - String filename = testFileDir + "/HYP_or_Cardio_[878].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(crcTargetEPR).sendReceive(requestElement); - String response = responseElement.toString(); - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 878); - else - assertTrue(false); - } - - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void Exclude_Demographic() throws Exception { //swc20160722 - String filename = testFileDir + "/Exclude_White_[181].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(crcTargetEPR).sendReceive(requestElement); - String response = responseElement.toString(); - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 181); - else - assertTrue(false); - } - - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void ValueConstraintLab() throws Exception { //swc20160722 - String filename = testFileDir + "/CBC_GT_[5].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(crcTargetEPR).sendReceive(requestElement); - String response = responseElement.toString(); - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 5); - else - assertTrue(false); - } - - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void EnumConstraintLab() throws Exception { - String filename = testFileDir + "/Poly_TRACE_[5].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(crcTargetEPR).sendReceive(requestElement); - String response = responseElement.toString(); - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 5); - else - assertTrue(false); - } - - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void DateConstraintProc() throws Exception { - String filename = testFileDir + "/Cardio_proc_after_2009_[15].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(crcTargetEPR).sendReceive(requestElement); - String response = responseElement.toString(); - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 15); - else - assertTrue(false); - } - - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void Temporal_3Domains() throws Exception { - String filename = testFileDir + "/Cardio_Meds_before_Operation_[42].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(crcTargetEPR).sendReceive(requestElement); - String response = responseElement.toString(); - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 42); - else - assertTrue(false); - } - - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * S.W.Chan + */ +package edu.harvard.i2b2.crc.axis2; + +import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; +import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.StatusType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterInstanceResultResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryResultInstanceType; + +import jakarta.xml.bind.JAXBElement; +import junit.framework.JUnit4TestAdapter; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import org.junit.BeforeClass; +import org.junit.Test; +import org.apache.axiom.om.OMElement; + +/** + * Class to test different CRC DBLookup request's + * @author S.W. Chan + */ +public class OMOPSetfinderQueryTest extends CRCAxisAbstract { + private static String testFileDir = ""; + private static String crcTargetEPR = "http://services.i2b2.org/i2b2/services/QueryToolService/request"; + + + @BeforeClass + public static void setUp() throws Exception { + testFileDir = "testfiles/omop/setfinder"; //System.getProperty("testfiledir"); + System.out.println("test file dir " + testFileDir); + if (testFileDir == null || 0 == testFileDir.trim().length()) { + throw new Exception("please provide test file directory info -Dtestfiledir"); + } + } + + public static junit.framework.Test suite() { + return new JUnit4TestAdapter(OMOPSetfinderQueryTest.class); + } + + @Test + public void TwoPanelAND() throws Exception { //swc20160722 + String filename = testFileDir + "/HYP_and_ISCH_[609].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(crcTargetEPR).sendReceive(requestElement); + String response = responseElement.toString(); + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 609); + else + assertTrue(false); + } + + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void TwoPanelOR() throws Exception { //swc20160722 + String filename = testFileDir + "/HYP_or_ISCH_[770].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(crcTargetEPR).sendReceive(requestElement); + String response = responseElement.toString(); + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 770); + else + assertTrue(false); + } + + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void TwoPanelAND_2Domains() throws Exception { //swc20160722 + String filename = testFileDir + "/HYP_and_Cardio_[635].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(crcTargetEPR).sendReceive(requestElement); + String response = responseElement.toString(); + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 635); + else + assertTrue(false); + } + + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void TwoPanelOR_2Domains() throws Exception { //swc20160722 + String filename = testFileDir + "/HYP_or_Cardio_[878].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(crcTargetEPR).sendReceive(requestElement); + String response = responseElement.toString(); + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 878); + else + assertTrue(false); + } + + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void Exclude_Demographic() throws Exception { //swc20160722 + String filename = testFileDir + "/Exclude_White_[181].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(crcTargetEPR).sendReceive(requestElement); + String response = responseElement.toString(); + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 181); + else + assertTrue(false); + } + + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void ValueConstraintLab() throws Exception { //swc20160722 + String filename = testFileDir + "/CBC_GT_[5].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(crcTargetEPR).sendReceive(requestElement); + String response = responseElement.toString(); + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 5); + else + assertTrue(false); + } + + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void EnumConstraintLab() throws Exception { + String filename = testFileDir + "/Poly_TRACE_[5].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(crcTargetEPR).sendReceive(requestElement); + String response = responseElement.toString(); + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 5); + else + assertTrue(false); + } + + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void DateConstraintProc() throws Exception { + String filename = testFileDir + "/Cardio_proc_after_2009_[15].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(crcTargetEPR).sendReceive(requestElement); + String response = responseElement.toString(); + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 15); + else + assertTrue(false); + } + + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void Temporal_3Domains() throws Exception { + String filename = testFileDir + "/Cardio_Meds_before_Operation_[42].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(crcTargetEPR).sendReceive(requestElement); + String response = responseElement.toString(); + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 42); + else + assertTrue(false); + } + + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } +} diff --git a/edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/axis2/PdoQueryTest.java b/edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/axis2/PdoQueryTest.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/axis2/PdoQueryTest.java rename to edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/axis2/PdoQueryTest.java index 076e24cb..d91bb31c --- a/edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/axis2/PdoQueryTest.java +++ b/edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/axis2/PdoQueryTest.java @@ -1,560 +1,560 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.axis2; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.StringWriter; -import java.util.GregorianCalendar; - -import jakarta.xml.bind.JAXBElement; -import javax.xml.datatype.DatatypeFactory; -import javax.xml.datatype.XMLGregorianCalendar; - -import junit.framework.JUnit4TestAdapter; - -import org.apache.axiom.om.OMElement; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; - -import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; - -import edu.harvard.i2b2.crc.datavo.pdo.ObservationSet; -import edu.harvard.i2b2.crc.datavo.pdo.ObservationType; -import edu.harvard.i2b2.crc.datavo.pdo.ParamType; -import edu.harvard.i2b2.crc.datavo.pdo.PatientType; -import edu.harvard.i2b2.crc.datavo.pdo.query.FactOutputOptionType; -import edu.harvard.i2b2.crc.datavo.pdo.query.FactPrimaryKeyType; -import edu.harvard.i2b2.crc.datavo.pdo.query.FilterListType; -import edu.harvard.i2b2.crc.datavo.pdo.query.GetObservationFactByPrimaryKeyRequestType; -import edu.harvard.i2b2.crc.datavo.pdo.query.GetPDOFromInputListRequestType; -import edu.harvard.i2b2.crc.datavo.pdo.query.InputOptionListType; -import edu.harvard.i2b2.crc.datavo.pdo.query.ItemType; -import edu.harvard.i2b2.crc.datavo.pdo.query.ObjectFactory; -import edu.harvard.i2b2.crc.datavo.pdo.query.OutputOptionListType; -import edu.harvard.i2b2.crc.datavo.pdo.query.OutputOptionNameType; -import edu.harvard.i2b2.crc.datavo.pdo.query.OutputOptionSelectType; -import edu.harvard.i2b2.crc.datavo.pdo.query.OutputOptionType; -import edu.harvard.i2b2.crc.datavo.pdo.query.PanelType; -import edu.harvard.i2b2.crc.datavo.pdo.query.PatientDataResponseType; -import edu.harvard.i2b2.crc.datavo.pdo.query.PatientListType; -import edu.harvard.i2b2.crc.datavo.pdo.query.PdoQryHeaderType; -import edu.harvard.i2b2.crc.datavo.pdo.query.PdoRequestTypeType; -import edu.harvard.i2b2.crc.datavo.pdo.query.RequestType; - -import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterInstanceResultResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryResultInstanceType; - -/** - * Class to test different pdo requests - * @author rkuttan - */ -public class PdoQueryTest extends CRCAxisAbstract { - - - private static QueryResultInstanceType queryResultInstance = null; - private static String testFileDir = null; - //:TODO accept server url as runtime parameter - private static String setfinderTargetEPR = null; - - private static String pdoTargetEPR = null; - //private static String patientSetId = null; - - - @BeforeClass - public static void setUp() throws Exception { - String host = (System.getProperty("testhost") == null ? "http://127.0.0.1:9090/i2b2/services" : System.getProperty("testhost") ) ; - setfinderTargetEPR = - host + "/QueryToolService/request"; - pdoTargetEPR = - host + "/QueryToolService/pdorequest"; - testFileDir = "testfiles"; //System.getProperty("testfiledir"); - System.out.println("test file dir " + testFileDir); - - if (!((testFileDir != null) && (testFileDir.trim().length() > 0))) { - throw new Exception( - "please provide test file directory info -Dtestfiledir"); - } - - } - - - - - - public static junit.framework.Test suite() { - return new JUnit4TestAdapter(PdoQueryTest.class); - } - - public static RequestHeaderType generateRequestHeader() { - RequestHeaderType reqHeaderType = new RequestHeaderType(); - reqHeaderType.setResultWaittimeMs(90000); - return reqHeaderType; - } - - - @Test - public void GetPDOFromInputList_requestType_labs() throws Exception { - - - try { - - String filename = testFileDir + "/GetPDOFromInputList_requestType_Labs.xml"; - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(pdoTargetEPR).sendReceive(requestElement); - String patientSetId = null; - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - PatientDataResponseType patientDataResponseType = (PatientDataResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),PatientDataResponseType.class); - - assertTrue("checking patient set size > 0 ",patientDataResponseType.getPatientData().getPatientSet().getPatient().size()>0); - //System.out.println(patientDataResponseType.getPatientData().getObservationSet().get(0).getObservation().get(0).getPatientId().getSource()); - - boolean found = false; - for (PatientType results : patientDataResponseType.getPatientData().getPatientSet().getPatient() ) - { - if (found) - break; - if (results.getPatientId().getValue().equals("1000000001")) - { - - for (ParamType params : results.getParam() ) - { - - if (params.getColumn().equals("language_cd")){ - - assertEquals("Checking patient 1000000001 Language of english", params.getValue(), "english"); - found = true; - break; - } - } - - - } - } - assertTrue(found); - } catch (Exception e2) { - System.out.println("Error in onemodifier:" + e2.getMessage()); - e2.printStackTrace(); - assertTrue(false); - } - } - - - - - @Test - public void pdo_onemodifier() throws Exception { - - - try { - String filename = testFileDir + "/MQP1I1_[65]_2320ms.xml"; - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderTargetEPR).sendReceive(requestElement); - - String patientSetId = null; - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull("Did not get masterInstanceResult", masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENTSET")) - { - assertEquals(results.getSetSize(), 65); - patientSetId = results.getResultInstanceId(); - } - } - - assertNotNull("Did not get Patientsetid", patientSetId); - - System.out.println("My patientsetID: " + patientSetId); - - filename = testFileDir + "/pdo_onemodifier.xml"; - requestString = getQueryString(filename); - requestString = requestString.replace("{patientSetId}", patientSetId); - requestElement = convertStringToOMElement(requestString); - responseElement = getServiceClient(pdoTargetEPR).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - r = (ResponseMessageType)responseJaxb.getValue(); - helper = new JAXBUnWrapHelper(); - - - - PatientDataResponseType patientDataResponseType = (PatientDataResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),PatientDataResponseType.class); - //StatusType.Condition condition = patientDataResponseType.getStatus().getCondition().get(0); - //assertEquals(condition.getType(),"DONE","checking crc message status 'DONE'"); - assertTrue("checking patient set size > 0 ",patientDataResponseType.getPatientData().getPatientSet().getPatient().size()>0); - //System.out.println(patientDataResponseType.getPatientData().getObservationSet().get(0).getObservation().get(0).getPatientId().getSource()); - - boolean found = false; - for (PatientType results : patientDataResponseType.getPatientData().getPatientSet().getPatient() ) - { - if (found) - break; - if (results.getPatientId().getValue().equals("1000000003")) - { - - for (ParamType params : results.getParam() ) - { - - if (params.getColumn().equals("language_cd")){ - - assertEquals("Checking patient 1000000003 Language of germae", params.getValue(), "german"); - found = true; - break; - } - } - - - } - } - assertTrue(found); - - } catch (Exception e2) { - System.out.println("Error in onemodifier:" + e2.getMessage()); - e2.printStackTrace(); - assertTrue(false); - } - } - - - @Test - public void pdo_minvalue() throws Exception { - try { - String filename = testFileDir + "/MQP1I1_[65]_2320ms.xml"; - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderTargetEPR).sendReceive(requestElement); - - String patientSetId = null; - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull("Did not get masterInstanceResult", masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENTSET")) - { - assertEquals(results.getSetSize(), 65); - patientSetId = results.getResultInstanceId(); - } - } - - assertNotNull("Did not get Patientsetid", patientSetId); - filename = testFileDir + "/pdo_minvalue.xml"; - - - System.out.println("My patientsetID: " + patientSetId); - requestString = getQueryString(filename); - requestString = requestString.replace("{patientSetId}", patientSetId); - requestElement = convertStringToOMElement(requestString); - responseElement = getServiceClient(pdoTargetEPR).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - r = (ResponseMessageType)responseJaxb.getValue(); - helper = new JAXBUnWrapHelper(); - - - - PatientDataResponseType patientDataResponseType = (PatientDataResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),PatientDataResponseType.class); - //StatusType.Condition condition = patientDataResponseType.getStatus().getCondition().get(0); - //assertEquals(condition.getType(),"DONE","checking crc message status 'DONE'"); - assertTrue("checking patient set size > 0 ",patientDataResponseType.getPatientData().getPatientSet().getPatient().size()>0); - //System.out.println(patientDataResponseType.getPatientData().getObservationSet().get(0).getObservation().get(0).getPatientId().getSource()); - - boolean found = false; - int count = 0; - for (ObservationType results : patientDataResponseType.getPatientData().getObservationSet().get(0).getObservation() ) - { - if (results.getPatientId().getValue().equals("1000000016") && results.getEventId().getValue().equals("473653") && - results.getConceptCd().getValue().equals("LOINC:2086-7")) - { - found = true; - if (results.getNvalNum().getValue().toPlainString().equals("44")) - assertEquals("Checking patient 100000003", results.getNvalNum().getValue().toPlainString(), "44"); - else - assertEquals("Checking patient 1000000016", results.getNvalNum().getValue().toPlainString(), "44.00000"); - count++; - } - } - assertEquals("Checking patient 1000000016 had 2 records", count, 2); - assertTrue(found); - } catch (Exception e) { - System.out.println("Error in minvalue:" + e.getMessage()); - - e.printStackTrace(); - assertTrue(false); - } - } - - - @Test - public void pdo_maxvalue() throws Exception { - - try { - - String filename = testFileDir + "/MQP1I1_[65]_2320ms.xml"; - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderTargetEPR).sendReceive(requestElement); - - String patientSetId = null; - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull("Did not get masterInstanceResult", masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENTSET")) - { - assertEquals(results.getSetSize(), 65); - patientSetId = results.getResultInstanceId(); - } - } - - - filename = testFileDir + "/pdo_maxvalue.xml"; - assertNotNull("Did not get Patientsetid", patientSetId); - - requestString = getQueryString(filename); - requestString = requestString.replace("{patientSetId}", patientSetId); - requestElement = convertStringToOMElement(requestString); - responseElement = getServiceClient(pdoTargetEPR).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - r = (ResponseMessageType)responseJaxb.getValue(); - helper = new JAXBUnWrapHelper(); - - - - PatientDataResponseType patientDataResponseType = (PatientDataResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),PatientDataResponseType.class); - //StatusType.Condition condition = patientDataResponseType.getStatus().getCondition().get(0); - //assertEquals(condition.getType(),"DONE","checking crc message status 'DONE'"); - assertTrue("checking patient set size > 0 ",patientDataResponseType.getPatientData().getPatientSet().getPatient().size()>0); - - boolean found = false; - for (ObservationType results : patientDataResponseType.getPatientData().getObservationSet().get(0).getObservation() ) - { - - if (results.getPatientId().getValue().equals("1000000003") && results.getEventId().getValue().equals("474080") && - results.getConceptCd().getValue().equals("LOINC:2086-7")) - { - found = true; - if (results.getNvalNum().getValue().toPlainString().equals("46")) - assertEquals("Checking patient 100000003", results.getNvalNum().getValue().toPlainString(), "46"); - else - assertEquals("Checking patient 100000003", results.getNvalNum().getValue().toPlainString(), "46.00000"); - } - } - assertTrue(found); - - } catch (Exception e) { - System.out.println("Error in maxvalue:" + e.getMessage()); - - e.printStackTrace(); - assertTrue(false); - } - } - - - - @Test - public void pdo_firstvalue_modtfalse() throws Exception { - try { - - String filename = testFileDir + "/MQP1I1_[65]_2320ms.xml"; - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderTargetEPR).sendReceive(requestElement); - - String patientSetId = null; - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull("Did not get masterInstanceResult", masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENTSET")) - { - assertEquals(results.getSetSize(), 65); - patientSetId = results.getResultInstanceId(); - } - } - - assertNotNull("Did not get Patientsetid", patientSetId); - - filename = testFileDir + "/pdo_firstvalue_modtfalse.xml"; - - requestString = getQueryString(filename); - requestString = requestString.replace("{patientSetId}", patientSetId); - - requestElement = convertStringToOMElement(requestString); - responseElement = getServiceClient(pdoTargetEPR).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - r = (ResponseMessageType)responseJaxb.getValue(); - helper = new JAXBUnWrapHelper(); - - - - PatientDataResponseType patientDataResponseType = (PatientDataResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),PatientDataResponseType.class); - //StatusType.Condition condition = patientDataResponseType.getStatus().getCondition().get(0); - //assertEquals(condition.getType(),"DONE","checking crc message status 'DONE'"); - assertTrue("checking patient set size > 0 ",patientDataResponseType.getPatientData().getPatientSet().getPatient().size()>0); - System.out.println(patientDataResponseType.getPatientData().getObservationSet().get(0).getObservation().get(0).getPatientId().getSource()); - - boolean found = false; - for (ObservationType results : patientDataResponseType.getPatientData().getObservationSet().get(0).getObservation() ) - { - if (results.getPatientId().getValue().equals("1000000003")) - { - found = true; - assertEquals("Checking patient 1000000003", results.getStartDate().toString(), "1997-11-26T00:00:00.000-05:00"); - } - if (found) - break; - } - assertTrue("Did not find patient 1000000003", found); - - } catch (Exception e) { - System.out.println("Error in modtfalse:" + e.getMessage()); - - e.printStackTrace(); - assertTrue(false); - } - } - - - @Test - public void pdo_lastvalue_modtfalse() throws Exception { - try { - String filename = testFileDir + "/MQP1I1_[65]_2320ms.xml"; - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderTargetEPR).sendReceive(requestElement); - String patientSetId = null; - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull("Did not get masterInstanceResult", masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENTSET")) - { - assertEquals(results.getSetSize(), 65); - patientSetId = results.getResultInstanceId(); - } - } - - assertNotNull("Did not get Patientsetid", patientSetId); - - filename = testFileDir + "/pdo_lastvalue_modfalse.xml"; - requestString = getQueryString(filename); - requestString = requestString.replace("{patientSetId}", patientSetId); - - requestElement = convertStringToOMElement(requestString); - responseElement = getServiceClient(pdoTargetEPR).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - r = (ResponseMessageType)responseJaxb.getValue(); - helper = new JAXBUnWrapHelper(); - - - - PatientDataResponseType patientDataResponseType = (PatientDataResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),PatientDataResponseType.class); - //StatusType.Condition condition = patientDataResponseType.getStatus().getCondition().get(0); - //assertEquals(condition.getType(),"DONE","checking crc message status 'DONE'"); - assertTrue("checking patient set size > 0 ",patientDataResponseType.getPatientData().getPatientSet().getPatient().size()>0); - System.out.println(patientDataResponseType.getPatientData().getObservationSet().get(0).getObservation().get(0).getPatientId().getSource()); - - boolean found = false; - for (ObservationType results : patientDataResponseType.getPatientData().getObservationSet().get(0).getObservation() ) - { - if (results.getPatientId().getValue().equals("1000000003") && results.getConceptCd().getValue().equals("LOINC:2090-9")) - { - found = true; - assertEquals("Checking patient 1000000003", results.getStartDate().toString(), "2005-12-09T00:00:00.000-05:00"); - } - if (found) - break; - - } - assertTrue(found); - - } catch (Exception e) { - System.out.println("Error in lastmodtfalse:" + e.getMessage()); - - e.printStackTrace(); - assertTrue(false); - } - } - - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.axis2; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.io.StringWriter; +import java.util.GregorianCalendar; + +import jakarta.xml.bind.JAXBElement; +import javax.xml.datatype.DatatypeFactory; +import javax.xml.datatype.XMLGregorianCalendar; + +import junit.framework.JUnit4TestAdapter; + +import org.apache.axiom.om.OMElement; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; + +import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; +import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; + +import edu.harvard.i2b2.crc.datavo.pdo.ObservationSet; +import edu.harvard.i2b2.crc.datavo.pdo.ObservationType; +import edu.harvard.i2b2.crc.datavo.pdo.ParamType; +import edu.harvard.i2b2.crc.datavo.pdo.PatientType; +import edu.harvard.i2b2.crc.datavo.pdo.query.FactOutputOptionType; +import edu.harvard.i2b2.crc.datavo.pdo.query.FactPrimaryKeyType; +import edu.harvard.i2b2.crc.datavo.pdo.query.FilterListType; +import edu.harvard.i2b2.crc.datavo.pdo.query.GetObservationFactByPrimaryKeyRequestType; +import edu.harvard.i2b2.crc.datavo.pdo.query.GetPDOFromInputListRequestType; +import edu.harvard.i2b2.crc.datavo.pdo.query.InputOptionListType; +import edu.harvard.i2b2.crc.datavo.pdo.query.ItemType; +import edu.harvard.i2b2.crc.datavo.pdo.query.ObjectFactory; +import edu.harvard.i2b2.crc.datavo.pdo.query.OutputOptionListType; +import edu.harvard.i2b2.crc.datavo.pdo.query.OutputOptionNameType; +import edu.harvard.i2b2.crc.datavo.pdo.query.OutputOptionSelectType; +import edu.harvard.i2b2.crc.datavo.pdo.query.OutputOptionType; +import edu.harvard.i2b2.crc.datavo.pdo.query.PanelType; +import edu.harvard.i2b2.crc.datavo.pdo.query.PatientDataResponseType; +import edu.harvard.i2b2.crc.datavo.pdo.query.PatientListType; +import edu.harvard.i2b2.crc.datavo.pdo.query.PdoQryHeaderType; +import edu.harvard.i2b2.crc.datavo.pdo.query.PdoRequestTypeType; +import edu.harvard.i2b2.crc.datavo.pdo.query.RequestType; + +import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterInstanceResultResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryResultInstanceType; + +/** + * Class to test different pdo requests + * @author rkuttan + */ +public class PdoQueryTest extends CRCAxisAbstract { + + + private static QueryResultInstanceType queryResultInstance = null; + private static String testFileDir = null; + //:TODO accept server url as runtime parameter + private static String setfinderTargetEPR = null; + + private static String pdoTargetEPR = null; + //private static String patientSetId = null; + + + @BeforeClass + public static void setUp() throws Exception { + String host = (System.getProperty("testhost") == null ? "http://127.0.0.1:9090/i2b2/services" : System.getProperty("testhost") ) ; + setfinderTargetEPR = + host + "/QueryToolService/request"; + pdoTargetEPR = + host + "/QueryToolService/pdorequest"; + testFileDir = "testfiles"; //System.getProperty("testfiledir"); + System.out.println("test file dir " + testFileDir); + + if (!((testFileDir != null) && (testFileDir.trim().length() > 0))) { + throw new Exception( + "please provide test file directory info -Dtestfiledir"); + } + + } + + + + + + public static junit.framework.Test suite() { + return new JUnit4TestAdapter(PdoQueryTest.class); + } + + public static RequestHeaderType generateRequestHeader() { + RequestHeaderType reqHeaderType = new RequestHeaderType(); + reqHeaderType.setResultWaittimeMs(90000); + return reqHeaderType; + } + + + @Test + public void GetPDOFromInputList_requestType_labs() throws Exception { + + + try { + + String filename = testFileDir + "/GetPDOFromInputList_requestType_Labs.xml"; + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(pdoTargetEPR).sendReceive(requestElement); + String patientSetId = null; + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + PatientDataResponseType patientDataResponseType = (PatientDataResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),PatientDataResponseType.class); + + assertTrue("checking patient set size > 0 ",patientDataResponseType.getPatientData().getPatientSet().getPatient().size()>0); + //System.out.println(patientDataResponseType.getPatientData().getObservationSet().get(0).getObservation().get(0).getPatientId().getSource()); + + boolean found = false; + for (PatientType results : patientDataResponseType.getPatientData().getPatientSet().getPatient() ) + { + if (found) + break; + if (results.getPatientId().getValue().equals("1000000001")) + { + + for (ParamType params : results.getParam() ) + { + + if (params.getColumn().equals("language_cd")){ + + assertEquals("Checking patient 1000000001 Language of english", params.getValue(), "english"); + found = true; + break; + } + } + + + } + } + assertTrue(found); + } catch (Exception e2) { + System.out.println("Error in onemodifier:" + e2.getMessage()); + e2.printStackTrace(); + assertTrue(false); + } + } + + + + + @Test + public void pdo_onemodifier() throws Exception { + + + try { + String filename = testFileDir + "/MQP1I1_[65]_2320ms.xml"; + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderTargetEPR).sendReceive(requestElement); + + String patientSetId = null; + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull("Did not get masterInstanceResult", masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENTSET")) + { + assertEquals(results.getSetSize(), 65); + patientSetId = results.getResultInstanceId(); + } + } + + assertNotNull("Did not get Patientsetid", patientSetId); + + System.out.println("My patientsetID: " + patientSetId); + + filename = testFileDir + "/pdo_onemodifier.xml"; + requestString = getQueryString(filename); + requestString = requestString.replace("{patientSetId}", patientSetId); + requestElement = convertStringToOMElement(requestString); + responseElement = getServiceClient(pdoTargetEPR).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + r = (ResponseMessageType)responseJaxb.getValue(); + helper = new JAXBUnWrapHelper(); + + + + PatientDataResponseType patientDataResponseType = (PatientDataResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),PatientDataResponseType.class); + //StatusType.Condition condition = patientDataResponseType.getStatus().getCondition().get(0); + //assertEquals(condition.getType(),"DONE","checking crc message status 'DONE'"); + assertTrue("checking patient set size > 0 ",patientDataResponseType.getPatientData().getPatientSet().getPatient().size()>0); + //System.out.println(patientDataResponseType.getPatientData().getObservationSet().get(0).getObservation().get(0).getPatientId().getSource()); + + boolean found = false; + for (PatientType results : patientDataResponseType.getPatientData().getPatientSet().getPatient() ) + { + if (found) + break; + if (results.getPatientId().getValue().equals("1000000003")) + { + + for (ParamType params : results.getParam() ) + { + + if (params.getColumn().equals("language_cd")){ + + assertEquals("Checking patient 1000000003 Language of germae", params.getValue(), "german"); + found = true; + break; + } + } + + + } + } + assertTrue(found); + + } catch (Exception e2) { + System.out.println("Error in onemodifier:" + e2.getMessage()); + e2.printStackTrace(); + assertTrue(false); + } + } + + + @Test + public void pdo_minvalue() throws Exception { + try { + String filename = testFileDir + "/MQP1I1_[65]_2320ms.xml"; + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderTargetEPR).sendReceive(requestElement); + + String patientSetId = null; + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull("Did not get masterInstanceResult", masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENTSET")) + { + assertEquals(results.getSetSize(), 65); + patientSetId = results.getResultInstanceId(); + } + } + + assertNotNull("Did not get Patientsetid", patientSetId); + filename = testFileDir + "/pdo_minvalue.xml"; + + + System.out.println("My patientsetID: " + patientSetId); + requestString = getQueryString(filename); + requestString = requestString.replace("{patientSetId}", patientSetId); + requestElement = convertStringToOMElement(requestString); + responseElement = getServiceClient(pdoTargetEPR).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + r = (ResponseMessageType)responseJaxb.getValue(); + helper = new JAXBUnWrapHelper(); + + + + PatientDataResponseType patientDataResponseType = (PatientDataResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),PatientDataResponseType.class); + //StatusType.Condition condition = patientDataResponseType.getStatus().getCondition().get(0); + //assertEquals(condition.getType(),"DONE","checking crc message status 'DONE'"); + assertTrue("checking patient set size > 0 ",patientDataResponseType.getPatientData().getPatientSet().getPatient().size()>0); + //System.out.println(patientDataResponseType.getPatientData().getObservationSet().get(0).getObservation().get(0).getPatientId().getSource()); + + boolean found = false; + int count = 0; + for (ObservationType results : patientDataResponseType.getPatientData().getObservationSet().get(0).getObservation() ) + { + if (results.getPatientId().getValue().equals("1000000016") && results.getEventId().getValue().equals("473653") && + results.getConceptCd().getValue().equals("LOINC:2086-7")) + { + found = true; + if (results.getNvalNum().getValue().toPlainString().equals("44")) + assertEquals("Checking patient 100000003", results.getNvalNum().getValue().toPlainString(), "44"); + else + assertEquals("Checking patient 1000000016", results.getNvalNum().getValue().toPlainString(), "44.00000"); + count++; + } + } + assertEquals("Checking patient 1000000016 had 2 records", count, 2); + assertTrue(found); + } catch (Exception e) { + System.out.println("Error in minvalue:" + e.getMessage()); + + e.printStackTrace(); + assertTrue(false); + } + } + + + @Test + public void pdo_maxvalue() throws Exception { + + try { + + String filename = testFileDir + "/MQP1I1_[65]_2320ms.xml"; + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderTargetEPR).sendReceive(requestElement); + + String patientSetId = null; + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull("Did not get masterInstanceResult", masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENTSET")) + { + assertEquals(results.getSetSize(), 65); + patientSetId = results.getResultInstanceId(); + } + } + + + filename = testFileDir + "/pdo_maxvalue.xml"; + assertNotNull("Did not get Patientsetid", patientSetId); + + requestString = getQueryString(filename); + requestString = requestString.replace("{patientSetId}", patientSetId); + requestElement = convertStringToOMElement(requestString); + responseElement = getServiceClient(pdoTargetEPR).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + r = (ResponseMessageType)responseJaxb.getValue(); + helper = new JAXBUnWrapHelper(); + + + + PatientDataResponseType patientDataResponseType = (PatientDataResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),PatientDataResponseType.class); + //StatusType.Condition condition = patientDataResponseType.getStatus().getCondition().get(0); + //assertEquals(condition.getType(),"DONE","checking crc message status 'DONE'"); + assertTrue("checking patient set size > 0 ",patientDataResponseType.getPatientData().getPatientSet().getPatient().size()>0); + + boolean found = false; + for (ObservationType results : patientDataResponseType.getPatientData().getObservationSet().get(0).getObservation() ) + { + + if (results.getPatientId().getValue().equals("1000000003") && results.getEventId().getValue().equals("474080") && + results.getConceptCd().getValue().equals("LOINC:2086-7")) + { + found = true; + if (results.getNvalNum().getValue().toPlainString().equals("46")) + assertEquals("Checking patient 100000003", results.getNvalNum().getValue().toPlainString(), "46"); + else + assertEquals("Checking patient 100000003", results.getNvalNum().getValue().toPlainString(), "46.00000"); + } + } + assertTrue(found); + + } catch (Exception e) { + System.out.println("Error in maxvalue:" + e.getMessage()); + + e.printStackTrace(); + assertTrue(false); + } + } + + + + @Test + public void pdo_firstvalue_modtfalse() throws Exception { + try { + + String filename = testFileDir + "/MQP1I1_[65]_2320ms.xml"; + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderTargetEPR).sendReceive(requestElement); + + String patientSetId = null; + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull("Did not get masterInstanceResult", masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENTSET")) + { + assertEquals(results.getSetSize(), 65); + patientSetId = results.getResultInstanceId(); + } + } + + assertNotNull("Did not get Patientsetid", patientSetId); + + filename = testFileDir + "/pdo_firstvalue_modtfalse.xml"; + + requestString = getQueryString(filename); + requestString = requestString.replace("{patientSetId}", patientSetId); + + requestElement = convertStringToOMElement(requestString); + responseElement = getServiceClient(pdoTargetEPR).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + r = (ResponseMessageType)responseJaxb.getValue(); + helper = new JAXBUnWrapHelper(); + + + + PatientDataResponseType patientDataResponseType = (PatientDataResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),PatientDataResponseType.class); + //StatusType.Condition condition = patientDataResponseType.getStatus().getCondition().get(0); + //assertEquals(condition.getType(),"DONE","checking crc message status 'DONE'"); + assertTrue("checking patient set size > 0 ",patientDataResponseType.getPatientData().getPatientSet().getPatient().size()>0); + System.out.println(patientDataResponseType.getPatientData().getObservationSet().get(0).getObservation().get(0).getPatientId().getSource()); + + boolean found = false; + for (ObservationType results : patientDataResponseType.getPatientData().getObservationSet().get(0).getObservation() ) + { + if (results.getPatientId().getValue().equals("1000000003")) + { + found = true; + assertEquals("Checking patient 1000000003", results.getStartDate().toString(), "1997-11-26T00:00:00.000-05:00"); + } + if (found) + break; + } + assertTrue("Did not find patient 1000000003", found); + + } catch (Exception e) { + System.out.println("Error in modtfalse:" + e.getMessage()); + + e.printStackTrace(); + assertTrue(false); + } + } + + + @Test + public void pdo_lastvalue_modtfalse() throws Exception { + try { + String filename = testFileDir + "/MQP1I1_[65]_2320ms.xml"; + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderTargetEPR).sendReceive(requestElement); + String patientSetId = null; + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull("Did not get masterInstanceResult", masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENTSET")) + { + assertEquals(results.getSetSize(), 65); + patientSetId = results.getResultInstanceId(); + } + } + + assertNotNull("Did not get Patientsetid", patientSetId); + + filename = testFileDir + "/pdo_lastvalue_modfalse.xml"; + requestString = getQueryString(filename); + requestString = requestString.replace("{patientSetId}", patientSetId); + + requestElement = convertStringToOMElement(requestString); + responseElement = getServiceClient(pdoTargetEPR).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + r = (ResponseMessageType)responseJaxb.getValue(); + helper = new JAXBUnWrapHelper(); + + + + PatientDataResponseType patientDataResponseType = (PatientDataResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),PatientDataResponseType.class); + //StatusType.Condition condition = patientDataResponseType.getStatus().getCondition().get(0); + //assertEquals(condition.getType(),"DONE","checking crc message status 'DONE'"); + assertTrue("checking patient set size > 0 ",patientDataResponseType.getPatientData().getPatientSet().getPatient().size()>0); + System.out.println(patientDataResponseType.getPatientData().getObservationSet().get(0).getObservation().get(0).getPatientId().getSource()); + + boolean found = false; + for (ObservationType results : patientDataResponseType.getPatientData().getObservationSet().get(0).getObservation() ) + { + if (results.getPatientId().getValue().equals("1000000003") && results.getConceptCd().getValue().equals("LOINC:2090-9")) + { + found = true; + assertEquals("Checking patient 1000000003", results.getStartDate().toString(), "2005-12-09T00:00:00.000-05:00"); + } + if (found) + break; + + } + assertTrue(found); + + } catch (Exception e) { + System.out.println("Error in lastmodtfalse:" + e.getMessage()); + + e.printStackTrace(); + assertTrue(false); + } + } + + + +} diff --git a/edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/axis2/SetfinderQueryTest.java b/edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/axis2/SetfinderQueryTest.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/axis2/SetfinderQueryTest.java rename to edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/axis2/SetfinderQueryTest.java index 12160ebf..58f164df --- a/edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/axis2/SetfinderQueryTest.java +++ b/edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/axis2/SetfinderQueryTest.java @@ -1,7594 +1,7594 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.crc.axis2; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import org.junit.runner.JUnitCore; -import org.junit.experimental.ParallelComputer; - -import java.io.ByteArrayInputStream; -import java.io.DataInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Arrays; - -import jakarta.xml.bind.JAXBElement; - -import junit.framework.JUnit4TestAdapter; - -import org.apache.axiom.om.OMElement; -import org.junit.BeforeClass; -import org.junit.Test; - -import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestHeaderType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.CrcXmlResultResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterInstanceResultResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory; -import edu.harvard.i2b2.crc.datavo.setfinder.query.PsmQryHeaderType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryInstanceType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryMasterType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryResultInstanceType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.RequestType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultResponseType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.XmlResultType; - -/** - * Class to test different setfinder request's - * @author rkuttan - */ -public class SetfinderQueryTest extends CRCAxisAbstract { - - private static QueryMasterType queryMaster = null; - private static QueryInstanceType queryInstance = null; - private static MasterInstanceResultResponseType masterInstanceResult = null; - private static String testFileDir = null; - - private static String setfinderUrl = null; - private static String nameInfoUrl = null; - - - @BeforeClass - public static void setUp() throws Exception { - String host = (System.getProperty("testhost") == null ? "http://127.0.0.1:9090/i2b2/services" : System.getProperty("testhost") ) ; - setfinderUrl = - host + "/QueryToolService/request"; - nameInfoUrl = - host + "/QueryToolService/getNameInfo"; - - testFileDir = "testfiles"; //System.getProperty("testfiledir"); - System.out.println("test file dir " + testFileDir); - - if (!((testFileDir != null) && (testFileDir.trim().length() > 0))) { - throw new Exception( - "please provide test file directory info -Dtestfiledir"); - } - - } - - - - - - public static junit.framework.Test suite() { - return new JUnit4TestAdapter(SetfinderQueryTest.class); - } - - public static RequestHeaderType generateRequestHeader() { - RequestHeaderType reqHeaderType = new RequestHeaderType(); - reqHeaderType.setResultWaittimeMs(90000); - return reqHeaderType; - } - - - @Test - public void breakdownNoninvert7panel1itemInvert8panel1item() throws Exception { - String filename = testFileDir + "/breakdown_noninvert_7panel_1item_invert_8panel_1item_[1]_12200ms.xml"; - try { - DataInputStream dataStream = new DataInputStream(new FileInputStream( - filename)); - OMElement requestElement = convertStringToOMElement(dataStream); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - String queryMasterId = masterInstanceResult.getQueryMaster().getQueryMasterId(); - - // First Query In Query - String requestString = getQueryString(testFileDir + "/CRC_QRY_getQueryInstanceList_fromQueryMasterId.xml"); - requestString = requestString.replace("masterid:32958", queryMasterId); - - requestElement = convertStringToOMElement(requestString); - responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - r = (ResponseMessageType)responseJaxb.getValue(); - helper = new JAXBUnWrapHelper(); - - InstanceResponseType instanceResults = (InstanceResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),InstanceResponseType.class); - - assertNotNull(instanceResults); - QueryInstanceType results = instanceResults.getQueryInstance().get(0); - String instanceId = results.getQueryInstanceId(); - - - - - // Get result Instance ID - requestString = getQueryString(testFileDir + "/CRC_QRY_getQueryResultInstanceList_fromQueryInstanceId.xml"); - requestString = requestString.replace("instanceid:32978", instanceId); - - requestElement = convertStringToOMElement(requestString); - responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - r = (ResponseMessageType)responseJaxb.getValue(); - helper = new JAXBUnWrapHelper(); - - ResultResponseType resultResponse = (ResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),ResultResponseType.class); - - assertNotNull(resultResponse); - String resultInstanceId = null; - for (QueryResultInstanceType results2 :resultResponse.getQueryResultInstance() ) - { - resultInstanceId = results2.getResultInstanceId(); - } - - assertNotNull(resultInstanceId); - - // Get result XML - requestString = getQueryString(testFileDir + "/CRC_QRY_getResultDocument_fromResultInstanceId.xml"); - requestString = requestString.replace("instaneid:67572", resultInstanceId); - - requestElement = convertStringToOMElement(requestString); - responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - r = (ResponseMessageType)responseJaxb.getValue(); - helper = new JAXBUnWrapHelper(); - - CrcXmlResultResponseType xmlResponse = (CrcXmlResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),CrcXmlResultResponseType.class); - - assertNotNull(xmlResponse); - XmlResultType results3 = xmlResponse.getCrcXmlResult(); - - - if (results3.getXmlValue().getContent().get(0).toString().contains("xml")) - assert (true); - else - assert(false); - - // Check invalid id - requestString = getQueryString(testFileDir + "/CRC_QRY_getResultDocument_fromResultInstanceId.xml"); - requestString = requestString.replace("instaneid:67572", "67572"); - - requestElement = convertStringToOMElement(requestString); - responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - r = (ResponseMessageType)responseJaxb.getValue(); - helper = new JAXBUnWrapHelper(); - - - xmlResponse = (CrcXmlResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),CrcXmlResultResponseType.class); - - assertEquals(xmlResponse.getStatus().getCondition().get(0).getType(), "ERROR"); - - - - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void QueryInQueryCKMB_OR() throws Exception { - String filename = testFileDir + "/4Q_CK-MB_OR_CPKGT120_[38].xml"; - try { - DataInputStream dataStream = new DataInputStream(new FileInputStream( - filename)); - OMElement requestElement = convertStringToOMElement(dataStream); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - String queryMasterId = masterInstanceResult.getQueryMaster().getQueryMasterId(); - - // First Query In Query - String requestString = getQueryString(testFileDir + "/QIQ_4Q_MALE_[28].xml"); - requestString = requestString.replace("masterid:431", "masterid:"+queryMasterId); - - requestElement = convertStringToOMElement(requestString); - responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - r = (ResponseMessageType)responseJaxb.getValue(); - helper = new JAXBUnWrapHelper(); - - masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 28); - else - assertTrue(false); - } - - - // Second Query In Query - requestString = getQueryString(testFileDir + "/QIQ_4Q_FEMALE_[10].xml"); - requestString = requestString.replace("masterid:431", "masterid:"+queryMasterId); - - requestElement = convertStringToOMElement(requestString); - responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - r = (ResponseMessageType)responseJaxb.getValue(); - helper = new JAXBUnWrapHelper(); - - masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 10); - else - assertTrue(false); - } - - - - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - - @Test - public void QueryInQueryCKMB() throws Exception { - String filename = testFileDir + "/3Q_CK-MB_AND_CPKGT120_[16].xml"; - try { - DataInputStream dataStream = new DataInputStream(new FileInputStream( - filename)); - OMElement requestElement = convertStringToOMElement(dataStream); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - String queryMasterId = masterInstanceResult.getQueryMaster().getQueryMasterId(); - - // First Query In Query - String requestString = getQueryString(testFileDir + "/QIQ_3Q_MALE_[12].xml"); - requestString = requestString.replace("masterid:427", "masterid:"+queryMasterId); - - requestElement = convertStringToOMElement(requestString); - responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - r = (ResponseMessageType)responseJaxb.getValue(); - helper = new JAXBUnWrapHelper(); - - masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 12); - else - assertTrue(false); - } - - - // Second Query In Query - requestString = getQueryString(testFileDir + "/QIQ_3Q_FEMALE_[4].xml"); - requestString = requestString.replace("masterid:427", "masterid:"+queryMasterId); - - requestElement = convertStringToOMElement(requestString); - responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - r = (ResponseMessageType)responseJaxb.getValue(); - helper = new JAXBUnWrapHelper(); - - masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 4); - else - assertTrue(false); - } - - - - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - - @Test - public void QueryInQueryHypertensionOR() throws Exception { - String filename = testFileDir + "/2Q_HYP_OR_ISCH_[44].xml"; - try { - DataInputStream dataStream = new DataInputStream(new FileInputStream( - filename)); - OMElement requestElement = convertStringToOMElement(dataStream); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - String queryMasterId = masterInstanceResult.getQueryMaster().getQueryMasterId(); - - // First Query In Query - String requestString = getQueryString(testFileDir + "/QIQ_2Q_MALE_[26].xml"); - requestString = requestString.replace("masterid:424", "masterid:"+queryMasterId); - - requestElement = convertStringToOMElement(requestString); - responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - r = (ResponseMessageType)responseJaxb.getValue(); - helper = new JAXBUnWrapHelper(); - - masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 26); - else - assertTrue(false); - } - - - // Second Query In Query - requestString = getQueryString(testFileDir + "/QIQ_2Q_FEMALE_[18].xml"); - requestString = requestString.replace("masterid:424", "masterid:"+queryMasterId); - - requestElement = convertStringToOMElement(requestString); - responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - r = (ResponseMessageType)responseJaxb.getValue(); - helper = new JAXBUnWrapHelper(); - - masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 18); - else - assertTrue(false); - } - - - - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - - @Test - public void QueryInQueryHypertension() throws Exception { - String filename = testFileDir + "/1Q_HYP_AND_ISCH_[13].xml"; - try { - DataInputStream dataStream = new DataInputStream(new FileInputStream( - filename)); - OMElement requestElement = convertStringToOMElement(dataStream); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - String queryMasterId = masterInstanceResult.getQueryMaster().getQueryMasterId(); - - // First Query In Query - String requestString = getQueryString(testFileDir + "/QIQ_1Q_MALE_[6].xml"); - requestString = requestString.replace("masterid:421", "masterid:"+queryMasterId); - - requestElement = convertStringToOMElement(requestString); - responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - r = (ResponseMessageType)responseJaxb.getValue(); - helper = new JAXBUnWrapHelper(); - - masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 6); - else - assertTrue(false); - } - - - // Second Query In Query - requestString = getQueryString(testFileDir + "/QIQ_1Q_FEMALE_[7].xml"); - requestString = requestString.replace("masterid:421", "masterid:"+queryMasterId); - - requestElement = convertStringToOMElement(requestString); - responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - r = (ResponseMessageType)responseJaxb.getValue(); - helper = new JAXBUnWrapHelper(); - - masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 7); - else - assertTrue(false); - } - - - - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void getNameInfoContains() throws Exception { - String filename = testFileDir + "/getNameInfo_contains.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(nameInfoUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterResponseType masterInstanceResult = (MasterResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryMasterType results :masterInstanceResult.getQueryMaster() ) - { - if (results.getName().contains("Hyperte")) - assertTrue(true); - else - assertTrue(false); - } - - //Check with Previous Query - requestString = getQueryString(filename); - requestString = requestString.replace("category=\"@\"", "category=\"top\""); - requestElement = convertStringToOMElement(requestString); - responseElement = getServiceClient(nameInfoUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - r = (ResponseMessageType)responseJaxb.getValue(); - helper = new JAXBUnWrapHelper(); - - masterInstanceResult = (MasterResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryMasterType results :masterInstanceResult.getQueryMaster() ) - { - if (results.getName().contains("Hyperte")) - assertTrue(true); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - - @Test - public void getNameInfoEndwith() throws Exception { - String filename = testFileDir + "/getNameInfo_endwith.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(nameInfoUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterResponseType masterInstanceResult = (MasterResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryMasterType results :masterInstanceResult.getQueryMaster() ) - { - if (results.getName().endsWith("10:24:10")) - assertTrue(true); - else - assertTrue(false); - } - //Check with Previous Query - requestString = getQueryString(filename); - requestString = requestString.replace("category=\"@\"", "category=\"top\""); - requestElement = convertStringToOMElement(requestString); - responseElement = getServiceClient(nameInfoUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - r = (ResponseMessageType)responseJaxb.getValue(); - helper = new JAXBUnWrapHelper(); - - masterInstanceResult = (MasterResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryMasterType results :masterInstanceResult.getQueryMaster() ) - { - if (results.getName().endsWith("10:24:10")) - assertTrue(true); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void getNameInfoStartWith() throws Exception { - String filename = testFileDir + "/getNameInfo_startwith.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(nameInfoUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterResponseType masterInstanceResult = (MasterResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryMasterType results :masterInstanceResult.getQueryMaster() ) - { - if (results.getName().startsWith("(PrevQu-Female")) - assertTrue(true); - else - assertTrue(false); - } - //Check with Previous Query - requestString = getQueryString(filename); - requestString = requestString.replace("category=\"@\"", "category=\"top\""); - requestElement = convertStringToOMElement(requestString); - responseElement = getServiceClient(nameInfoUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - r = (ResponseMessageType)responseJaxb.getValue(); - helper = new JAXBUnWrapHelper(); - - masterInstanceResult = (MasterResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryMasterType results :masterInstanceResult.getQueryMaster() ) - { - if (results.getName().startsWith("(PrevQu-Female")) - assertTrue(true); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void getNameInfoExact() throws Exception { - String filename = testFileDir + "/getNameInfo_exact.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(nameInfoUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterResponseType masterInstanceResult = (MasterResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryMasterType results :masterInstanceResult.getQueryMaster() ) - { - if (results.getName().endsWith("(PrevQu-Female@10:24:10")) - assertTrue(true); - else - assertTrue(false); - } - //Check with Previous Query - requestString = getQueryString(filename); - requestString = requestString.replace("category=\"@\"", "category=\"top\""); - requestElement = convertStringToOMElement(requestString); - responseElement = getServiceClient(nameInfoUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - r = (ResponseMessageType)responseJaxb.getValue(); - helper = new JAXBUnWrapHelper(); - - masterInstanceResult = (MasterResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryMasterType results :masterInstanceResult.getQueryMaster() ) - { - if (results.getName().endsWith("(PrevQu-Female@10:24:10")) - assertTrue(true); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - - @Test - public void ExcludeOccurancesMultiplePanelsSame() throws Exception { - String filename = testFileDir + "/setfinder_exclude_and_occurances_same_[63]_1432ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 99); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void ExcludeOccurancesMultiplePanelsSameParallel() throws Exception { - Class[] cls = { JunitRunA.class, JunitRunB.class, JunitRunC.class, JunitRunD.class, JunitRunE.class }; - - // Parallel among classes - JUnitCore.runClasses(ParallelComputer.classes(), cls); - - // Parallel among methods in a class - JUnitCore.runClasses(ParallelComputer.methods(), cls); - - // Parallel all methods in all classes - JUnitCore.runClasses(new ParallelComputer(true, true), cls); - } - - @Test - public void ExcludeOccurancesMultiplePanelsAny() throws Exception { - String filename = testFileDir + "/setfinder_exclude_and_occurances_any_[63]_1432ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 63); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - - @Test - public void TestOObfuscatedLoockout() throws Exception { - String filename = testFileDir + "/obfuscated_lockout.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - - //read test file and store query instance ; - //unmarshall this response string - String lockout = ""; - ArrayList list = new ArrayList(); - for (int i=0; i < 14; i++) { - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - //MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - System.out.println("Query:"+ i); - //assertNotNull(masterInstanceResult); - - //if (r.getResponseHeader().getResultStatus().getStatus().getType().equals("ERROR")) - //{ - // lockout = r.getResponseHeader().getResultStatus().getStatus().getValue(); - //} else - - if (r != null) { - // assertNotNull(masterInstanceResult); - // for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - // { - if (r.getResponseHeader().getResultStatus().getStatus().getType().equals("ERROR")) - { - lockout = r.getResponseHeader().getResultStatus().getStatus().getValue(); - break; - } - - // if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - // { - // if (!list.contains(results.getSetSize())) - // list.add(results.getSetSize()); - // } - // } - } - } - //assertTrue(list.size() > 3); - assertTrue(lockout.startsWith("LOCKEDOUT")); - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - /* - @Test - public void Panel1Item3Missing() throws Exception { - String filename = testFileDir + "/setfinder_panel_1_item_3_missing_[Error].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - - - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 1); - else - assertTrue(false); - } - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - */ - /* - @Test - public void QueryOver50000() throws Exception { - String filename = testFileDir + "/SQP1I1_Circulatory_[66]_3016ms.xml"; - try { - for (int i=0; i < 50000; i++) { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 66); - else - assertTrue(false); - System.out.println("Query number: " + i + " total number is " +results.getSetSize()); - } - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - */ - - - @Test - public void QueryLargeTextConstaintwithSpace() throws Exception { - String filename = testFileDir + "/setfinder_query_largetextconstraint_withspace_[18]_1200ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - { - if (results.getSetSize() == 18) - assertEquals(results.getSetSize(), 18); - else if (results.getSetSize() == 19) - assertEquals(results.getSetSize(), 19); - else - assertTrue(false); - } - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void MQP1I1P2I13() throws Exception { - String filename = testFileDir + "/MQP1I1P2I1_[48]_6658ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 48); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void getInvertPanel1Items1() throws Exception { - String filename = testFileDir + "/setfinder_invert_1panel_1item_[94]_5800ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 94); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - - - @Test - public void QueryNumericConstraintGreaterThan() throws Exception { - String filename = testFileDir + "/setfinder_query_numericconstraint_greatthan_[103]_2100ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 103); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - - @Test - public void DateContraintEnddateBetween() throws Exception { - String filename = testFileDir + "/setfinder_dateconstraint_enddate_between_[1].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 1); - else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) - assertEquals(results.getSetSize(), 1); - else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) - assertEquals(results.getSetSize(), 1); - else if (results.getQueryResultType().getName().equals("PATIENTSET")) - assertEquals(results.getSetSize(), 1); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - - - @Test - public void CQEx_circDigestNeuro() throws Exception { - String filename = testFileDir + "/CQEx_circDigestNeuro_[14]_21704ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 14); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void TQQemptyStringPSI() throws Exception { - String filename = testFileDir + "/TQQemptyStringPSI_[0]_4570ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 0); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - - - @Test - public void TQNoQueryTimingPSI() throws Exception { - // Will default to ANY and should cause a error - String filename = testFileDir + "/TQNoQueryTimingPSI_[0]_557ms.xml"; - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 0); - else - assertTrue(false); - } - } - - - - @Test - public void TQQAPASI() throws Exception { - String filename = testFileDir + "/TQQAPASI_[Error]_659ms.xml"; - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - - - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 7); - else - assertTrue(false); - } - } - - - @Test - public void TQQSIPSI3() throws Exception { - String filename = testFileDir + "/TQQSIPSI-a_[0]_557ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 0); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - - @Test - public void TQNoQueryTimingPAny() throws Exception { - // Will default to ANY and should cause a error - String filename = testFileDir + "/TQNoQueryTimingPAny_[18]_6057ms.xml"; - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 18); - else - assertTrue(false); - } - } - - - @Test - public void TQQemptyStringPSV() throws Exception { - String filename = testFileDir + "/TQQemptyStringPSV_[18]_630msxml.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 18); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - - - @Test - public void PanelTimingSameMissingQueryTiming() throws Exception { - // Will default to ANY and should cause a error - String filename = testFileDir + "/setfinder_paneltiming_same_[133].xml"; - // try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 133); - } - } - - @Test - public void TQQSIPSISVc() throws Exception { - String filename = testFileDir + "/TQQSIPSISV-c_[0]_4105ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 0); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - - - @Test - public void Panel4Item3Missing() throws Exception { - String filename = testFileDir + "/setfinder_panel_4_item_3_missing_[1].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - - int size = -2; - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - size = results.getSetSize(); - } - //assertEquals(size, 1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void TextconstraintIN() throws Exception { - String filename = testFileDir + "/setfinder_query_textconstraint_IN_[0].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 0); - else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) - assertEquals(results.getSetSize(), 0); - else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) - assertEquals(results.getSetSize(), 0); - else if (results.getQueryResultType().getName().equals("PATIENTSET")) - assertEquals(results.getSetSize(), 0); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - - /* For post 1.6.03 - @Test - public void NumberConstraintNotEqual() throws Exception { - String filename = testFileDir + "/setfinder_numberconstraint_NE.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 0); - else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) - assertEquals(results.getSetSize(), 0); - else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) - assertEquals(results.getSetSize(), 0); - else if (results.getQueryResultType().getName().equals("PATIENTSET")) - assertEquals(results.getSetSize(), 0); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - */ - - @Test - public void TQQemptyStringPEmptyString() throws Exception { - String filename = testFileDir + "/TQQemptyStringPEmptyString_[18]_4994ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 18); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void TQQAPSV() throws Exception { - String filename = testFileDir + "/TQQAPSV_[Error]_646ms.xml"; - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - - - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 18); - else - assertTrue(false); - } - - } - - @Test - public void TQQemptyStringPAny() throws Exception { - String filename = testFileDir + "/TQQemptyStringPAny_[18]_603ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 18); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - - public void TQQAPSI() throws Exception { - String filename = testFileDir + "/TQQAPSI_[Error]_4654ms.xml"; - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - - - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 0); - else - assertTrue(false); - } - - } - - @Test - public void TQNoQueryOrPanelTiming() throws Exception { - String filename = testFileDir + "/TQNoQueryOrPanelTiming_[18]_6057ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 18); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void TQNoQueryTimingPSV() throws Exception { - String filename = testFileDir + "/TQNoQueryTimingPSV_[18]_6490ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 18); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void TQQSIPSV() throws Exception { - String filename = testFileDir + "/TQQSIPSV_[18]_4491ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 18); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - - - @Test - public void MQDtBtw() throws Exception { - String filename = testFileDir + "/MQDtBtw_[4]_3006ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 4); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void MQDtBtw2() throws Exception { - String filename = testFileDir + "/MQDtBtw2_[4]_3006ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 4); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void MQDtBtw3() throws Exception { - String filename = testFileDir + "/MQDtBtw3_[4]_3006ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 4); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void MQDtBtw4() throws Exception { - String filename = testFileDir + "/MQDtBtw4_[4]_3006ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 4); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void MQP1I1() throws Exception { - String filename = testFileDir + "/MQP1I1_[31]_3207ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 31); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void TQQSVPSV2() throws Exception { - String filename = testFileDir + "/TQQSVPSV_[4]_4578ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 4); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void MQP1I1P2I1() throws Exception { - String filename = testFileDir + "/MQP1I1P2I1_[1]_3135ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 1); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void MQP1I12() throws Exception { - String filename = testFileDir + "/MQP1I1_[48]_2005ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 48); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void TQQSVPSV3() throws Exception { - String filename = testFileDir + "/TQQSVPSV_[5]_5800ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 5); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void MQP1I1P2I12() throws Exception { - String filename = testFileDir + "/MQP1I1P2I1_[10]_3013ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 10); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void MQP1I1b() throws Exception { - String filename = testFileDir + "/MQP1I1-b_[8]_1855ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 8); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - public void TQQSVPSVb() throws Exception { - String filename = testFileDir + "/TQQSVPSV-b_[5]_5761ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 5); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void MQP1I2() throws Exception { - String filename = testFileDir + "/MQP1I1_[13]_1903ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 13); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void MQValEnmMV() throws Exception { - String filename = testFileDir + "/MQValEnmMV_[14]_1877ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 14); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void MQP1I13() throws Exception { - String filename = testFileDir + "/MQP1I1_[1]_1861ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 1); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void MQFolderf() throws Exception { - String filename = testFileDir + "/MQFolder-f_[3]_1882ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 3); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void MQFolderc() throws Exception { - String filename = testFileDir + "/MQFolder-c_[3]_1893ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 3); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void TQQSIPASI() throws Exception { - String filename = testFileDir + "/TQQSIPASI_[5]_4492ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 5); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void TQQSVPSV4() throws Exception { - String filename = testFileDir + "/TQQSVPSV_[17]_5659ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 17); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void MQFolderd() throws Exception { - String filename = testFileDir + "/MQFolder-d_[3]_3206ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 3); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void MQP1I1P2I14() throws Exception { - String filename = testFileDir + "/MQP1I1P2I1_[6]_1919ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 6); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void MQP1I14() throws Exception { - String filename = testFileDir + "/MQP1I1_[70]_1997ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 70); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void MQP1I2P2I2() throws Exception { - String filename = testFileDir + "/MQP1I2P2I2_[73]_12585ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 73); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void MQP1I1P2I15() throws Exception { - String filename = testFileDir + "/MQP1I1P2I1_[3]_5145ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 3); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void MQP1I15() throws Exception { - String filename = testFileDir + "/MQP1I1_[7]_1908ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 7); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void MQP1I1P2I16() throws Exception { - String filename = testFileDir + "/MQP1I1P2I1_[7]_3563ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 7); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void MQValNumLT() throws Exception { - String filename = testFileDir + "/MQValNumLT_[19]_1896.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 19); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void MQP1I22() throws Exception { - String filename = testFileDir + "/MQP1I2_[32]_2969ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 32); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void MQP1I16() throws Exception { - String filename = testFileDir + "/MQP1I1_[16]_1879ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 16); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void MQExValNumLTandGTEandE() throws Exception { - String filename = testFileDir + "/MQExValNumLTandGTEandE_[7]_4389ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 7); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void MQFoldere() throws Exception { - String filename = testFileDir + "/MQFolder-e_[3]_1882ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 3); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void MQP1I17() throws Exception { - String filename = testFileDir + "/MQP1I1_[5]_3237ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 5); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void MQP1I18() throws Exception { - String filename = testFileDir + "/MQP1I1_[4]_2348ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 4); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void MQValNumLTandGTEandE() throws Exception { - String filename = testFileDir + "/MQValNumLTandGTEandE_[9]_4171ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 9); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void MQFolder() throws Exception { - String filename = testFileDir + "/MQFolder-h_[3]_1919ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 3); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void MQFolderb() throws Exception { - String filename = testFileDir + "/MQFolder-b_[2]_1876ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 2); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void MQP1I19() throws Exception { - String filename = testFileDir + "/MQP1I1_[65]_2320ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML") || results.getQueryResultType().getName().equals("PATIENTSET")) - assertEquals(results.getSetSize(), 65); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void MQP1I1P2I1P3I1() throws Exception { - String filename = testFileDir + "/MQP1I1P2I1P3I1_[3]_4523ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 3); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void MQP1I1b2() throws Exception { - String filename = testFileDir + "/MQP1I1-b_[6]_1896ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 6); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void MQP1I110() throws Exception { - String filename = testFileDir + "/MQP1I1_[54]_1984ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 54); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void TQQSIPSI() throws Exception { - String filename = testFileDir + "/TQQSIPSI_[0]_3117ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 0); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void MQP1I11() throws Exception { - String filename = testFileDir + "/MQP1I1_[89]_1895ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 89); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void MQDtFrom() throws Exception { - String filename = testFileDir + "/MQDtFrom_[3]_2988ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 3); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void MQValNumLTandEnm() throws Exception { - String filename = testFileDir + "/MQValNumLTandEnm_[6]_3109ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 6); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void MQFolder2() throws Exception { - String filename = testFileDir + "/MQFolder_[14]_1876ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 14); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void MQValNumLTandGTE() throws Exception { - String filename = testFileDir + "/MQValNumLTandGTE_[9]_4454ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 9); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void MQFolder3() throws Exception { - String filename = testFileDir + "/MQFolder-g_[2]_1866ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 2); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void MQP1I3() throws Exception { - String filename = testFileDir + "/MQP1I3_[5]_6018ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 5); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void TQQSIPSI2() throws Exception { - String filename = testFileDir + "/TQQSIPSI_[17]_4310ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 17); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void MQValEnmMV2() throws Exception { - String filename = testFileDir + "/MQValEnmMV_[8]_4578ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 8); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void MQValNumLTandEnm2() throws Exception { - String filename = testFileDir + "/MQValNumLTandEnm_[17]_5758ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 17); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void MQFolderb2() throws Exception { - String filename = testFileDir + "/MQFolder-i_[3]_1866ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 3); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void MQP1I111() throws Exception { - String filename = testFileDir + "/MQP1I1_[12]_3298ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 12); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void MQValNumLTandEnm3() throws Exception { - String filename = testFileDir + "/MQValNumLTandEnm_[5]_4585ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 5); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void TQQSVPSV5() throws Exception { - String filename = testFileDir + "/TQQSVPSV_[0]_3557ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 0); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void MQP1I112() throws Exception { - String filename = testFileDir + "/MQP1I1_[58]_1893ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 58); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void MQDtTo() throws Exception { - String filename = testFileDir + "/MQDtTo_[1]_4371ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 1); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void TQQSVPSV6() throws Exception { - String filename = testFileDir + "/TQQSVPSV_[3]_4944ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 3); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void MQValEnmMV3() throws Exception { - String filename = testFileDir + "/MQValEnmMV_[6]_2580ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 6); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void MQP1I1b3() throws Exception { - String filename = testFileDir + "/MQP1I1-b_[7]_1904ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 7); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void TQQSIPSIb() throws Exception { - String filename = testFileDir + "/TQQSIPSI-b_[0]_5704ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 0); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void MQP1I113() throws Exception { - String filename = testFileDir + "/MQP1I1_[17]_1915ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 17); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void MQP1I114() throws Exception { - String filename = testFileDir + "/MQP1I1_[8]_3276ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 8); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void MQP1I1P2I1P3I11() throws Exception { - String filename = testFileDir + "/MQP1I1P2I1P3I1_[2]_5653ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 2); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void TQQSVPSV12() throws Exception { - String filename = testFileDir + "/TQQSVPSV_[111]_3098ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 111); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void MQP1I115() throws Exception { - String filename = testFileDir + "/MQP1I1_[6]_1912ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 6); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - - - @Test - public void TQQSIPSISV() throws Exception { - String filename = testFileDir + "/TQQSIPSISV_[18]_4491ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 18); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - - - - @Test - public void TQQSIPASI2() throws Exception { - String filename = testFileDir + "/TQQSIPASI_[18]_4681ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 18); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - - @Test - public void MQQSVPSV() throws Exception { - String filename = testFileDir + "/MQQSVPSV_[18]_5254ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 18); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - - @Test - public void TQQSVPASV2() throws Exception { - String filename = testFileDir + "/TQQSVPASV_[18]_6805ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 18); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void TQQSIPSISVb() throws Exception { - String filename = testFileDir + "/TQQSIPSISV-b_[18]_5873ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 18); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - - - @Test - public void TQQSVPASI() throws Exception { - // Will default to ANY and should cause a error - String filename = testFileDir + "/TQQSVPASI_[Error]_6793ms.xml"; - // try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - - - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 18); - else - assertTrue(false); - } - } - - - /* - @Test - public void PanelTimingSameInstancenumMissingQueryTiming() throws Exception { - // Will default to ANY and should cause a error - String filename = testFileDir + "/setfinder_paneltiming_sameinstancenum_[Error].xml"; - // try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - - - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 133); - else - assertTrue(false); - } - - // } catch (Exception e) { - // e.printStackTrace(); - // throw e; - // } - } - - */ - @Test - public void QueryTimingSame() throws Exception { - String filename = testFileDir + "/setfinder_querytiming_same_[133].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 133); - else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) - assertEquals(results.getSetSize(), 133); - else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) - assertEquals(results.getSetSize(), 133); - else if (results.getQueryResultType().getName().equals("PATIENTSET")) - assertEquals(results.getSetSize(), 133); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void TextconstraintBetween() throws Exception { - String filename = testFileDir + "/setfinder_query_textconstraint_BETWEEN_[error].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - assertEquals(masterInstanceResult.getQueryInstance().getQueryStatusType().getName(), "ERROR"); - - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void Panel4Item3() throws Exception { - String filename = testFileDir + "/setfinder_panel_4_item_3_[1].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 1); - else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) - assertEquals(results.getSetSize(), 1); - else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) - assertEquals(results.getSetSize(), 1); - else if (results.getQueryResultType().getName().equals("PATIENTSET")) - assertEquals(results.getSetSize(), 1); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void InvertWithItem() throws Exception { - String filename = testFileDir + "/setfinder_invert_withitem_[1].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 1); - else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) - assertEquals(results.getSetSize(), 1); - else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) - assertEquals(results.getSetSize(), 1); - else if (results.getQueryResultType().getName().equals("PATIENTSET")) - assertEquals(results.getSetSize(), 1); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void QueryNumericConstraintBetween() throws Exception { - String filename = testFileDir + "/setfinder_query_numericconstraint_between_[9]_2800ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 9); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void QueryNumericConstraintEqual() throws Exception { - String filename = testFileDir + "/setfinder_query_numericconstraint_eq_[3]_2300ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 3); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - - @Test - public void QuerySmallTextConstraintLessThan() throws Exception { - String filename = testFileDir + "/setfinder_query_numericconstraint_lessthan_[6]_2100ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 6); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void QuerySmallTextConstraintBegin() throws Exception { - String filename = testFileDir + "/setfinder_query_smalltextconstraint_begin_[1]_1500ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 1); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - - - @Test - public void QuerySmallTextConstraintEnd() throws Exception { - String filename = testFileDir + "/setfinder_query_smalltextconstraint_end_[1]_1600ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 1); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - - - @Test - public void QuerySmallTextConstraintContains() throws Exception { - String filename = testFileDir + "/setfinder_query_smalltextconstraint_contains_[3]_1400ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 3); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - - - @Test - public void EncounterContraint1() throws Exception { - String filename = testFileDir + "/setfinder_query_enumconstraint_[1]_1700ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 1); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void EncounterContraint2() throws Exception { - String filename = testFileDir + "/setfinder_query_enumconstraint_[3]_1900ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 3); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void EncounterContraint3() throws Exception { - String filename = testFileDir + "/setfinder_query_enumconstraint_[4]_2100ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 4); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void LargeTextContraint() throws Exception { - String filename = testFileDir + "/setfinder_query_largetextconstraint_[10]_1700ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 10); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - - @Test - public void NumericContraintBetween() throws Exception { - String filename = testFileDir + "/setfinder_query_numericconstraint_between_[9]_2800ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 9); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void SmallTextContraintContains() throws Exception { - String filename = testFileDir + "/setfinder_query_smalltextconstraint_contains_[3]_1400ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 3); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - - @Test - public void getPanel1Items2Panel2InvertItem1() throws Exception { - String filename = testFileDir + "/setfinder_pane_1_item_2_panel_2_INV_item_1_[33].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 33); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - - - @Test - public void getInvertPanel1Items2InvertPanel2Item2InvertPanel3Item2() throws Exception { - String filename = testFileDir + "/setfinder_invert_1panel_2item_invert_2panel_2item_invert_3panel_2item_[50]_7000ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 50); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void getInvertPanel1Items2InvertPanel2Item2NonInvertPanel3Item1() throws Exception { - String filename = testFileDir + "/setfinder_invert_1panel_2item_invert_2panel_2item_noninvert_3panel_1item_[6]_6000ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 6); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void getInvertPanel1Items2InvertPanel2Item2NonInvertPanel3Item2() throws Exception { - String filename = testFileDir + "/setfinder_invert_1panel_2item_invert_2panel_2item_noninvert_3panel_2item_[13]_7100ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 13); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void getInvertPanel1Items2InvertPanel2Item2() throws Exception { - String filename = testFileDir + "/setfinder_invert_1panel_2item_invert_2panel_2item_[63]_4100ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 63); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void getInvertPanel1Items2NonInvertPanel2Item1() throws Exception { - String filename = testFileDir + "/setfinder_invert_1panel_2item_noninvert_2panel_1item_[11]_7000ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 11); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void getInvertPanel1Items2NonInvertPanel2Item2() throws Exception { - String filename = testFileDir + "/setfinder_invert_1panel_2item_noninvert_2panel_2item_[20]_6100ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 20); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void getInvertPanel1Items2() throws Exception { - String filename = testFileDir + "/setfinder_invert_1panel_2item_[83]_5300ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 83); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void getNonInvertPanel1Items1InvertPanel2Item2InvertPanel3Item2() throws Exception { - String filename = testFileDir + "/setfinder_noninvert_1panel_1item_invert_2panel_2item_invert_3panel_2item_[6]_6000ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 6); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void getNonInvertPanel1Items2InvertPanel2Item1() throws Exception { - String filename = testFileDir + "/setfinder_noninvert_1panel_2item_invert_2panel_1item_[11]_7000ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 11); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void getNonInvertPanel1Items2InvertPanel2Item2InvertPanel3Item2() throws Exception { - String filename = testFileDir + "/setfinder_noninvert_1panel_2item_invert_2panel_2item_invert_3panel_2item_[13]_7100ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 13); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void getNonInvertPanel1Items2InvertPanel2Item2() throws Exception { - String filename = testFileDir + "/setfinder_noninvert_1panel_2item_invert_2panel_2item_[20]_6100ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 20); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void getNonInvertPanel7Items2InvertPanel8Item1() throws Exception { - String filename = testFileDir + "/setfinder_noninvert_7panel_1item_invert_8panel_1item_[1]_12200ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - { - if (results.getSetSize() == 1 || results.getSetSize() == 2) - assertTrue(true); - //assertEquals(results.getSetSize(), 2); - } - else - { - assertTrue(false); - } - - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void AgePanel1Item1a() throws Exception { - String filename = testFileDir + "/setfinder_age_panel_1_item_1_[20]_4000ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - { - assertTrue("age is to high", 3 >= results.getSetSize()); - assertTrue("age is to low", 0 <= results.getSetSize()); - } - else - { - assertTrue(false); - } - - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void AgePanel1Item1b() throws Exception { - String filename = testFileDir + "/setfinder_age_panel_1_item_1_[14]_5500ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 24); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void AgePanel1Item1c() throws Exception { - String filename = testFileDir + "/setfinder_age_panel_1_item_1_[20]_4000ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - { - assertTrue("age is to high", 3 >= results.getSetSize()); - assertTrue("age is to low", 0 <= results.getSetSize()); - } - else - { - assertTrue(false); - } - - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void AgeVisitPanel2Item1() throws Exception { - String filename = testFileDir + "/setfinder_age_visit_panel_2_item_1_[20]_5900ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - { - assertTrue("age is to high", 3 >= results.getSetSize()); - assertTrue("age is to low", 0 <= results.getSetSize()); - } - else - { - assertTrue(false); - } - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void AgeVisitProviderPanel3Item1() throws Exception { - String filename = testFileDir + "/setfinder_age_visit_prov_panel_3_item_1_[3]_7700ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 0); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void AgeVisitLengthPanel2Item1() throws Exception { - String filename = testFileDir + "/setfinder_age_visitLen_panel_2_item_1_[3]_6100ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 5); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void IncRaceHypTenPanel3Item1() throws Exception { - String filename = testFileDir + "/setfinder_inc_race_HypTen_panel_3_item_2_[9]_9200ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 9); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void IncRacePanel2Item2() throws Exception { - String filename = testFileDir + "/setfinder_inc_race_panel_2_item_2_[26]_6600ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 26); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void IncRacProcedurePanel3Item2() throws Exception { - String filename = testFileDir + "/setfinder_inc_race_Procedure_panel_3_item_2_[1]_9200ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 1); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void IncomePanel1Item1() throws Exception { - String filename = testFileDir + "/setfinder_income_panel_1_item_1_[42]_5200ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 42); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - - @Test - public void SQP1I1_DxMI() throws Exception { - String filename = testFileDir + "/SQP1I1_DxMI_[7]_1625ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 7); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - - @Test - public void MQ_princDx_Diabetes() throws Exception { - String filename = testFileDir + "/MQ_princDx_Diabetes_[2]_2141ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 2); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void MCQValMix_DoseFreqRoute_trimox() throws Exception { - String filename = testFileDir + "/MCQValMix_DoseFreqRoute_trimox_[17]_6516ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 17); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void CQOcrGt5x_IschHrt() throws Exception { - String filename = testFileDir + "/CQOcrGt5x_IschHrt_[2]_1641ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 2); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void CQOcrGt7x_CircSys() throws Exception { - String filename = testFileDir + "/CQOcrGt7x_CircSys_[17]_1672ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 17); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void SQP1I1_Circulatory() throws Exception { - String filename = testFileDir + "/SQP1I1_Circulatory_[66]_3016ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 66); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void CQValFlgH_CPK() throws Exception { - String filename = testFileDir + "/CQValFlgH_CPK_[0]_1657ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 0); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void CQValFlgL_CPK() throws Exception { - String filename = testFileDir + "/CQValFlgL_CPK_[0]_3032ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 0); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void CQValNum_CPK() throws Exception { - String filename = testFileDir + "/CQValNum_CPK_[40]_1610ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 40); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - - @Test - public void CQValNum110_CPK() throws Exception { - String filename = testFileDir + "/CQValNum110_CPK_[3]_1672ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 3); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void CQValNumBtw52_250_CPK() throws Exception { - String filename = testFileDir + "/CQValNumBtw52-250_CPK_[35]_1625ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 35); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void CQValNumGT110_CPK() throws Exception { - String filename = testFileDir + "/CQValNumGT110_CPK_[29]_1625ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 29); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void CQValNumGTE110_CPK() throws Exception { - String filename = testFileDir + "/CQValNumGTE110_CPK_[30]_1625ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 30); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void CQValNumLT110_CPK() throws Exception { - String filename = testFileDir + "/CQValNumLT110_CPK_[16]_1594ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 16); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void CQValNumLTE110_CPK() throws Exception { - String filename = testFileDir + "/CQValNumLTE110_CPK_[17]_3078ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 17); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void MCQValEnmMV_Route() throws Exception { - String filename = testFileDir + "/MCQValEnmMV_Route[63]_2015ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 63); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void MCQValNum_Dose() throws Exception { - String filename = testFileDir + "/MCQValNum_Dose_[18]_2047ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 18); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - - @Test - public void MCQValNumBtw100_900_Dose() throws Exception { - String filename = testFileDir + "/MCQValNumBtw100-900_Dose_[18]_2000ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 18); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void MCQValNumE500_Dose() throws Exception { - String filename = testFileDir + "/MCQValNumE500_Dose_[17]_2047ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 17); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void MCQValNumGT500_Dose() throws Exception { - String filename = testFileDir + "/MCQValNumGT500_Dose_[6]_2047ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 6); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - - @Test - public void MCQValNumGTE500_Dose() throws Exception { - String filename = testFileDir + "/MCQValNumGTE500_Dose_[18]_1984ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 18); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void MCQValNumLT500_Dose() throws Exception { - String filename = testFileDir + "/MCQValNumLT500_Dose_[0]_3391ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 0); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void MCQValNumLTE500_Dose() throws Exception { - String filename = testFileDir + "/MCQValNumLTE500_Dose_[17]_2000ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 17); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void TQQAPA() throws Exception { - String filename = testFileDir + "/TQQAPA_[17]_4219ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 17); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - - @Test - public void TQQSVPASV() throws Exception { - String filename = testFileDir + "/TQQSVPASV_[17]_14516ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 17); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void TQQSVPSV() throws Exception { - String filename = testFileDir + "/TQQSVPSV_[17]_5532ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 17); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void CQOcrGt1x() throws Exception { - String filename = testFileDir + "/CQOcrGt1x_[12]_1671ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 12); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void CQEx_ischHrt_Fem() throws Exception { - String filename = testFileDir + "/CQEx_ischHrt-Fem_[9]_2485ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 9); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void CQDt_ischHrt() throws Exception { - String filename = testFileDir + "/CQDt_ischHrt_[2]_1657ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 2); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void SQP1I1P2I1_ischHrt_Fem() throws Exception { - String filename = testFileDir + "/SQP1I1P2I1_ischHrt-Fem_[8]_2344ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 8); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void SQP1I1_ischHrt() throws Exception { - String filename = testFileDir + "/SQP1I1_ischHrt_[17]_1657ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 17); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - - - @Test - public void getAllResults() throws Exception { - String filename = testFileDir + "/setfinder_allresulttype_[133].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 133); - else if (results.getQueryResultType().getName().equals("PATIENTSET")) - assertEquals(results.getSetSize(), 133); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - - @Test - public void DateContraintEnddateEqual() throws Exception { - String filename = testFileDir + "/setfinder_dateconstraint_enddate_equal_[0].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 0); - else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) - assertEquals(results.getSetSize(), 0); - else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) - assertEquals(results.getSetSize(), 0); - else if (results.getQueryResultType().getName().equals("PATIENTSET")) - assertEquals(results.getSetSize(), 0); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void DateContraintEnddateGreaterthan() throws Exception { - String filename = testFileDir + "/setfinder_dateconstraint_enddate_greaterthan_[5].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 5); - else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) - assertEquals(results.getSetSize(), 5); - else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) - assertEquals(results.getSetSize(), 5); - else if (results.getQueryResultType().getName().equals("PATIENTSET")) - assertEquals(results.getSetSize(), 5); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void DateContraintEnddateLessthan() throws Exception { - String filename = testFileDir + "/setfinder_dateconstraint_enddate_lessthan_[3].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 3); - else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) - assertEquals(results.getSetSize(), 3); - else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) - assertEquals(results.getSetSize(), 3); - else if (results.getQueryResultType().getName().equals("PATIENTSET")) - assertEquals(results.getSetSize(), 3); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void DateContraintStartdateBetween() throws Exception { - String filename = testFileDir + "/setfinder_dateconstraint_startdate_between_[1].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 1); - else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) - assertEquals(results.getSetSize(), 1); - else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) - assertEquals(results.getSetSize(), 1); - else if (results.getQueryResultType().getName().equals("PATIENTSET")) - assertEquals(results.getSetSize(), 1); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void DateContraintStartdateEqual() throws Exception { - String filename = testFileDir + "/setfinder_dateconstraint_startdate_equal_[0].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 0); - else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) - assertEquals(results.getSetSize(), 0); - else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) - assertEquals(results.getSetSize(), 0); - else if (results.getQueryResultType().getName().equals("PATIENTSET")) - assertEquals(results.getSetSize(), 0); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void DateContraintStartdateGreaterthan() throws Exception { - String filename = testFileDir + "/setfinder_dateconstraint_startdate_greaterthan_[12].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 12); - else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) - assertEquals(results.getSetSize(), 12); - else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) - assertEquals(results.getSetSize(), 12); - else if (results.getQueryResultType().getName().equals("PATIENTSET")) - assertEquals(results.getSetSize(), 12); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void DateContraintStartdateLessthan() throws Exception { - String filename = testFileDir + "/setfinder_dateconstraint_startdate_lessthan_[3].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 3); - else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) - assertEquals(results.getSetSize(), 3); - else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) - assertEquals(results.getSetSize(), 3); - else if (results.getQueryResultType().getName().equals("PATIENTSET")) - assertEquals(results.getSetSize(), 3); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - - @Test - public void DateContraintStartenddate() throws Exception { - String filename = testFileDir + "/setfinder_dateconstraint_startenddate_[3].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 3); - else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) - assertEquals(results.getSetSize(), 3); - else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) - assertEquals(results.getSetSize(), 3); - else if (results.getQueryResultType().getName().equals("PATIENTSET")) - assertEquals(results.getSetSize(), 3); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - - @Test - public void DateContraint() throws Exception { - String filename = testFileDir + "/setfinder_dateconstraint_[131].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 131); - else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) - assertEquals(results.getSetSize(), 131); - else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) - assertEquals(results.getSetSize(), 131); - else if (results.getQueryResultType().getName().equals("PATIENTSET")) - assertEquals(results.getSetSize(), 131); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - - @Test - public void InvertWithNoItem() throws Exception { - String filename = testFileDir + "/setfinder_invert_withnoitem_[134].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 134); - else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) - assertEquals(results.getSetSize(), 134); - else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) - assertEquals(results.getSetSize(), 134); - else if (results.getQueryResultType().getName().equals("PATIENTSET")) - assertEquals(results.getSetSize(), 134); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void ModifierConstraint() throws Exception { - String filename = testFileDir + "/setfinder_modifierconstraint_[11].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 11); - else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) - assertEquals(results.getSetSize(), 11); - else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) - assertEquals(results.getSetSize(), 11); - else if (results.getQueryResultType().getName().equals("PATIENTSET")) - assertEquals(results.getSetSize(), 11); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void NumberConstraintBetween() throws Exception { - String filename = testFileDir + "/setfinder_numberconstraint_BETWEEN_[113].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 113); - else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) - assertEquals(results.getSetSize(), 113); - else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) - assertEquals(results.getSetSize(), 113); - else if (results.getQueryResultType().getName().equals("PATIENTSET")) - assertEquals(results.getSetSize(), 113); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void NumberConstraintEqual() throws Exception { - String filename = testFileDir + "/setfinder_numberconstraint_EQ_[11].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 11); - else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) - assertEquals(results.getSetSize(), 11); - else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) - assertEquals(results.getSetSize(), 11); - else if (results.getQueryResultType().getName().equals("PATIENTSET")) - assertEquals(results.getSetSize(), 11); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - @Test - public void NumberConstraintGreaterEqual() throws Exception { - String filename = testFileDir + "/setfinder_numberconstraint_GE_[114].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 114); - else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) - assertEquals(results.getSetSize(), 114); - else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) - assertEquals(results.getSetSize(), 114); - else if (results.getQueryResultType().getName().equals("PATIENTSET")) - assertEquals(results.getSetSize(), 114); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void NumberConstraintGreaterThan() throws Exception { - String filename = testFileDir + "/setfinder_numberconstraint_GT_[114].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 114); - else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) - assertEquals(results.getSetSize(), 114); - else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) - assertEquals(results.getSetSize(), 114); - else if (results.getQueryResultType().getName().equals("PATIENTSET")) - assertEquals(results.getSetSize(), 114); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - @Test - public void NumberConstraintLessEqual() throws Exception { - String filename = testFileDir + "/setfinder_numberconstraint_LE_[122].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 122); - else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) - assertEquals(results.getSetSize(), 122); - else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) - assertEquals(results.getSetSize(), 122); - else if (results.getQueryResultType().getName().equals("PATIENTSET")) - assertEquals(results.getSetSize(), 122); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - @Test - public void NumberConstraintLessThan() throws Exception { - String filename = testFileDir + "/setfinder_numberconstraint_LT_[121].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 121); - else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) - assertEquals(results.getSetSize(), 121); - else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) - assertEquals(results.getSetSize(), 121); - else if (results.getQueryResultType().getName().equals("PATIENTSET")) - assertEquals(results.getSetSize(), 121); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - - @Test - public void NumberConstraint() throws Exception { - String filename = testFileDir + "/setfinder_numberconstraint_[22].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 22); - else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) - assertEquals(results.getSetSize(), 22); - else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) - assertEquals(results.getSetSize(), 22); - else if (results.getQueryResultType().getName().equals("PATIENTSET")) - assertEquals(results.getSetSize(), 22); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void Panel1Item3() throws Exception { - String filename = testFileDir + "/setfinder_panel_1_item_3_[1].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 1); - else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) - assertEquals(results.getSetSize(), 1); - else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) - assertEquals(results.getSetSize(), 1); - else if (results.getQueryResultType().getName().equals("PATIENTSET")) - assertEquals(results.getSetSize(), 1); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - - - - - @Test - public void PanelTimingAny() throws Exception { - String filename = testFileDir + "/setfinder_paneltiming_any_[133].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 133); - else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) - assertEquals(results.getSetSize(), 133); - else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) - assertEquals(results.getSetSize(), 133); - else if (results.getQueryResultType().getName().equals("PATIENTSET")) - assertEquals(results.getSetSize(), 133); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - - - @Test - public void FlagconstraintEqual() throws Exception { - String filename = testFileDir + "/setfinder_query_flagconstraint_EQ_[1].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 1); - else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) - assertEquals(results.getSetSize(), 1); - else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) - assertEquals(results.getSetSize(), 1); - else if (results.getQueryResultType().getName().equals("PATIENTSET")) - assertEquals(results.getSetSize(), 1); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - - @Test - public void FlagconstraintIN() throws Exception { - String filename = testFileDir + "/setfinder_query_flagconstraint_IN_[1].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 1); - else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) - assertEquals(results.getSetSize(), 1); - else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) - assertEquals(results.getSetSize(), 1); - else if (results.getQueryResultType().getName().equals("PATIENTSET")) - assertEquals(results.getSetSize(), 1); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void FlagconstraintNotEqual() throws Exception { - String filename = testFileDir + "/setfinder_query_flagconstraint_NE_[3].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 3); - else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) - assertEquals(results.getSetSize(), 3); - else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) - assertEquals(results.getSetSize(), 3); - else if (results.getQueryResultType().getName().equals("PATIENTSET")) - assertEquals(results.getSetSize(), 3); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void Flagconstraint() throws Exception { - String filename = testFileDir + "/setfinder_query_flagconstraint_[1].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 1); - else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) - assertEquals(results.getSetSize(), 1); - else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) - assertEquals(results.getSetSize(), 1); - else if (results.getQueryResultType().getName().equals("PATIENTSET")) - assertEquals(results.getSetSize(), 1); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - - @Test - public void ModifierconstraintEqual() throws Exception { - String filename = testFileDir + "/setfinder_query_modifierconstraint_EQ_[0].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 0); - else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) - assertEquals(results.getSetSize(), 0); - else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) - assertEquals(results.getSetSize(), 0); - else if (results.getQueryResultType().getName().equals("PATIENTSET")) - assertEquals(results.getSetSize(), 0); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void ModifierconstraintIN() throws Exception { - String filename = testFileDir + "/setfinder_query_modifierconstraint_IN_[0].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 0); - else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) - assertEquals(results.getSetSize(), 0); - else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) - assertEquals(results.getSetSize(), 0); - else if (results.getQueryResultType().getName().equals("PATIENTSET")) - assertEquals(results.getSetSize(), 0); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - @Test - public void ModifierconstraintLike() throws Exception { - String filename = testFileDir + "/setfinder_query_modifierconstraint_LIKE_[10].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 10); - else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) - assertEquals(results.getSetSize(), 10); - else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) - assertEquals(results.getSetSize(), 10); - else if (results.getQueryResultType().getName().equals("PATIENTSET")) - assertEquals(results.getSetSize(), 10); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void ModifierconstraintNotEqual() throws Exception { - String filename = testFileDir + "/setfinder_query_modifierconstraint_NE_[0].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 0); - else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) - assertEquals(results.getSetSize(), 0); - else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) - assertEquals(results.getSetSize(), 0); - else if (results.getQueryResultType().getName().equals("PATIENTSET")) - assertEquals(results.getSetSize(), 0); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void Modifierconstraint() throws Exception { - String filename = testFileDir + "/setfinder_query_modifierconstraint_[0].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 0); - else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) - assertEquals(results.getSetSize(), 0); - else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) - assertEquals(results.getSetSize(), 0); - else if (results.getQueryResultType().getName().equals("PATIENTSET")) - assertEquals(results.getSetSize(), 0); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - - @Test - public void TextconstraintEqual() throws Exception { - String filename = testFileDir + "/setfinder_query_textconstraint_EQ_[23 OR 13].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - { - if (results.getSetSize() == 13) - assertEquals(results.getSetSize(), 13); - else if (results.getSetSize() == 23) - assertEquals(results.getSetSize(), 23); - else - assertTrue(false); - } - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - - @Test - public void TextconstraintLike() throws Exception { - String filename = testFileDir + "/setfinder_query_textconstraint_LIKE_[90].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 90); - else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) - assertEquals(results.getSetSize(), 90); - else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) - assertEquals(results.getSetSize(), 90); - else if (results.getQueryResultType().getName().equals("PATIENTSET")) - assertEquals(results.getSetSize(), 90); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void TextconstraintNotEqual() throws Exception { - String filename = testFileDir + "/setfinder_query_textconstraint_NE_[99 OR 101].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - { - if (results.getSetSize() == 101) - assertEquals(results.getSetSize(), 101); - else if (results.getSetSize() == 99) - assertEquals(results.getSetSize(), 99); - else - assertTrue(false); - } - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void Textconstraint() throws Exception { - String filename = testFileDir + "/setfinder_query_textconstraint_[23 OR 13].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - { - if (results.getSetSize() == 13) - assertEquals(results.getSetSize(), 13); - else if (results.getSetSize() == 23) - assertEquals(results.getSetSize(), 23); - else - assertTrue(false); - } - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - - - @Test - public void QueryTimingSameInstanceNum() throws Exception { - String filename = testFileDir + "/setfinder_querytiming_sameinstancenum_[133].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 133); - else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) - assertEquals(results.getSetSize(), 133); - else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) - assertEquals(results.getSetSize(), 133); - else if (results.getQueryResultType().getName().equals("PATIENTSET")) - assertEquals(results.getSetSize(), 133); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void TotalItemOccurrencesEqual() throws Exception { - String filename = testFileDir + "/setfinder_totalitemoccurrences_EQ_[133].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 133); - else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) - assertEquals(results.getSetSize(), 133); - else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) - assertEquals(results.getSetSize(), 133); - else if (results.getQueryResultType().getName().equals("PATIENTSET")) - assertEquals(results.getSetSize(), 133); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void TotalItemOccurrences_GreaterEqual() throws Exception { - String filename = testFileDir + "/setfinder_totalitemoccurrences_GE_[133].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 133); - else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) - assertEquals(results.getSetSize(), 133); - else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) - assertEquals(results.getSetSize(), 133); - else if (results.getQueryResultType().getName().equals("PATIENTSET")) - assertEquals(results.getSetSize(), 133); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void TotalItemOccurrencesLessEqual() throws Exception { - String filename = testFileDir + "/setfinder_totalitemoccurrences_LE_[133].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 133); - else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) - assertEquals(results.getSetSize(), 133); - else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) - assertEquals(results.getSetSize(), 133); - else if (results.getQueryResultType().getName().equals("PATIENTSET")) - assertEquals(results.getSetSize(), 133); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void TotalItemOccurrencesNotEqual() throws Exception { - String filename = testFileDir + "/setfinder_totalitemoccurrences_NE_[133].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 133); - else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) - assertEquals(results.getSetSize(), 133); - else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) - assertEquals(results.getSetSize(), 133); - else if (results.getQueryResultType().getName().equals("PATIENTSET")) - assertEquals(results.getSetSize(), 133); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void TotalItemOccurrences() throws Exception { - String filename = testFileDir + "/setfinder_totalitemoccurrences_[133].xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 133); - else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) - assertEquals(results.getSetSize(), 133); - else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) - assertEquals(results.getSetSize(), 133); - else if (results.getQueryResultType().getName().equals("PATIENTSET")) - assertEquals(results.getSetSize(), 133); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void SQP1I1_Circulatory4TemporalAny() throws Exception { - String filename = testFileDir + "/SQP1I1_Circulatory_Any_[66]_3016ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 66); - else if (results.getQueryResultType().getName().equals("PATIENTSET")) - assertEquals(results.getSetSize(), 66); - else if (results.getQueryResultType().getName().equals("PATIENT_ENCOUNTER_SET")) - assertEquals(results.getSetSize(), 66); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - @Test - public void SQP1I1_Circulatory4TemporalSame() throws Exception { - String filename = testFileDir + "/SQP1I1_Circulatory_Same_[66]_3016ms.xml"; - try { - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals(results.getSetSize(), 66); - else if (results.getQueryResultType().getName().equals("PATIENTSET")) - assertEquals(results.getSetSize(), 66); - else if (results.getQueryResultType().getName().equals("PATIENT_ENCOUNTER_SET")) - assertEquals(results.getSetSize(), 66); - else - assertTrue(false); - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - - @Test - public void AllTemporalTests() throws Exception { - // String filename = testFileDir + "/SQP1I1_Circulatory_Same_[66]_3016ms.xml"; - try { - File f = new File(testFileDir + "/temporal"); - ArrayList names = new ArrayList(Arrays.asList(f.list())); - - for (String filename: names) { - if (filename.startsWith("QT_SI_P")) { - int result = Integer.parseInt(filename.substring(filename.indexOf('[')+1,filename.indexOf(']') )); - filename = testFileDir + "/temporal/" + filename; - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals("Working on: " + filename, results.getSetSize(), result); - else - assertTrue(false); - } - } - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - @Test - public void AllIdentityTests() throws Exception { - // String filename = testFileDir + "/SQP1I1_Circulatory_Same_[66]_3016ms.xml"; - try { - File f = new File(testFileDir + "/identity"); - ArrayList names = new ArrayList(Arrays.asList(f.list())); - - for (String filename: names) { - if (filename.startsWith("QT_SI")) { - int result = Integer.parseInt(filename.substring(filename.indexOf('[')+1,filename.indexOf(']') )); - filename = testFileDir + "/identity/" + filename; - String requestString = getQueryString(filename); - OMElement requestElement = convertStringToOMElement(requestString); - OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); - - //read test file and store query instance ; - //unmarshall this response string - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); - ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); - - assertNotNull(masterInstanceResult); - for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) - { - if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) - assertEquals("Working on: " + filename, results.getSetSize(), result); - else - assertTrue(false); - } - } - } - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - public static RequestMessageType buildRequestMessage(PsmQryHeaderType requestHeaderType, RequestType requestType) { - //create body type - BodyType bodyType = new BodyType(); - ObjectFactory of = new ObjectFactory(); - bodyType.getAny().add(of.createPsmheader(requestHeaderType)); - bodyType.getAny().add(of.createRequest(requestType)); - RequestMessageType requestMessageType = new RequestMessageType(); - requestMessageType.setMessageHeader(generateMessageHeader()); - requestMessageType.setMessageBody(bodyType); - requestMessageType.setRequestHeader(generateRequestHeader()); - return requestMessageType; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.crc.axis2; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import org.junit.runner.JUnitCore; +import org.junit.experimental.ParallelComputer; + +import java.io.ByteArrayInputStream; +import java.io.DataInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Arrays; + +import jakarta.xml.bind.JAXBElement; + +import junit.framework.JUnit4TestAdapter; + +import org.apache.axiom.om.OMElement; +import org.junit.BeforeClass; +import org.junit.Test; + +import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; +import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.CrcXmlResultResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.InstanceResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterInstanceResultResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.MasterResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory; +import edu.harvard.i2b2.crc.datavo.setfinder.query.PsmQryHeaderType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryInstanceType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryMasterType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryResultInstanceType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.RequestType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.ResultResponseType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.XmlResultType; + +/** + * Class to test different setfinder request's + * @author rkuttan + */ +public class SetfinderQueryTest extends CRCAxisAbstract { + + private static QueryMasterType queryMaster = null; + private static QueryInstanceType queryInstance = null; + private static MasterInstanceResultResponseType masterInstanceResult = null; + private static String testFileDir = null; + + private static String setfinderUrl = null; + private static String nameInfoUrl = null; + + + @BeforeClass + public static void setUp() throws Exception { + String host = (System.getProperty("testhost") == null ? "http://127.0.0.1:9090/i2b2/services" : System.getProperty("testhost") ) ; + setfinderUrl = + host + "/QueryToolService/request"; + nameInfoUrl = + host + "/QueryToolService/getNameInfo"; + + testFileDir = "testfiles"; //System.getProperty("testfiledir"); + System.out.println("test file dir " + testFileDir); + + if (!((testFileDir != null) && (testFileDir.trim().length() > 0))) { + throw new Exception( + "please provide test file directory info -Dtestfiledir"); + } + + } + + + + + + public static junit.framework.Test suite() { + return new JUnit4TestAdapter(SetfinderQueryTest.class); + } + + public static RequestHeaderType generateRequestHeader() { + RequestHeaderType reqHeaderType = new RequestHeaderType(); + reqHeaderType.setResultWaittimeMs(90000); + return reqHeaderType; + } + + + @Test + public void breakdownNoninvert7panel1itemInvert8panel1item() throws Exception { + String filename = testFileDir + "/breakdown_noninvert_7panel_1item_invert_8panel_1item_[1]_12200ms.xml"; + try { + DataInputStream dataStream = new DataInputStream(new FileInputStream( + filename)); + OMElement requestElement = convertStringToOMElement(dataStream); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + String queryMasterId = masterInstanceResult.getQueryMaster().getQueryMasterId(); + + // First Query In Query + String requestString = getQueryString(testFileDir + "/CRC_QRY_getQueryInstanceList_fromQueryMasterId.xml"); + requestString = requestString.replace("masterid:32958", queryMasterId); + + requestElement = convertStringToOMElement(requestString); + responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + r = (ResponseMessageType)responseJaxb.getValue(); + helper = new JAXBUnWrapHelper(); + + InstanceResponseType instanceResults = (InstanceResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),InstanceResponseType.class); + + assertNotNull(instanceResults); + QueryInstanceType results = instanceResults.getQueryInstance().get(0); + String instanceId = results.getQueryInstanceId(); + + + + + // Get result Instance ID + requestString = getQueryString(testFileDir + "/CRC_QRY_getQueryResultInstanceList_fromQueryInstanceId.xml"); + requestString = requestString.replace("instanceid:32978", instanceId); + + requestElement = convertStringToOMElement(requestString); + responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + r = (ResponseMessageType)responseJaxb.getValue(); + helper = new JAXBUnWrapHelper(); + + ResultResponseType resultResponse = (ResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),ResultResponseType.class); + + assertNotNull(resultResponse); + String resultInstanceId = null; + for (QueryResultInstanceType results2 :resultResponse.getQueryResultInstance() ) + { + resultInstanceId = results2.getResultInstanceId(); + } + + assertNotNull(resultInstanceId); + + // Get result XML + requestString = getQueryString(testFileDir + "/CRC_QRY_getResultDocument_fromResultInstanceId.xml"); + requestString = requestString.replace("instaneid:67572", resultInstanceId); + + requestElement = convertStringToOMElement(requestString); + responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + r = (ResponseMessageType)responseJaxb.getValue(); + helper = new JAXBUnWrapHelper(); + + CrcXmlResultResponseType xmlResponse = (CrcXmlResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),CrcXmlResultResponseType.class); + + assertNotNull(xmlResponse); + XmlResultType results3 = xmlResponse.getCrcXmlResult(); + + + if (results3.getXmlValue().getContent().get(0).toString().contains("xml")) + assert (true); + else + assert(false); + + // Check invalid id + requestString = getQueryString(testFileDir + "/CRC_QRY_getResultDocument_fromResultInstanceId.xml"); + requestString = requestString.replace("instaneid:67572", "67572"); + + requestElement = convertStringToOMElement(requestString); + responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + r = (ResponseMessageType)responseJaxb.getValue(); + helper = new JAXBUnWrapHelper(); + + + xmlResponse = (CrcXmlResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),CrcXmlResultResponseType.class); + + assertEquals(xmlResponse.getStatus().getCondition().get(0).getType(), "ERROR"); + + + + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void QueryInQueryCKMB_OR() throws Exception { + String filename = testFileDir + "/4Q_CK-MB_OR_CPKGT120_[38].xml"; + try { + DataInputStream dataStream = new DataInputStream(new FileInputStream( + filename)); + OMElement requestElement = convertStringToOMElement(dataStream); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + String queryMasterId = masterInstanceResult.getQueryMaster().getQueryMasterId(); + + // First Query In Query + String requestString = getQueryString(testFileDir + "/QIQ_4Q_MALE_[28].xml"); + requestString = requestString.replace("masterid:431", "masterid:"+queryMasterId); + + requestElement = convertStringToOMElement(requestString); + responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + r = (ResponseMessageType)responseJaxb.getValue(); + helper = new JAXBUnWrapHelper(); + + masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 28); + else + assertTrue(false); + } + + + // Second Query In Query + requestString = getQueryString(testFileDir + "/QIQ_4Q_FEMALE_[10].xml"); + requestString = requestString.replace("masterid:431", "masterid:"+queryMasterId); + + requestElement = convertStringToOMElement(requestString); + responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + r = (ResponseMessageType)responseJaxb.getValue(); + helper = new JAXBUnWrapHelper(); + + masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 10); + else + assertTrue(false); + } + + + + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + + @Test + public void QueryInQueryCKMB() throws Exception { + String filename = testFileDir + "/3Q_CK-MB_AND_CPKGT120_[16].xml"; + try { + DataInputStream dataStream = new DataInputStream(new FileInputStream( + filename)); + OMElement requestElement = convertStringToOMElement(dataStream); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + String queryMasterId = masterInstanceResult.getQueryMaster().getQueryMasterId(); + + // First Query In Query + String requestString = getQueryString(testFileDir + "/QIQ_3Q_MALE_[12].xml"); + requestString = requestString.replace("masterid:427", "masterid:"+queryMasterId); + + requestElement = convertStringToOMElement(requestString); + responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + r = (ResponseMessageType)responseJaxb.getValue(); + helper = new JAXBUnWrapHelper(); + + masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 12); + else + assertTrue(false); + } + + + // Second Query In Query + requestString = getQueryString(testFileDir + "/QIQ_3Q_FEMALE_[4].xml"); + requestString = requestString.replace("masterid:427", "masterid:"+queryMasterId); + + requestElement = convertStringToOMElement(requestString); + responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + r = (ResponseMessageType)responseJaxb.getValue(); + helper = new JAXBUnWrapHelper(); + + masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 4); + else + assertTrue(false); + } + + + + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + + @Test + public void QueryInQueryHypertensionOR() throws Exception { + String filename = testFileDir + "/2Q_HYP_OR_ISCH_[44].xml"; + try { + DataInputStream dataStream = new DataInputStream(new FileInputStream( + filename)); + OMElement requestElement = convertStringToOMElement(dataStream); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + String queryMasterId = masterInstanceResult.getQueryMaster().getQueryMasterId(); + + // First Query In Query + String requestString = getQueryString(testFileDir + "/QIQ_2Q_MALE_[26].xml"); + requestString = requestString.replace("masterid:424", "masterid:"+queryMasterId); + + requestElement = convertStringToOMElement(requestString); + responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + r = (ResponseMessageType)responseJaxb.getValue(); + helper = new JAXBUnWrapHelper(); + + masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 26); + else + assertTrue(false); + } + + + // Second Query In Query + requestString = getQueryString(testFileDir + "/QIQ_2Q_FEMALE_[18].xml"); + requestString = requestString.replace("masterid:424", "masterid:"+queryMasterId); + + requestElement = convertStringToOMElement(requestString); + responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + r = (ResponseMessageType)responseJaxb.getValue(); + helper = new JAXBUnWrapHelper(); + + masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 18); + else + assertTrue(false); + } + + + + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + + @Test + public void QueryInQueryHypertension() throws Exception { + String filename = testFileDir + "/1Q_HYP_AND_ISCH_[13].xml"; + try { + DataInputStream dataStream = new DataInputStream(new FileInputStream( + filename)); + OMElement requestElement = convertStringToOMElement(dataStream); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + String queryMasterId = masterInstanceResult.getQueryMaster().getQueryMasterId(); + + // First Query In Query + String requestString = getQueryString(testFileDir + "/QIQ_1Q_MALE_[6].xml"); + requestString = requestString.replace("masterid:421", "masterid:"+queryMasterId); + + requestElement = convertStringToOMElement(requestString); + responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + r = (ResponseMessageType)responseJaxb.getValue(); + helper = new JAXBUnWrapHelper(); + + masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 6); + else + assertTrue(false); + } + + + // Second Query In Query + requestString = getQueryString(testFileDir + "/QIQ_1Q_FEMALE_[7].xml"); + requestString = requestString.replace("masterid:421", "masterid:"+queryMasterId); + + requestElement = convertStringToOMElement(requestString); + responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + r = (ResponseMessageType)responseJaxb.getValue(); + helper = new JAXBUnWrapHelper(); + + masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 7); + else + assertTrue(false); + } + + + + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void getNameInfoContains() throws Exception { + String filename = testFileDir + "/getNameInfo_contains.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(nameInfoUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterResponseType masterInstanceResult = (MasterResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryMasterType results :masterInstanceResult.getQueryMaster() ) + { + if (results.getName().contains("Hyperte")) + assertTrue(true); + else + assertTrue(false); + } + + //Check with Previous Query + requestString = getQueryString(filename); + requestString = requestString.replace("category=\"@\"", "category=\"top\""); + requestElement = convertStringToOMElement(requestString); + responseElement = getServiceClient(nameInfoUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + r = (ResponseMessageType)responseJaxb.getValue(); + helper = new JAXBUnWrapHelper(); + + masterInstanceResult = (MasterResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryMasterType results :masterInstanceResult.getQueryMaster() ) + { + if (results.getName().contains("Hyperte")) + assertTrue(true); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + + @Test + public void getNameInfoEndwith() throws Exception { + String filename = testFileDir + "/getNameInfo_endwith.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(nameInfoUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterResponseType masterInstanceResult = (MasterResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryMasterType results :masterInstanceResult.getQueryMaster() ) + { + if (results.getName().endsWith("10:24:10")) + assertTrue(true); + else + assertTrue(false); + } + //Check with Previous Query + requestString = getQueryString(filename); + requestString = requestString.replace("category=\"@\"", "category=\"top\""); + requestElement = convertStringToOMElement(requestString); + responseElement = getServiceClient(nameInfoUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + r = (ResponseMessageType)responseJaxb.getValue(); + helper = new JAXBUnWrapHelper(); + + masterInstanceResult = (MasterResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryMasterType results :masterInstanceResult.getQueryMaster() ) + { + if (results.getName().endsWith("10:24:10")) + assertTrue(true); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void getNameInfoStartWith() throws Exception { + String filename = testFileDir + "/getNameInfo_startwith.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(nameInfoUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterResponseType masterInstanceResult = (MasterResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryMasterType results :masterInstanceResult.getQueryMaster() ) + { + if (results.getName().startsWith("(PrevQu-Female")) + assertTrue(true); + else + assertTrue(false); + } + //Check with Previous Query + requestString = getQueryString(filename); + requestString = requestString.replace("category=\"@\"", "category=\"top\""); + requestElement = convertStringToOMElement(requestString); + responseElement = getServiceClient(nameInfoUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + r = (ResponseMessageType)responseJaxb.getValue(); + helper = new JAXBUnWrapHelper(); + + masterInstanceResult = (MasterResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryMasterType results :masterInstanceResult.getQueryMaster() ) + { + if (results.getName().startsWith("(PrevQu-Female")) + assertTrue(true); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void getNameInfoExact() throws Exception { + String filename = testFileDir + "/getNameInfo_exact.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(nameInfoUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterResponseType masterInstanceResult = (MasterResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryMasterType results :masterInstanceResult.getQueryMaster() ) + { + if (results.getName().endsWith("(PrevQu-Female@10:24:10")) + assertTrue(true); + else + assertTrue(false); + } + //Check with Previous Query + requestString = getQueryString(filename); + requestString = requestString.replace("category=\"@\"", "category=\"top\""); + requestElement = convertStringToOMElement(requestString); + responseElement = getServiceClient(nameInfoUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + r = (ResponseMessageType)responseJaxb.getValue(); + helper = new JAXBUnWrapHelper(); + + masterInstanceResult = (MasterResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryMasterType results :masterInstanceResult.getQueryMaster() ) + { + if (results.getName().endsWith("(PrevQu-Female@10:24:10")) + assertTrue(true); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + + @Test + public void ExcludeOccurancesMultiplePanelsSame() throws Exception { + String filename = testFileDir + "/setfinder_exclude_and_occurances_same_[63]_1432ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 99); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void ExcludeOccurancesMultiplePanelsSameParallel() throws Exception { + Class[] cls = { JunitRunA.class, JunitRunB.class, JunitRunC.class, JunitRunD.class, JunitRunE.class }; + + // Parallel among classes + JUnitCore.runClasses(ParallelComputer.classes(), cls); + + // Parallel among methods in a class + JUnitCore.runClasses(ParallelComputer.methods(), cls); + + // Parallel all methods in all classes + JUnitCore.runClasses(new ParallelComputer(true, true), cls); + } + + @Test + public void ExcludeOccurancesMultiplePanelsAny() throws Exception { + String filename = testFileDir + "/setfinder_exclude_and_occurances_any_[63]_1432ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 63); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + + @Test + public void TestOObfuscatedLoockout() throws Exception { + String filename = testFileDir + "/obfuscated_lockout.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + + //read test file and store query instance ; + //unmarshall this response string + String lockout = ""; + ArrayList list = new ArrayList(); + for (int i=0; i < 14; i++) { + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + //MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + System.out.println("Query:"+ i); + //assertNotNull(masterInstanceResult); + + //if (r.getResponseHeader().getResultStatus().getStatus().getType().equals("ERROR")) + //{ + // lockout = r.getResponseHeader().getResultStatus().getStatus().getValue(); + //} else + + if (r != null) { + // assertNotNull(masterInstanceResult); + // for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + // { + if (r.getResponseHeader().getResultStatus().getStatus().getType().equals("ERROR")) + { + lockout = r.getResponseHeader().getResultStatus().getStatus().getValue(); + break; + } + + // if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + // { + // if (!list.contains(results.getSetSize())) + // list.add(results.getSetSize()); + // } + // } + } + } + //assertTrue(list.size() > 3); + assertTrue(lockout.startsWith("LOCKEDOUT")); + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + /* + @Test + public void Panel1Item3Missing() throws Exception { + String filename = testFileDir + "/setfinder_panel_1_item_3_missing_[Error].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + + + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 1); + else + assertTrue(false); + } + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + */ + /* + @Test + public void QueryOver50000() throws Exception { + String filename = testFileDir + "/SQP1I1_Circulatory_[66]_3016ms.xml"; + try { + for (int i=0; i < 50000; i++) { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 66); + else + assertTrue(false); + System.out.println("Query number: " + i + " total number is " +results.getSetSize()); + } + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + */ + + + @Test + public void QueryLargeTextConstaintwithSpace() throws Exception { + String filename = testFileDir + "/setfinder_query_largetextconstraint_withspace_[18]_1200ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + { + if (results.getSetSize() == 18) + assertEquals(results.getSetSize(), 18); + else if (results.getSetSize() == 19) + assertEquals(results.getSetSize(), 19); + else + assertTrue(false); + } + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void MQP1I1P2I13() throws Exception { + String filename = testFileDir + "/MQP1I1P2I1_[48]_6658ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 48); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void getInvertPanel1Items1() throws Exception { + String filename = testFileDir + "/setfinder_invert_1panel_1item_[94]_5800ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 94); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + + + @Test + public void QueryNumericConstraintGreaterThan() throws Exception { + String filename = testFileDir + "/setfinder_query_numericconstraint_greatthan_[103]_2100ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 103); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + + @Test + public void DateContraintEnddateBetween() throws Exception { + String filename = testFileDir + "/setfinder_dateconstraint_enddate_between_[1].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 1); + else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) + assertEquals(results.getSetSize(), 1); + else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) + assertEquals(results.getSetSize(), 1); + else if (results.getQueryResultType().getName().equals("PATIENTSET")) + assertEquals(results.getSetSize(), 1); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + + + @Test + public void CQEx_circDigestNeuro() throws Exception { + String filename = testFileDir + "/CQEx_circDigestNeuro_[14]_21704ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 14); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void TQQemptyStringPSI() throws Exception { + String filename = testFileDir + "/TQQemptyStringPSI_[0]_4570ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 0); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + + + @Test + public void TQNoQueryTimingPSI() throws Exception { + // Will default to ANY and should cause a error + String filename = testFileDir + "/TQNoQueryTimingPSI_[0]_557ms.xml"; + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 0); + else + assertTrue(false); + } + } + + + + @Test + public void TQQAPASI() throws Exception { + String filename = testFileDir + "/TQQAPASI_[Error]_659ms.xml"; + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + + + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 7); + else + assertTrue(false); + } + } + + + @Test + public void TQQSIPSI3() throws Exception { + String filename = testFileDir + "/TQQSIPSI-a_[0]_557ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 0); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + + @Test + public void TQNoQueryTimingPAny() throws Exception { + // Will default to ANY and should cause a error + String filename = testFileDir + "/TQNoQueryTimingPAny_[18]_6057ms.xml"; + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 18); + else + assertTrue(false); + } + } + + + @Test + public void TQQemptyStringPSV() throws Exception { + String filename = testFileDir + "/TQQemptyStringPSV_[18]_630msxml.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 18); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + + + @Test + public void PanelTimingSameMissingQueryTiming() throws Exception { + // Will default to ANY and should cause a error + String filename = testFileDir + "/setfinder_paneltiming_same_[133].xml"; + // try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 133); + } + } + + @Test + public void TQQSIPSISVc() throws Exception { + String filename = testFileDir + "/TQQSIPSISV-c_[0]_4105ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 0); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + + + @Test + public void Panel4Item3Missing() throws Exception { + String filename = testFileDir + "/setfinder_panel_4_item_3_missing_[1].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + + int size = -2; + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + size = results.getSetSize(); + } + //assertEquals(size, 1); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void TextconstraintIN() throws Exception { + String filename = testFileDir + "/setfinder_query_textconstraint_IN_[0].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 0); + else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) + assertEquals(results.getSetSize(), 0); + else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) + assertEquals(results.getSetSize(), 0); + else if (results.getQueryResultType().getName().equals("PATIENTSET")) + assertEquals(results.getSetSize(), 0); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + + /* For post 1.6.03 + @Test + public void NumberConstraintNotEqual() throws Exception { + String filename = testFileDir + "/setfinder_numberconstraint_NE.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 0); + else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) + assertEquals(results.getSetSize(), 0); + else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) + assertEquals(results.getSetSize(), 0); + else if (results.getQueryResultType().getName().equals("PATIENTSET")) + assertEquals(results.getSetSize(), 0); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + */ + + @Test + public void TQQemptyStringPEmptyString() throws Exception { + String filename = testFileDir + "/TQQemptyStringPEmptyString_[18]_4994ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 18); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void TQQAPSV() throws Exception { + String filename = testFileDir + "/TQQAPSV_[Error]_646ms.xml"; + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + + + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 18); + else + assertTrue(false); + } + + } + + @Test + public void TQQemptyStringPAny() throws Exception { + String filename = testFileDir + "/TQQemptyStringPAny_[18]_603ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 18); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + + public void TQQAPSI() throws Exception { + String filename = testFileDir + "/TQQAPSI_[Error]_4654ms.xml"; + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + + + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 0); + else + assertTrue(false); + } + + } + + @Test + public void TQNoQueryOrPanelTiming() throws Exception { + String filename = testFileDir + "/TQNoQueryOrPanelTiming_[18]_6057ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 18); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void TQNoQueryTimingPSV() throws Exception { + String filename = testFileDir + "/TQNoQueryTimingPSV_[18]_6490ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 18); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void TQQSIPSV() throws Exception { + String filename = testFileDir + "/TQQSIPSV_[18]_4491ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 18); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + + + @Test + public void MQDtBtw() throws Exception { + String filename = testFileDir + "/MQDtBtw_[4]_3006ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 4); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void MQDtBtw2() throws Exception { + String filename = testFileDir + "/MQDtBtw2_[4]_3006ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 4); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void MQDtBtw3() throws Exception { + String filename = testFileDir + "/MQDtBtw3_[4]_3006ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 4); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void MQDtBtw4() throws Exception { + String filename = testFileDir + "/MQDtBtw4_[4]_3006ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 4); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void MQP1I1() throws Exception { + String filename = testFileDir + "/MQP1I1_[31]_3207ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 31); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void TQQSVPSV2() throws Exception { + String filename = testFileDir + "/TQQSVPSV_[4]_4578ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 4); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void MQP1I1P2I1() throws Exception { + String filename = testFileDir + "/MQP1I1P2I1_[1]_3135ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 1); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void MQP1I12() throws Exception { + String filename = testFileDir + "/MQP1I1_[48]_2005ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 48); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void TQQSVPSV3() throws Exception { + String filename = testFileDir + "/TQQSVPSV_[5]_5800ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 5); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void MQP1I1P2I12() throws Exception { + String filename = testFileDir + "/MQP1I1P2I1_[10]_3013ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 10); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void MQP1I1b() throws Exception { + String filename = testFileDir + "/MQP1I1-b_[8]_1855ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 8); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + public void TQQSVPSVb() throws Exception { + String filename = testFileDir + "/TQQSVPSV-b_[5]_5761ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 5); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void MQP1I2() throws Exception { + String filename = testFileDir + "/MQP1I1_[13]_1903ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 13); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void MQValEnmMV() throws Exception { + String filename = testFileDir + "/MQValEnmMV_[14]_1877ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 14); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void MQP1I13() throws Exception { + String filename = testFileDir + "/MQP1I1_[1]_1861ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 1); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void MQFolderf() throws Exception { + String filename = testFileDir + "/MQFolder-f_[3]_1882ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 3); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void MQFolderc() throws Exception { + String filename = testFileDir + "/MQFolder-c_[3]_1893ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 3); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void TQQSIPASI() throws Exception { + String filename = testFileDir + "/TQQSIPASI_[5]_4492ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 5); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void TQQSVPSV4() throws Exception { + String filename = testFileDir + "/TQQSVPSV_[17]_5659ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 17); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void MQFolderd() throws Exception { + String filename = testFileDir + "/MQFolder-d_[3]_3206ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 3); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void MQP1I1P2I14() throws Exception { + String filename = testFileDir + "/MQP1I1P2I1_[6]_1919ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 6); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void MQP1I14() throws Exception { + String filename = testFileDir + "/MQP1I1_[70]_1997ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 70); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void MQP1I2P2I2() throws Exception { + String filename = testFileDir + "/MQP1I2P2I2_[73]_12585ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 73); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void MQP1I1P2I15() throws Exception { + String filename = testFileDir + "/MQP1I1P2I1_[3]_5145ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 3); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void MQP1I15() throws Exception { + String filename = testFileDir + "/MQP1I1_[7]_1908ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 7); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void MQP1I1P2I16() throws Exception { + String filename = testFileDir + "/MQP1I1P2I1_[7]_3563ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 7); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void MQValNumLT() throws Exception { + String filename = testFileDir + "/MQValNumLT_[19]_1896.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 19); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void MQP1I22() throws Exception { + String filename = testFileDir + "/MQP1I2_[32]_2969ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 32); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void MQP1I16() throws Exception { + String filename = testFileDir + "/MQP1I1_[16]_1879ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 16); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void MQExValNumLTandGTEandE() throws Exception { + String filename = testFileDir + "/MQExValNumLTandGTEandE_[7]_4389ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 7); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void MQFoldere() throws Exception { + String filename = testFileDir + "/MQFolder-e_[3]_1882ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 3); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void MQP1I17() throws Exception { + String filename = testFileDir + "/MQP1I1_[5]_3237ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 5); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void MQP1I18() throws Exception { + String filename = testFileDir + "/MQP1I1_[4]_2348ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 4); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void MQValNumLTandGTEandE() throws Exception { + String filename = testFileDir + "/MQValNumLTandGTEandE_[9]_4171ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 9); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void MQFolder() throws Exception { + String filename = testFileDir + "/MQFolder-h_[3]_1919ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 3); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void MQFolderb() throws Exception { + String filename = testFileDir + "/MQFolder-b_[2]_1876ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 2); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void MQP1I19() throws Exception { + String filename = testFileDir + "/MQP1I1_[65]_2320ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML") || results.getQueryResultType().getName().equals("PATIENTSET")) + assertEquals(results.getSetSize(), 65); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void MQP1I1P2I1P3I1() throws Exception { + String filename = testFileDir + "/MQP1I1P2I1P3I1_[3]_4523ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 3); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void MQP1I1b2() throws Exception { + String filename = testFileDir + "/MQP1I1-b_[6]_1896ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 6); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void MQP1I110() throws Exception { + String filename = testFileDir + "/MQP1I1_[54]_1984ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 54); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void TQQSIPSI() throws Exception { + String filename = testFileDir + "/TQQSIPSI_[0]_3117ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 0); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void MQP1I11() throws Exception { + String filename = testFileDir + "/MQP1I1_[89]_1895ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 89); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void MQDtFrom() throws Exception { + String filename = testFileDir + "/MQDtFrom_[3]_2988ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 3); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void MQValNumLTandEnm() throws Exception { + String filename = testFileDir + "/MQValNumLTandEnm_[6]_3109ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 6); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void MQFolder2() throws Exception { + String filename = testFileDir + "/MQFolder_[14]_1876ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 14); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void MQValNumLTandGTE() throws Exception { + String filename = testFileDir + "/MQValNumLTandGTE_[9]_4454ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 9); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void MQFolder3() throws Exception { + String filename = testFileDir + "/MQFolder-g_[2]_1866ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 2); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void MQP1I3() throws Exception { + String filename = testFileDir + "/MQP1I3_[5]_6018ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 5); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void TQQSIPSI2() throws Exception { + String filename = testFileDir + "/TQQSIPSI_[17]_4310ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 17); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void MQValEnmMV2() throws Exception { + String filename = testFileDir + "/MQValEnmMV_[8]_4578ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 8); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void MQValNumLTandEnm2() throws Exception { + String filename = testFileDir + "/MQValNumLTandEnm_[17]_5758ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 17); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void MQFolderb2() throws Exception { + String filename = testFileDir + "/MQFolder-i_[3]_1866ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 3); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void MQP1I111() throws Exception { + String filename = testFileDir + "/MQP1I1_[12]_3298ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 12); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void MQValNumLTandEnm3() throws Exception { + String filename = testFileDir + "/MQValNumLTandEnm_[5]_4585ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 5); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void TQQSVPSV5() throws Exception { + String filename = testFileDir + "/TQQSVPSV_[0]_3557ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 0); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void MQP1I112() throws Exception { + String filename = testFileDir + "/MQP1I1_[58]_1893ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 58); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void MQDtTo() throws Exception { + String filename = testFileDir + "/MQDtTo_[1]_4371ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 1); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void TQQSVPSV6() throws Exception { + String filename = testFileDir + "/TQQSVPSV_[3]_4944ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 3); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void MQValEnmMV3() throws Exception { + String filename = testFileDir + "/MQValEnmMV_[6]_2580ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 6); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void MQP1I1b3() throws Exception { + String filename = testFileDir + "/MQP1I1-b_[7]_1904ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 7); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void TQQSIPSIb() throws Exception { + String filename = testFileDir + "/TQQSIPSI-b_[0]_5704ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 0); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void MQP1I113() throws Exception { + String filename = testFileDir + "/MQP1I1_[17]_1915ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 17); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void MQP1I114() throws Exception { + String filename = testFileDir + "/MQP1I1_[8]_3276ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 8); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void MQP1I1P2I1P3I11() throws Exception { + String filename = testFileDir + "/MQP1I1P2I1P3I1_[2]_5653ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 2); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void TQQSVPSV12() throws Exception { + String filename = testFileDir + "/TQQSVPSV_[111]_3098ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 111); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void MQP1I115() throws Exception { + String filename = testFileDir + "/MQP1I1_[6]_1912ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 6); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + + + @Test + public void TQQSIPSISV() throws Exception { + String filename = testFileDir + "/TQQSIPSISV_[18]_4491ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 18); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + + + + @Test + public void TQQSIPASI2() throws Exception { + String filename = testFileDir + "/TQQSIPASI_[18]_4681ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 18); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + + @Test + public void MQQSVPSV() throws Exception { + String filename = testFileDir + "/MQQSVPSV_[18]_5254ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 18); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + + @Test + public void TQQSVPASV2() throws Exception { + String filename = testFileDir + "/TQQSVPASV_[18]_6805ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 18); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void TQQSIPSISVb() throws Exception { + String filename = testFileDir + "/TQQSIPSISV-b_[18]_5873ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 18); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + + + @Test + public void TQQSVPASI() throws Exception { + // Will default to ANY and should cause a error + String filename = testFileDir + "/TQQSVPASI_[Error]_6793ms.xml"; + // try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + + + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 18); + else + assertTrue(false); + } + } + + + /* + @Test + public void PanelTimingSameInstancenumMissingQueryTiming() throws Exception { + // Will default to ANY and should cause a error + String filename = testFileDir + "/setfinder_paneltiming_sameinstancenum_[Error].xml"; + // try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + + + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 133); + else + assertTrue(false); + } + + // } catch (Exception e) { + // e.printStackTrace(); + // throw e; + // } + } + + */ + @Test + public void QueryTimingSame() throws Exception { + String filename = testFileDir + "/setfinder_querytiming_same_[133].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 133); + else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) + assertEquals(results.getSetSize(), 133); + else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) + assertEquals(results.getSetSize(), 133); + else if (results.getQueryResultType().getName().equals("PATIENTSET")) + assertEquals(results.getSetSize(), 133); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void TextconstraintBetween() throws Exception { + String filename = testFileDir + "/setfinder_query_textconstraint_BETWEEN_[error].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + assertEquals(masterInstanceResult.getQueryInstance().getQueryStatusType().getName(), "ERROR"); + + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void Panel4Item3() throws Exception { + String filename = testFileDir + "/setfinder_panel_4_item_3_[1].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 1); + else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) + assertEquals(results.getSetSize(), 1); + else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) + assertEquals(results.getSetSize(), 1); + else if (results.getQueryResultType().getName().equals("PATIENTSET")) + assertEquals(results.getSetSize(), 1); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void InvertWithItem() throws Exception { + String filename = testFileDir + "/setfinder_invert_withitem_[1].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 1); + else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) + assertEquals(results.getSetSize(), 1); + else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) + assertEquals(results.getSetSize(), 1); + else if (results.getQueryResultType().getName().equals("PATIENTSET")) + assertEquals(results.getSetSize(), 1); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void QueryNumericConstraintBetween() throws Exception { + String filename = testFileDir + "/setfinder_query_numericconstraint_between_[9]_2800ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 9); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void QueryNumericConstraintEqual() throws Exception { + String filename = testFileDir + "/setfinder_query_numericconstraint_eq_[3]_2300ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 3); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + + @Test + public void QuerySmallTextConstraintLessThan() throws Exception { + String filename = testFileDir + "/setfinder_query_numericconstraint_lessthan_[6]_2100ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 6); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void QuerySmallTextConstraintBegin() throws Exception { + String filename = testFileDir + "/setfinder_query_smalltextconstraint_begin_[1]_1500ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 1); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + + + @Test + public void QuerySmallTextConstraintEnd() throws Exception { + String filename = testFileDir + "/setfinder_query_smalltextconstraint_end_[1]_1600ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 1); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + + + @Test + public void QuerySmallTextConstraintContains() throws Exception { + String filename = testFileDir + "/setfinder_query_smalltextconstraint_contains_[3]_1400ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 3); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + + + @Test + public void EncounterContraint1() throws Exception { + String filename = testFileDir + "/setfinder_query_enumconstraint_[1]_1700ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 1); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void EncounterContraint2() throws Exception { + String filename = testFileDir + "/setfinder_query_enumconstraint_[3]_1900ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 3); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void EncounterContraint3() throws Exception { + String filename = testFileDir + "/setfinder_query_enumconstraint_[4]_2100ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 4); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void LargeTextContraint() throws Exception { + String filename = testFileDir + "/setfinder_query_largetextconstraint_[10]_1700ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 10); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + + @Test + public void NumericContraintBetween() throws Exception { + String filename = testFileDir + "/setfinder_query_numericconstraint_between_[9]_2800ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 9); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void SmallTextContraintContains() throws Exception { + String filename = testFileDir + "/setfinder_query_smalltextconstraint_contains_[3]_1400ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 3); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + + @Test + public void getPanel1Items2Panel2InvertItem1() throws Exception { + String filename = testFileDir + "/setfinder_pane_1_item_2_panel_2_INV_item_1_[33].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 33); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + + + @Test + public void getInvertPanel1Items2InvertPanel2Item2InvertPanel3Item2() throws Exception { + String filename = testFileDir + "/setfinder_invert_1panel_2item_invert_2panel_2item_invert_3panel_2item_[50]_7000ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 50); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void getInvertPanel1Items2InvertPanel2Item2NonInvertPanel3Item1() throws Exception { + String filename = testFileDir + "/setfinder_invert_1panel_2item_invert_2panel_2item_noninvert_3panel_1item_[6]_6000ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 6); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void getInvertPanel1Items2InvertPanel2Item2NonInvertPanel3Item2() throws Exception { + String filename = testFileDir + "/setfinder_invert_1panel_2item_invert_2panel_2item_noninvert_3panel_2item_[13]_7100ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 13); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void getInvertPanel1Items2InvertPanel2Item2() throws Exception { + String filename = testFileDir + "/setfinder_invert_1panel_2item_invert_2panel_2item_[63]_4100ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 63); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void getInvertPanel1Items2NonInvertPanel2Item1() throws Exception { + String filename = testFileDir + "/setfinder_invert_1panel_2item_noninvert_2panel_1item_[11]_7000ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 11); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void getInvertPanel1Items2NonInvertPanel2Item2() throws Exception { + String filename = testFileDir + "/setfinder_invert_1panel_2item_noninvert_2panel_2item_[20]_6100ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 20); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void getInvertPanel1Items2() throws Exception { + String filename = testFileDir + "/setfinder_invert_1panel_2item_[83]_5300ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 83); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void getNonInvertPanel1Items1InvertPanel2Item2InvertPanel3Item2() throws Exception { + String filename = testFileDir + "/setfinder_noninvert_1panel_1item_invert_2panel_2item_invert_3panel_2item_[6]_6000ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 6); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void getNonInvertPanel1Items2InvertPanel2Item1() throws Exception { + String filename = testFileDir + "/setfinder_noninvert_1panel_2item_invert_2panel_1item_[11]_7000ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 11); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void getNonInvertPanel1Items2InvertPanel2Item2InvertPanel3Item2() throws Exception { + String filename = testFileDir + "/setfinder_noninvert_1panel_2item_invert_2panel_2item_invert_3panel_2item_[13]_7100ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 13); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void getNonInvertPanel1Items2InvertPanel2Item2() throws Exception { + String filename = testFileDir + "/setfinder_noninvert_1panel_2item_invert_2panel_2item_[20]_6100ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 20); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void getNonInvertPanel7Items2InvertPanel8Item1() throws Exception { + String filename = testFileDir + "/setfinder_noninvert_7panel_1item_invert_8panel_1item_[1]_12200ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + { + if (results.getSetSize() == 1 || results.getSetSize() == 2) + assertTrue(true); + //assertEquals(results.getSetSize(), 2); + } + else + { + assertTrue(false); + } + + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void AgePanel1Item1a() throws Exception { + String filename = testFileDir + "/setfinder_age_panel_1_item_1_[20]_4000ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + { + assertTrue("age is to high", 3 >= results.getSetSize()); + assertTrue("age is to low", 0 <= results.getSetSize()); + } + else + { + assertTrue(false); + } + + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void AgePanel1Item1b() throws Exception { + String filename = testFileDir + "/setfinder_age_panel_1_item_1_[14]_5500ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 24); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void AgePanel1Item1c() throws Exception { + String filename = testFileDir + "/setfinder_age_panel_1_item_1_[20]_4000ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + { + assertTrue("age is to high", 3 >= results.getSetSize()); + assertTrue("age is to low", 0 <= results.getSetSize()); + } + else + { + assertTrue(false); + } + + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void AgeVisitPanel2Item1() throws Exception { + String filename = testFileDir + "/setfinder_age_visit_panel_2_item_1_[20]_5900ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + { + assertTrue("age is to high", 3 >= results.getSetSize()); + assertTrue("age is to low", 0 <= results.getSetSize()); + } + else + { + assertTrue(false); + } + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void AgeVisitProviderPanel3Item1() throws Exception { + String filename = testFileDir + "/setfinder_age_visit_prov_panel_3_item_1_[3]_7700ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 0); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void AgeVisitLengthPanel2Item1() throws Exception { + String filename = testFileDir + "/setfinder_age_visitLen_panel_2_item_1_[3]_6100ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 5); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void IncRaceHypTenPanel3Item1() throws Exception { + String filename = testFileDir + "/setfinder_inc_race_HypTen_panel_3_item_2_[9]_9200ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 9); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void IncRacePanel2Item2() throws Exception { + String filename = testFileDir + "/setfinder_inc_race_panel_2_item_2_[26]_6600ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 26); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void IncRacProcedurePanel3Item2() throws Exception { + String filename = testFileDir + "/setfinder_inc_race_Procedure_panel_3_item_2_[1]_9200ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 1); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void IncomePanel1Item1() throws Exception { + String filename = testFileDir + "/setfinder_income_panel_1_item_1_[42]_5200ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 42); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + + @Test + public void SQP1I1_DxMI() throws Exception { + String filename = testFileDir + "/SQP1I1_DxMI_[7]_1625ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 7); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + + @Test + public void MQ_princDx_Diabetes() throws Exception { + String filename = testFileDir + "/MQ_princDx_Diabetes_[2]_2141ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 2); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void MCQValMix_DoseFreqRoute_trimox() throws Exception { + String filename = testFileDir + "/MCQValMix_DoseFreqRoute_trimox_[17]_6516ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 17); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void CQOcrGt5x_IschHrt() throws Exception { + String filename = testFileDir + "/CQOcrGt5x_IschHrt_[2]_1641ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 2); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void CQOcrGt7x_CircSys() throws Exception { + String filename = testFileDir + "/CQOcrGt7x_CircSys_[17]_1672ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 17); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void SQP1I1_Circulatory() throws Exception { + String filename = testFileDir + "/SQP1I1_Circulatory_[66]_3016ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 66); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void CQValFlgH_CPK() throws Exception { + String filename = testFileDir + "/CQValFlgH_CPK_[0]_1657ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 0); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void CQValFlgL_CPK() throws Exception { + String filename = testFileDir + "/CQValFlgL_CPK_[0]_3032ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 0); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void CQValNum_CPK() throws Exception { + String filename = testFileDir + "/CQValNum_CPK_[40]_1610ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 40); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + + @Test + public void CQValNum110_CPK() throws Exception { + String filename = testFileDir + "/CQValNum110_CPK_[3]_1672ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 3); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void CQValNumBtw52_250_CPK() throws Exception { + String filename = testFileDir + "/CQValNumBtw52-250_CPK_[35]_1625ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 35); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void CQValNumGT110_CPK() throws Exception { + String filename = testFileDir + "/CQValNumGT110_CPK_[29]_1625ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 29); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void CQValNumGTE110_CPK() throws Exception { + String filename = testFileDir + "/CQValNumGTE110_CPK_[30]_1625ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 30); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void CQValNumLT110_CPK() throws Exception { + String filename = testFileDir + "/CQValNumLT110_CPK_[16]_1594ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 16); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void CQValNumLTE110_CPK() throws Exception { + String filename = testFileDir + "/CQValNumLTE110_CPK_[17]_3078ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 17); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void MCQValEnmMV_Route() throws Exception { + String filename = testFileDir + "/MCQValEnmMV_Route[63]_2015ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 63); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void MCQValNum_Dose() throws Exception { + String filename = testFileDir + "/MCQValNum_Dose_[18]_2047ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 18); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + + @Test + public void MCQValNumBtw100_900_Dose() throws Exception { + String filename = testFileDir + "/MCQValNumBtw100-900_Dose_[18]_2000ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 18); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void MCQValNumE500_Dose() throws Exception { + String filename = testFileDir + "/MCQValNumE500_Dose_[17]_2047ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 17); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void MCQValNumGT500_Dose() throws Exception { + String filename = testFileDir + "/MCQValNumGT500_Dose_[6]_2047ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 6); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + + @Test + public void MCQValNumGTE500_Dose() throws Exception { + String filename = testFileDir + "/MCQValNumGTE500_Dose_[18]_1984ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 18); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void MCQValNumLT500_Dose() throws Exception { + String filename = testFileDir + "/MCQValNumLT500_Dose_[0]_3391ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 0); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void MCQValNumLTE500_Dose() throws Exception { + String filename = testFileDir + "/MCQValNumLTE500_Dose_[17]_2000ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 17); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void TQQAPA() throws Exception { + String filename = testFileDir + "/TQQAPA_[17]_4219ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 17); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + + @Test + public void TQQSVPASV() throws Exception { + String filename = testFileDir + "/TQQSVPASV_[17]_14516ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 17); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void TQQSVPSV() throws Exception { + String filename = testFileDir + "/TQQSVPSV_[17]_5532ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 17); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void CQOcrGt1x() throws Exception { + String filename = testFileDir + "/CQOcrGt1x_[12]_1671ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 12); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void CQEx_ischHrt_Fem() throws Exception { + String filename = testFileDir + "/CQEx_ischHrt-Fem_[9]_2485ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 9); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void CQDt_ischHrt() throws Exception { + String filename = testFileDir + "/CQDt_ischHrt_[2]_1657ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 2); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void SQP1I1P2I1_ischHrt_Fem() throws Exception { + String filename = testFileDir + "/SQP1I1P2I1_ischHrt-Fem_[8]_2344ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 8); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void SQP1I1_ischHrt() throws Exception { + String filename = testFileDir + "/SQP1I1_ischHrt_[17]_1657ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 17); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + + + @Test + public void getAllResults() throws Exception { + String filename = testFileDir + "/setfinder_allresulttype_[133].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 133); + else if (results.getQueryResultType().getName().equals("PATIENTSET")) + assertEquals(results.getSetSize(), 133); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + + @Test + public void DateContraintEnddateEqual() throws Exception { + String filename = testFileDir + "/setfinder_dateconstraint_enddate_equal_[0].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 0); + else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) + assertEquals(results.getSetSize(), 0); + else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) + assertEquals(results.getSetSize(), 0); + else if (results.getQueryResultType().getName().equals("PATIENTSET")) + assertEquals(results.getSetSize(), 0); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void DateContraintEnddateGreaterthan() throws Exception { + String filename = testFileDir + "/setfinder_dateconstraint_enddate_greaterthan_[5].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 5); + else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) + assertEquals(results.getSetSize(), 5); + else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) + assertEquals(results.getSetSize(), 5); + else if (results.getQueryResultType().getName().equals("PATIENTSET")) + assertEquals(results.getSetSize(), 5); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void DateContraintEnddateLessthan() throws Exception { + String filename = testFileDir + "/setfinder_dateconstraint_enddate_lessthan_[3].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 3); + else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) + assertEquals(results.getSetSize(), 3); + else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) + assertEquals(results.getSetSize(), 3); + else if (results.getQueryResultType().getName().equals("PATIENTSET")) + assertEquals(results.getSetSize(), 3); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void DateContraintStartdateBetween() throws Exception { + String filename = testFileDir + "/setfinder_dateconstraint_startdate_between_[1].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 1); + else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) + assertEquals(results.getSetSize(), 1); + else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) + assertEquals(results.getSetSize(), 1); + else if (results.getQueryResultType().getName().equals("PATIENTSET")) + assertEquals(results.getSetSize(), 1); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void DateContraintStartdateEqual() throws Exception { + String filename = testFileDir + "/setfinder_dateconstraint_startdate_equal_[0].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 0); + else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) + assertEquals(results.getSetSize(), 0); + else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) + assertEquals(results.getSetSize(), 0); + else if (results.getQueryResultType().getName().equals("PATIENTSET")) + assertEquals(results.getSetSize(), 0); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void DateContraintStartdateGreaterthan() throws Exception { + String filename = testFileDir + "/setfinder_dateconstraint_startdate_greaterthan_[12].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 12); + else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) + assertEquals(results.getSetSize(), 12); + else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) + assertEquals(results.getSetSize(), 12); + else if (results.getQueryResultType().getName().equals("PATIENTSET")) + assertEquals(results.getSetSize(), 12); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void DateContraintStartdateLessthan() throws Exception { + String filename = testFileDir + "/setfinder_dateconstraint_startdate_lessthan_[3].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 3); + else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) + assertEquals(results.getSetSize(), 3); + else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) + assertEquals(results.getSetSize(), 3); + else if (results.getQueryResultType().getName().equals("PATIENTSET")) + assertEquals(results.getSetSize(), 3); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + + @Test + public void DateContraintStartenddate() throws Exception { + String filename = testFileDir + "/setfinder_dateconstraint_startenddate_[3].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 3); + else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) + assertEquals(results.getSetSize(), 3); + else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) + assertEquals(results.getSetSize(), 3); + else if (results.getQueryResultType().getName().equals("PATIENTSET")) + assertEquals(results.getSetSize(), 3); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + + @Test + public void DateContraint() throws Exception { + String filename = testFileDir + "/setfinder_dateconstraint_[131].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 131); + else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) + assertEquals(results.getSetSize(), 131); + else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) + assertEquals(results.getSetSize(), 131); + else if (results.getQueryResultType().getName().equals("PATIENTSET")) + assertEquals(results.getSetSize(), 131); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + + @Test + public void InvertWithNoItem() throws Exception { + String filename = testFileDir + "/setfinder_invert_withnoitem_[134].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 134); + else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) + assertEquals(results.getSetSize(), 134); + else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) + assertEquals(results.getSetSize(), 134); + else if (results.getQueryResultType().getName().equals("PATIENTSET")) + assertEquals(results.getSetSize(), 134); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void ModifierConstraint() throws Exception { + String filename = testFileDir + "/setfinder_modifierconstraint_[11].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 11); + else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) + assertEquals(results.getSetSize(), 11); + else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) + assertEquals(results.getSetSize(), 11); + else if (results.getQueryResultType().getName().equals("PATIENTSET")) + assertEquals(results.getSetSize(), 11); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void NumberConstraintBetween() throws Exception { + String filename = testFileDir + "/setfinder_numberconstraint_BETWEEN_[113].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 113); + else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) + assertEquals(results.getSetSize(), 113); + else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) + assertEquals(results.getSetSize(), 113); + else if (results.getQueryResultType().getName().equals("PATIENTSET")) + assertEquals(results.getSetSize(), 113); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void NumberConstraintEqual() throws Exception { + String filename = testFileDir + "/setfinder_numberconstraint_EQ_[11].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 11); + else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) + assertEquals(results.getSetSize(), 11); + else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) + assertEquals(results.getSetSize(), 11); + else if (results.getQueryResultType().getName().equals("PATIENTSET")) + assertEquals(results.getSetSize(), 11); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + @Test + public void NumberConstraintGreaterEqual() throws Exception { + String filename = testFileDir + "/setfinder_numberconstraint_GE_[114].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 114); + else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) + assertEquals(results.getSetSize(), 114); + else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) + assertEquals(results.getSetSize(), 114); + else if (results.getQueryResultType().getName().equals("PATIENTSET")) + assertEquals(results.getSetSize(), 114); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void NumberConstraintGreaterThan() throws Exception { + String filename = testFileDir + "/setfinder_numberconstraint_GT_[114].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 114); + else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) + assertEquals(results.getSetSize(), 114); + else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) + assertEquals(results.getSetSize(), 114); + else if (results.getQueryResultType().getName().equals("PATIENTSET")) + assertEquals(results.getSetSize(), 114); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + @Test + public void NumberConstraintLessEqual() throws Exception { + String filename = testFileDir + "/setfinder_numberconstraint_LE_[122].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 122); + else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) + assertEquals(results.getSetSize(), 122); + else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) + assertEquals(results.getSetSize(), 122); + else if (results.getQueryResultType().getName().equals("PATIENTSET")) + assertEquals(results.getSetSize(), 122); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + @Test + public void NumberConstraintLessThan() throws Exception { + String filename = testFileDir + "/setfinder_numberconstraint_LT_[121].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 121); + else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) + assertEquals(results.getSetSize(), 121); + else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) + assertEquals(results.getSetSize(), 121); + else if (results.getQueryResultType().getName().equals("PATIENTSET")) + assertEquals(results.getSetSize(), 121); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + + @Test + public void NumberConstraint() throws Exception { + String filename = testFileDir + "/setfinder_numberconstraint_[22].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 22); + else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) + assertEquals(results.getSetSize(), 22); + else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) + assertEquals(results.getSetSize(), 22); + else if (results.getQueryResultType().getName().equals("PATIENTSET")) + assertEquals(results.getSetSize(), 22); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void Panel1Item3() throws Exception { + String filename = testFileDir + "/setfinder_panel_1_item_3_[1].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 1); + else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) + assertEquals(results.getSetSize(), 1); + else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) + assertEquals(results.getSetSize(), 1); + else if (results.getQueryResultType().getName().equals("PATIENTSET")) + assertEquals(results.getSetSize(), 1); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + + + + + @Test + public void PanelTimingAny() throws Exception { + String filename = testFileDir + "/setfinder_paneltiming_any_[133].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 133); + else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) + assertEquals(results.getSetSize(), 133); + else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) + assertEquals(results.getSetSize(), 133); + else if (results.getQueryResultType().getName().equals("PATIENTSET")) + assertEquals(results.getSetSize(), 133); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + + + @Test + public void FlagconstraintEqual() throws Exception { + String filename = testFileDir + "/setfinder_query_flagconstraint_EQ_[1].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 1); + else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) + assertEquals(results.getSetSize(), 1); + else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) + assertEquals(results.getSetSize(), 1); + else if (results.getQueryResultType().getName().equals("PATIENTSET")) + assertEquals(results.getSetSize(), 1); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + + @Test + public void FlagconstraintIN() throws Exception { + String filename = testFileDir + "/setfinder_query_flagconstraint_IN_[1].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 1); + else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) + assertEquals(results.getSetSize(), 1); + else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) + assertEquals(results.getSetSize(), 1); + else if (results.getQueryResultType().getName().equals("PATIENTSET")) + assertEquals(results.getSetSize(), 1); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void FlagconstraintNotEqual() throws Exception { + String filename = testFileDir + "/setfinder_query_flagconstraint_NE_[3].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 3); + else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) + assertEquals(results.getSetSize(), 3); + else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) + assertEquals(results.getSetSize(), 3); + else if (results.getQueryResultType().getName().equals("PATIENTSET")) + assertEquals(results.getSetSize(), 3); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void Flagconstraint() throws Exception { + String filename = testFileDir + "/setfinder_query_flagconstraint_[1].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 1); + else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) + assertEquals(results.getSetSize(), 1); + else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) + assertEquals(results.getSetSize(), 1); + else if (results.getQueryResultType().getName().equals("PATIENTSET")) + assertEquals(results.getSetSize(), 1); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + + @Test + public void ModifierconstraintEqual() throws Exception { + String filename = testFileDir + "/setfinder_query_modifierconstraint_EQ_[0].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 0); + else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) + assertEquals(results.getSetSize(), 0); + else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) + assertEquals(results.getSetSize(), 0); + else if (results.getQueryResultType().getName().equals("PATIENTSET")) + assertEquals(results.getSetSize(), 0); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void ModifierconstraintIN() throws Exception { + String filename = testFileDir + "/setfinder_query_modifierconstraint_IN_[0].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 0); + else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) + assertEquals(results.getSetSize(), 0); + else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) + assertEquals(results.getSetSize(), 0); + else if (results.getQueryResultType().getName().equals("PATIENTSET")) + assertEquals(results.getSetSize(), 0); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + @Test + public void ModifierconstraintLike() throws Exception { + String filename = testFileDir + "/setfinder_query_modifierconstraint_LIKE_[10].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 10); + else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) + assertEquals(results.getSetSize(), 10); + else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) + assertEquals(results.getSetSize(), 10); + else if (results.getQueryResultType().getName().equals("PATIENTSET")) + assertEquals(results.getSetSize(), 10); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void ModifierconstraintNotEqual() throws Exception { + String filename = testFileDir + "/setfinder_query_modifierconstraint_NE_[0].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 0); + else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) + assertEquals(results.getSetSize(), 0); + else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) + assertEquals(results.getSetSize(), 0); + else if (results.getQueryResultType().getName().equals("PATIENTSET")) + assertEquals(results.getSetSize(), 0); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void Modifierconstraint() throws Exception { + String filename = testFileDir + "/setfinder_query_modifierconstraint_[0].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 0); + else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) + assertEquals(results.getSetSize(), 0); + else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) + assertEquals(results.getSetSize(), 0); + else if (results.getQueryResultType().getName().equals("PATIENTSET")) + assertEquals(results.getSetSize(), 0); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + + @Test + public void TextconstraintEqual() throws Exception { + String filename = testFileDir + "/setfinder_query_textconstraint_EQ_[23 OR 13].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + { + if (results.getSetSize() == 13) + assertEquals(results.getSetSize(), 13); + else if (results.getSetSize() == 23) + assertEquals(results.getSetSize(), 23); + else + assertTrue(false); + } + } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + + @Test + public void TextconstraintLike() throws Exception { + String filename = testFileDir + "/setfinder_query_textconstraint_LIKE_[90].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 90); + else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) + assertEquals(results.getSetSize(), 90); + else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) + assertEquals(results.getSetSize(), 90); + else if (results.getQueryResultType().getName().equals("PATIENTSET")) + assertEquals(results.getSetSize(), 90); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void TextconstraintNotEqual() throws Exception { + String filename = testFileDir + "/setfinder_query_textconstraint_NE_[99 OR 101].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + { + if (results.getSetSize() == 101) + assertEquals(results.getSetSize(), 101); + else if (results.getSetSize() == 99) + assertEquals(results.getSetSize(), 99); + else + assertTrue(false); + } + } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void Textconstraint() throws Exception { + String filename = testFileDir + "/setfinder_query_textconstraint_[23 OR 13].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + { + if (results.getSetSize() == 13) + assertEquals(results.getSetSize(), 13); + else if (results.getSetSize() == 23) + assertEquals(results.getSetSize(), 23); + else + assertTrue(false); + } + } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + + + @Test + public void QueryTimingSameInstanceNum() throws Exception { + String filename = testFileDir + "/setfinder_querytiming_sameinstancenum_[133].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 133); + else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) + assertEquals(results.getSetSize(), 133); + else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) + assertEquals(results.getSetSize(), 133); + else if (results.getQueryResultType().getName().equals("PATIENTSET")) + assertEquals(results.getSetSize(), 133); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void TotalItemOccurrencesEqual() throws Exception { + String filename = testFileDir + "/setfinder_totalitemoccurrences_EQ_[133].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 133); + else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) + assertEquals(results.getSetSize(), 133); + else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) + assertEquals(results.getSetSize(), 133); + else if (results.getQueryResultType().getName().equals("PATIENTSET")) + assertEquals(results.getSetSize(), 133); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void TotalItemOccurrences_GreaterEqual() throws Exception { + String filename = testFileDir + "/setfinder_totalitemoccurrences_GE_[133].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 133); + else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) + assertEquals(results.getSetSize(), 133); + else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) + assertEquals(results.getSetSize(), 133); + else if (results.getQueryResultType().getName().equals("PATIENTSET")) + assertEquals(results.getSetSize(), 133); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void TotalItemOccurrencesLessEqual() throws Exception { + String filename = testFileDir + "/setfinder_totalitemoccurrences_LE_[133].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 133); + else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) + assertEquals(results.getSetSize(), 133); + else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) + assertEquals(results.getSetSize(), 133); + else if (results.getQueryResultType().getName().equals("PATIENTSET")) + assertEquals(results.getSetSize(), 133); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void TotalItemOccurrencesNotEqual() throws Exception { + String filename = testFileDir + "/setfinder_totalitemoccurrences_NE_[133].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 133); + else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) + assertEquals(results.getSetSize(), 133); + else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) + assertEquals(results.getSetSize(), 133); + else if (results.getQueryResultType().getName().equals("PATIENTSET")) + assertEquals(results.getSetSize(), 133); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void TotalItemOccurrences() throws Exception { + String filename = testFileDir + "/setfinder_totalitemoccurrences_[133].xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 133); + else if (results.getQueryResultType().getName().equals("PATIENT_GENDER_COUNT_XML")) + assertEquals(results.getSetSize(), 133); + else if (results.getQueryResultType().getName().equals("PATIENT_VITALSTATUS_COUNT_XML")) + assertEquals(results.getSetSize(), 133); + else if (results.getQueryResultType().getName().equals("PATIENTSET")) + assertEquals(results.getSetSize(), 133); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void SQP1I1_Circulatory4TemporalAny() throws Exception { + String filename = testFileDir + "/SQP1I1_Circulatory_Any_[66]_3016ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 66); + else if (results.getQueryResultType().getName().equals("PATIENTSET")) + assertEquals(results.getSetSize(), 66); + else if (results.getQueryResultType().getName().equals("PATIENT_ENCOUNTER_SET")) + assertEquals(results.getSetSize(), 66); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + @Test + public void SQP1I1_Circulatory4TemporalSame() throws Exception { + String filename = testFileDir + "/SQP1I1_Circulatory_Same_[66]_3016ms.xml"; + try { + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals(results.getSetSize(), 66); + else if (results.getQueryResultType().getName().equals("PATIENTSET")) + assertEquals(results.getSetSize(), 66); + else if (results.getQueryResultType().getName().equals("PATIENT_ENCOUNTER_SET")) + assertEquals(results.getSetSize(), 66); + else + assertTrue(false); + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + + @Test + public void AllTemporalTests() throws Exception { + // String filename = testFileDir + "/SQP1I1_Circulatory_Same_[66]_3016ms.xml"; + try { + File f = new File(testFileDir + "/temporal"); + ArrayList names = new ArrayList(Arrays.asList(f.list())); + + for (String filename: names) { + if (filename.startsWith("QT_SI_P")) { + int result = Integer.parseInt(filename.substring(filename.indexOf('[')+1,filename.indexOf(']') )); + filename = testFileDir + "/temporal/" + filename; + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals("Working on: " + filename, results.getSetSize(), result); + else + assertTrue(false); + } + } + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + + @Test + public void AllIdentityTests() throws Exception { + // String filename = testFileDir + "/SQP1I1_Circulatory_Same_[66]_3016ms.xml"; + try { + File f = new File(testFileDir + "/identity"); + ArrayList names = new ArrayList(Arrays.asList(f.list())); + + for (String filename: names) { + if (filename.startsWith("QT_SI")) { + int result = Integer.parseInt(filename.substring(filename.indexOf('[')+1,filename.indexOf(']') )); + filename = testFileDir + "/identity/" + filename; + String requestString = getQueryString(filename); + OMElement requestElement = convertStringToOMElement(requestString); + OMElement responseElement = getServiceClient(setfinderUrl).sendReceive(requestElement); + + //read test file and store query instance ; + //unmarshall this response string + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil().unMashallFromString(responseElement.toString()); + ResponseMessageType r = (ResponseMessageType)responseJaxb.getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + MasterInstanceResultResponseType masterInstanceResult = (MasterInstanceResultResponseType)helper.getObjectByClass(r.getMessageBody().getAny(),MasterInstanceResultResponseType.class); + + assertNotNull(masterInstanceResult); + for (QueryResultInstanceType results :masterInstanceResult.getQueryResultInstance() ) + { + if (results.getQueryResultType().getName().equals("PATIENT_COUNT_XML")) + assertEquals("Working on: " + filename, results.getSetSize(), result); + else + assertTrue(false); + } + } + } + } catch (Exception e) { + e.printStackTrace(); + assertTrue(false); + } + } + public static RequestMessageType buildRequestMessage(PsmQryHeaderType requestHeaderType, RequestType requestType) { + //create body type + BodyType bodyType = new BodyType(); + ObjectFactory of = new ObjectFactory(); + bodyType.getAny().add(of.createPsmheader(requestHeaderType)); + bodyType.getAny().add(of.createRequest(requestType)); + RequestMessageType requestMessageType = new RequestMessageType(); + requestMessageType.setMessageHeader(generateMessageHeader()); + requestMessageType.setMessageBody(bodyType); + requestMessageType.setRequestHeader(generateRequestHeader()); + return requestMessageType; + } + +} diff --git a/edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/dao/pdo/DataSourceLookupTest.java b/edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/dao/pdo/DataSourceLookupTest.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/dao/pdo/DataSourceLookupTest.java rename to edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/dao/pdo/DataSourceLookupTest.java diff --git a/edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/dao/pdo/FactRelatedQueryHandlerTest.java b/edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/dao/pdo/FactRelatedQueryHandlerTest.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/dao/pdo/FactRelatedQueryHandlerTest.java rename to edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/dao/pdo/FactRelatedQueryHandlerTest.java diff --git a/edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/dao/pdo/TablePdoQueryConceptDaoTest.java b/edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/dao/pdo/TablePdoQueryConceptDaoTest.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/dao/pdo/TablePdoQueryConceptDaoTest.java rename to edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/dao/pdo/TablePdoQueryConceptDaoTest.java diff --git a/edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/dao/pdo/TablePdoQueryEidDaoTest.java b/edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/dao/pdo/TablePdoQueryEidDaoTest.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/dao/pdo/TablePdoQueryEidDaoTest.java rename to edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/dao/pdo/TablePdoQueryEidDaoTest.java diff --git a/edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/dao/pdo/TablePdoQueryPatientDaoTest.java b/edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/dao/pdo/TablePdoQueryPatientDaoTest.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/dao/pdo/TablePdoQueryPatientDaoTest.java rename to edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/dao/pdo/TablePdoQueryPatientDaoTest.java diff --git a/edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/dao/pdo/TablePdoQueryPidDaoTest.java b/edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/dao/pdo/TablePdoQueryPidDaoTest.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/dao/pdo/TablePdoQueryPidDaoTest.java rename to edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/dao/pdo/TablePdoQueryPidDaoTest.java diff --git a/edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/dao/pdo/TablePdoQueryProviderDaoTest.java b/edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/dao/pdo/TablePdoQueryProviderDaoTest.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/dao/pdo/TablePdoQueryProviderDaoTest.java rename to edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/dao/pdo/TablePdoQueryProviderDaoTest.java diff --git a/edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/dao/pdo/TablePdoQueryVisitDaoTest.java b/edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/dao/pdo/TablePdoQueryVisitDaoTest.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/dao/pdo/TablePdoQueryVisitDaoTest.java rename to edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/dao/pdo/TablePdoQueryVisitDaoTest.java diff --git a/edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/dao/setfinder/PatientSetResultDaoTest.java b/edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/dao/setfinder/PatientSetResultDaoTest.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/dao/setfinder/PatientSetResultDaoTest.java rename to edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/dao/setfinder/PatientSetResultDaoTest.java diff --git a/edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/dao/setfinder/QueryInstanceDaoTest.java b/edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/dao/setfinder/QueryInstanceDaoTest.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/dao/setfinder/QueryInstanceDaoTest.java rename to edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/dao/setfinder/QueryInstanceDaoTest.java diff --git a/edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/dao/setfinder/QueryMasterDaoTest.java b/edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/dao/setfinder/QueryMasterDaoTest.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/dao/setfinder/QueryMasterDaoTest.java rename to edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/dao/setfinder/QueryMasterDaoTest.java index fc8429b9..23e8a6b4 --- a/edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/dao/setfinder/QueryMasterDaoTest.java +++ b/edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/dao/setfinder/QueryMasterDaoTest.java @@ -1,95 +1,95 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder; - -import java.util.Date; -import java.util.List; - -import javax.sql.DataSource; - -import org.junit.BeforeClass; -import org.junit.Test; - -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.db.QtQueryMaster; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - -public class QueryMasterDaoTest { - - static QueryMasterSpringDao qmDAO = null; - static String queryMasterId = null; - - @BeforeClass - public static void setUp() throws Exception { - /* - * String hiveId = "HIVE",projectId="/Asthma/1/1/",ownerId="@"; - * DAOFactoryHelper daoFactoryHelper = new DAOFactoryHelper(hiveId, - * projectId, ownerId); IDAOFactory daoFactory = - * daoFactoryHelper.getDAOFactory(); sfDaoFactory = - * daoFactory.getSetFinderDAOFactory(); IQueryMasterDao qmDAO = - * sfDaoFactory.getQueryMasterDAO(); - */ - - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - DataSourceLookup dataSourceLookup = null; - // instanciate datasource - DataSource dataSource = QueryProcessorUtil.getInstance() - .getSpringDataSource(dataSourceLookup.getDataSource()); - - // create QueryMasterDao - qmDAO = new QueryMasterSpringDao(dataSource, dataSourceLookup); - QtQueryMaster queryMaster = new QtQueryMaster(); - queryMaster.setUserId("test_user"); - queryMaster.setGroupId("test_group_id"); - queryMaster.setName("test_name"); - queryMaster.setCreateDate(new Date(System.currentTimeMillis())); - queryMaster.setRequestXml("test_request_xml"); - queryMaster.setDeleteFlag("N"); - queryMasterId = qmDAO.createQueryMaster(queryMaster, "i2b2xml", null); - System.out.println("Query master id " + queryMasterId); - } - - @Test - public void getQueryMasterByUserId() { - - List queryMasterList = qmDAO.getQueryMasterByUserId( - "test_user", 100, null, false); - org.junit.Assert.assertTrue(queryMasterList.size() > 0); - } - - @Test - public void getQueryMasterByGroup() { - - List queryMasterList = qmDAO.getQueryMasterByGroupId( - "test_group_id", 5, null, false); - org.junit.Assert.assertTrue(queryMasterList.size() > 0); - } - - @Test - public void getQueryDefinition() { - - QtQueryMaster queryMaster = qmDAO.getQueryDefinition(queryMasterId); - System.out.println(queryMaster.getQueryMasterId()); - org.junit.Assert.assertEquals("test_request_xml", queryMaster - .getRequestXml()); - } - - @Test - public void renameQuery() throws Exception { - - qmDAO.renameQuery(queryMasterId, "test_rename"); - } - - @Test - public void deleteQuery() throws Exception { - - qmDAO.deleteQuery(queryMasterId); - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder; + +import java.util.Date; +import java.util.List; + +import javax.sql.DataSource; + +import org.junit.BeforeClass; +import org.junit.Test; + +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.db.QtQueryMaster; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + +public class QueryMasterDaoTest { + + static QueryMasterSpringDao qmDAO = null; + static String queryMasterId = null; + + @BeforeClass + public static void setUp() throws Exception { + /* + * String hiveId = "HIVE",projectId="/Asthma/1/1/",ownerId="@"; + * DAOFactoryHelper daoFactoryHelper = new DAOFactoryHelper(hiveId, + * projectId, ownerId); IDAOFactory daoFactory = + * daoFactoryHelper.getDAOFactory(); sfDaoFactory = + * daoFactory.getSetFinderDAOFactory(); IQueryMasterDao qmDAO = + * sfDaoFactory.getQueryMasterDAO(); + */ + + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + DataSourceLookup dataSourceLookup = null; + // instanciate datasource + DataSource dataSource = QueryProcessorUtil.getInstance() + .getSpringDataSource(dataSourceLookup.getDataSource()); + + // create QueryMasterDao + qmDAO = new QueryMasterSpringDao(dataSource, dataSourceLookup); + QtQueryMaster queryMaster = new QtQueryMaster(); + queryMaster.setUserId("test_user"); + queryMaster.setGroupId("test_group_id"); + queryMaster.setName("test_name"); + queryMaster.setCreateDate(new Date(System.currentTimeMillis())); + queryMaster.setRequestXml("test_request_xml"); + queryMaster.setDeleteFlag("N"); + queryMasterId = qmDAO.createQueryMaster(queryMaster, "i2b2xml", null); + System.out.println("Query master id " + queryMasterId); + } + + @Test + public void getQueryMasterByUserId() { + + List queryMasterList = qmDAO.getQueryMasterByUserId( + "test_user", 100, null, false); + org.junit.Assert.assertTrue(queryMasterList.size() > 0); + } + + @Test + public void getQueryMasterByGroup() { + + List queryMasterList = qmDAO.getQueryMasterByGroupId( + "test_group_id", 5, null, false); + org.junit.Assert.assertTrue(queryMasterList.size() > 0); + } + + @Test + public void getQueryDefinition() { + + QtQueryMaster queryMaster = qmDAO.getQueryDefinition(queryMasterId); + System.out.println(queryMaster.getQueryMasterId()); + org.junit.Assert.assertEquals("test_request_xml", queryMaster + .getRequestXml()); + } + + @Test + public void renameQuery() throws Exception { + + qmDAO.renameQuery(queryMasterId, "test_rename"); + } + + @Test + public void deleteQuery() throws Exception { + + qmDAO.deleteQuery(queryMasterId); + } + +} diff --git a/edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/dao/setfinder/QueryProcessorUtilTest.java b/edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/dao/setfinder/QueryProcessorUtilTest.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/dao/setfinder/QueryProcessorUtilTest.java rename to edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/dao/setfinder/QueryProcessorUtilTest.java index d93e92d1..7213df36 --- a/edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/dao/setfinder/QueryProcessorUtilTest.java +++ b/edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/dao/setfinder/QueryProcessorUtilTest.java @@ -1,135 +1,135 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.dao.setfinder; - -import static org.junit.Assert.assertNotNull; - -import java.io.StringReader; -import java.sql.Connection; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Calendar; - -import jakarta.xml.bind.JAXBContext; -import jakarta.xml.bind.JAXBElement; -import jakarta.xml.bind.Marshaller; -import jakarta.xml.bind.Unmarshaller; -import javax.xml.datatype.DatatypeFactory; -import javax.xml.datatype.XMLGregorianCalendar; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; - -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; -import org.w3c.dom.Document; - -import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.crc.axis2.CRCAxisAbstract; -import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.QueryToolUtil; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionRequestType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionType; -import edu.harvard.i2b2.crc.util.QueryProcessorUtil; - -public class QueryProcessorUtilTest { - - private static String testFileDir = null; - - @BeforeClass - public static void init() throws Exception { - testFileDir = System.getProperty("testfiledir"); - System.out.println("test file dir " + testFileDir); - - if (!((testFileDir != null) && (testFileDir.trim().length() > 0))) { - throw new Exception( - "please provide test file directory info -Dtestfiledir"); - } - } - - /* - @Ignore - @Test - - public void testQueryDefinitionDOM() throws Exception { - QueryToolUtil queryUtil = new QueryToolUtil(); - QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); - Connection conn = qpUtil.getManualConnection(); - assertNotNull("check database connection not null", conn); - - String filename = testFileDir - + "\\edu.harvard.i2b2.crc.dao.setfinder.querybuilder\\setfinder_query.xml"; - String xml = CRCAxisAbstract.getQueryString(filename); - JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); - RequestMessageType reqMsgType = (RequestMessageType) jaxbUtil - .unMashallFromString(xml).getValue(); - System.out.println(reqMsgType.getMessageHeader().getMessageControlId()); - JAXBUnWrapHelper unWrapHelper = new JAXBUnWrapHelper(); - QueryDefinitionRequestType queryDefinitionType = (QueryDefinitionRequestType) unWrapHelper - .getObjectByClass( - reqMsgType.getMessageBody().getAny(), - edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionRequestType.class); - System.out.println("query namef" - + queryDefinitionType.getQueryDefinition().getQueryName()); - - JAXBContext jc = JAXBContext - .newInstance(edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionType.class); - Marshaller m = jc.createMarshaller(); - DocumentBuilderFactory f = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = f.newDocumentBuilder(); - Document doc = builder.newDocument(); - m - .marshal( - (new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory()) - .createQueryDefinition(queryDefinitionType - .getQueryDefinition()), doc); - - String domString = edu.harvard.i2b2.common.util.xml.XMLUtil - .convertDOMToString(doc); - System.out.println("string output" + domString); - - Document doc1 = edu.harvard.i2b2.common.util.xml.XMLUtil - .convertStringToDOM(domString); - System.out.println("string output" - + edu.harvard.i2b2.common.util.xml.XMLUtil - .convertDOMToString(doc1)); - - JAXBContext jc1 = JAXBContext - .newInstance(edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory.class); - Unmarshaller unMarshaller = jc1.createUnmarshaller(); - JAXBElement jaxbElement = (JAXBElement) unMarshaller - .unmarshal(new StringReader(domString)); - QueryDefinitionType qftype = (QueryDefinitionType) jaxbElement - .getValue(); - System.out.println("query name " + qftype.getQueryName()); - - } -*/ - @Test - public void testXmlToSqlDateConverion() throws Exception { - DatatypeFactory dataTypeFactory = DatatypeFactory.newInstance(); - XMLGregorianCalendar cal = dataTypeFactory - .newXMLGregorianCalendar("2004-07-15T00:00:00.000-04:00"); - System.out.println("XMLCalendar Hour " + cal.getHour() - + " Gregorian calendar hour " - + cal.toGregorianCalendar().get(Calendar.HOUR_OF_DAY)); - SimpleDateFormat dateFormat = new SimpleDateFormat( - "dd-MMM-yyyy HH:mm:ss"); - System.out.println("SimpleDate Format " - + dateFormat.format(cal.toGregorianCalendar().getTime()) - + " orginal XML string " + "2004-07-15T00:00:00.000-04:00"); - System.out.println("DateFormat Format " - + DateFormat.getInstance().format( - cal.toGregorianCalendar().getTime())); - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.dao.setfinder; + +import static org.junit.Assert.assertNotNull; + +import java.io.StringReader; +import java.sql.Connection; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Calendar; + +import jakarta.xml.bind.JAXBContext; +import jakarta.xml.bind.JAXBElement; +import jakarta.xml.bind.Marshaller; +import jakarta.xml.bind.Unmarshaller; +import javax.xml.datatype.DatatypeFactory; +import javax.xml.datatype.XMLGregorianCalendar; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; + +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; +import org.w3c.dom.Document; + +import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.crc.axis2.CRCAxisAbstract; +import edu.harvard.i2b2.crc.dao.setfinder.querybuilder.QueryToolUtil; +import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; +import edu.harvard.i2b2.crc.datavo.db.DataSourceLookup; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionRequestType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionType; +import edu.harvard.i2b2.crc.util.QueryProcessorUtil; + +public class QueryProcessorUtilTest { + + private static String testFileDir = null; + + @BeforeClass + public static void init() throws Exception { + testFileDir = System.getProperty("testfiledir"); + System.out.println("test file dir " + testFileDir); + + if (!((testFileDir != null) && (testFileDir.trim().length() > 0))) { + throw new Exception( + "please provide test file directory info -Dtestfiledir"); + } + } + + /* + @Ignore + @Test + + public void testQueryDefinitionDOM() throws Exception { + QueryToolUtil queryUtil = new QueryToolUtil(); + QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); + Connection conn = qpUtil.getManualConnection(); + assertNotNull("check database connection not null", conn); + + String filename = testFileDir + + "\\edu.harvard.i2b2.crc.dao.setfinder.querybuilder\\setfinder_query.xml"; + String xml = CRCAxisAbstract.getQueryString(filename); + JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); + RequestMessageType reqMsgType = (RequestMessageType) jaxbUtil + .unMashallFromString(xml).getValue(); + System.out.println(reqMsgType.getMessageHeader().getMessageControlId()); + JAXBUnWrapHelper unWrapHelper = new JAXBUnWrapHelper(); + QueryDefinitionRequestType queryDefinitionType = (QueryDefinitionRequestType) unWrapHelper + .getObjectByClass( + reqMsgType.getMessageBody().getAny(), + edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionRequestType.class); + System.out.println("query namef" + + queryDefinitionType.getQueryDefinition().getQueryName()); + + JAXBContext jc = JAXBContext + .newInstance(edu.harvard.i2b2.crc.datavo.setfinder.query.QueryDefinitionType.class); + Marshaller m = jc.createMarshaller(); + DocumentBuilderFactory f = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = f.newDocumentBuilder(); + Document doc = builder.newDocument(); + m + .marshal( + (new edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory()) + .createQueryDefinition(queryDefinitionType + .getQueryDefinition()), doc); + + String domString = edu.harvard.i2b2.common.util.xml.XMLUtil + .convertDOMToString(doc); + System.out.println("string output" + domString); + + Document doc1 = edu.harvard.i2b2.common.util.xml.XMLUtil + .convertStringToDOM(domString); + System.out.println("string output" + + edu.harvard.i2b2.common.util.xml.XMLUtil + .convertDOMToString(doc1)); + + JAXBContext jc1 = JAXBContext + .newInstance(edu.harvard.i2b2.crc.datavo.setfinder.query.ObjectFactory.class); + Unmarshaller unMarshaller = jc1.createUnmarshaller(); + JAXBElement jaxbElement = (JAXBElement) unMarshaller + .unmarshal(new StringReader(domString)); + QueryDefinitionType qftype = (QueryDefinitionType) jaxbElement + .getValue(); + System.out.println("query name " + qftype.getQueryName()); + + } +*/ + @Test + public void testXmlToSqlDateConverion() throws Exception { + DatatypeFactory dataTypeFactory = DatatypeFactory.newInstance(); + XMLGregorianCalendar cal = dataTypeFactory + .newXMLGregorianCalendar("2004-07-15T00:00:00.000-04:00"); + System.out.println("XMLCalendar Hour " + cal.getHour() + + " Gregorian calendar hour " + + cal.toGregorianCalendar().get(Calendar.HOUR_OF_DAY)); + SimpleDateFormat dateFormat = new SimpleDateFormat( + "dd-MMM-yyyy HH:mm:ss"); + System.out.println("SimpleDate Format " + + dateFormat.format(cal.toGregorianCalendar().getTime()) + + " orginal XML string " + "2004-07-15T00:00:00.000-04:00"); + System.out.println("DateFormat Format " + + DateFormat.getInstance().format( + cal.toGregorianCalendar().getTime())); + } + +} diff --git a/edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/dao/setfinder/SQLServerTest.java b/edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/dao/setfinder/SQLServerTest.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/dao/setfinder/SQLServerTest.java rename to edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/dao/setfinder/SQLServerTest.java diff --git a/edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/dao/setfinder/UnitConverstionTest.java b/edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/dao/setfinder/UnitConverstionTest.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/dao/setfinder/UnitConverstionTest.java rename to edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/dao/setfinder/UnitConverstionTest.java diff --git a/edu.harvard.i2b2.server-common/src/test/edu/harvard/i2b2/common/datavo/I2B2MessageReadTest.java b/edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/datavo/common/I2B2MessageReadTest.java old mode 100755 new mode 100644 similarity index 83% rename from edu.harvard.i2b2.server-common/src/test/edu/harvard/i2b2/common/datavo/I2B2MessageReadTest.java rename to edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/datavo/common/I2B2MessageReadTest.java index b4818023..f352e7e4 --- a/edu.harvard.i2b2.server-common/src/test/edu/harvard/i2b2/common/datavo/I2B2MessageReadTest.java +++ b/edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/datavo/common/I2B2MessageReadTest.java @@ -1,74 +1,83 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.common.datavo; - -import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.core.datavo.pdo.PatientDataType; -import edu.harvard.i2b2.datavo.i2b2message.RequestMessageType; - -import junit.framework.TestCase; - -import java.io.BufferedReader; -import java.io.DataInputStream; -import java.io.InputStreamReader; - -import jakarta.xml.bind.JAXBElement; - - -public class I2B2MessageReadTest extends TestCase { - public void testReadI2B2RequestMessage() throws Exception { - RequestMessageType rmType = unMarshaller(); - log.debug("Sending app name: " + - rmType.getMessageHeader().getSendingApplication().getApplicationName()); - - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - PatientDataType pdType = (PatientDataType) helper.getObjectByClass(rmType.getMessageBody() - .getAny(), - PatientDataType.class); - - log.debug("Observation blob " + - pdType.getObservationFactSet().get(0).getObservationFact().get(0) - .getObservationBlob()); - - JAXBElement je = (JAXBElement) rmType.getMessageBody().getAny().get(0); - PatientDataType pd = (PatientDataType) je.getValue(); - log.debug("Concept cd " + - pd.getObservationFactSet().get(0).getObservationFact().get(0) - .getConceptCd()); - } - - - - private String getPFTString() throws Exception { - StringBuffer queryStr = new StringBuffer(); - DataInputStream dataStream = new DataInputStream(I2B2MessageReadTest.class.getResourceAsStream( - "Samplei2b2RequestMessage.xml")); - BufferedReader reader = new BufferedReader(new InputStreamReader( - dataStream)); - String singleLine = null; - - while ((singleLine = reader.readLine()) != null) { - queryStr.append(singleLine + "\n"); - } - return queryStr.toString(); - } - - private RequestMessageType unMarshaller() throws Exception { - String[] pak = new String[] { - "edu.harvard.i2b2.datavo.i2b2message", - "edu.harvard.i2b2.core.datavo.pdo" - }; - JAXBUtil util = new JAXBUtil(pak); - RequestMessageType rmType = (RequestMessageType) util.unMashallFromString(getPFTString()) - .getValue(); - - return rmType; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.datavo.common; + +import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.crc.datavo.pdo.PatientDataType; +import edu.harvard.i2b2.crc.ejb.ExecRunnable; +import junit.framework.TestCase; + +import java.io.BufferedReader; +import java.io.DataInputStream; +import java.io.InputStreamReader; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import jakarta.xml.bind.JAXBElement; + + +public class I2B2MessageReadTest extends TestCase { + + private static Log log = LogFactory.getLog(I2B2MessageReadTest.class); + + public void testReadI2B2RequestMessage() throws Exception { + + + + RequestMessageType rmType = unMarshaller(); + log.debug("Sending app name: " + + rmType.getMessageHeader().getSendingApplication().getApplicationName()); + + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + PatientDataType pdType = (PatientDataType) helper.getObjectByClass(rmType.getMessageBody() + .getAny(), + PatientDataType.class); + + /*log.debug("Observation blob " + + pdType.getObservationFactSet().get(0).getObservationFact().get(0) + .getObservationBlob());*/ + + JAXBElement je = (JAXBElement) rmType.getMessageBody().getAny().get(0); + PatientDataType pd = (PatientDataType) je.getValue(); + /*log.debug("Concept cd " + + pd.getObservationFactSet().get(0).getObservationFact().get(0) + .getConceptCd());*/ + } + + + + private String getPFTString() throws Exception { + StringBuffer queryStr = new StringBuffer(); + DataInputStream dataStream = new DataInputStream(I2B2MessageReadTest.class.getResourceAsStream( + "Samplei2b2RequestMessage.xml")); + BufferedReader reader = new BufferedReader(new InputStreamReader( + dataStream)); + String singleLine = null; + + while ((singleLine = reader.readLine()) != null) { + queryStr.append(singleLine + "\n"); + } + return queryStr.toString(); + } + + private RequestMessageType unMarshaller() throws Exception { + String[] pak = new String[] { + "edu.harvard.i2b2.datavo.i2b2message", + "edu.harvard.i2b2.core.datavo.pdo" + }; + JAXBUtil util = new JAXBUtil(pak); + RequestMessageType rmType = (RequestMessageType) util.unMashallFromString(getPFTString()) + .getValue(); + + return rmType; + } +} diff --git a/edu.harvard.i2b2.server-common/src/test/edu/harvard/i2b2/common/datavo/I2B2MessageWriteTest.java b/edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/datavo/common/I2B2MessageWriteTest.java old mode 100755 new mode 100644 similarity index 75% rename from edu.harvard.i2b2.server-common/src/test/edu/harvard/i2b2/common/datavo/I2B2MessageWriteTest.java rename to edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/datavo/common/I2B2MessageWriteTest.java index fb6cf33a..ce2b7e7c --- a/edu.harvard.i2b2.server-common/src/test/edu/harvard/i2b2/common/datavo/I2B2MessageWriteTest.java +++ b/edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/datavo/common/I2B2MessageWriteTest.java @@ -1,108 +1,113 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.common.datavo; - -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.core.datavo.pdo.PatientDataType; -import edu.harvard.i2b2.datavo.i2b2message.ApplicationType; -import edu.harvard.i2b2.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.datavo.i2b2message.MessageControlIdType; -import edu.harvard.i2b2.datavo.i2b2message.MessageHeaderType; -import edu.harvard.i2b2.datavo.i2b2message.MessageTypeType; -import edu.harvard.i2b2.datavo.i2b2message.RequestHeaderType; -import edu.harvard.i2b2.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.datavo.i2b2message.ResponseMessageType; - -import junit.framework.TestCase; - -import java.io.StringWriter; - -import jakarta.xml.bind.JAXBElement; - - -public class I2B2MessageWriteTest extends TestCase { - private MessageHeaderType createMessageHeader() { - MessageHeaderType messageHeader = new MessageHeaderType(); - messageHeader.setAcceptAcknowledgementType(new String("messageId")); - - MessageControlIdType mcIdType = new MessageControlIdType(); - mcIdType.setInstanceNum(1); - mcIdType.setMessageNum("1"); - mcIdType.setSessionId("1"); - messageHeader.setMessageControlId(mcIdType); - - MessageTypeType messageTypeType = new MessageTypeType(); - messageTypeType.setEventType("eventype"); - messageTypeType.setMessageCode("messageCode"); - messageHeader.setMessageType(messageTypeType); - - ApplicationType appType = new ApplicationType(); - appType.setApplicationName("appname"); - appType.setApplicationVersion("1.0"); - messageHeader.setSendingApplication(appType); - messageHeader.setReceivingApplication(appType); - - return messageHeader; - } - - public RequestHeaderType createRequestHeader() { - RequestHeaderType reqHeader = new RequestHeaderType(); - reqHeader.setResultWaittimeMs(1000); - - return reqHeader; - } - - private BodyType createBodyWithPDO() { - PatientDataMessageTest pdoTest = new PatientDataMessageTest(); - PatientDataType pdo = pdoTest.createPatientDataType(); - edu.harvard.i2b2.core.datavo.pdo.ObjectFactory of = new edu.harvard.i2b2.core.datavo.pdo.ObjectFactory(); - BodyType bodyType = new BodyType(); - bodyType.getAny().add(of.createPatientData(pdo)); - - return bodyType; - } - - private String getXMLString(JAXBElement jaxbElement) - throws Exception { - JAXBUtil jaxbUtil = new JAXBUtil(new String[] { - "edu.harvard.i2b2.datavo.i2b2message", - "edu.harvard.i2b2.core.datavo.pdo" - }); - StringWriter strWriter = new StringWriter(); - - jaxbUtil.marshaller(jaxbElement, strWriter); - - return strWriter.toString(); - } - - public void testWritei2b2RequestMessage() throws Exception { - RequestMessageType reqMsgType = new RequestMessageType(); - reqMsgType.setMessageHeader(createMessageHeader()); - reqMsgType.setMessageBody(createBodyWithPDO()); - reqMsgType.setRequestHeader(createRequestHeader()); - - edu.harvard.i2b2.datavo.i2b2message.ObjectFactory of = new edu.harvard.i2b2.datavo.i2b2message.ObjectFactory(); - JAXBElement jaxbElement = of.createRequest(reqMsgType); - String xmlMessage = getXMLString(jaxbElement); - log.debug("Request Message"); - log.debug(xmlMessage); - } - - public void testWritei2b2ResponseMessage() throws Exception { - ResponseMessageType resMsgType = new ResponseMessageType(); - resMsgType.setMessageHeader(createMessageHeader()); - resMsgType.setMessageBody(createBodyWithPDO()); - - edu.harvard.i2b2.datavo.i2b2message.ObjectFactory of = new edu.harvard.i2b2.datavo.i2b2message.ObjectFactory(); - JAXBElement jaxbElement = of.createResponse(resMsgType); - String xmlMessage = getXMLString(jaxbElement); - log.debug("Response Message"); - log.debug(xmlMessage); - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.datavo.common; + +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.crc.datavo.i2b2message.ApplicationType; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2message.MessageControlIdType; +import edu.harvard.i2b2.crc.datavo.i2b2message.MessageHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.MessageTypeType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestHeaderType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.crc.datavo.pdo.PatientDataType; +import junit.framework.TestCase; + +import java.io.StringWriter; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import jakarta.xml.bind.JAXBElement; + + +public class I2B2MessageWriteTest extends TestCase { + + private static Log log = LogFactory.getLog(I2B2MessageWriteTest.class); + + private MessageHeaderType createMessageHeader() { + MessageHeaderType messageHeader = new MessageHeaderType(); + messageHeader.setAcceptAcknowledgementType(new String("messageId")); + + MessageControlIdType mcIdType = new MessageControlIdType(); + mcIdType.setInstanceNum(1); + mcIdType.setMessageNum("1"); + mcIdType.setSessionId("1"); + messageHeader.setMessageControlId(mcIdType); + + MessageTypeType messageTypeType = new MessageTypeType(); + messageTypeType.setEventType("eventype"); + messageTypeType.setMessageCode("messageCode"); + messageHeader.setMessageType(messageTypeType); + + ApplicationType appType = new ApplicationType(); + appType.setApplicationName("appname"); + appType.setApplicationVersion("1.0"); + messageHeader.setSendingApplication(appType); + messageHeader.setReceivingApplication(appType); + + return messageHeader; + } + + public RequestHeaderType createRequestHeader() { + RequestHeaderType reqHeader = new RequestHeaderType(); + reqHeader.setResultWaittimeMs(1000); + + return reqHeader; + } + + private BodyType createBodyWithPDO() { + PatientDataMessageTest pdoTest = new PatientDataMessageTest(); + PatientDataType pdo = pdoTest.createPatientDataType(); + edu.harvard.i2b2.crc.datavo.pdo.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.pdo.ObjectFactory(); + BodyType bodyType = new BodyType(); + bodyType.getAny().add(of.createPatientData(pdo)); + + return bodyType; + } + + private String getXMLString(JAXBElement jaxbElement) + throws Exception { + JAXBUtil jaxbUtil = new JAXBUtil(new String[] { + "edu.harvard.i2b2.datavo.i2b2message", + "edu.harvard.i2b2.core.datavo.pdo" + }); + StringWriter strWriter = new StringWriter(); + + jaxbUtil.marshaller(jaxbElement, strWriter); + + return strWriter.toString(); + } + + public void testWritei2b2RequestMessage() throws Exception { + RequestMessageType reqMsgType = new RequestMessageType(); + reqMsgType.setMessageHeader(createMessageHeader()); + reqMsgType.setMessageBody(createBodyWithPDO()); + reqMsgType.setRequestHeader(createRequestHeader()); + + edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory(); + JAXBElement jaxbElement = of.createRequest(reqMsgType); + String xmlMessage = getXMLString(jaxbElement); + log.debug("Request Message"); + log.debug(xmlMessage); + } + + public void testWritei2b2ResponseMessage() throws Exception { + ResponseMessageType resMsgType = new ResponseMessageType(); + resMsgType.setMessageHeader(createMessageHeader()); + resMsgType.setMessageBody(createBodyWithPDO()); + + edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory(); + JAXBElement jaxbElement = of.createResponse(resMsgType); + String xmlMessage = getXMLString(jaxbElement); + log.debug("Response Message"); + log.debug(xmlMessage); + } +} diff --git a/edu.harvard.i2b2.server-common/src/test/edu/harvard/i2b2/common/datavo/PatientDataMessageTest.java b/edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/datavo/common/PatientDataMessageTest.java old mode 100755 new mode 100644 similarity index 74% rename from edu.harvard.i2b2.server-common/src/test/edu/harvard/i2b2/common/datavo/PatientDataMessageTest.java rename to edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/datavo/common/PatientDataMessageTest.java index b231b5d5..b5b9ff1f --- a/edu.harvard.i2b2.server-common/src/test/edu/harvard/i2b2/common/datavo/PatientDataMessageTest.java +++ b/edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/datavo/common/PatientDataMessageTest.java @@ -1,105 +1,107 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.common.datavo; - -import edu.harvard.i2b2.common.util.jaxb.DTOFactory; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.core.datavo.pdo.EncounterIdeType; -import edu.harvard.i2b2.core.datavo.pdo.ObservationFactType; -import edu.harvard.i2b2.core.datavo.pdo.PatientDataType; -import edu.harvard.i2b2.core.datavo.pdo.PatientIdeType; -import edu.harvard.i2b2.core.datavo.pdo.VisitDimensionType; - -import junit.framework.TestCase; - -import java.io.StringWriter; - -import java.util.Date; - -import jakarta.xml.bind.JAXBElement; - - -public class PatientDataMessageTest extends TestCase { - public VisitDimensionType getVisitDimensionType() { - VisitDimensionType visitType = new VisitDimensionType(); - visitType.setPatientIde(getPatientIde()); - visitType.setEncounterIde(getEncounterIde()); - visitType.setSourcesystemCd("i2b2"); - - return visitType; - } - - private PatientIdeType getPatientIde() { - PatientIdeType patientIde = new PatientIdeType(); - patientIde.setSource("i2b2"); - patientIde.setValue("10000"); - - return patientIde; - } - - private EncounterIdeType getEncounterIde() { - EncounterIdeType encounterIde = new EncounterIdeType(); - encounterIde.setSource("i2b2"); - encounterIde.setValue("1000001"); - - return encounterIde; - } - - // Function to build observation fact - public ObservationFactType getObservationFactType() { - Date currentDate = new Date(); - ObservationFactType obType = new ObservationFactType(); - DTOFactory dtoFactory = new DTOFactory(); - obType.setEndDate(dtoFactory.getXMLGregorianCalendar( - currentDate.getTime())); - obType.setConceptCd("i2b2:60004"); - obType.setConfidenceNum(1d); - obType.setEncounterIde(getEncounterIde()); - obType.setPatientIde(getPatientIde()); - obType.setSourcesystemCd("i2b2"); - obType.setTvalChar("tval"); - obType.setNvalNum(100.0); - obType.setObservationBlob("BLOB"); - - return obType; - } - - public PatientDataType createPatientDataType() { - PatientDataType patientData = new PatientDataType(); - PatientDataType.VisitDimensionSet vdSet = new PatientDataType.VisitDimensionSet(); - vdSet.getVisitDimension().add(getVisitDimensionType()); - patientData.setVisitDimensionSet(vdSet); - - PatientDataType.ObservationFactSet obsSet = new PatientDataType.ObservationFactSet(); - obsSet.getObservationFact().add(getObservationFactType()); - patientData.getObservationFactSet().add(obsSet); - - return patientData; - } - - private String getXMLString(JAXBElement jaxbElement) - throws Exception { - JAXBUtil jaxbUtil = new JAXBUtil(new String[] { - "edu.harvard.i2b2.core.datavo.pdo" - }); - StringWriter strWriter = new StringWriter(); - - jaxbUtil.marshaller(jaxbElement, strWriter); - - return strWriter.toString(); - } - - public void testPatientDataMessage() throws Exception { - edu.harvard.i2b2.core.datavo.pdo.ObjectFactory of = new edu.harvard.i2b2.core.datavo.pdo.ObjectFactory(); - JAXBElement jaxbElement = of.createPatientData(createPatientDataType()); - String xmlMessage = getXMLString(jaxbElement); - log.debug("Patient Data Message"); - log.debug(xmlMessage); - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.datavo.common; + +import edu.harvard.i2b2.common.util.jaxb.DTOFactory; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.crc.datavo.pdo.PatientDataType; +import junit.framework.TestCase; + +import java.io.StringWriter; + +import java.util.Date; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import jakarta.xml.bind.JAXBElement; + + +public class PatientDataMessageTest extends TestCase { + + private static Log log = LogFactory.getLog(PatientDataMessageTest.class); + + /*public VisitDimensionType getVisitDimensionType() { + VisitDimensionType visitType = new VisitDimensionType(); + visitType.setPatientIde(getPatientIde()); + visitType.setEncounterIde(getEncounterIde()); + visitType.setSourcesystemCd("i2b2"); + + return visitType; + } + + private PatientIdeType getPatientIde() { + PatientIdeType patientIde = new PatientIdeType(); + patientIde.setSource("i2b2"); + patientIde.setValue("10000"); + + return patientIde; + } + + private EncounterIdeType getEncounterIde() { + EncounterIdeType encounterIde = new EncounterIdeType(); + encounterIde.setSource("i2b2"); + encounterIde.setValue("1000001"); + + return encounterIde; + } + + // Function to build observation fact + public ObservationFactType getObservationFactType() { + Date currentDate = new Date(); + ObservationFactType obType = new ObservationFactType(); + DTOFactory dtoFactory = new DTOFactory(); + obType.setEndDate(dtoFactory.getXMLGregorianCalendar( + currentDate.getTime())); + obType.setConceptCd("i2b2:60004"); + obType.setConfidenceNum(1d); + obType.setEncounterIde(getEncounterIde()); + obType.setPatientIde(getPatientIde()); + obType.setSourcesystemCd("i2b2"); + obType.setTvalChar("tval"); + obType.setNvalNum(100.0); + obType.setObservationBlob("BLOB"); + + return obType; + }*/ + + public PatientDataType createPatientDataType() { + PatientDataType patientData = new PatientDataType(); + //PatientDataType.VisitDimensionSet vdSet = new PatientDataType.VisitDimensionSet(); + //vdSet.getVisitDimension().add(getVisitDimensionType()); + //patientData.setVisitDimensionSet(vdSet); + + //PatientDataType.ObservationFactSet obsSet = new PatientDataType.ObservationFactSet(); + //obsSet.getObservationFact().add(getObservationFactType()); + //patientData.getObservationFactSet().add(obsSet); + + return patientData; + } + + private String getXMLString(JAXBElement jaxbElement) + throws Exception { + JAXBUtil jaxbUtil = new JAXBUtil(new String[] { + "edu.harvard.i2b2.core.datavo.pdo" + }); + StringWriter strWriter = new StringWriter(); + + jaxbUtil.marshaller(jaxbElement, strWriter); + + return strWriter.toString(); + } + + public void testPatientDataMessage() throws Exception { + edu.harvard.i2b2.crc.datavo.pdo.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.pdo.ObjectFactory(); + JAXBElement jaxbElement = of.createPatientData(createPatientDataType()); + String xmlMessage = getXMLString(jaxbElement); + log.debug("Patient Data Message"); + log.debug(xmlMessage); + } + +} diff --git a/edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/datavo/pdo/query/PDOResponseTypeTest.java b/edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/datavo/pdo/query/PDOResponseTypeTest.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/datavo/pdo/query/PDOResponseTypeTest.java rename to edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/datavo/pdo/query/PDOResponseTypeTest.java index 91d25487..42e3d829 --- a/edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/datavo/pdo/query/PDOResponseTypeTest.java +++ b/edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/datavo/pdo/query/PDOResponseTypeTest.java @@ -1,217 +1,217 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.datavo.pdo.query; - -import java.io.StringWriter; - -import jakarta.xml.bind.JAXBElement; - -import org.junit.BeforeClass; -import org.junit.Test; - -import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.crc.axis2.PdoQueryTest; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.crc.datavo.i2b2result.DataType; -import edu.harvard.i2b2.crc.datavo.i2b2result.ResultEnvelopeType; -import edu.harvard.i2b2.crc.datavo.i2b2result.ResultType; -import edu.harvard.i2b2.crc.datavo.pdo.ObservationSet; -import edu.harvard.i2b2.crc.datavo.pdo.ObservationType; -import edu.harvard.i2b2.crc.datavo.pdo.PatientDataType; -import edu.harvard.i2b2.crc.datavo.pdo.PatientIdType; -import edu.harvard.i2b2.crc.datavo.setfinder.query.XmlValueType; - -public class PDOResponseTypeTest { - private static String testFileDir = null; - - @BeforeClass - public static void init() throws Exception { - testFileDir = System.getProperty("testfiledir"); - System.out.println("test file dir " + testFileDir); - - if (!((testFileDir != null) && (testFileDir.trim().length() > 0))) { - throw new Exception( - "please provide test file directory info -Dtestfiledir"); - } - } - - @Test - public void testPDOMarshall() throws Exception { - PatientDataType patientData = new PatientDataType(); - ObservationType observation = new ObservationType(); - // observation.setPatientId("patientid"); - // observation.setPatientIdSource("source"); - PatientIdType patientIdType = new PatientIdType(); - // patientIdType.setSource("soruce"); - patientIdType.setValue("patient_id"); - observation.setPatientId(patientIdType); - ObservationSet observationSet = new ObservationSet(); - observationSet.getObservation().add(observation); - patientData.getObservationSet().add(observationSet); - - try { - JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); - edu.harvard.i2b2.crc.datavo.pdo.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.pdo.ObjectFactory(); - - StringWriter strWriter = new StringWriter(); - jaxbUtil.marshaller(of.createPatientData(patientData), strWriter); - System.out.print(strWriter.toString()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testResult() throws Exception { - DataType dataType = new DataType(); - dataType.setValue("100"); - dataType.setColumn("count"); - dataType.setType("int"); - - ResultType resultType = new ResultType(); - resultType.setName("PATIENT_DEMOGRAPHICS_COUNT"); - resultType.getData().add(dataType); - edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory(); - - edu.harvard.i2b2.crc.datavo.i2b2result.BodyType bodyType = new edu.harvard.i2b2.crc.datavo.i2b2result.BodyType(); - bodyType.getAny().add(of.createResult(resultType)); - ResultEnvelopeType resultEnvelopeType = new ResultEnvelopeType(); - resultEnvelopeType.setBody(bodyType); - - StringWriter strWriter = new StringWriter(); - JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); - jaxbUtil.marshaller(of.createI2B2ResultEnvelope(resultEnvelopeType), - strWriter); - - System.out.println("Results marshalled" + strWriter.toString()); - JAXBElement jaxbElement = jaxbUtil.unMashallFromString(strWriter - .toString()); - ResultEnvelopeType resultEnvelopeType1 = (ResultEnvelopeType) jaxbElement - .getValue(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - ResultType umResultType = (ResultType) helper.getObjectByClass( - resultEnvelopeType1.getBody().getAny(), ResultType.class); - - XmlValueType xmlValueType = new XmlValueType(); - xmlValueType.getContent().add(resultEnvelopeType); - - ResultEnvelopeType resultEnvelopeType2 = (ResultEnvelopeType) helper - .getObjectByClass(xmlValueType.getContent(), - ResultEnvelopeType.class); - - if (resultEnvelopeType2 == null) { - System.out.println("null"); - } - - } - - @Test - public void pdoRequestUnMarshallTest() throws Exception { - String filename = testFileDir + "/pdo_query1.xml"; - // read file as string - String requestString = PdoQueryTest.getQueryString(filename); - // unmarshall - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil() - .unMashallFromString(requestString); - RequestMessageType r = (RequestMessageType) responseJaxb.getValue(); - BodyType bodyType = r.getMessageBody(); - // get body and search for analysis definition - JAXBUnWrapHelper unWraphHelper = new JAXBUnWrapHelper(); - GetPDOFromInputListRequestType pdoReqType = (GetPDOFromInputListRequestType) unWraphHelper - .getObjectByClass(bodyType.getAny(), - GetPDOFromInputListRequestType.class); - System.out.println("boolean flag " + checkForBlob(pdoReqType)); - - } - - private boolean checkForBlob( - GetPDOFromInputListRequestType getPDOFromInputListReqType) { - boolean booleanConcept = true, booleanEid = true, booleanEvent = true, booleanObservation = true, booleanObserver = true, booleanPatient = true; - boolean booleanPid = true; - - if (getPDOFromInputListReqType.getOutputOption() - .getConceptSetUsingFilterList() != null) { - booleanConcept = getPDOFromInputListReqType.getOutputOption() - .getConceptSetUsingFilterList().isBlob(); - if (booleanConcept) { - booleanConcept = false; - } else { - booleanConcept = true; - } - } - if (getPDOFromInputListReqType.getOutputOption().getEidSet() != null) { - booleanEid = getPDOFromInputListReqType.getOutputOption() - .getEidSet().isBlob(); - if (booleanEid) { - booleanEid = false; - } else { - booleanEid = true; - } - } - if (getPDOFromInputListReqType.getOutputOption().getEventSet() != null) { - booleanEvent = getPDOFromInputListReqType.getOutputOption() - .getEventSet().isBlob(); - if (booleanEvent) { - booleanEvent = false; - } else { - booleanEvent = true; - } - } - if (getPDOFromInputListReqType.getOutputOption().getObservationSet() != null) { - booleanObservation = getPDOFromInputListReqType.getOutputOption() - .getObservationSet().isBlob(); - if (booleanObservation) { - booleanObservation = false; - } else { - booleanObservation = true; - } - } - if (getPDOFromInputListReqType.getOutputOption() - .getObserverSetUsingFilterList() != null) { - booleanObserver = getPDOFromInputListReqType.getOutputOption() - .getObserverSetUsingFilterList().isBlob(); - if (booleanObserver) { - booleanObserver = false; - } else { - booleanObserver = true; - } - } - - if (getPDOFromInputListReqType.getOutputOption().getPatientSet() != null) { - booleanPatient = getPDOFromInputListReqType.getOutputOption() - .getPatientSet().isBlob(); - if (booleanPatient) { - booleanPatient = false; - } else { - booleanPatient = true; - } - } - - if (getPDOFromInputListReqType.getOutputOption().getPidSet() != null) { - booleanPid = getPDOFromInputListReqType.getOutputOption() - .getPidSet().isBlob(); - if (booleanPid) { - booleanPid = false; - } else { - booleanPid = true; - } - } - if (booleanConcept && booleanEid && booleanEvent && booleanObservation - && booleanObserver && booleanPatient && booleanPid) { - return false; - } else { - return true; - } - - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.datavo.pdo.query; + +import java.io.StringWriter; + +import jakarta.xml.bind.JAXBElement; + +import org.junit.BeforeClass; +import org.junit.Test; + +import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.crc.axis2.PdoQueryTest; +import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.crc.datavo.i2b2result.DataType; +import edu.harvard.i2b2.crc.datavo.i2b2result.ResultEnvelopeType; +import edu.harvard.i2b2.crc.datavo.i2b2result.ResultType; +import edu.harvard.i2b2.crc.datavo.pdo.ObservationSet; +import edu.harvard.i2b2.crc.datavo.pdo.ObservationType; +import edu.harvard.i2b2.crc.datavo.pdo.PatientDataType; +import edu.harvard.i2b2.crc.datavo.pdo.PatientIdType; +import edu.harvard.i2b2.crc.datavo.setfinder.query.XmlValueType; + +public class PDOResponseTypeTest { + private static String testFileDir = null; + + @BeforeClass + public static void init() throws Exception { + testFileDir = System.getProperty("testfiledir"); + System.out.println("test file dir " + testFileDir); + + if (!((testFileDir != null) && (testFileDir.trim().length() > 0))) { + throw new Exception( + "please provide test file directory info -Dtestfiledir"); + } + } + + @Test + public void testPDOMarshall() throws Exception { + PatientDataType patientData = new PatientDataType(); + ObservationType observation = new ObservationType(); + // observation.setPatientId("patientid"); + // observation.setPatientIdSource("source"); + PatientIdType patientIdType = new PatientIdType(); + // patientIdType.setSource("soruce"); + patientIdType.setValue("patient_id"); + observation.setPatientId(patientIdType); + ObservationSet observationSet = new ObservationSet(); + observationSet.getObservation().add(observation); + patientData.getObservationSet().add(observationSet); + + try { + JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); + edu.harvard.i2b2.crc.datavo.pdo.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.pdo.ObjectFactory(); + + StringWriter strWriter = new StringWriter(); + jaxbUtil.marshaller(of.createPatientData(patientData), strWriter); + System.out.print(strWriter.toString()); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testResult() throws Exception { + DataType dataType = new DataType(); + dataType.setValue("100"); + dataType.setColumn("count"); + dataType.setType("int"); + + ResultType resultType = new ResultType(); + resultType.setName("PATIENT_DEMOGRAPHICS_COUNT"); + resultType.getData().add(dataType); + edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory of = new edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory(); + + edu.harvard.i2b2.crc.datavo.i2b2result.BodyType bodyType = new edu.harvard.i2b2.crc.datavo.i2b2result.BodyType(); + bodyType.getAny().add(of.createResult(resultType)); + ResultEnvelopeType resultEnvelopeType = new ResultEnvelopeType(); + resultEnvelopeType.setBody(bodyType); + + StringWriter strWriter = new StringWriter(); + JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil(); + jaxbUtil.marshaller(of.createI2B2ResultEnvelope(resultEnvelopeType), + strWriter); + + System.out.println("Results marshalled" + strWriter.toString()); + JAXBElement jaxbElement = jaxbUtil.unMashallFromString(strWriter + .toString()); + ResultEnvelopeType resultEnvelopeType1 = (ResultEnvelopeType) jaxbElement + .getValue(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + ResultType umResultType = (ResultType) helper.getObjectByClass( + resultEnvelopeType1.getBody().getAny(), ResultType.class); + + XmlValueType xmlValueType = new XmlValueType(); + xmlValueType.getContent().add(resultEnvelopeType); + + ResultEnvelopeType resultEnvelopeType2 = (ResultEnvelopeType) helper + .getObjectByClass(xmlValueType.getContent(), + ResultEnvelopeType.class); + + if (resultEnvelopeType2 == null) { + System.out.println("null"); + } + + } + + @Test + public void pdoRequestUnMarshallTest() throws Exception { + String filename = testFileDir + "/pdo_query1.xml"; + // read file as string + String requestString = PdoQueryTest.getQueryString(filename); + // unmarshall + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil() + .unMashallFromString(requestString); + RequestMessageType r = (RequestMessageType) responseJaxb.getValue(); + BodyType bodyType = r.getMessageBody(); + // get body and search for analysis definition + JAXBUnWrapHelper unWraphHelper = new JAXBUnWrapHelper(); + GetPDOFromInputListRequestType pdoReqType = (GetPDOFromInputListRequestType) unWraphHelper + .getObjectByClass(bodyType.getAny(), + GetPDOFromInputListRequestType.class); + System.out.println("boolean flag " + checkForBlob(pdoReqType)); + + } + + private boolean checkForBlob( + GetPDOFromInputListRequestType getPDOFromInputListReqType) { + boolean booleanConcept = true, booleanEid = true, booleanEvent = true, booleanObservation = true, booleanObserver = true, booleanPatient = true; + boolean booleanPid = true; + + if (getPDOFromInputListReqType.getOutputOption() + .getConceptSetUsingFilterList() != null) { + booleanConcept = getPDOFromInputListReqType.getOutputOption() + .getConceptSetUsingFilterList().isBlob(); + if (booleanConcept) { + booleanConcept = false; + } else { + booleanConcept = true; + } + } + if (getPDOFromInputListReqType.getOutputOption().getEidSet() != null) { + booleanEid = getPDOFromInputListReqType.getOutputOption() + .getEidSet().isBlob(); + if (booleanEid) { + booleanEid = false; + } else { + booleanEid = true; + } + } + if (getPDOFromInputListReqType.getOutputOption().getEventSet() != null) { + booleanEvent = getPDOFromInputListReqType.getOutputOption() + .getEventSet().isBlob(); + if (booleanEvent) { + booleanEvent = false; + } else { + booleanEvent = true; + } + } + if (getPDOFromInputListReqType.getOutputOption().getObservationSet() != null) { + booleanObservation = getPDOFromInputListReqType.getOutputOption() + .getObservationSet().isBlob(); + if (booleanObservation) { + booleanObservation = false; + } else { + booleanObservation = true; + } + } + if (getPDOFromInputListReqType.getOutputOption() + .getObserverSetUsingFilterList() != null) { + booleanObserver = getPDOFromInputListReqType.getOutputOption() + .getObserverSetUsingFilterList().isBlob(); + if (booleanObserver) { + booleanObserver = false; + } else { + booleanObserver = true; + } + } + + if (getPDOFromInputListReqType.getOutputOption().getPatientSet() != null) { + booleanPatient = getPDOFromInputListReqType.getOutputOption() + .getPatientSet().isBlob(); + if (booleanPatient) { + booleanPatient = false; + } else { + booleanPatient = true; + } + } + + if (getPDOFromInputListReqType.getOutputOption().getPidSet() != null) { + booleanPid = getPDOFromInputListReqType.getOutputOption() + .getPidSet().isBlob(); + if (booleanPid) { + booleanPid = false; + } else { + booleanPid = true; + } + } + if (booleanConcept && booleanEid && booleanEvent && booleanObservation + && booleanObserver && booleanPatient && booleanPid) { + return false; + } else { + return true; + } + + } +} diff --git a/edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/datavo/setfinder/query/AnalysisDefinitionTypeTest.java b/edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/datavo/setfinder/query/AnalysisDefinitionTypeTest.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/datavo/setfinder/query/AnalysisDefinitionTypeTest.java rename to edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/datavo/setfinder/query/AnalysisDefinitionTypeTest.java index 4c73eaa6..011a9239 --- a/edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/datavo/setfinder/query/AnalysisDefinitionTypeTest.java +++ b/edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/datavo/setfinder/query/AnalysisDefinitionTypeTest.java @@ -1,85 +1,85 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.datavo.setfinder.query; - -import java.io.StringWriter; - -import jakarta.xml.bind.JAXBElement; - -import org.junit.BeforeClass; -import org.junit.Test; - -import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.crc.axis2.PdoQueryTest; -import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; - -public class AnalysisDefinitionTypeTest { - - private static String testFileDir = null; - - @BeforeClass - public static void init() throws Exception { - testFileDir = System.getProperty("testfiledir"); - System.out.println("test file dir " + testFileDir); - - if (!((testFileDir != null) && (testFileDir.trim().length() > 0))) { - throw new Exception( - "please provide test file directory info -Dtestfiledir"); - } - } - - @Test - public void analysisRequestMarshallTest() throws JAXBUtilException { - - AnalysisDefinitionType analysisDefType = new AnalysisDefinitionType(); - analysisDefType.setAnalysisPluginName("analysis_name"); - - AnalysisDefinitionRequestType analysisDef = new AnalysisDefinitionRequestType(); - analysisDef.setAnalysisDefinition(analysisDefType); - - BodyType bodyType = new BodyType(); - - ObjectFactory of = new ObjectFactory(); - - bodyType.getAny().add(of.createRequest(analysisDef)); - edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory of1 = new edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory(); - - RequestMessageType requestMsgType = new RequestMessageType(); - requestMsgType.setMessageBody(bodyType); - StringWriter strWriter = new StringWriter(); - CRCJAXBUtil.getJAXBUtil().marshaller(of1.createRequest(requestMsgType), - strWriter); - System.out.println("request str :" + strWriter.toString()); - - } - - @Test - public void analysisRequestUnMarshallTest() throws Exception { - String filename = testFileDir + "/setfinder_analysis_query.xml"; - // read file as string - String requestString = PdoQueryTest.getQueryString(filename); - // unmarshall - JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil() - .unMashallFromString(requestString); - RequestMessageType r = (RequestMessageType) responseJaxb.getValue(); - BodyType bodyType = r.getMessageBody(); - // get body and search for analysis definition - JAXBUnWrapHelper unWraphHelper = new JAXBUnWrapHelper(); - AnalysisDefinitionRequestType analysisDefReqType = (AnalysisDefinitionRequestType) unWraphHelper - .getObjectByClass(bodyType.getAny(), - AnalysisDefinitionRequestType.class); - System.out.println("analysis name " - + analysisDefReqType.getAnalysisDefinition() - .getAnalysisPluginName()); - - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.datavo.setfinder.query; + +import java.io.StringWriter; + +import jakarta.xml.bind.JAXBElement; + +import org.junit.BeforeClass; +import org.junit.Test; + +import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.crc.axis2.PdoQueryTest; +import edu.harvard.i2b2.crc.datavo.CRCJAXBUtil; +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.crc.datavo.i2b2message.RequestMessageType; + +public class AnalysisDefinitionTypeTest { + + private static String testFileDir = null; + + @BeforeClass + public static void init() throws Exception { + testFileDir = System.getProperty("testfiledir"); + System.out.println("test file dir " + testFileDir); + + if (!((testFileDir != null) && (testFileDir.trim().length() > 0))) { + throw new Exception( + "please provide test file directory info -Dtestfiledir"); + } + } + + @Test + public void analysisRequestMarshallTest() throws JAXBUtilException { + + AnalysisDefinitionType analysisDefType = new AnalysisDefinitionType(); + analysisDefType.setAnalysisPluginName("analysis_name"); + + AnalysisDefinitionRequestType analysisDef = new AnalysisDefinitionRequestType(); + analysisDef.setAnalysisDefinition(analysisDefType); + + BodyType bodyType = new BodyType(); + + ObjectFactory of = new ObjectFactory(); + + bodyType.getAny().add(of.createRequest(analysisDef)); + edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory of1 = new edu.harvard.i2b2.crc.datavo.i2b2message.ObjectFactory(); + + RequestMessageType requestMsgType = new RequestMessageType(); + requestMsgType.setMessageBody(bodyType); + StringWriter strWriter = new StringWriter(); + CRCJAXBUtil.getJAXBUtil().marshaller(of1.createRequest(requestMsgType), + strWriter); + System.out.println("request str :" + strWriter.toString()); + + } + + @Test + public void analysisRequestUnMarshallTest() throws Exception { + String filename = testFileDir + "/setfinder_analysis_query.xml"; + // read file as string + String requestString = PdoQueryTest.getQueryString(filename); + // unmarshall + JAXBElement responseJaxb = CRCJAXBUtil.getJAXBUtil() + .unMashallFromString(requestString); + RequestMessageType r = (RequestMessageType) responseJaxb.getValue(); + BodyType bodyType = r.getMessageBody(); + // get body and search for analysis definition + JAXBUnWrapHelper unWraphHelper = new JAXBUnWrapHelper(); + AnalysisDefinitionRequestType analysisDefReqType = (AnalysisDefinitionRequestType) unWraphHelper + .getObjectByClass(bodyType.getAny(), + AnalysisDefinitionRequestType.class); + System.out.println("analysis name " + + analysisDefReqType.getAnalysisDefinition() + .getAnalysisPluginName()); + + } +} diff --git a/edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/ejb/analysis/AnalysisRequestMessageTest.java b/edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/ejb/analysis/AnalysisRequestMessageTest.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/test/edu/harvard/i2b2/crc/ejb/analysis/AnalysisRequestMessageTest.java rename to edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/ejb/analysis/AnalysisRequestMessageTest.java diff --git a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/xml/StaxParser.java b/edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/loader/xml/StaxParser.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/xml/StaxParser.java rename to edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/loader/xml/StaxParser.java index 80d656a7..d1e21d73 --- a/edu.harvard.i2b2.crc/src/server/edu/harvard/i2b2/crc/loader/xml/StaxParser.java +++ b/edu.harvard.i2b2.crc/src/test/java/edu/harvard/i2b2/crc/loader/xml/StaxParser.java @@ -1,66 +1,66 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.crc.loader.xml; - -import java.io.FileReader; - -import jakarta.xml.bind.JAXBContext; -import jakarta.xml.bind.Unmarshaller; -import javax.xml.stream.EventFilter; -import javax.xml.stream.XMLEventReader; -import javax.xml.stream.XMLInputFactory; -import javax.xml.stream.events.StartElement; -import javax.xml.stream.events.XMLEvent; - -import org.junit.Test; - -import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; - - - -public class StaxParser { - - @Test - public void start() throws Exception { - XMLInputFactory xmlif = XMLInputFactory.newInstance(); - FileReader fr = new FileReader("testfiles/stax.xml"); - XMLEventReader xmler = xmlif.createXMLEventReader(fr); - EventFilter filter = new EventFilter() { - @Override - public boolean accept(XMLEvent event) { - return event.isStartElement(); - } - }; - XMLEventReader xmlfer = xmlif.createFilteredReader(xmler, filter); - - // Jump to the first element in the document, the enclosing BugCollection - StartElement e = (StartElement) xmlfer.nextEvent(); - - JAXBContext ctx = JAXBContext.newInstance("edu.harvard.i2b2.crc.datavo.i2b2message"); - Unmarshaller um = ctx.createUnmarshaller(); - int bugs = 0; - - while (xmlfer.peek() != null) { - Object o = um.unmarshal(xmler); - if (o instanceof BodyType) { - BodyType bi = (BodyType) o; - // process the bug instance - bugs++; - } - } - //assertEquals(180, bugs); - fr.close(); - - } - - public static void main(String args[]) throws Exception { - StaxParser p = new StaxParser(); - p.start(); - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.crc.loader.xml; + +import java.io.FileReader; + +import jakarta.xml.bind.JAXBContext; +import jakarta.xml.bind.Unmarshaller; +import javax.xml.stream.EventFilter; +import javax.xml.stream.XMLEventReader; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.events.StartElement; +import javax.xml.stream.events.XMLEvent; + +import org.junit.Test; + +import edu.harvard.i2b2.crc.datavo.i2b2message.BodyType; + + + +public class StaxParser { + + @Test + public void start() throws Exception { + XMLInputFactory xmlif = XMLInputFactory.newInstance(); + FileReader fr = new FileReader("testfiles/stax.xml"); + XMLEventReader xmler = xmlif.createXMLEventReader(fr); + EventFilter filter = new EventFilter() { + @Override + public boolean accept(XMLEvent event) { + return event.isStartElement(); + } + }; + XMLEventReader xmlfer = xmlif.createFilteredReader(xmler, filter); + + // Jump to the first element in the document, the enclosing BugCollection + StartElement e = (StartElement) xmlfer.nextEvent(); + + JAXBContext ctx = JAXBContext.newInstance("edu.harvard.i2b2.crc.datavo.i2b2message"); + Unmarshaller um = ctx.createUnmarshaller(); + int bugs = 0; + + while (xmlfer.peek() != null) { + Object o = um.unmarshal(xmler); + if (o instanceof BodyType) { + BodyType bi = (BodyType) o; + // process the bug instance + bugs++; + } + } + //assertEquals(180, bugs); + fr.close(); + + } + + public static void main(String args[]) throws Exception { + StaxParser p = new StaxParser(); + p.start(); + } +} diff --git a/edu.harvard.i2b2.server-common/src/test/edu/harvard/i2b2/common/datavo/Samplei2b2RequestMessage.xml b/edu.harvard.i2b2.crc/src/test/resources/Samplei2b2RequestMessage.xml old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.server-common/src/test/edu/harvard/i2b2/common/datavo/Samplei2b2RequestMessage.xml rename to edu.harvard.i2b2.crc/src/test/resources/Samplei2b2RequestMessage.xml diff --git a/edu.harvard.i2b2.crc/src/test/test.hibernate.cfg.xml b/edu.harvard.i2b2.crc/src/test/resources/test.hibernate.cfg.xml old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.crc/src/test/test.hibernate.cfg.xml rename to edu.harvard.i2b2.crc/src/test/resources/test.hibernate.cfg.xml diff --git a/edu.harvard.i2b2.crc/velocity.log.1 b/edu.harvard.i2b2.crc/velocity.log.1 deleted file mode 100755 index 82a63200..00000000 --- a/edu.harvard.i2b2.crc/velocity.log.1 +++ /dev/null @@ -1,732 +0,0 @@ -2007-01-18 14:43:05,280 - Velocimacro : allowInlineLocal = false : VMs defined inline will be global in scope if allowed. -2007-01-18 14:43:05,280 - Velocimacro : messages on : VM system will output logging messages -2007-01-18 14:43:05,280 - Velocimacro : autoload off : VM system will not automatically reload global library macros -2007-01-18 14:43:05,280 - Velocimacro : initialization complete. -2007-01-18 14:43:05,280 - Velocity successfully started. -2007-01-18 14:43:06,358 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 14:43:06,515 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 14:43:06,561 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 14:43:06,593 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 14:43:06,640 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 14:43:06,671 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 14:43:06,765 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 14:43:06,796 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 14:43:06,858 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 14:43:06,890 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 14:43:06,905 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 14:43:06,936 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 14:43:07,030 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 14:43:07,061 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 14:43:07,093 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 14:43:07,140 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 14:43:07,155 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 14:43:07,186 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 14:43:07,280 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 14:43:07,327 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 14:43:07,358 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 14:43:07,390 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 14:43:07,405 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 14:43:07,436 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:14:41,898 - SimpleLog4JLogSystem initialized using logfile 'velocity.log' -2007-01-18 15:14:41,914 - ************************************************************** -2007-01-18 15:14:41,914 - Starting Jakarta Velocity v1.4 -2007-01-18 15:14:41,914 - RuntimeInstance initializing. -2007-01-18 15:14:41,914 - Default Properties File: org\apache\velocity\runtime\defaults\velocity.properties -2007-01-18 15:14:41,914 - Trying to use logger class org.apache.velocity.runtime.log.AvalonLogSystem -2007-01-18 15:14:41,914 - Couldn't find class org.apache.velocity.runtime.log.AvalonLogSystem or necessary supporting classes in classpath. Exception : java.lang.NoClassDefFoundError: org/apache/log/format/Formatter -2007-01-18 15:14:41,914 - Trying to use logger class org.apache.velocity.runtime.log.SimpleLog4JLogSystem -2007-01-18 15:14:41,914 - Using logger class org.apache.velocity.runtime.log.SimpleLog4JLogSystem -2007-01-18 15:14:41,914 - Default ResourceManager initializing. (class org.generama.velocity.ResourceLoaderExposingResourceManager) -2007-01-18 15:14:41,914 - Resource Loader Instantiated: org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:14:41,914 - ClasspathResourceLoader : initialization starting. -2007-01-18 15:14:41,914 - ClasspathResourceLoader : initialization complete. -2007-01-18 15:14:41,929 - Resource Loader Instantiated: org.generama.velocity.ConfigurableFileResourceLoader -2007-01-18 15:14:41,929 - FileResourceLoader : initialization starting. -2007-01-18 15:14:41,929 - FileResourceLoader : initialization complete. -2007-01-18 15:14:41,929 - ResourceCache : initialized. (class org.apache.velocity.runtime.resource.ResourceCacheImpl) -2007-01-18 15:14:41,929 - Default ResourceManager initialization complete. -2007-01-18 15:14:41,945 - Loaded System Directive: org.apache.velocity.runtime.directive.Literal -2007-01-18 15:14:41,945 - Loaded System Directive: org.apache.velocity.runtime.directive.Macro -2007-01-18 15:14:41,961 - Loaded System Directive: org.apache.velocity.runtime.directive.Parse -2007-01-18 15:14:41,976 - Loaded System Directive: org.apache.velocity.runtime.directive.Include -2007-01-18 15:14:41,976 - Loaded System Directive: org.apache.velocity.runtime.directive.Foreach -2007-01-18 15:14:42,148 - Created: 20 parsers. -2007-01-18 15:14:42,179 - Velocimacro : initialization starting. -2007-01-18 15:14:42,179 - Velocimacro : adding VMs from VM library template : VM_global_library.vm -2007-01-18 15:14:42,211 - ResourceManager : unable to find resource 'VM_global_library.vm' in any resource loader. -2007-01-18 15:14:42,211 - Velocimacro : error using VM library template VM_global_library.vm : org.apache.velocity.exception.ResourceNotFoundException: Unable to find resource 'VM_global_library.vm' -2007-01-18 15:14:42,211 - Velocimacro : VM library template macro registration complete. -2007-01-18 15:14:42,211 - Velocimacro : allowInline = true : VMs can be defined inline in templates -2007-01-18 15:14:42,211 - Velocimacro : allowInlineToOverride = false : VMs defined inline may NOT replace previous VM definitions -2007-01-18 15:14:42,211 - Velocimacro : allowInlineLocal = false : VMs defined inline will be global in scope if allowed. -2007-01-18 15:14:42,211 - Velocimacro : messages on : VM system will output logging messages -2007-01-18 15:14:42,211 - Velocimacro : autoload off : VM system will not automatically reload global library macros -2007-01-18 15:14:42,211 - Velocimacro : initialization complete. -2007-01-18 15:14:42,211 - Velocity successfully started. -2007-01-18 15:14:43,383 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:14:43,555 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:14:43,601 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:14:43,633 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:14:43,664 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:14:43,711 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:14:43,789 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:14:43,820 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:14:43,883 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:14:43,914 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:14:43,930 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:14:43,961 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:14:44,039 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:14:44,070 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:14:44,101 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:14:44,148 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:14:44,164 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:14:44,195 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:14:44,289 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:14:44,320 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:14:44,351 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:14:44,383 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:14:44,398 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:14:44,430 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:17:15,322 - SimpleLog4JLogSystem initialized using logfile 'velocity.log' -2007-01-18 15:17:15,322 - ************************************************************** -2007-01-18 15:17:15,322 - Starting Jakarta Velocity v1.4 -2007-01-18 15:17:15,322 - RuntimeInstance initializing. -2007-01-18 15:17:15,322 - Default Properties File: org\apache\velocity\runtime\defaults\velocity.properties -2007-01-18 15:17:15,322 - Trying to use logger class org.apache.velocity.runtime.log.AvalonLogSystem -2007-01-18 15:17:15,322 - Couldn't find class org.apache.velocity.runtime.log.AvalonLogSystem or necessary supporting classes in classpath. Exception : java.lang.NoClassDefFoundError: org/apache/log/format/Formatter -2007-01-18 15:17:15,322 - Trying to use logger class org.apache.velocity.runtime.log.SimpleLog4JLogSystem -2007-01-18 15:17:15,322 - Using logger class org.apache.velocity.runtime.log.SimpleLog4JLogSystem -2007-01-18 15:17:15,322 - Default ResourceManager initializing. (class org.generama.velocity.ResourceLoaderExposingResourceManager) -2007-01-18 15:17:15,338 - Resource Loader Instantiated: org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:17:15,338 - ClasspathResourceLoader : initialization starting. -2007-01-18 15:17:15,338 - ClasspathResourceLoader : initialization complete. -2007-01-18 15:17:15,338 - Resource Loader Instantiated: org.generama.velocity.ConfigurableFileResourceLoader -2007-01-18 15:17:15,338 - FileResourceLoader : initialization starting. -2007-01-18 15:17:15,338 - FileResourceLoader : initialization complete. -2007-01-18 15:17:15,353 - ResourceCache : initialized. (class org.apache.velocity.runtime.resource.ResourceCacheImpl) -2007-01-18 15:17:15,353 - Default ResourceManager initialization complete. -2007-01-18 15:17:15,353 - Loaded System Directive: org.apache.velocity.runtime.directive.Literal -2007-01-18 15:17:15,369 - Loaded System Directive: org.apache.velocity.runtime.directive.Macro -2007-01-18 15:17:15,369 - Loaded System Directive: org.apache.velocity.runtime.directive.Parse -2007-01-18 15:17:15,385 - Loaded System Directive: org.apache.velocity.runtime.directive.Include -2007-01-18 15:17:15,385 - Loaded System Directive: org.apache.velocity.runtime.directive.Foreach -2007-01-18 15:17:15,556 - Created: 20 parsers. -2007-01-18 15:17:15,603 - Velocimacro : initialization starting. -2007-01-18 15:17:15,603 - Velocimacro : adding VMs from VM library template : VM_global_library.vm -2007-01-18 15:17:15,619 - ResourceManager : unable to find resource 'VM_global_library.vm' in any resource loader. -2007-01-18 15:17:15,619 - Velocimacro : error using VM library template VM_global_library.vm : org.apache.velocity.exception.ResourceNotFoundException: Unable to find resource 'VM_global_library.vm' -2007-01-18 15:17:15,619 - Velocimacro : VM library template macro registration complete. -2007-01-18 15:17:15,619 - Velocimacro : allowInline = true : VMs can be defined inline in templates -2007-01-18 15:17:15,619 - Velocimacro : allowInlineToOverride = false : VMs defined inline may NOT replace previous VM definitions -2007-01-18 15:17:15,619 - Velocimacro : allowInlineLocal = false : VMs defined inline will be global in scope if allowed. -2007-01-18 15:17:15,619 - Velocimacro : messages on : VM system will output logging messages -2007-01-18 15:17:15,619 - Velocimacro : autoload off : VM system will not automatically reload global library macros -2007-01-18 15:17:15,619 - Velocimacro : initialization complete. -2007-01-18 15:17:15,619 - Velocity successfully started. -2007-01-18 15:17:16,635 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:17:16,775 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:17:16,822 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:17:16,869 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:17:16,900 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:17:16,931 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:17:17,025 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:17:17,056 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:17:17,103 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:17:17,135 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:17:17,166 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:17:17,181 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:17:17,275 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:17:17,291 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:17:17,322 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:17:17,369 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:17:17,385 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:17:17,416 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:17:17,510 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:17:17,541 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:17:17,588 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:17:17,603 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:17:17,635 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:17:17,650 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:22:13,092 - SimpleLog4JLogSystem initialized using logfile 'velocity.log' -2007-01-18 15:22:13,092 - ************************************************************** -2007-01-18 15:22:13,092 - Starting Jakarta Velocity v1.4 -2007-01-18 15:22:13,092 - RuntimeInstance initializing. -2007-01-18 15:22:13,092 - Default Properties File: org\apache\velocity\runtime\defaults\velocity.properties -2007-01-18 15:22:13,092 - Trying to use logger class org.apache.velocity.runtime.log.AvalonLogSystem -2007-01-18 15:22:13,092 - Couldn't find class org.apache.velocity.runtime.log.AvalonLogSystem or necessary supporting classes in classpath. Exception : java.lang.NoClassDefFoundError: org/apache/log/format/Formatter -2007-01-18 15:22:13,092 - Trying to use logger class org.apache.velocity.runtime.log.SimpleLog4JLogSystem -2007-01-18 15:22:13,092 - Using logger class org.apache.velocity.runtime.log.SimpleLog4JLogSystem -2007-01-18 15:22:13,092 - Default ResourceManager initializing. (class org.generama.velocity.ResourceLoaderExposingResourceManager) -2007-01-18 15:22:13,092 - Resource Loader Instantiated: org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:22:13,092 - ClasspathResourceLoader : initialization starting. -2007-01-18 15:22:13,092 - ClasspathResourceLoader : initialization complete. -2007-01-18 15:22:13,107 - Resource Loader Instantiated: org.generama.velocity.ConfigurableFileResourceLoader -2007-01-18 15:22:13,107 - FileResourceLoader : initialization starting. -2007-01-18 15:22:13,107 - FileResourceLoader : initialization complete. -2007-01-18 15:22:13,107 - ResourceCache : initialized. (class org.apache.velocity.runtime.resource.ResourceCacheImpl) -2007-01-18 15:22:13,107 - Default ResourceManager initialization complete. -2007-01-18 15:22:13,123 - Loaded System Directive: org.apache.velocity.runtime.directive.Literal -2007-01-18 15:22:13,138 - Loaded System Directive: org.apache.velocity.runtime.directive.Macro -2007-01-18 15:22:13,138 - Loaded System Directive: org.apache.velocity.runtime.directive.Parse -2007-01-18 15:22:13,154 - Loaded System Directive: org.apache.velocity.runtime.directive.Include -2007-01-18 15:22:13,154 - Loaded System Directive: org.apache.velocity.runtime.directive.Foreach -2007-01-18 15:22:13,357 - Created: 20 parsers. -2007-01-18 15:22:13,404 - Velocimacro : initialization starting. -2007-01-18 15:22:13,404 - Velocimacro : adding VMs from VM library template : VM_global_library.vm -2007-01-18 15:22:13,420 - ResourceManager : unable to find resource 'VM_global_library.vm' in any resource loader. -2007-01-18 15:22:13,420 - Velocimacro : error using VM library template VM_global_library.vm : org.apache.velocity.exception.ResourceNotFoundException: Unable to find resource 'VM_global_library.vm' -2007-01-18 15:22:13,420 - Velocimacro : VM library template macro registration complete. -2007-01-18 15:22:13,420 - Velocimacro : allowInline = true : VMs can be defined inline in templates -2007-01-18 15:22:13,420 - Velocimacro : allowInlineToOverride = false : VMs defined inline may NOT replace previous VM definitions -2007-01-18 15:22:13,420 - Velocimacro : allowInlineLocal = false : VMs defined inline will be global in scope if allowed. -2007-01-18 15:22:13,420 - Velocimacro : messages on : VM system will output logging messages -2007-01-18 15:22:13,420 - Velocimacro : autoload off : VM system will not automatically reload global library macros -2007-01-18 15:22:13,420 - Velocimacro : initialization complete. -2007-01-18 15:22:13,420 - Velocity successfully started. -2007-01-18 15:22:14,638 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:22:14,857 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:22:14,920 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:22:14,982 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:22:15,029 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:22:15,076 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:22:15,232 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:22:15,279 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:22:15,357 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:22:15,404 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:22:15,435 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:22:15,482 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:22:15,607 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:22:15,638 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:22:15,717 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:22:15,763 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:22:15,873 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:22:16,076 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:22:16,263 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:22:16,326 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:22:16,373 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:22:16,420 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:22:16,451 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:22:16,498 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:28:21,815 - SimpleLog4JLogSystem initialized using logfile 'velocity.log' -2007-01-18 15:28:21,815 - ************************************************************** -2007-01-18 15:28:21,815 - Starting Jakarta Velocity v1.4 -2007-01-18 15:28:21,815 - RuntimeInstance initializing. -2007-01-18 15:28:21,815 - Default Properties File: org\apache\velocity\runtime\defaults\velocity.properties -2007-01-18 15:28:21,815 - Trying to use logger class org.apache.velocity.runtime.log.AvalonLogSystem -2007-01-18 15:28:21,815 - Couldn't find class org.apache.velocity.runtime.log.AvalonLogSystem or necessary supporting classes in classpath. Exception : java.lang.NoClassDefFoundError: org/apache/log/format/Formatter -2007-01-18 15:28:21,815 - Trying to use logger class org.apache.velocity.runtime.log.SimpleLog4JLogSystem -2007-01-18 15:28:21,815 - Using logger class org.apache.velocity.runtime.log.SimpleLog4JLogSystem -2007-01-18 15:28:21,815 - Default ResourceManager initializing. (class org.generama.velocity.ResourceLoaderExposingResourceManager) -2007-01-18 15:28:21,815 - Resource Loader Instantiated: org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:28:21,815 - ClasspathResourceLoader : initialization starting. -2007-01-18 15:28:21,815 - ClasspathResourceLoader : initialization complete. -2007-01-18 15:28:21,831 - Resource Loader Instantiated: org.generama.velocity.ConfigurableFileResourceLoader -2007-01-18 15:28:21,831 - FileResourceLoader : initialization starting. -2007-01-18 15:28:21,831 - FileResourceLoader : initialization complete. -2007-01-18 15:28:21,831 - ResourceCache : initialized. (class org.apache.velocity.runtime.resource.ResourceCacheImpl) -2007-01-18 15:28:21,831 - Default ResourceManager initialization complete. -2007-01-18 15:28:21,846 - Loaded System Directive: org.apache.velocity.runtime.directive.Literal -2007-01-18 15:28:21,862 - Loaded System Directive: org.apache.velocity.runtime.directive.Macro -2007-01-18 15:28:21,877 - Loaded System Directive: org.apache.velocity.runtime.directive.Parse -2007-01-18 15:28:21,877 - Loaded System Directive: org.apache.velocity.runtime.directive.Include -2007-01-18 15:28:21,893 - Loaded System Directive: org.apache.velocity.runtime.directive.Foreach -2007-01-18 15:28:22,112 - Created: 20 parsers. -2007-01-18 15:28:22,159 - Velocimacro : initialization starting. -2007-01-18 15:28:22,159 - Velocimacro : adding VMs from VM library template : VM_global_library.vm -2007-01-18 15:28:22,190 - ResourceManager : unable to find resource 'VM_global_library.vm' in any resource loader. -2007-01-18 15:28:22,190 - Velocimacro : error using VM library template VM_global_library.vm : org.apache.velocity.exception.ResourceNotFoundException: Unable to find resource 'VM_global_library.vm' -2007-01-18 15:28:22,190 - Velocimacro : VM library template macro registration complete. -2007-01-18 15:28:22,190 - Velocimacro : allowInline = true : VMs can be defined inline in templates -2007-01-18 15:28:22,190 - Velocimacro : allowInlineToOverride = false : VMs defined inline may NOT replace previous VM definitions -2007-01-18 15:28:22,190 - Velocimacro : allowInlineLocal = false : VMs defined inline will be global in scope if allowed. -2007-01-18 15:28:22,190 - Velocimacro : messages on : VM system will output logging messages -2007-01-18 15:28:22,190 - Velocimacro : autoload off : VM system will not automatically reload global library macros -2007-01-18 15:28:22,190 - Velocimacro : initialization complete. -2007-01-18 15:28:22,190 - Velocity successfully started. -2007-01-18 15:28:23,674 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:28:23,971 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:28:24,081 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:28:24,128 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:28:24,206 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:28:24,268 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:28:24,424 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:28:24,487 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:28:24,565 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:28:24,643 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:28:24,674 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:28:24,706 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:28:24,815 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:28:24,846 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:28:24,893 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:28:24,940 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:28:24,987 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:28:25,034 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:28:25,174 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:28:25,237 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:28:25,284 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:28:25,315 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:28:25,331 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-18 15:28:25,362 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-22 14:15:12,368 - SimpleLog4JLogSystem initialized using logfile 'velocity.log' -2007-01-22 14:15:12,368 - ************************************************************** -2007-01-22 14:15:12,368 - Starting Jakarta Velocity v1.4 -2007-01-22 14:15:12,368 - RuntimeInstance initializing. -2007-01-22 14:15:12,368 - Default Properties File: org\apache\velocity\runtime\defaults\velocity.properties -2007-01-22 14:15:12,368 - Trying to use logger class org.apache.velocity.runtime.log.AvalonLogSystem -2007-01-22 14:15:12,368 - Couldn't find class org.apache.velocity.runtime.log.AvalonLogSystem or necessary supporting classes in classpath. Exception : java.lang.NoClassDefFoundError: org/apache/log/format/Formatter -2007-01-22 14:15:12,368 - Trying to use logger class org.apache.velocity.runtime.log.SimpleLog4JLogSystem -2007-01-22 14:15:12,368 - Using logger class org.apache.velocity.runtime.log.SimpleLog4JLogSystem -2007-01-22 14:15:12,368 - Default ResourceManager initializing. (class org.generama.velocity.ResourceLoaderExposingResourceManager) -2007-01-22 14:15:12,383 - Resource Loader Instantiated: org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-22 14:15:12,383 - ClasspathResourceLoader : initialization starting. -2007-01-22 14:15:12,383 - ClasspathResourceLoader : initialization complete. -2007-01-22 14:15:12,383 - Resource Loader Instantiated: org.generama.velocity.ConfigurableFileResourceLoader -2007-01-22 14:15:12,383 - FileResourceLoader : initialization starting. -2007-01-22 14:15:12,383 - FileResourceLoader : initialization complete. -2007-01-22 14:15:12,399 - ResourceCache : initialized. (class org.apache.velocity.runtime.resource.ResourceCacheImpl) -2007-01-22 14:15:12,399 - Default ResourceManager initialization complete. -2007-01-22 14:15:12,399 - Loaded System Directive: org.apache.velocity.runtime.directive.Literal -2007-01-22 14:15:12,415 - Loaded System Directive: org.apache.velocity.runtime.directive.Macro -2007-01-22 14:15:12,415 - Loaded System Directive: org.apache.velocity.runtime.directive.Parse -2007-01-22 14:15:12,430 - Loaded System Directive: org.apache.velocity.runtime.directive.Include -2007-01-22 14:15:12,446 - Loaded System Directive: org.apache.velocity.runtime.directive.Foreach -2007-01-22 14:15:12,618 - Created: 20 parsers. -2007-01-22 14:15:12,649 - Velocimacro : initialization starting. -2007-01-22 14:15:12,649 - Velocimacro : adding VMs from VM library template : VM_global_library.vm -2007-01-22 14:15:12,665 - ResourceManager : unable to find resource 'VM_global_library.vm' in any resource loader. -2007-01-22 14:15:12,665 - Velocimacro : error using VM library template VM_global_library.vm : org.apache.velocity.exception.ResourceNotFoundException: Unable to find resource 'VM_global_library.vm' -2007-01-22 14:15:12,665 - Velocimacro : VM library template macro registration complete. -2007-01-22 14:15:12,665 - Velocimacro : allowInline = true : VMs can be defined inline in templates -2007-01-22 14:15:12,665 - Velocimacro : allowInlineToOverride = false : VMs defined inline may NOT replace previous VM definitions -2007-01-22 14:15:12,665 - Velocimacro : allowInlineLocal = false : VMs defined inline will be global in scope if allowed. -2007-01-22 14:15:12,665 - Velocimacro : messages on : VM system will output logging messages -2007-01-22 14:15:12,665 - Velocimacro : autoload off : VM system will not automatically reload global library macros -2007-01-22 14:15:12,665 - Velocimacro : initialization complete. -2007-01-22 14:15:12,665 - Velocity successfully started. -2007-01-22 14:15:13,962 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-22 14:15:14,118 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-22 14:15:14,180 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-22 14:15:14,212 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-22 14:15:14,258 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-22 14:15:14,305 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-22 14:15:14,399 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-22 14:15:14,430 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-22 14:15:14,493 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-22 14:15:14,524 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-22 14:15:14,540 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-22 14:15:14,571 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-22 14:15:14,649 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-22 14:15:14,680 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-22 14:15:14,712 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-22 14:15:14,743 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-22 14:15:14,758 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-22 14:15:14,790 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-22 14:15:14,883 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-22 14:15:14,915 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-22 14:15:14,946 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-22 14:15:14,977 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-22 14:15:14,993 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-22 14:15:15,024 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 09:26:44,217 - SimpleLog4JLogSystem initialized using logfile 'velocity.log' -2007-01-23 09:26:44,248 - ************************************************************** -2007-01-23 09:26:44,248 - Starting Jakarta Velocity v1.4 -2007-01-23 09:26:44,248 - RuntimeInstance initializing. -2007-01-23 09:26:44,248 - Default Properties File: org\apache\velocity\runtime\defaults\velocity.properties -2007-01-23 09:26:44,248 - Trying to use logger class org.apache.velocity.runtime.log.AvalonLogSystem -2007-01-23 09:26:44,248 - Couldn't find class org.apache.velocity.runtime.log.AvalonLogSystem or necessary supporting classes in classpath. Exception : java.lang.NoClassDefFoundError: org/apache/log/format/Formatter -2007-01-23 09:26:44,248 - Trying to use logger class org.apache.velocity.runtime.log.SimpleLog4JLogSystem -2007-01-23 09:26:44,248 - Using logger class org.apache.velocity.runtime.log.SimpleLog4JLogSystem -2007-01-23 09:26:44,248 - Default ResourceManager initializing. (class org.generama.velocity.ResourceLoaderExposingResourceManager) -2007-01-23 09:26:44,248 - Resource Loader Instantiated: org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 09:26:44,248 - ClasspathResourceLoader : initialization starting. -2007-01-23 09:26:44,248 - ClasspathResourceLoader : initialization complete. -2007-01-23 09:26:44,264 - Resource Loader Instantiated: org.generama.velocity.ConfigurableFileResourceLoader -2007-01-23 09:26:44,264 - FileResourceLoader : initialization starting. -2007-01-23 09:26:44,264 - FileResourceLoader : initialization complete. -2007-01-23 09:26:44,264 - ResourceCache : initialized. (class org.apache.velocity.runtime.resource.ResourceCacheImpl) -2007-01-23 09:26:44,264 - Default ResourceManager initialization complete. -2007-01-23 09:26:44,279 - Loaded System Directive: org.apache.velocity.runtime.directive.Literal -2007-01-23 09:26:44,279 - Loaded System Directive: org.apache.velocity.runtime.directive.Macro -2007-01-23 09:26:44,295 - Loaded System Directive: org.apache.velocity.runtime.directive.Parse -2007-01-23 09:26:44,311 - Loaded System Directive: org.apache.velocity.runtime.directive.Include -2007-01-23 09:26:44,326 - Loaded System Directive: org.apache.velocity.runtime.directive.Foreach -2007-01-23 09:26:44,498 - Created: 20 parsers. -2007-01-23 09:26:44,545 - Velocimacro : initialization starting. -2007-01-23 09:26:44,545 - Velocimacro : adding VMs from VM library template : VM_global_library.vm -2007-01-23 09:26:44,561 - ResourceManager : unable to find resource 'VM_global_library.vm' in any resource loader. -2007-01-23 09:26:44,561 - Velocimacro : error using VM library template VM_global_library.vm : org.apache.velocity.exception.ResourceNotFoundException: Unable to find resource 'VM_global_library.vm' -2007-01-23 09:26:44,561 - Velocimacro : VM library template macro registration complete. -2007-01-23 09:26:44,561 - Velocimacro : allowInline = true : VMs can be defined inline in templates -2007-01-23 09:26:44,561 - Velocimacro : allowInlineToOverride = false : VMs defined inline may NOT replace previous VM definitions -2007-01-23 09:26:44,561 - Velocimacro : allowInlineLocal = false : VMs defined inline will be global in scope if allowed. -2007-01-23 09:26:44,561 - Velocimacro : messages on : VM system will output logging messages -2007-01-23 09:26:44,561 - Velocimacro : autoload off : VM system will not automatically reload global library macros -2007-01-23 09:26:44,561 - Velocimacro : initialization complete. -2007-01-23 09:26:44,561 - Velocity successfully started. -2007-01-23 09:26:45,779 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 09:26:45,936 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 09:26:45,998 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 09:26:46,045 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 09:26:46,076 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 09:26:46,107 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 09:26:46,201 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 09:26:46,232 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 09:26:46,295 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 09:26:46,326 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 09:26:46,342 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 09:26:46,373 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 09:26:46,498 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 09:26:46,545 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 09:26:46,607 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 09:26:46,670 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 09:26:46,717 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 09:26:46,764 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 09:26:46,889 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 09:26:46,920 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 09:26:46,951 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 09:26:46,982 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 09:26:46,998 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 09:26:47,045 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:01:53,306 - SimpleLog4JLogSystem initialized using logfile 'velocity.log' -2007-01-23 10:01:53,322 - ************************************************************** -2007-01-23 10:01:53,322 - Starting Jakarta Velocity v1.4 -2007-01-23 10:01:53,322 - RuntimeInstance initializing. -2007-01-23 10:01:53,322 - Default Properties File: org\apache\velocity\runtime\defaults\velocity.properties -2007-01-23 10:01:53,322 - Trying to use logger class org.apache.velocity.runtime.log.AvalonLogSystem -2007-01-23 10:01:53,322 - Couldn't find class org.apache.velocity.runtime.log.AvalonLogSystem or necessary supporting classes in classpath. Exception : java.lang.NoClassDefFoundError: org/apache/log/format/Formatter -2007-01-23 10:01:53,322 - Trying to use logger class org.apache.velocity.runtime.log.SimpleLog4JLogSystem -2007-01-23 10:01:53,322 - Using logger class org.apache.velocity.runtime.log.SimpleLog4JLogSystem -2007-01-23 10:01:53,322 - Default ResourceManager initializing. (class org.generama.velocity.ResourceLoaderExposingResourceManager) -2007-01-23 10:01:53,322 - Resource Loader Instantiated: org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:01:53,322 - ClasspathResourceLoader : initialization starting. -2007-01-23 10:01:53,322 - ClasspathResourceLoader : initialization complete. -2007-01-23 10:01:53,338 - Resource Loader Instantiated: org.generama.velocity.ConfigurableFileResourceLoader -2007-01-23 10:01:53,338 - FileResourceLoader : initialization starting. -2007-01-23 10:01:53,338 - FileResourceLoader : initialization complete. -2007-01-23 10:01:53,338 - ResourceCache : initialized. (class org.apache.velocity.runtime.resource.ResourceCacheImpl) -2007-01-23 10:01:53,338 - Default ResourceManager initialization complete. -2007-01-23 10:01:53,353 - Loaded System Directive: org.apache.velocity.runtime.directive.Literal -2007-01-23 10:01:53,353 - Loaded System Directive: org.apache.velocity.runtime.directive.Macro -2007-01-23 10:01:53,369 - Loaded System Directive: org.apache.velocity.runtime.directive.Parse -2007-01-23 10:01:53,369 - Loaded System Directive: org.apache.velocity.runtime.directive.Include -2007-01-23 10:01:53,384 - Loaded System Directive: org.apache.velocity.runtime.directive.Foreach -2007-01-23 10:01:53,541 - Created: 20 parsers. -2007-01-23 10:01:53,588 - Velocimacro : initialization starting. -2007-01-23 10:01:53,588 - Velocimacro : adding VMs from VM library template : VM_global_library.vm -2007-01-23 10:01:53,603 - ResourceManager : unable to find resource 'VM_global_library.vm' in any resource loader. -2007-01-23 10:01:53,603 - Velocimacro : error using VM library template VM_global_library.vm : org.apache.velocity.exception.ResourceNotFoundException: Unable to find resource 'VM_global_library.vm' -2007-01-23 10:01:53,603 - Velocimacro : VM library template macro registration complete. -2007-01-23 10:01:53,603 - Velocimacro : allowInline = true : VMs can be defined inline in templates -2007-01-23 10:01:53,603 - Velocimacro : allowInlineToOverride = false : VMs defined inline may NOT replace previous VM definitions -2007-01-23 10:01:53,603 - Velocimacro : allowInlineLocal = false : VMs defined inline will be global in scope if allowed. -2007-01-23 10:01:53,603 - Velocimacro : messages on : VM system will output logging messages -2007-01-23 10:01:53,603 - Velocimacro : autoload off : VM system will not automatically reload global library macros -2007-01-23 10:01:53,603 - Velocimacro : initialization complete. -2007-01-23 10:01:53,603 - Velocity successfully started. -2007-01-23 10:01:54,697 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:01:54,869 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:01:54,916 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:01:54,947 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:01:54,978 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:01:55,009 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:01:55,088 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:01:55,119 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:01:55,181 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:01:55,213 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:01:55,228 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:01:55,259 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:01:55,338 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:01:55,353 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:01:55,384 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:01:55,431 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:01:55,447 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:01:55,478 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:01:55,572 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:01:55,603 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:01:55,634 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:01:55,666 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:01:55,681 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:01:55,713 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:06:10,060 - SimpleLog4JLogSystem initialized using logfile 'velocity.log' -2007-01-23 10:06:10,060 - ************************************************************** -2007-01-23 10:06:10,060 - Starting Jakarta Velocity v1.4 -2007-01-23 10:06:10,060 - RuntimeInstance initializing. -2007-01-23 10:06:10,060 - Default Properties File: org\apache\velocity\runtime\defaults\velocity.properties -2007-01-23 10:06:10,060 - Trying to use logger class org.apache.velocity.runtime.log.AvalonLogSystem -2007-01-23 10:06:10,060 - Couldn't find class org.apache.velocity.runtime.log.AvalonLogSystem or necessary supporting classes in classpath. Exception : java.lang.NoClassDefFoundError: org/apache/log/format/Formatter -2007-01-23 10:06:10,060 - Trying to use logger class org.apache.velocity.runtime.log.SimpleLog4JLogSystem -2007-01-23 10:06:10,060 - Using logger class org.apache.velocity.runtime.log.SimpleLog4JLogSystem -2007-01-23 10:06:10,060 - Default ResourceManager initializing. (class org.generama.velocity.ResourceLoaderExposingResourceManager) -2007-01-23 10:06:10,060 - Resource Loader Instantiated: org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:06:10,060 - ClasspathResourceLoader : initialization starting. -2007-01-23 10:06:10,060 - ClasspathResourceLoader : initialization complete. -2007-01-23 10:06:10,075 - Resource Loader Instantiated: org.generama.velocity.ConfigurableFileResourceLoader -2007-01-23 10:06:10,075 - FileResourceLoader : initialization starting. -2007-01-23 10:06:10,075 - FileResourceLoader : initialization complete. -2007-01-23 10:06:10,075 - ResourceCache : initialized. (class org.apache.velocity.runtime.resource.ResourceCacheImpl) -2007-01-23 10:06:10,075 - Default ResourceManager initialization complete. -2007-01-23 10:06:10,091 - Loaded System Directive: org.apache.velocity.runtime.directive.Literal -2007-01-23 10:06:10,091 - Loaded System Directive: org.apache.velocity.runtime.directive.Macro -2007-01-23 10:06:10,106 - Loaded System Directive: org.apache.velocity.runtime.directive.Parse -2007-01-23 10:06:10,106 - Loaded System Directive: org.apache.velocity.runtime.directive.Include -2007-01-23 10:06:10,122 - Loaded System Directive: org.apache.velocity.runtime.directive.Foreach -2007-01-23 10:06:10,278 - Created: 20 parsers. -2007-01-23 10:06:10,325 - Velocimacro : initialization starting. -2007-01-23 10:06:10,325 - Velocimacro : adding VMs from VM library template : VM_global_library.vm -2007-01-23 10:06:10,341 - ResourceManager : unable to find resource 'VM_global_library.vm' in any resource loader. -2007-01-23 10:06:10,341 - Velocimacro : error using VM library template VM_global_library.vm : org.apache.velocity.exception.ResourceNotFoundException: Unable to find resource 'VM_global_library.vm' -2007-01-23 10:06:10,341 - Velocimacro : VM library template macro registration complete. -2007-01-23 10:06:10,341 - Velocimacro : allowInline = true : VMs can be defined inline in templates -2007-01-23 10:06:10,341 - Velocimacro : allowInlineToOverride = false : VMs defined inline may NOT replace previous VM definitions -2007-01-23 10:06:10,341 - Velocimacro : allowInlineLocal = false : VMs defined inline will be global in scope if allowed. -2007-01-23 10:06:10,341 - Velocimacro : messages on : VM system will output logging messages -2007-01-23 10:06:10,341 - Velocimacro : autoload off : VM system will not automatically reload global library macros -2007-01-23 10:06:10,341 - Velocimacro : initialization complete. -2007-01-23 10:06:10,341 - Velocity successfully started. -2007-01-23 10:06:11,356 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:06:11,528 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:06:11,575 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:06:11,606 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:06:11,638 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:06:11,669 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:06:11,763 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:06:11,794 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:06:11,841 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:06:11,872 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:06:11,888 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:06:11,919 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:06:11,997 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:06:12,028 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:06:12,060 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:06:12,091 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:06:12,122 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:06:12,153 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:06:12,231 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:06:12,263 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:06:12,310 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:06:12,325 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:06:12,356 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:06:12,372 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:23:14,745 - SimpleLog4JLogSystem initialized using logfile 'velocity.log' -2007-01-23 10:23:14,745 - ************************************************************** -2007-01-23 10:23:14,745 - Starting Jakarta Velocity v1.4 -2007-01-23 10:23:14,745 - RuntimeInstance initializing. -2007-01-23 10:23:14,745 - Default Properties File: org\apache\velocity\runtime\defaults\velocity.properties -2007-01-23 10:23:14,745 - Trying to use logger class org.apache.velocity.runtime.log.AvalonLogSystem -2007-01-23 10:23:14,745 - Couldn't find class org.apache.velocity.runtime.log.AvalonLogSystem or necessary supporting classes in classpath. Exception : java.lang.NoClassDefFoundError: org/apache/log/format/Formatter -2007-01-23 10:23:14,745 - Trying to use logger class org.apache.velocity.runtime.log.SimpleLog4JLogSystem -2007-01-23 10:23:14,745 - Using logger class org.apache.velocity.runtime.log.SimpleLog4JLogSystem -2007-01-23 10:23:14,745 - Default ResourceManager initializing. (class org.generama.velocity.ResourceLoaderExposingResourceManager) -2007-01-23 10:23:14,745 - Resource Loader Instantiated: org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:23:14,745 - ClasspathResourceLoader : initialization starting. -2007-01-23 10:23:14,760 - ClasspathResourceLoader : initialization complete. -2007-01-23 10:23:14,760 - Resource Loader Instantiated: org.generama.velocity.ConfigurableFileResourceLoader -2007-01-23 10:23:14,760 - FileResourceLoader : initialization starting. -2007-01-23 10:23:14,760 - FileResourceLoader : initialization complete. -2007-01-23 10:23:14,776 - ResourceCache : initialized. (class org.apache.velocity.runtime.resource.ResourceCacheImpl) -2007-01-23 10:23:14,776 - Default ResourceManager initialization complete. -2007-01-23 10:23:14,776 - Loaded System Directive: org.apache.velocity.runtime.directive.Literal -2007-01-23 10:23:14,791 - Loaded System Directive: org.apache.velocity.runtime.directive.Macro -2007-01-23 10:23:14,791 - Loaded System Directive: org.apache.velocity.runtime.directive.Parse -2007-01-23 10:23:14,807 - Loaded System Directive: org.apache.velocity.runtime.directive.Include -2007-01-23 10:23:14,807 - Loaded System Directive: org.apache.velocity.runtime.directive.Foreach -2007-01-23 10:23:14,979 - Created: 20 parsers. -2007-01-23 10:23:15,010 - Velocimacro : initialization starting. -2007-01-23 10:23:15,010 - Velocimacro : adding VMs from VM library template : VM_global_library.vm -2007-01-23 10:23:15,026 - ResourceManager : unable to find resource 'VM_global_library.vm' in any resource loader. -2007-01-23 10:23:15,026 - Velocimacro : error using VM library template VM_global_library.vm : org.apache.velocity.exception.ResourceNotFoundException: Unable to find resource 'VM_global_library.vm' -2007-01-23 10:23:15,026 - Velocimacro : VM library template macro registration complete. -2007-01-23 10:23:15,026 - Velocimacro : allowInline = true : VMs can be defined inline in templates -2007-01-23 10:23:15,026 - Velocimacro : allowInlineToOverride = false : VMs defined inline may NOT replace previous VM definitions -2007-01-23 10:23:15,026 - Velocimacro : allowInlineLocal = false : VMs defined inline will be global in scope if allowed. -2007-01-23 10:23:15,026 - Velocimacro : messages on : VM system will output logging messages -2007-01-23 10:23:15,026 - Velocimacro : autoload off : VM system will not automatically reload global library macros -2007-01-23 10:23:15,041 - Velocimacro : initialization complete. -2007-01-23 10:23:15,041 - Velocity successfully started. -2007-01-23 10:23:16,104 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:23:16,260 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:23:16,307 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:23:16,338 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:23:16,370 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:23:16,401 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:23:16,495 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:23:16,526 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:23:16,573 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:23:16,604 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:23:16,620 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:23:16,651 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:23:16,729 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:23:16,760 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:23:16,791 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:23:16,838 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:23:16,854 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:23:16,885 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:23:16,979 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:23:17,010 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:23:17,041 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:23:17,073 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:23:17,088 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:23:17,120 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:28:41,155 - SimpleLog4JLogSystem initialized using logfile 'velocity.log' -2007-01-23 10:28:41,155 - ************************************************************** -2007-01-23 10:28:41,155 - Starting Jakarta Velocity v1.4 -2007-01-23 10:28:41,155 - RuntimeInstance initializing. -2007-01-23 10:28:41,155 - Default Properties File: org\apache\velocity\runtime\defaults\velocity.properties -2007-01-23 10:28:41,155 - Trying to use logger class org.apache.velocity.runtime.log.AvalonLogSystem -2007-01-23 10:28:41,155 - Couldn't find class org.apache.velocity.runtime.log.AvalonLogSystem or necessary supporting classes in classpath. Exception : java.lang.NoClassDefFoundError: org/apache/log/format/Formatter -2007-01-23 10:28:41,155 - Trying to use logger class org.apache.velocity.runtime.log.SimpleLog4JLogSystem -2007-01-23 10:28:41,155 - Using logger class org.apache.velocity.runtime.log.SimpleLog4JLogSystem -2007-01-23 10:28:41,171 - Default ResourceManager initializing. (class org.generama.velocity.ResourceLoaderExposingResourceManager) -2007-01-23 10:28:41,171 - Resource Loader Instantiated: org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:28:41,171 - ClasspathResourceLoader : initialization starting. -2007-01-23 10:28:41,171 - ClasspathResourceLoader : initialization complete. -2007-01-23 10:28:41,171 - Resource Loader Instantiated: org.generama.velocity.ConfigurableFileResourceLoader -2007-01-23 10:28:41,171 - FileResourceLoader : initialization starting. -2007-01-23 10:28:41,171 - FileResourceLoader : initialization complete. -2007-01-23 10:28:41,186 - ResourceCache : initialized. (class org.apache.velocity.runtime.resource.ResourceCacheImpl) -2007-01-23 10:28:41,186 - Default ResourceManager initialization complete. -2007-01-23 10:28:41,186 - Loaded System Directive: org.apache.velocity.runtime.directive.Literal -2007-01-23 10:28:41,202 - Loaded System Directive: org.apache.velocity.runtime.directive.Macro -2007-01-23 10:28:41,218 - Loaded System Directive: org.apache.velocity.runtime.directive.Parse -2007-01-23 10:28:41,218 - Loaded System Directive: org.apache.velocity.runtime.directive.Include -2007-01-23 10:28:41,218 - Loaded System Directive: org.apache.velocity.runtime.directive.Foreach -2007-01-23 10:28:41,389 - Created: 20 parsers. -2007-01-23 10:28:41,436 - Velocimacro : initialization starting. -2007-01-23 10:28:41,436 - Velocimacro : adding VMs from VM library template : VM_global_library.vm -2007-01-23 10:28:41,452 - ResourceManager : unable to find resource 'VM_global_library.vm' in any resource loader. -2007-01-23 10:28:41,452 - Velocimacro : error using VM library template VM_global_library.vm : org.apache.velocity.exception.ResourceNotFoundException: Unable to find resource 'VM_global_library.vm' -2007-01-23 10:28:41,452 - Velocimacro : VM library template macro registration complete. -2007-01-23 10:28:41,452 - Velocimacro : allowInline = true : VMs can be defined inline in templates -2007-01-23 10:28:41,452 - Velocimacro : allowInlineToOverride = false : VMs defined inline may NOT replace previous VM definitions -2007-01-23 10:28:41,452 - Velocimacro : allowInlineLocal = false : VMs defined inline will be global in scope if allowed. -2007-01-23 10:28:41,452 - Velocimacro : messages on : VM system will output logging messages -2007-01-23 10:28:41,452 - Velocimacro : autoload off : VM system will not automatically reload global library macros -2007-01-23 10:28:41,452 - Velocimacro : initialization complete. -2007-01-23 10:28:41,452 - Velocity successfully started. -2007-01-23 10:28:42,436 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:28:42,577 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:28:42,624 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:28:42,655 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:28:42,686 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:28:42,733 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:28:42,811 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:28:42,843 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:28:42,905 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:28:42,936 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:28:42,952 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:28:42,983 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:28:43,061 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:28:43,077 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:28:43,124 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:28:43,155 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:28:43,186 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:28:43,202 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:28:43,296 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:28:43,327 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:28:43,374 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:28:43,405 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:28:43,421 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 10:28:43,452 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 16:12:36,180 - SimpleLog4JLogSystem initialized using logfile 'velocity.log' -2007-01-23 16:12:36,195 - ************************************************************** -2007-01-23 16:12:36,195 - Starting Jakarta Velocity v1.4 -2007-01-23 16:12:36,195 - RuntimeInstance initializing. -2007-01-23 16:12:36,195 - Default Properties File: org\apache\velocity\runtime\defaults\velocity.properties -2007-01-23 16:12:36,195 - Trying to use logger class org.apache.velocity.runtime.log.AvalonLogSystem -2007-01-23 16:12:36,195 - Couldn't find class org.apache.velocity.runtime.log.AvalonLogSystem or necessary supporting classes in classpath. Exception : java.lang.NoClassDefFoundError: org/apache/log/format/Formatter -2007-01-23 16:12:36,195 - Trying to use logger class org.apache.velocity.runtime.log.SimpleLog4JLogSystem -2007-01-23 16:12:36,195 - Using logger class org.apache.velocity.runtime.log.SimpleLog4JLogSystem -2007-01-23 16:12:36,195 - Default ResourceManager initializing. (class org.generama.velocity.ResourceLoaderExposingResourceManager) -2007-01-23 16:12:36,195 - Resource Loader Instantiated: org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 16:12:36,195 - ClasspathResourceLoader : initialization starting. -2007-01-23 16:12:36,195 - ClasspathResourceLoader : initialization complete. -2007-01-23 16:12:36,195 - Resource Loader Instantiated: org.generama.velocity.ConfigurableFileResourceLoader -2007-01-23 16:12:36,211 - FileResourceLoader : initialization starting. -2007-01-23 16:12:36,211 - FileResourceLoader : initialization complete. -2007-01-23 16:12:36,211 - ResourceCache : initialized. (class org.apache.velocity.runtime.resource.ResourceCacheImpl) -2007-01-23 16:12:36,211 - Default ResourceManager initialization complete. -2007-01-23 16:12:36,226 - Loaded System Directive: org.apache.velocity.runtime.directive.Literal -2007-01-23 16:12:36,226 - Loaded System Directive: org.apache.velocity.runtime.directive.Macro -2007-01-23 16:12:36,242 - Loaded System Directive: org.apache.velocity.runtime.directive.Parse -2007-01-23 16:12:36,242 - Loaded System Directive: org.apache.velocity.runtime.directive.Include -2007-01-23 16:12:36,258 - Loaded System Directive: org.apache.velocity.runtime.directive.Foreach -2007-01-23 16:12:36,430 - Created: 20 parsers. -2007-01-23 16:12:36,476 - Velocimacro : initialization starting. -2007-01-23 16:12:36,476 - Velocimacro : adding VMs from VM library template : VM_global_library.vm -2007-01-23 16:12:36,492 - ResourceManager : unable to find resource 'VM_global_library.vm' in any resource loader. -2007-01-23 16:12:36,492 - Velocimacro : error using VM library template VM_global_library.vm : org.apache.velocity.exception.ResourceNotFoundException: Unable to find resource 'VM_global_library.vm' -2007-01-23 16:12:36,492 - Velocimacro : VM library template macro registration complete. -2007-01-23 16:12:36,492 - Velocimacro : allowInline = true : VMs can be defined inline in templates -2007-01-23 16:12:36,492 - Velocimacro : allowInlineToOverride = false : VMs defined inline may NOT replace previous VM definitions -2007-01-23 16:12:36,492 - Velocimacro : allowInlineLocal = false : VMs defined inline will be global in scope if allowed. -2007-01-23 16:12:36,492 - Velocimacro : messages on : VM system will output logging messages -2007-01-23 16:12:36,492 - Velocimacro : autoload off : VM system will not automatically reload global library macros -2007-01-23 16:12:36,492 - Velocimacro : initialization complete. -2007-01-23 16:12:36,492 - Velocity successfully started. -2007-01-23 16:12:37,633 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 16:12:37,898 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 16:12:37,945 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 16:12:37,992 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 16:12:38,023 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 16:12:38,070 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 16:12:38,164 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 16:12:38,180 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 16:12:38,242 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 16:12:38,273 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 16:12:38,305 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 16:12:38,320 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 16:12:38,414 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 16:12:38,430 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 16:12:38,476 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 16:12:38,508 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 16:12:38,539 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 16:12:38,570 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 16:12:38,648 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 16:12:38,695 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 16:12:38,726 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 16:12:38,758 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 16:12:38,773 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 16:12:38,805 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/RemoteInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 17:48:46,160 - SimpleLog4JLogSystem initialized using logfile 'velocity.log' -2007-01-23 17:48:46,175 - ************************************************************** -2007-01-23 17:48:46,175 - Starting Jakarta Velocity v1.4 -2007-01-23 17:48:46,175 - RuntimeInstance initializing. -2007-01-23 17:48:46,175 - Default Properties File: org\apache\velocity\runtime\defaults\velocity.properties -2007-01-23 17:48:46,175 - Trying to use logger class org.apache.velocity.runtime.log.AvalonLogSystem -2007-01-23 17:48:46,175 - Couldn't find class org.apache.velocity.runtime.log.AvalonLogSystem or necessary supporting classes in classpath. Exception : java.lang.NoClassDefFoundError: org/apache/log/format/Formatter -2007-01-23 17:48:46,175 - Trying to use logger class org.apache.velocity.runtime.log.SimpleLog4JLogSystem -2007-01-23 17:48:46,175 - Using logger class org.apache.velocity.runtime.log.SimpleLog4JLogSystem -2007-01-23 17:48:46,175 - Default ResourceManager initializing. (class org.generama.velocity.ResourceLoaderExposingResourceManager) -2007-01-23 17:48:46,175 - Resource Loader Instantiated: org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 17:48:46,175 - ClasspathResourceLoader : initialization starting. -2007-01-23 17:48:46,175 - ClasspathResourceLoader : initialization complete. -2007-01-23 17:48:46,191 - Resource Loader Instantiated: org.generama.velocity.ConfigurableFileResourceLoader -2007-01-23 17:48:46,191 - FileResourceLoader : initialization starting. -2007-01-23 17:48:46,191 - FileResourceLoader : initialization complete. -2007-01-23 17:48:46,191 - ResourceCache : initialized. (class org.apache.velocity.runtime.resource.ResourceCacheImpl) -2007-01-23 17:48:46,191 - Default ResourceManager initialization complete. -2007-01-23 17:48:46,207 - Loaded System Directive: org.apache.velocity.runtime.directive.Literal -2007-01-23 17:48:46,207 - Loaded System Directive: org.apache.velocity.runtime.directive.Macro -2007-01-23 17:48:46,222 - Loaded System Directive: org.apache.velocity.runtime.directive.Parse -2007-01-23 17:48:46,222 - Loaded System Directive: org.apache.velocity.runtime.directive.Include -2007-01-23 17:48:46,222 - Loaded System Directive: org.apache.velocity.runtime.directive.Foreach -2007-01-23 17:48:46,394 - Created: 20 parsers. -2007-01-23 17:48:46,425 - Velocimacro : initialization starting. -2007-01-23 17:48:46,425 - Velocimacro : adding VMs from VM library template : VM_global_library.vm -2007-01-23 17:48:46,441 - ResourceManager : unable to find resource 'VM_global_library.vm' in any resource loader. -2007-01-23 17:48:46,441 - Velocimacro : error using VM library template VM_global_library.vm : org.apache.velocity.exception.ResourceNotFoundException: Unable to find resource 'VM_global_library.vm' -2007-01-23 17:48:46,441 - Velocimacro : VM library template macro registration complete. -2007-01-23 17:48:46,441 - Velocimacro : allowInline = true : VMs can be defined inline in templates -2007-01-23 17:48:46,441 - Velocimacro : allowInlineToOverride = false : VMs defined inline may NOT replace previous VM definitions -2007-01-23 17:48:46,441 - Velocimacro : allowInlineLocal = false : VMs defined inline will be global in scope if allowed. -2007-01-23 17:48:46,441 - Velocimacro : messages on : VM system will output logging messages -2007-01-23 17:48:46,441 - Velocimacro : autoload off : VM system will not automatically reload global library macros -2007-01-23 17:48:46,441 - Velocimacro : initialization complete. -2007-01-23 17:48:46,441 - Velocity successfully started. -2007-01-23 17:48:47,472 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 17:48:47,628 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 17:48:47,660 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 17:48:47,707 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 17:48:47,722 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 17:48:47,769 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalHomeInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader -2007-01-23 17:48:47,847 - ResourceManager : found org/xdoclet/plugin/ejb/interfaces/LocalInterfacePlugin.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader diff --git a/edu.harvard.i2b2.fr/.classpath b/edu.harvard.i2b2.fr/.classpath index 7de02578..b9f6029d 100755 --- a/edu.harvard.i2b2.fr/.classpath +++ b/edu.harvard.i2b2.fr/.classpath @@ -1,122 +1,46 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/edu.harvard.i2b2.fr/.cvsignore b/edu.harvard.i2b2.fr/.cvsignore deleted file mode 100755 index e4488222..00000000 --- a/edu.harvard.i2b2.fr/.cvsignore +++ /dev/null @@ -1,4 +0,0 @@ -dist -genlib -report -classes diff --git a/edu.harvard.i2b2.fr/.gitignore b/edu.harvard.i2b2.fr/.gitignore deleted file mode 100644 index 840e7d31..00000000 --- a/edu.harvard.i2b2.fr/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/classes/ diff --git a/edu.harvard.i2b2.fr/.project b/edu.harvard.i2b2.fr/.project index 2633c154..caae7142 100755 --- a/edu.harvard.i2b2.fr/.project +++ b/edu.harvard.i2b2.fr/.project @@ -10,8 +10,14 @@ + + org.eclipse.m2e.core.maven2Builder + + + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature diff --git a/edu.harvard.i2b2.fr/LICENSE.txt b/edu.harvard.i2b2.fr/LICENSE.txt deleted file mode 100644 index e5a5569a..00000000 --- a/edu.harvard.i2b2.fr/LICENSE.txt +++ /dev/null @@ -1,406 +0,0 @@ -#------------------------------------------------------------------------------- -# Copyright (c) 2006-2018 Massachusetts General Hospital -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Mozilla Public License, -# v. 2.0. If a copy of the MPL was not distributed with this file, You can -# obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under -# the terms of the Healthcare Disclaimer. -#------------------------------------------------------------------------------- -Mozilla Public License, version 2.0 - -1. Definitions - -1.1. "Contributor" - - means each individual or legal entity that creates, contributes to the - creation of, or owns Covered Software. - -1.2. "Contributor Version" - - means the combination of the Contributions of others (if any) used by a - Contributor and that particular Contributor's Contribution. - -1.3. "Contribution" - - means Covered Software of a particular Contributor. - -1.4. "Covered Software" - - means Source Code Form to which the initial Contributor has attached the - notice in Exhibit A, the Executable Form of such Source Code Form, and - Modifications of such Source Code Form, in each case including portions - thereof. - -1.5. "Incompatible With Secondary Licenses" - means - - a. that the initial Contributor has attached the notice described in - Exhibit B to the Covered Software; or - - b. that the Covered Software was made available under the terms of - version 1.1 or earlier of the License, but not also under the terms of - a Secondary License. - -1.6. "Executable Form" - - means any form of the work other than Source Code Form. - -1.7. "Larger Work" - - means a work that combines Covered Software with other material, in a - separate file or files, that is not Covered Software. - -1.8. "License" - - means this document. - -1.9. "Licensable" - - means having the right to grant, to the maximum extent possible, whether - at the time of the initial grant or subsequently, any and all of the - rights conveyed by this License. - -1.10. "Modifications" - - means any of the following: - - a. any file in Source Code Form that results from an addition to, - deletion from, or modification of the contents of Covered Software; or - - b. any new file in Source Code Form that contains any Covered Software. - -1.11. "Patent Claims" of a Contributor - - means any patent claim(s), including without limitation, method, - process, and apparatus claims, in any patent Licensable by such - Contributor that would be infringed, but for the grant of the License, - by the making, using, selling, offering for sale, having made, import, - or transfer of either its Contributions or its Contributor Version. - -1.12. "Secondary License" - - means either the GNU General Public License, Version 2.0, the GNU Lesser - General Public License, Version 2.1, the GNU Affero General Public - License, Version 3.0, or any later versions of those licenses. - -1.13. "Source Code Form" - - means the form of the work preferred for making modifications. - -1.14. "You" (or "Your") - - means an individual or a legal entity exercising rights under this - License. For legal entities, "You" includes any entity that controls, is - controlled by, or is under common control with You. For purposes of this - definition, "control" means (a) the power, direct or indirect, to cause - the direction or management of such entity, whether by contract or - otherwise, or (b) ownership of more than fifty percent (50%) of the - outstanding shares or beneficial ownership of such entity. - - -2. License Grants and Conditions - -2.1. Grants - - Each Contributor hereby grants You a world-wide, royalty-free, - non-exclusive license: - - a. under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or - as part of a Larger Work; and - - b. under Patent Claims of such Contributor to make, use, sell, offer for - sale, have made, import, and otherwise transfer either its - Contributions or its Contributor Version. - -2.2. Effective Date - - The licenses granted in Section 2.1 with respect to any Contribution - become effective for each Contribution on the date the Contributor first - distributes such Contribution. - -2.3. Limitations on Grant Scope - - The licenses granted in this Section 2 are the only rights granted under - this License. No additional rights or licenses will be implied from the - distribution or licensing of Covered Software under this License. - Notwithstanding Section 2.1(b) above, no patent license is granted by a - Contributor: - - a. for any code that a Contributor has removed from Covered Software; or - - b. for infringements caused by: (i) Your and any other third party's - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - - c. under Patent Claims infringed by Covered Software in the absence of - its Contributions. - - This License does not grant any rights in the trademarks, service marks, - or logos of any Contributor (except as may be necessary to comply with - the notice requirements in Section 3.4). - -2.4. Subsequent Licenses - - No Contributor makes additional grants as a result of Your choice to - distribute the Covered Software under a subsequent version of this - License (see Section 10.2) or under the terms of a Secondary License (if - permitted under the terms of Section 3.3). - -2.5. Representation - - Each Contributor represents that the Contributor believes its - Contributions are its original creation(s) or it has sufficient rights to - grant the rights to its Contributions conveyed by this License. - -2.6. Fair Use - - This License is not intended to limit any rights You have under - applicable copyright doctrines of fair use, fair dealing, or other - equivalents. - -2.7. Conditions - - Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in - Section 2.1. - - -3. Responsibilities - -3.1. Distribution of Source Form - - All distribution of Covered Software in Source Code Form, including any - Modifications that You create or to which You contribute, must be under - the terms of this License. You must inform recipients that the Source - Code Form of the Covered Software is governed by the terms of this - License, and how they can obtain a copy of this License. You may not - attempt to alter or restrict the recipients' rights in the Source Code - Form. - -3.2. Distribution of Executable Form - - If You distribute Covered Software in Executable Form then: - - a. such Covered Software must also be made available in Source Code Form, - as described in Section 3.1, and You must inform recipients of the - Executable Form how they can obtain a copy of such Source Code Form by - reasonable means in a timely manner, at a charge no more than the cost - of distribution to the recipient; and - - b. You may distribute such Executable Form under the terms of this - License, or sublicense it under different terms, provided that the - license for the Executable Form does not attempt to limit or alter the - recipients' rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - - You may create and distribute a Larger Work under terms of Your choice, - provided that You also comply with the requirements of this License for - the Covered Software. If the Larger Work is a combination of Covered - Software with a work governed by one or more Secondary Licenses, and the - Covered Software is not Incompatible With Secondary Licenses, this - License permits You to additionally distribute such Covered Software - under the terms of such Secondary License(s), so that the recipient of - the Larger Work may, at their option, further distribute the Covered - Software under the terms of either this License or such Secondary - License(s). - -3.4. Notices - - You may not remove or alter the substance of any license notices - (including copyright notices, patent notices, disclaimers of warranty, or - limitations of liability) contained within the Source Code Form of the - Covered Software, except that You may alter any license notices to the - extent required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - - You may choose to offer, and to charge a fee for, warranty, support, - indemnity or liability obligations to one or more recipients of Covered - Software. However, You may do so only on Your own behalf, and not on - behalf of any Contributor. You must make it absolutely clear that any - such warranty, support, indemnity, or liability obligation is offered by - You alone, and You hereby agree to indemnify every Contributor for any - liability incurred by such Contributor as a result of warranty, support, - indemnity or liability terms You offer. You may include additional - disclaimers of warranty and limitations of liability specific to any - jurisdiction. - -4. Inability to Comply Due to Statute or Regulation - - If it is impossible for You to comply with any of the terms of this License - with respect to some or all of the Covered Software due to statute, - judicial order, or regulation then You must: (a) comply with the terms of - this License to the maximum extent possible; and (b) describe the - limitations and the code they affect. Such description must be placed in a - text file included with all distributions of the Covered Software under - this License. Except to the extent prohibited by statute or regulation, - such description must be sufficiently detailed for a recipient of ordinary - skill to be able to understand it. - -5. Termination - -5.1. The rights granted under this License will terminate automatically if You - fail to comply with any of its terms. However, if You become compliant, - then the rights granted under this License from a particular Contributor - are reinstated (a) provisionally, unless and until such Contributor - explicitly and finally terminates Your grants, and (b) on an ongoing - basis, if such Contributor fails to notify You of the non-compliance by - some reasonable means prior to 60 days after You have come back into - compliance. Moreover, Your grants from a particular Contributor are - reinstated on an ongoing basis if such Contributor notifies You of the - non-compliance by some reasonable means, this is the first time You have - received notice of non-compliance with this License from such - Contributor, and You become compliant prior to 30 days after Your receipt - of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent - infringement claim (excluding declaratory judgment actions, - counter-claims, and cross-claims) alleging that a Contributor Version - directly or indirectly infringes any patent, then the rights granted to - You by any and all Contributors for the Covered Software under Section - 2.1 of this License shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user - license agreements (excluding distributors and resellers) which have been - validly granted by You or Your distributors under this License prior to - termination shall survive termination. - -6. Disclaimer of Warranty - - Covered Software is provided under this License on an "as is" basis, - without warranty of any kind, either expressed, implied, or statutory, - including, without limitation, warranties that the Covered Software is free - of defects, merchantable, fit for a particular purpose or non-infringing. - The entire risk as to the quality and performance of the Covered Software - is with You. Should any Covered Software prove defective in any respect, - You (not any Contributor) assume the cost of any necessary servicing, - repair, or correction. This disclaimer of warranty constitutes an essential - part of this License. No use of any Covered Software is authorized under - this License except under this disclaimer. - -7. Limitation of Liability - - Under no circumstances and under no legal theory, whether tort (including - negligence), contract, or otherwise, shall any Contributor, or anyone who - distributes Covered Software as permitted above, be liable to You for any - direct, indirect, special, incidental, or consequential damages of any - character including, without limitation, damages for lost profits, loss of - goodwill, work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses, even if such party shall have been - informed of the possibility of such damages. This limitation of liability - shall not apply to liability for death or personal injury resulting from - such party's negligence to the extent applicable law prohibits such - limitation. Some jurisdictions do not allow the exclusion or limitation of - incidental or consequential damages, so this exclusion and limitation may - not apply to You. - -8. Litigation - - Any litigation relating to this License may be brought only in the courts - of a jurisdiction where the defendant maintains its principal place of - business and such litigation shall be governed by laws of that - jurisdiction, without reference to its conflict-of-law provisions. Nothing - in this Section shall prevent a party's ability to bring cross-claims or - counter-claims. - -9. Miscellaneous - - This License represents the complete agreement concerning the subject - matter hereof. If any provision of this License is held to be - unenforceable, such provision shall be reformed only to the extent - necessary to make it enforceable. Any law or regulation which provides that - the language of a contract shall be construed against the drafter shall not - be used to construe this License against a Contributor. - - -10. Versions of the License - -10.1. New Versions - - Mozilla Foundation is the license steward. Except as provided in Section - 10.3, no one other than the license steward has the right to modify or - publish new versions of this License. Each version will be given a - distinguishing version number. - -10.2. Effect of New Versions - - You may distribute the Covered Software under the terms of the version - of the License under which You originally received the Covered Software, - or under the terms of any subsequent version published by the license - steward. - -10.3. Modified Versions - - If you create software not governed by this License, and you want to - create a new license for such software, you may create and use a - modified version of this License if you rename the license and remove - any references to the name of the license steward (except to note that - such modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary - Licenses If You choose to distribute Source Code Form that is - Incompatible With Secondary Licenses under the terms of this version of - the License, the notice described in Exhibit B of this License must be - attached. - -Exhibit A - Source Code Form License Notice - - This Source Code Form is subject to the - terms of the Mozilla Public License, v. - 2.0. If a copy of the MPL was not - distributed with this file, You can - obtain one at - http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular file, -then You may include the notice in a location (such as a LICENSE file in a -relevant directory) where a recipient would be likely to look for such a -notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - "Incompatible With Secondary Licenses" Notice - - This Source Code Form is "Incompatible - With Secondary Licenses", as defined by - the Mozilla Public License, v. 2.0. - ---------------------- - -Healthcare Disclaimer - -In the United States, or any other jurisdictions where they may apply, the -following additional disclaimer of warranty and limitation of liability are -hereby incorporated into the terms and conditions of MPL 2.0: - -1. No warranties of any kind whatsoever are made as to the results that - You will obtain from relying upon the covered code (or any information - or content obtained by way of the covered code), including but not - limited to compliance with privacy laws or regulations or clinical - care industry standards and protocols. Use of the covered code is not - a substitute for a health care provider’s standard practice or - professional judgment. Any decision with regard to the appropriateness - of treatment, or the validity or reliability of information or content - made available by the covered code, is the sole responsibility of the - health care provider. Consequently, it is incumbent upon each health - care provider to verify all medical history and treatment plans with - each patient. - -2. Under no circumstances and under no legal theory, whether tort - (including negligence), contract, or otherwise, shall any Contributor, - or anyone who distributes Covered Software as permitted by the - license, be liable to You for any indirect, special, incidental, - consequential damages of any character including, without limitation, - damages for loss of goodwill, work stoppage, computer failure or - malfunction, or any and all other damages or losses, of any nature - whatsoever (direct or otherwise) on account of or associated with the - use or inability to use the covered content (including, without - limitation, the use of information or content made available by the - covered code, all documentation associated therewith, and the failure - of the covered code to comply with privacy laws and regulations or - clinical care industry standards and protocols), even if such party - shall have been informed of the possibility of such damages. diff --git a/edu.harvard.i2b2.fr/build.properties b/edu.harvard.i2b2.fr/build.properties deleted file mode 100755 index 137949a9..00000000 --- a/edu.harvard.i2b2.fr/build.properties +++ /dev/null @@ -1,15 +0,0 @@ -#Ant build property file - -##JBOSS HOME -jboss.home=/opt/wildfly-17.0.1.Final -axis2.war.name=i2b2.war - -#Test files home -testfiledir=testfiles - -report=test-reports -testhost=http://127.0.0.1:9090/i2b2/services - - - - diff --git a/edu.harvard.i2b2.fr/build.xml b/edu.harvard.i2b2.fr/build.xml deleted file mode 100755 index 92b94875..00000000 --- a/edu.harvard.i2b2.fr/build.xml +++ /dev/null @@ -1,203 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/edu.harvard.i2b2.fr/common-build.xml b/edu.harvard.i2b2.fr/common-build.xml deleted file mode 100755 index 5d08e5f3..00000000 --- a/edu.harvard.i2b2.fr/common-build.xml +++ /dev/null @@ -1,75 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/edu.harvard.i2b2.fr/master_build.xml b/edu.harvard.i2b2.fr/master_build.xml deleted file mode 100755 index 7ad3f9d8..00000000 --- a/edu.harvard.i2b2.fr/master_build.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/edu.harvard.i2b2.fr/pom.xml b/edu.harvard.i2b2.fr/pom.xml new file mode 100644 index 00000000..9e333eef --- /dev/null +++ b/edu.harvard.i2b2.fr/pom.xml @@ -0,0 +1,44 @@ + + 4.0.0 + + edu.harvard.i2b2 + i2b2-parent + 2.0.0-SNAPSHOT + + edu.harvard.i2b2.fr + jar + FR Module + + + + + org.codehaus.mojo + build-helper-maven-plugin + 3.0.0 + + + generate-sources + + add-source + + + + gensrc + + + + + + + + + + + + edu.harvard.i2b2 + edu.harvard.i2b2.server-common + + + + \ No newline at end of file diff --git a/edu.harvard.i2b2.fr/responseGraph.png b/edu.harvard.i2b2.fr/responseGraph.png deleted file mode 100755 index f079a15c..00000000 --- a/edu.harvard.i2b2.fr/responseGraph.png +++ /dev/null @@ -1,38 +0,0 @@ -c2RmCnNkZnNkZnMKCmRzCmQKZAoK - - 1.1 - 2.4 - - edu.harvard.i2b2.fr - 1.0 - - - i2b2 Hive - - - i2b2_QueryTool - 0.2 - - - i2b2 Hive - - - 1 - - - - - Log information - - DONE - - - - - - - /tmp/myfilename - - - - \ No newline at end of file diff --git a/edu.harvard.i2b2.fr/src/server/edu/harvard/i2b2/fr/datavo/FRJAXBUtil.java b/edu.harvard.i2b2.fr/src/main/java/edu/harvard/i2b2/fr/datavo/FRJAXBUtil.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.fr/src/server/edu/harvard/i2b2/fr/datavo/FRJAXBUtil.java rename to edu.harvard.i2b2.fr/src/main/java/edu/harvard/i2b2/fr/datavo/FRJAXBUtil.java diff --git a/edu.harvard.i2b2.fr/src/server/edu/harvard/i2b2/fr/datavo/I2B2MessageResponseFactory.java b/edu.harvard.i2b2.fr/src/main/java/edu/harvard/i2b2/fr/datavo/I2B2MessageResponseFactory.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.fr/src/server/edu/harvard/i2b2/fr/datavo/I2B2MessageResponseFactory.java rename to edu.harvard.i2b2.fr/src/main/java/edu/harvard/i2b2/fr/datavo/I2B2MessageResponseFactory.java index 0b5dab2e..85fbe876 --- a/edu.harvard.i2b2.fr/src/server/edu/harvard/i2b2/fr/datavo/I2B2MessageResponseFactory.java +++ b/edu.harvard.i2b2.fr/src/main/java/edu/harvard/i2b2/fr/datavo/I2B2MessageResponseFactory.java @@ -1,184 +1,184 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.fr.datavo; - -import java.io.StringWriter; -import java.math.BigDecimal; - -import jakarta.xml.bind.JAXBElement; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.fr.datavo.i2b2message.ApplicationType; -import edu.harvard.i2b2.fr.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.fr.datavo.i2b2message.FacilityType; -import edu.harvard.i2b2.fr.datavo.i2b2message.InfoType; -import edu.harvard.i2b2.fr.datavo.i2b2message.MessageControlIdType; -import edu.harvard.i2b2.fr.datavo.i2b2message.MessageHeaderType; -import edu.harvard.i2b2.fr.datavo.i2b2message.PollingUrlType; -import edu.harvard.i2b2.fr.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.fr.datavo.i2b2message.ResponseHeaderType; -import edu.harvard.i2b2.fr.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.fr.datavo.i2b2message.ResultStatusType; -import edu.harvard.i2b2.fr.datavo.i2b2message.StatusType; - - -public class I2B2MessageResponseFactory { - - /** log * */ - protected final static Log log = LogFactory - .getLog(I2B2MessageResponseFactory.class); - - /** - * Function to build response message type using given bodytype and request - * xml - * - * @param requestXml - * @param bodyType - * @return i2b2 response message xml - * @throws JAXBUtilException - */ - public static String buildResponseMessage(String requestXml, - StatusType statusType, BodyType bodyType, boolean splCharFilterFlag) - throws JAXBUtilException { - JAXBUtil util = FRJAXBUtil.getJAXBUtil(); - - MessageHeaderType messageHeader = new MessageHeaderType(); - ApplicationType appType = new ApplicationType(); - appType.setApplicationName("FRC Cell"); - appType.setApplicationVersion("1.7"); - - - if (requestXml != null) { - RequestMessageType requestMsgType = getI2B2RequestMessageType(requestXml); - MessageHeaderType clientMessageHeader = requestMsgType.getMessageHeader(); - // reverse sending and receiving app - if (clientMessageHeader != null) { - ApplicationType sendingApp = clientMessageHeader - .getSendingApplication(); - messageHeader.setSendingApplication(appType); - messageHeader.setReceivingApplication(sendingApp); - messageHeader.setProjectId(clientMessageHeader.getProjectId()); - } - } else { - messageHeader = new MessageHeaderType(); - messageHeader.setSendingApplication(appType); - } - - messageHeader.setI2B2VersionCompatible(new BigDecimal("1.1")); - messageHeader.setHl7VersionCompatible(new BigDecimal("2.4")); - - MessageControlIdType messageControlIdType = new MessageControlIdType(); - messageControlIdType.setInstanceNum(1); - messageHeader.setMessageControlId(messageControlIdType); - - FacilityType facility = new FacilityType(); - facility.setFacilityName("i2b2 Hive"); - messageHeader.setSendingFacility(facility); - messageHeader.setReceivingFacility(facility); - - // :TODO statusType.setValue(sessionId); - PollingUrlType pollingType = new PollingUrlType(); - pollingType.setIntervalMs(100); - - // :TODO value come from property file - // pollingType.setValue("http://localhost:8080/QueryProcessor/getResult"); - ResultStatusType resultStatusType = new ResultStatusType(); - resultStatusType.setStatus(statusType); - resultStatusType.setPollingUrl(pollingType); - - InfoType infoType = new InfoType(); - // :TODO value come from property file - // infoType.setUrl("http://localhost:8080/QueryProcessor/getStatus"); - infoType.setValue("Log information"); - - ResponseHeaderType responseHeader = new ResponseHeaderType(); - responseHeader.setResultStatus(resultStatusType); - responseHeader.setInfo(infoType); - - ResponseMessageType responseMessageType = new ResponseMessageType(); - responseMessageType.setMessageHeader(messageHeader); - responseMessageType.setResponseHeader(responseHeader); - responseMessageType.setMessageBody(bodyType); - - edu.harvard.i2b2.fr.datavo.i2b2message.ObjectFactory of = new edu.harvard.i2b2.fr.datavo.i2b2message.ObjectFactory(); - StringWriter strWriter = new StringWriter(); - util.marshaller(of.createResponse(responseMessageType), strWriter);//, -// splCharFilterFlag); - - - - - return strWriter.toString(); - } - - /** - * Function to build response message type using given bodytype and request - * xml - * - * @param requestXml - * @param bodyType - * @return i2b2 response message xml - * @throws JAXBUtilException - */ - public static String buildResponseMessage(String requestXml, - StatusType statusType, BodyType bodyType) throws JAXBUtilException { - return buildResponseMessage(requestXml, statusType, bodyType, false); - } - - /** - * Function to unmarshall i2b2 request message type - * - * @param requestXml - * @return RequestMessageType - * @throws JAXBUtilException - */ - private static RequestMessageType getI2B2RequestMessageType( - String requestXml) throws JAXBUtilException { - JAXBUtil jaxbUtil = FRJAXBUtil.getJAXBUtil(); - JAXBElement jaxbElement = jaxbUtil.unMashallFromString(requestXml); - RequestMessageType requestMessageType = (RequestMessageType) jaxbElement - .getValue(); - - return requestMessageType; - } - - /** - * Function marshall i2b2 response message type - * - * @param responseMessageType - * @return - */ - public static String getResponseString( - ResponseMessageType responseMessageType) { - StringWriter strWriter = new StringWriter(); - - try { - edu.harvard.i2b2.fr.datavo.i2b2message.ObjectFactory of = new edu.harvard.i2b2.fr.datavo.i2b2message.ObjectFactory(); - JAXBUtil jaxbUtil = FRJAXBUtil.getJAXBUtil(); - jaxbUtil.marshaller(of.createResponse(responseMessageType), - strWriter); - } catch (JAXBUtilException e) { - log.error("Error while generating response message" - + e.getMessage()); - } - - return strWriter.toString(); - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.fr.datavo; + +import java.io.StringWriter; +import java.math.BigDecimal; + +import jakarta.xml.bind.JAXBElement; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.fr.datavo.i2b2message.ApplicationType; +import edu.harvard.i2b2.fr.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.fr.datavo.i2b2message.FacilityType; +import edu.harvard.i2b2.fr.datavo.i2b2message.InfoType; +import edu.harvard.i2b2.fr.datavo.i2b2message.MessageControlIdType; +import edu.harvard.i2b2.fr.datavo.i2b2message.MessageHeaderType; +import edu.harvard.i2b2.fr.datavo.i2b2message.PollingUrlType; +import edu.harvard.i2b2.fr.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.fr.datavo.i2b2message.ResponseHeaderType; +import edu.harvard.i2b2.fr.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.fr.datavo.i2b2message.ResultStatusType; +import edu.harvard.i2b2.fr.datavo.i2b2message.StatusType; + + +public class I2B2MessageResponseFactory { + + /** log * */ + protected final static Log log = LogFactory + .getLog(I2B2MessageResponseFactory.class); + + /** + * Function to build response message type using given bodytype and request + * xml + * + * @param requestXml + * @param bodyType + * @return i2b2 response message xml + * @throws JAXBUtilException + */ + public static String buildResponseMessage(String requestXml, + StatusType statusType, BodyType bodyType, boolean splCharFilterFlag) + throws JAXBUtilException { + JAXBUtil util = FRJAXBUtil.getJAXBUtil(); + + MessageHeaderType messageHeader = new MessageHeaderType(); + ApplicationType appType = new ApplicationType(); + appType.setApplicationName("FRC Cell"); + appType.setApplicationVersion("1.7"); + + + if (requestXml != null) { + RequestMessageType requestMsgType = getI2B2RequestMessageType(requestXml); + MessageHeaderType clientMessageHeader = requestMsgType.getMessageHeader(); + // reverse sending and receiving app + if (clientMessageHeader != null) { + ApplicationType sendingApp = clientMessageHeader + .getSendingApplication(); + messageHeader.setSendingApplication(appType); + messageHeader.setReceivingApplication(sendingApp); + messageHeader.setProjectId(clientMessageHeader.getProjectId()); + } + } else { + messageHeader = new MessageHeaderType(); + messageHeader.setSendingApplication(appType); + } + + messageHeader.setI2B2VersionCompatible(new BigDecimal("1.1")); + messageHeader.setHl7VersionCompatible(new BigDecimal("2.4")); + + MessageControlIdType messageControlIdType = new MessageControlIdType(); + messageControlIdType.setInstanceNum(1); + messageHeader.setMessageControlId(messageControlIdType); + + FacilityType facility = new FacilityType(); + facility.setFacilityName("i2b2 Hive"); + messageHeader.setSendingFacility(facility); + messageHeader.setReceivingFacility(facility); + + // :TODO statusType.setValue(sessionId); + PollingUrlType pollingType = new PollingUrlType(); + pollingType.setIntervalMs(100); + + // :TODO value come from property file + // pollingType.setValue("http://localhost:8080/QueryProcessor/getResult"); + ResultStatusType resultStatusType = new ResultStatusType(); + resultStatusType.setStatus(statusType); + resultStatusType.setPollingUrl(pollingType); + + InfoType infoType = new InfoType(); + // :TODO value come from property file + // infoType.setUrl("http://localhost:8080/QueryProcessor/getStatus"); + infoType.setValue("Log information"); + + ResponseHeaderType responseHeader = new ResponseHeaderType(); + responseHeader.setResultStatus(resultStatusType); + responseHeader.setInfo(infoType); + + ResponseMessageType responseMessageType = new ResponseMessageType(); + responseMessageType.setMessageHeader(messageHeader); + responseMessageType.setResponseHeader(responseHeader); + responseMessageType.setMessageBody(bodyType); + + edu.harvard.i2b2.fr.datavo.i2b2message.ObjectFactory of = new edu.harvard.i2b2.fr.datavo.i2b2message.ObjectFactory(); + StringWriter strWriter = new StringWriter(); + util.marshaller(of.createResponse(responseMessageType), strWriter);//, +// splCharFilterFlag); + + + + + return strWriter.toString(); + } + + /** + * Function to build response message type using given bodytype and request + * xml + * + * @param requestXml + * @param bodyType + * @return i2b2 response message xml + * @throws JAXBUtilException + */ + public static String buildResponseMessage(String requestXml, + StatusType statusType, BodyType bodyType) throws JAXBUtilException { + return buildResponseMessage(requestXml, statusType, bodyType, false); + } + + /** + * Function to unmarshall i2b2 request message type + * + * @param requestXml + * @return RequestMessageType + * @throws JAXBUtilException + */ + private static RequestMessageType getI2B2RequestMessageType( + String requestXml) throws JAXBUtilException { + JAXBUtil jaxbUtil = FRJAXBUtil.getJAXBUtil(); + JAXBElement jaxbElement = jaxbUtil.unMashallFromString(requestXml); + RequestMessageType requestMessageType = (RequestMessageType) jaxbElement + .getValue(); + + return requestMessageType; + } + + /** + * Function marshall i2b2 response message type + * + * @param responseMessageType + * @return + */ + public static String getResponseString( + ResponseMessageType responseMessageType) { + StringWriter strWriter = new StringWriter(); + + try { + edu.harvard.i2b2.fr.datavo.i2b2message.ObjectFactory of = new edu.harvard.i2b2.fr.datavo.i2b2message.ObjectFactory(); + JAXBUtil jaxbUtil = FRJAXBUtil.getJAXBUtil(); + jaxbUtil.marshaller(of.createResponse(responseMessageType), + strWriter); + } catch (JAXBUtilException e) { + log.error("Error while generating response message" + + e.getMessage()); + } + + return strWriter.toString(); + } + +} diff --git a/edu.harvard.i2b2.fr/src/server/edu/harvard/i2b2/fr/delegate/GetFileListRequestHandler.java b/edu.harvard.i2b2.fr/src/main/java/edu/harvard/i2b2/fr/delegate/GetFileListRequestHandler.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.fr/src/server/edu/harvard/i2b2/fr/delegate/GetFileListRequestHandler.java rename to edu.harvard.i2b2.fr/src/main/java/edu/harvard/i2b2/fr/delegate/GetFileListRequestHandler.java diff --git a/edu.harvard.i2b2.fr/src/server/edu/harvard/i2b2/fr/delegate/LoaderQueryRequestDelegate.java b/edu.harvard.i2b2.fr/src/main/java/edu/harvard/i2b2/fr/delegate/LoaderQueryRequestDelegate.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.fr/src/server/edu/harvard/i2b2/fr/delegate/LoaderQueryRequestDelegate.java rename to edu.harvard.i2b2.fr/src/main/java/edu/harvard/i2b2/fr/delegate/LoaderQueryRequestDelegate.java index 7844442d..1d8a9f29 --- a/edu.harvard.i2b2.fr/src/server/edu/harvard/i2b2/fr/delegate/LoaderQueryRequestDelegate.java +++ b/edu.harvard.i2b2.fr/src/main/java/edu/harvard/i2b2/fr/delegate/LoaderQueryRequestDelegate.java @@ -1,261 +1,261 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.fr.delegate; - -import java.util.ArrayList; -import java.util.Iterator; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.exception.StackTraceUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; - -import edu.harvard.i2b2.fr.datavo.FRJAXBUtil; -import edu.harvard.i2b2.fr.datavo.I2B2MessageResponseFactory; -import edu.harvard.i2b2.fr.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.fr.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.fr.datavo.i2b2message.SecurityType; -import edu.harvard.i2b2.fr.datavo.i2b2message.StatusType; -import edu.harvard.i2b2.fr.datavo.pm.ConfigureType; -import edu.harvard.i2b2.fr.datavo.pm.ParamType; -import edu.harvard.i2b2.fr.datavo.pm.ProjectType; -import edu.harvard.i2b2.fr.delegate.RequestHandlerDelegate; -import edu.harvard.i2b2.fr.delegate.pm.PMServiceDriver; - - -import org.apache.axis2.AxisFault; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import jakarta.xml.bind.JAXBElement; - - -/** - * PDO query request delegate class - * $Id: LoaderQueryRequestDelegate.java,v 1.7 2008/10/21 17:56:30 mem61 Exp $ - * @author rkuttan - */ -public class LoaderQueryRequestDelegate extends RequestHandlerDelegate { - /** log **/ - protected final Log log = LogFactory.getLog(getClass()); - //ConfigureType pmResponseUserInfo = null; - - @Override - public String handleRequest(String requestXml,RequestHandler requestHandler) throws I2B2Exception { - String response = null; - JAXBUtil jaxbUtil = FRJAXBUtil.getJAXBUtil(); - - try { - log.debug("LoaderQueryRequestDelegate - RequestXML: " + requestXml); - - JAXBElement jaxbElement = jaxbUtil.unMashallFromString(requestXml); - RequestMessageType requestMessageType = (RequestMessageType) jaxbElement.getValue(); - BodyType bodyType = requestMessageType.getMessageBody(); - - if (bodyType == null) { - log.error("null value in body type"); - throw new I2B2Exception("null value in body type"); - } - - log.debug("Calling PM Cell to vaidate user"); - //Call PM cell to validate user - StatusType procStatus = null; - ProjectType projectType = null; - ConfigureType pmResponseUserInfo = null; - try { - SecurityType securityType = null; - if (requestMessageType.getMessageHeader() != null ){ - if (requestMessageType.getMessageHeader().getSecurity() != null) { - securityType = requestMessageType.getMessageHeader().getSecurity(); - } - } - if (securityType == null) { - procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus.setValue("Request message missing user/password"); - response = I2B2MessageResponseFactory.buildResponseMessage(requestXml, procStatus, bodyType); - return response; - } - - pmResponseUserInfo = PMServiceDriver.checkValidUser(securityType); - //projectType = pmResponseUserInfo.getUser().getProject().get(0); - - Iterator it = pmResponseUserInfo.getUser().getProject().iterator(); - - - - while (it.hasNext()) - { - projectType = (ProjectType)it.next(); - if (projectType.getId().equals(requestMessageType.getMessageHeader().getProjectId())) { - // log.info(header.getProjectId()); - // log.info(projectType.getId()); - break; - } - - } - - if (projectType == null) { - procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus.setValue("Invalid user/password for the given domain"); - response = I2B2MessageResponseFactory.buildResponseMessage(requestXml, procStatus, bodyType); - return response; - } - - - log.debug("project name from PM " + projectType.getName()); - log.debug("project id from PM " + projectType.getId()); - log.debug("Project role from PM " + projectType.getRole().get(0)); - - - } catch (AxisFault e) { - log.error("AxisFault exception",e); - procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus.setValue("Could not connect to server"); - response = I2B2MessageResponseFactory.buildResponseMessage(requestXml, procStatus, bodyType); - return response; - } catch (I2B2Exception e) { - log.error("I2B2Exception exception",e); - procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus.setValue("Message error connecting Project Management cell"); - response = I2B2MessageResponseFactory.buildResponseMessage(requestXml, procStatus, bodyType); - return response; - } catch (JAXBUtilException e) { - log.error("JAXBUtil exception",e); - procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus.setValue("Message error from Project Management cell"); - response = I2B2MessageResponseFactory.buildResponseMessage(requestXml, procStatus, bodyType); - return response; - } - - - JAXBUnWrapHelper unWrapHelper = new JAXBUnWrapHelper(); - - BodyType responseBodyType = null; - if (requestHandler instanceof SendfileRequestHandler) { - String irodsStorageResource = null; - - // check if user have right permission to access this request - log.debug("Number of roles:" + projectType.getRole().size()); - - if (projectType != null && projectType.getRole().size() > 0) { - //for (String a : projectType.getRole()) - // log.debug("Roles:" + a); - - if (isRoleValid(projectType) == false) { - //!projectType.getRole().contains("MANAGER") && !projectType.getRole().contains("EDITOR")) { - // Not authorized - procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus - .setValue("Authorization failure, need MANAGER or EDITOR role"); - response = I2B2MessageResponseFactory - .buildResponseMessage(requestXml, procStatus, - bodyType); - return response; - } - } else { - // Not authorized - procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus - .setValue("Authorization failure, need MANAGER or EDITOR role"); - response = I2B2MessageResponseFactory.buildResponseMessage( - requestXml, procStatus, bodyType); - return response; - } - - for (ParamType paramType : projectType.getParam()) { - - if (paramType.getName().equalsIgnoreCase("SRBDefaultStorageResource")) { - irodsStorageResource = paramType.getValue(); - log.debug("param value for SRBDefaultStorageResource" + paramType.getValue()); - } - } - ((SendfileRequestHandler)requestHandler).setPmResponseUserInfo(pmResponseUserInfo); - } - - if (requestHandler instanceof RecvfileRequestHandler) { - String irodsStorageResource = null; - for (ParamType paramType : projectType.getParam()) { - - if (paramType.getName().equalsIgnoreCase("SRBDefaultStorageResource")) { - irodsStorageResource = paramType.getValue(); - log.debug("param value for SRBDefaultStorageResource" + paramType.getValue()); - } - } - ((RecvfileRequestHandler)requestHandler).setPmResponseUserInfo(pmResponseUserInfo); - } - - responseBodyType = requestHandler.execute(); - - - procStatus = new StatusType(); - procStatus.setType("DONE"); - procStatus.setValue("DONE"); - - response = I2B2MessageResponseFactory.buildResponseMessage(requestXml, procStatus, responseBodyType,true); - - } catch (JAXBUtilException e) { - log.error("JAXBUtil exception",e); - StatusType procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus.setValue(requestXml + "\n\n" + StackTraceUtil.getStackTrace(e)); - try { - response = I2B2MessageResponseFactory.buildResponseMessage(null, procStatus, null); - } catch (JAXBUtilException e1) { - e1.printStackTrace(); - } - } catch (I2B2Exception e) { - log.error("I2B2Exception",e); - StatusType procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus.setValue(StackTraceUtil.getStackTrace(e)); - try { - response = I2B2MessageResponseFactory.buildResponseMessage(requestXml, procStatus, null); - } catch (JAXBUtilException e1) { - e1.printStackTrace(); - } - } catch (Throwable e) { - log.error("Throwable",e); - StatusType procStatus = new StatusType(); - procStatus.setType("ERROR"); - procStatus.setValue(StackTraceUtil.getStackTrace(e)); - try { - response = I2B2MessageResponseFactory.buildResponseMessage(requestXml, procStatus, null); - } catch (JAXBUtilException e1) { - e1.printStackTrace(); - } - } - return response; - } - - public boolean isRoleValid(ProjectType projectInfo){ - - ArrayList roles = (ArrayList) projectInfo.getRole(); - for(String param :roles) { - if(param.equalsIgnoreCase("manager")) - return true; - if(param.equalsIgnoreCase("editor")) - return true; - } - return false; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.fr.delegate; + +import java.util.ArrayList; +import java.util.Iterator; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.exception.StackTraceUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; + +import edu.harvard.i2b2.fr.datavo.FRJAXBUtil; +import edu.harvard.i2b2.fr.datavo.I2B2MessageResponseFactory; +import edu.harvard.i2b2.fr.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.fr.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.fr.datavo.i2b2message.SecurityType; +import edu.harvard.i2b2.fr.datavo.i2b2message.StatusType; +import edu.harvard.i2b2.fr.datavo.pm.ConfigureType; +import edu.harvard.i2b2.fr.datavo.pm.ParamType; +import edu.harvard.i2b2.fr.datavo.pm.ProjectType; +import edu.harvard.i2b2.fr.delegate.RequestHandlerDelegate; +import edu.harvard.i2b2.fr.delegate.pm.PMServiceDriver; + + +import org.apache.axis2.AxisFault; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import jakarta.xml.bind.JAXBElement; + + +/** + * PDO query request delegate class + * $Id: LoaderQueryRequestDelegate.java,v 1.7 2008/10/21 17:56:30 mem61 Exp $ + * @author rkuttan + */ +public class LoaderQueryRequestDelegate extends RequestHandlerDelegate { + /** log **/ + protected final Log log = LogFactory.getLog(getClass()); + //ConfigureType pmResponseUserInfo = null; + + @Override + public String handleRequest(String requestXml,RequestHandler requestHandler) throws I2B2Exception { + String response = null; + JAXBUtil jaxbUtil = FRJAXBUtil.getJAXBUtil(); + + try { + log.debug("LoaderQueryRequestDelegate - RequestXML: " + requestXml); + + JAXBElement jaxbElement = jaxbUtil.unMashallFromString(requestXml); + RequestMessageType requestMessageType = (RequestMessageType) jaxbElement.getValue(); + BodyType bodyType = requestMessageType.getMessageBody(); + + if (bodyType == null) { + log.error("null value in body type"); + throw new I2B2Exception("null value in body type"); + } + + log.debug("Calling PM Cell to vaidate user"); + //Call PM cell to validate user + StatusType procStatus = null; + ProjectType projectType = null; + ConfigureType pmResponseUserInfo = null; + try { + SecurityType securityType = null; + if (requestMessageType.getMessageHeader() != null ){ + if (requestMessageType.getMessageHeader().getSecurity() != null) { + securityType = requestMessageType.getMessageHeader().getSecurity(); + } + } + if (securityType == null) { + procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus.setValue("Request message missing user/password"); + response = I2B2MessageResponseFactory.buildResponseMessage(requestXml, procStatus, bodyType); + return response; + } + + pmResponseUserInfo = PMServiceDriver.checkValidUser(securityType); + //projectType = pmResponseUserInfo.getUser().getProject().get(0); + + Iterator it = pmResponseUserInfo.getUser().getProject().iterator(); + + + + while (it.hasNext()) + { + projectType = (ProjectType)it.next(); + if (projectType.getId().equals(requestMessageType.getMessageHeader().getProjectId())) { + // log.info(header.getProjectId()); + // log.info(projectType.getId()); + break; + } + + } + + if (projectType == null) { + procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus.setValue("Invalid user/password for the given domain"); + response = I2B2MessageResponseFactory.buildResponseMessage(requestXml, procStatus, bodyType); + return response; + } + + + log.debug("project name from PM " + projectType.getName()); + log.debug("project id from PM " + projectType.getId()); + log.debug("Project role from PM " + projectType.getRole().get(0)); + + + } catch (AxisFault e) { + log.error("AxisFault exception",e); + procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus.setValue("Could not connect to server"); + response = I2B2MessageResponseFactory.buildResponseMessage(requestXml, procStatus, bodyType); + return response; + } catch (I2B2Exception e) { + log.error("I2B2Exception exception",e); + procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus.setValue("Message error connecting Project Management cell"); + response = I2B2MessageResponseFactory.buildResponseMessage(requestXml, procStatus, bodyType); + return response; + } catch (JAXBUtilException e) { + log.error("JAXBUtil exception",e); + procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus.setValue("Message error from Project Management cell"); + response = I2B2MessageResponseFactory.buildResponseMessage(requestXml, procStatus, bodyType); + return response; + } + + + JAXBUnWrapHelper unWrapHelper = new JAXBUnWrapHelper(); + + BodyType responseBodyType = null; + if (requestHandler instanceof SendfileRequestHandler) { + String irodsStorageResource = null; + + // check if user have right permission to access this request + log.debug("Number of roles:" + projectType.getRole().size()); + + if (projectType != null && projectType.getRole().size() > 0) { + //for (String a : projectType.getRole()) + // log.debug("Roles:" + a); + + if (isRoleValid(projectType) == false) { + //!projectType.getRole().contains("MANAGER") && !projectType.getRole().contains("EDITOR")) { + // Not authorized + procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus + .setValue("Authorization failure, need MANAGER or EDITOR role"); + response = I2B2MessageResponseFactory + .buildResponseMessage(requestXml, procStatus, + bodyType); + return response; + } + } else { + // Not authorized + procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus + .setValue("Authorization failure, need MANAGER or EDITOR role"); + response = I2B2MessageResponseFactory.buildResponseMessage( + requestXml, procStatus, bodyType); + return response; + } + + for (ParamType paramType : projectType.getParam()) { + + if (paramType.getName().equalsIgnoreCase("SRBDefaultStorageResource")) { + irodsStorageResource = paramType.getValue(); + log.debug("param value for SRBDefaultStorageResource" + paramType.getValue()); + } + } + ((SendfileRequestHandler)requestHandler).setPmResponseUserInfo(pmResponseUserInfo); + } + + if (requestHandler instanceof RecvfileRequestHandler) { + String irodsStorageResource = null; + for (ParamType paramType : projectType.getParam()) { + + if (paramType.getName().equalsIgnoreCase("SRBDefaultStorageResource")) { + irodsStorageResource = paramType.getValue(); + log.debug("param value for SRBDefaultStorageResource" + paramType.getValue()); + } + } + ((RecvfileRequestHandler)requestHandler).setPmResponseUserInfo(pmResponseUserInfo); + } + + responseBodyType = requestHandler.execute(); + + + procStatus = new StatusType(); + procStatus.setType("DONE"); + procStatus.setValue("DONE"); + + response = I2B2MessageResponseFactory.buildResponseMessage(requestXml, procStatus, responseBodyType,true); + + } catch (JAXBUtilException e) { + log.error("JAXBUtil exception",e); + StatusType procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus.setValue(requestXml + "\n\n" + StackTraceUtil.getStackTrace(e)); + try { + response = I2B2MessageResponseFactory.buildResponseMessage(null, procStatus, null); + } catch (JAXBUtilException e1) { + e1.printStackTrace(); + } + } catch (I2B2Exception e) { + log.error("I2B2Exception",e); + StatusType procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus.setValue(StackTraceUtil.getStackTrace(e)); + try { + response = I2B2MessageResponseFactory.buildResponseMessage(requestXml, procStatus, null); + } catch (JAXBUtilException e1) { + e1.printStackTrace(); + } + } catch (Throwable e) { + log.error("Throwable",e); + StatusType procStatus = new StatusType(); + procStatus.setType("ERROR"); + procStatus.setValue(StackTraceUtil.getStackTrace(e)); + try { + response = I2B2MessageResponseFactory.buildResponseMessage(requestXml, procStatus, null); + } catch (JAXBUtilException e1) { + e1.printStackTrace(); + } + } + return response; + } + + public boolean isRoleValid(ProjectType projectInfo){ + + ArrayList roles = (ArrayList) projectInfo.getRole(); + for(String param :roles) { + if(param.equalsIgnoreCase("manager")) + return true; + if(param.equalsIgnoreCase("editor")) + return true; + } + return false; + } +} diff --git a/edu.harvard.i2b2.fr/src/server/edu/harvard/i2b2/fr/delegate/RecvfileRequestHandler.java b/edu.harvard.i2b2.fr/src/main/java/edu/harvard/i2b2/fr/delegate/RecvfileRequestHandler.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.fr/src/server/edu/harvard/i2b2/fr/delegate/RecvfileRequestHandler.java rename to edu.harvard.i2b2.fr/src/main/java/edu/harvard/i2b2/fr/delegate/RecvfileRequestHandler.java diff --git a/edu.harvard.i2b2.fr/src/server/edu/harvard/i2b2/fr/delegate/RequestHandler.java b/edu.harvard.i2b2.fr/src/main/java/edu/harvard/i2b2/fr/delegate/RequestHandler.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.fr/src/server/edu/harvard/i2b2/fr/delegate/RequestHandler.java rename to edu.harvard.i2b2.fr/src/main/java/edu/harvard/i2b2/fr/delegate/RequestHandler.java index 3cf20c77..ac856ffb --- a/edu.harvard.i2b2.fr/src/server/edu/harvard/i2b2/fr/delegate/RequestHandler.java +++ b/edu.harvard.i2b2.fr/src/main/java/edu/harvard/i2b2/fr/delegate/RequestHandler.java @@ -1,206 +1,206 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.fr.delegate; - -import java.io.StringWriter; - -import jakarta.xml.bind.JAXBElement; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.fr.datavo.FRJAXBUtil; -import edu.harvard.i2b2.fr.datavo.i2b2message.ApplicationType; -import edu.harvard.i2b2.fr.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.fr.datavo.i2b2message.InfoType; -import edu.harvard.i2b2.fr.datavo.i2b2message.MessageControlIdType; -import edu.harvard.i2b2.fr.datavo.i2b2message.MessageHeaderType; -import edu.harvard.i2b2.fr.datavo.i2b2message.PollingUrlType; -import edu.harvard.i2b2.fr.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.fr.datavo.i2b2message.ResponseHeaderType; -import edu.harvard.i2b2.fr.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.fr.datavo.i2b2message.ResultStatusType; -import edu.harvard.i2b2.fr.datavo.i2b2message.StatusType; - - -/** - * Top level class to process the request. There will be - * seperate requesthandler class for each request type. - * The main processing of for the request will be done inside - * execute function - * $Id: RequestHandler.java,v 1.1 2008/05/29 18:01:11 mem61 Exp $ - * @author rkuttan - */ -public abstract class RequestHandler { - /** log **/ - protected final Log log = LogFactory.getLog(getClass()); - - /** - * Function to perform operation on the given - * request - * @return response xml message - * @throws Exception - */ - public abstract BodyType execute() throws I2B2Exception, Exception; - - /** - * Class to fetch specific request message - * from i2b2 message xml - * @param requestXml - * @param classname - * @return object which is of type classname - * @throws JAXBUtilException - */ - protected Object getRequestType(String requestXml, Class classname) - throws JAXBUtilException { - log.debug("RequestHandler - RequestXML: " + requestXml); - - Object returnObject = null; - log.debug("MM1"); - - JAXBUtil jaxbUtil = FRJAXBUtil.getJAXBUtil(); - JAXBElement jaxbElement = jaxbUtil.unMashallFromString(requestXml); - RequestMessageType requestMessageType = (RequestMessageType) jaxbElement.getValue(); - BodyType bodyType = requestMessageType.getMessageBody(); - JAXBUnWrapHelper unWrapHelper = new JAXBUnWrapHelper(); - log.debug("MM6"); - //get request header type - returnObject = unWrapHelper.getObjectByClass(bodyType.getAny(), - classname); - log.debug("MM7"); - return returnObject; - } - - protected MessageHeaderType getMessageHeaderType(String requestXml) - throws JAXBUtilException { - JAXBUtil jaxbUtil = FRJAXBUtil.getJAXBUtil(); - JAXBElement jaxbElement = jaxbUtil.unMashallFromString(requestXml); - RequestMessageType requestMessageType = (RequestMessageType) jaxbElement.getValue(); - - return requestMessageType.getMessageHeader(); - } - - /** - * Function to build response message type - * using given bodytype and request xml - * @param requestXml - * @param bodyType - * @return i2b2 response message xml - * @throws JAXBUtilException - */ - protected String buildResponseMessage(String requestXml, BodyType bodyType) - throws JAXBUtilException { - JAXBUtil util = FRJAXBUtil.getJAXBUtil(); - RequestMessageType requestMsgType = getI2B2RequestMessageType(requestXml); - MessageHeaderType messageHeader = requestMsgType.getMessageHeader(); - - //reverse sending and receiving app - ApplicationType sendingApp = messageHeader.getSendingApplication(); - ApplicationType receiveApp = messageHeader.getReceivingApplication(); - messageHeader.setSendingApplication(receiveApp); - messageHeader.setReceivingApplication(sendingApp); - - //set instance num - MessageControlIdType messageControlIdType = messageHeader.getMessageControlId(); - - if (messageControlIdType != null) { - messageControlIdType.setInstanceNum(1); - } - - StatusType statusType = new StatusType(); - statusType.setType("DONE"); - - //:TODO statusType.setValue(sessionId); - PollingUrlType pollingType = new PollingUrlType(); - pollingType.setIntervalMs(100); - - //:TODO value come from property file - - ResultStatusType resultStatusType = new ResultStatusType(); - resultStatusType.setStatus(statusType); - resultStatusType.setPollingUrl(pollingType); - - InfoType infoType = new InfoType(); - //:TODO value come from property file - - infoType.setValue("Log information"); - - ResponseHeaderType responseHeader = new ResponseHeaderType(); - responseHeader.setResultStatus(resultStatusType); - responseHeader.setInfo(infoType); - - ResponseMessageType responseMessageType = new ResponseMessageType(); - responseMessageType.setMessageHeader(messageHeader); - responseMessageType.setResponseHeader(responseHeader); - responseMessageType.setMessageBody(bodyType); - - edu.harvard.i2b2.fr.datavo.i2b2message.ObjectFactory of = new edu.harvard.i2b2.fr.datavo.i2b2message.ObjectFactory(); - StringWriter strWriter = new StringWriter(); - util.marshaller(of.createResponse(responseMessageType), strWriter); - - return strWriter.toString(); - } - - /** - * Function to unmarshall i2b2 request message type - * @param requestXml - * @return RequestMessageType - * @throws JAXBUtilException - */ - protected RequestMessageType getI2B2RequestMessageType(String requestXml) - throws JAXBUtilException { - JAXBUtil jaxbUtil = FRJAXBUtil.getJAXBUtil(); - JAXBElement jaxbElement = jaxbUtil.unMashallFromString(requestXml); - RequestMessageType requestMessageType = (RequestMessageType) jaxbElement.getValue(); - - return requestMessageType; - } - - /** - * Function marshall i2b2 response message type - * @param responseMessageType - * @return - */ - protected String getResponseString(ResponseMessageType responseMessageType) { - StringWriter strWriter = new StringWriter(); - - try { - edu.harvard.i2b2.fr.datavo.i2b2message.ObjectFactory of = new edu.harvard.i2b2.fr.datavo.i2b2message.ObjectFactory(); - JAXBUtil jaxbUtil = FRJAXBUtil.getJAXBUtil(); - jaxbUtil.marshaller(of.createResponse(responseMessageType), - strWriter); - } catch (JAXBUtilException e) { - log.error("Error while generating response message" + - e.getMessage()); - } - - return strWriter.toString(); - } - - protected edu.harvard.i2b2.fr.datavo.fr.query.StatusType buildCRCStausType(String statusType,String message) { - edu.harvard.i2b2.fr.datavo.fr.query.StatusType st = new edu.harvard.i2b2.fr.datavo.fr.query.StatusType(); - edu.harvard.i2b2.fr.datavo.fr.query.StatusType.Condition condition = new edu.harvard.i2b2.fr.datavo.fr.query.StatusType.Condition(); - condition.setType(statusType); - condition.setValue(message); - st.getCondition().add(condition); - return st; - } - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.fr.delegate; + +import java.io.StringWriter; + +import jakarta.xml.bind.JAXBElement; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.fr.datavo.FRJAXBUtil; +import edu.harvard.i2b2.fr.datavo.i2b2message.ApplicationType; +import edu.harvard.i2b2.fr.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.fr.datavo.i2b2message.InfoType; +import edu.harvard.i2b2.fr.datavo.i2b2message.MessageControlIdType; +import edu.harvard.i2b2.fr.datavo.i2b2message.MessageHeaderType; +import edu.harvard.i2b2.fr.datavo.i2b2message.PollingUrlType; +import edu.harvard.i2b2.fr.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.fr.datavo.i2b2message.ResponseHeaderType; +import edu.harvard.i2b2.fr.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.fr.datavo.i2b2message.ResultStatusType; +import edu.harvard.i2b2.fr.datavo.i2b2message.StatusType; + + +/** + * Top level class to process the request. There will be + * seperate requesthandler class for each request type. + * The main processing of for the request will be done inside + * execute function + * $Id: RequestHandler.java,v 1.1 2008/05/29 18:01:11 mem61 Exp $ + * @author rkuttan + */ +public abstract class RequestHandler { + /** log **/ + protected final Log log = LogFactory.getLog(getClass()); + + /** + * Function to perform operation on the given + * request + * @return response xml message + * @throws Exception + */ + public abstract BodyType execute() throws I2B2Exception, Exception; + + /** + * Class to fetch specific request message + * from i2b2 message xml + * @param requestXml + * @param classname + * @return object which is of type classname + * @throws JAXBUtilException + */ + protected Object getRequestType(String requestXml, Class classname) + throws JAXBUtilException { + log.debug("RequestHandler - RequestXML: " + requestXml); + + Object returnObject = null; + log.debug("MM1"); + + JAXBUtil jaxbUtil = FRJAXBUtil.getJAXBUtil(); + JAXBElement jaxbElement = jaxbUtil.unMashallFromString(requestXml); + RequestMessageType requestMessageType = (RequestMessageType) jaxbElement.getValue(); + BodyType bodyType = requestMessageType.getMessageBody(); + JAXBUnWrapHelper unWrapHelper = new JAXBUnWrapHelper(); + log.debug("MM6"); + //get request header type + returnObject = unWrapHelper.getObjectByClass(bodyType.getAny(), + classname); + log.debug("MM7"); + return returnObject; + } + + protected MessageHeaderType getMessageHeaderType(String requestXml) + throws JAXBUtilException { + JAXBUtil jaxbUtil = FRJAXBUtil.getJAXBUtil(); + JAXBElement jaxbElement = jaxbUtil.unMashallFromString(requestXml); + RequestMessageType requestMessageType = (RequestMessageType) jaxbElement.getValue(); + + return requestMessageType.getMessageHeader(); + } + + /** + * Function to build response message type + * using given bodytype and request xml + * @param requestXml + * @param bodyType + * @return i2b2 response message xml + * @throws JAXBUtilException + */ + protected String buildResponseMessage(String requestXml, BodyType bodyType) + throws JAXBUtilException { + JAXBUtil util = FRJAXBUtil.getJAXBUtil(); + RequestMessageType requestMsgType = getI2B2RequestMessageType(requestXml); + MessageHeaderType messageHeader = requestMsgType.getMessageHeader(); + + //reverse sending and receiving app + ApplicationType sendingApp = messageHeader.getSendingApplication(); + ApplicationType receiveApp = messageHeader.getReceivingApplication(); + messageHeader.setSendingApplication(receiveApp); + messageHeader.setReceivingApplication(sendingApp); + + //set instance num + MessageControlIdType messageControlIdType = messageHeader.getMessageControlId(); + + if (messageControlIdType != null) { + messageControlIdType.setInstanceNum(1); + } + + StatusType statusType = new StatusType(); + statusType.setType("DONE"); + + //:TODO statusType.setValue(sessionId); + PollingUrlType pollingType = new PollingUrlType(); + pollingType.setIntervalMs(100); + + //:TODO value come from property file + + ResultStatusType resultStatusType = new ResultStatusType(); + resultStatusType.setStatus(statusType); + resultStatusType.setPollingUrl(pollingType); + + InfoType infoType = new InfoType(); + //:TODO value come from property file + + infoType.setValue("Log information"); + + ResponseHeaderType responseHeader = new ResponseHeaderType(); + responseHeader.setResultStatus(resultStatusType); + responseHeader.setInfo(infoType); + + ResponseMessageType responseMessageType = new ResponseMessageType(); + responseMessageType.setMessageHeader(messageHeader); + responseMessageType.setResponseHeader(responseHeader); + responseMessageType.setMessageBody(bodyType); + + edu.harvard.i2b2.fr.datavo.i2b2message.ObjectFactory of = new edu.harvard.i2b2.fr.datavo.i2b2message.ObjectFactory(); + StringWriter strWriter = new StringWriter(); + util.marshaller(of.createResponse(responseMessageType), strWriter); + + return strWriter.toString(); + } + + /** + * Function to unmarshall i2b2 request message type + * @param requestXml + * @return RequestMessageType + * @throws JAXBUtilException + */ + protected RequestMessageType getI2B2RequestMessageType(String requestXml) + throws JAXBUtilException { + JAXBUtil jaxbUtil = FRJAXBUtil.getJAXBUtil(); + JAXBElement jaxbElement = jaxbUtil.unMashallFromString(requestXml); + RequestMessageType requestMessageType = (RequestMessageType) jaxbElement.getValue(); + + return requestMessageType; + } + + /** + * Function marshall i2b2 response message type + * @param responseMessageType + * @return + */ + protected String getResponseString(ResponseMessageType responseMessageType) { + StringWriter strWriter = new StringWriter(); + + try { + edu.harvard.i2b2.fr.datavo.i2b2message.ObjectFactory of = new edu.harvard.i2b2.fr.datavo.i2b2message.ObjectFactory(); + JAXBUtil jaxbUtil = FRJAXBUtil.getJAXBUtil(); + jaxbUtil.marshaller(of.createResponse(responseMessageType), + strWriter); + } catch (JAXBUtilException e) { + log.error("Error while generating response message" + + e.getMessage()); + } + + return strWriter.toString(); + } + + protected edu.harvard.i2b2.fr.datavo.fr.query.StatusType buildCRCStausType(String statusType,String message) { + edu.harvard.i2b2.fr.datavo.fr.query.StatusType st = new edu.harvard.i2b2.fr.datavo.fr.query.StatusType(); + edu.harvard.i2b2.fr.datavo.fr.query.StatusType.Condition condition = new edu.harvard.i2b2.fr.datavo.fr.query.StatusType.Condition(); + condition.setType(statusType); + condition.setValue(message); + st.getCondition().add(condition); + return st; + } + + +} diff --git a/edu.harvard.i2b2.fr/src/server/edu/harvard/i2b2/fr/delegate/RequestHandlerDelegate.java b/edu.harvard.i2b2.fr/src/main/java/edu/harvard/i2b2/fr/delegate/RequestHandlerDelegate.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.fr/src/server/edu/harvard/i2b2/fr/delegate/RequestHandlerDelegate.java rename to edu.harvard.i2b2.fr/src/main/java/edu/harvard/i2b2/fr/delegate/RequestHandlerDelegate.java index 972ccde2..e9dfcb72 --- a/edu.harvard.i2b2.fr/src/server/edu/harvard/i2b2/fr/delegate/RequestHandlerDelegate.java +++ b/edu.harvard.i2b2.fr/src/main/java/edu/harvard/i2b2/fr/delegate/RequestHandlerDelegate.java @@ -1,96 +1,96 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.fr.delegate; - -import java.io.StringWriter; - -import jakarta.xml.bind.JAXBElement; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.fr.datavo.FRJAXBUtil; -import edu.harvard.i2b2.fr.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.fr.datavo.i2b2message.ResponseMessageType; - - -/** - * Class to delegate i2b2 requests to appropriate - * {@link RequestHandler} - * Class unwraps i2b2 request message and based on the - * request type, the request will be delegated to appropriate - * request handler by calling execute function. The return value - * from execute function is just passed back to the client - * $Id: RequestHandlerDelegate.java,v 1.1 2008/05/29 18:01:11 mem61 Exp $ - * @author rkuttan - */ -public abstract class RequestHandlerDelegate { - /** log **/ - protected final Log log = LogFactory.getLog(getClass()); - - public static final String ERROR_TYPE = "ERROR"; - public static final String DONE_TYPE = "DONE"; - - /** - * Function to delegate request to appropriate - * request handler class and passes back the - * response message output back to client - * @param requestXml - * @return response message xml - * @throws I2B2Exception - */ - public abstract String handleRequest(String requestXml,RequestHandler requestHandler) throws I2B2Exception; - - - - /** - * Function to unmarshall i2b2 request message type - * @param requestXml - * @return RequestMessageType - * @throws JAXBUtilException - */ - protected RequestMessageType getI2B2RequestMessageType(String requestXml) - throws JAXBUtilException { - JAXBUtil jaxbUtil = FRJAXBUtil.getJAXBUtil(); - JAXBElement jaxbElement = jaxbUtil.unMashallFromString(requestXml); - RequestMessageType requestMessageType = (RequestMessageType) jaxbElement.getValue(); - - return requestMessageType; - } - - /** - * Function marshall i2b2 response message type - * @param responseMessageType - * @return - */ - protected String getResponseString(ResponseMessageType responseMessageType) { - StringWriter strWriter = new StringWriter(); - - try { - edu.harvard.i2b2.fr.datavo.i2b2message.ObjectFactory of = new edu.harvard.i2b2.fr.datavo.i2b2message.ObjectFactory(); - JAXBUtil jaxbUtil = FRJAXBUtil.getJAXBUtil(); - jaxbUtil.marshaller(of.createResponse(responseMessageType), - strWriter); - } catch (JAXBUtilException e) { - log.error("Error while generating response message" + - e.getMessage()); - } - - return strWriter.toString(); - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.fr.delegate; + +import java.io.StringWriter; + +import jakarta.xml.bind.JAXBElement; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.fr.datavo.FRJAXBUtil; +import edu.harvard.i2b2.fr.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.fr.datavo.i2b2message.ResponseMessageType; + + +/** + * Class to delegate i2b2 requests to appropriate + * {@link RequestHandler} + * Class unwraps i2b2 request message and based on the + * request type, the request will be delegated to appropriate + * request handler by calling execute function. The return value + * from execute function is just passed back to the client + * $Id: RequestHandlerDelegate.java,v 1.1 2008/05/29 18:01:11 mem61 Exp $ + * @author rkuttan + */ +public abstract class RequestHandlerDelegate { + /** log **/ + protected final Log log = LogFactory.getLog(getClass()); + + public static final String ERROR_TYPE = "ERROR"; + public static final String DONE_TYPE = "DONE"; + + /** + * Function to delegate request to appropriate + * request handler class and passes back the + * response message output back to client + * @param requestXml + * @return response message xml + * @throws I2B2Exception + */ + public abstract String handleRequest(String requestXml,RequestHandler requestHandler) throws I2B2Exception; + + + + /** + * Function to unmarshall i2b2 request message type + * @param requestXml + * @return RequestMessageType + * @throws JAXBUtilException + */ + protected RequestMessageType getI2B2RequestMessageType(String requestXml) + throws JAXBUtilException { + JAXBUtil jaxbUtil = FRJAXBUtil.getJAXBUtil(); + JAXBElement jaxbElement = jaxbUtil.unMashallFromString(requestXml); + RequestMessageType requestMessageType = (RequestMessageType) jaxbElement.getValue(); + + return requestMessageType; + } + + /** + * Function marshall i2b2 response message type + * @param responseMessageType + * @return + */ + protected String getResponseString(ResponseMessageType responseMessageType) { + StringWriter strWriter = new StringWriter(); + + try { + edu.harvard.i2b2.fr.datavo.i2b2message.ObjectFactory of = new edu.harvard.i2b2.fr.datavo.i2b2message.ObjectFactory(); + JAXBUtil jaxbUtil = FRJAXBUtil.getJAXBUtil(); + jaxbUtil.marshaller(of.createResponse(responseMessageType), + strWriter); + } catch (JAXBUtilException e) { + log.error("Error while generating response message" + + e.getMessage()); + } + + return strWriter.toString(); + } +} diff --git a/edu.harvard.i2b2.fr/src/server/edu/harvard/i2b2/fr/delegate/SendfileRequestHandler.java b/edu.harvard.i2b2.fr/src/main/java/edu/harvard/i2b2/fr/delegate/SendfileRequestHandler.java old mode 100755 new mode 100644 similarity index 99% rename from edu.harvard.i2b2.fr/src/server/edu/harvard/i2b2/fr/delegate/SendfileRequestHandler.java rename to edu.harvard.i2b2.fr/src/main/java/edu/harvard/i2b2/fr/delegate/SendfileRequestHandler.java index a13f24b6..048424c4 --- a/edu.harvard.i2b2.fr/src/server/edu/harvard/i2b2/fr/delegate/SendfileRequestHandler.java +++ b/edu.harvard.i2b2.fr/src/main/java/edu/harvard/i2b2/fr/delegate/SendfileRequestHandler.java @@ -22,7 +22,7 @@ import java.io.StringReader; import java.io.StringWriter; -import javax.activation.DataHandler; +import jakarta.activation.DataHandler; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamReader; diff --git a/edu.harvard.i2b2.fr/src/server/edu/harvard/i2b2/fr/delegate/pm/GetUserConfigurationRequestMessage.java b/edu.harvard.i2b2.fr/src/main/java/edu/harvard/i2b2/fr/delegate/pm/GetUserConfigurationRequestMessage.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.fr/src/server/edu/harvard/i2b2/fr/delegate/pm/GetUserConfigurationRequestMessage.java rename to edu.harvard.i2b2.fr/src/main/java/edu/harvard/i2b2/fr/delegate/pm/GetUserConfigurationRequestMessage.java diff --git a/edu.harvard.i2b2.fr/src/server/edu/harvard/i2b2/fr/delegate/pm/PMResponseMessage.java b/edu.harvard.i2b2.fr/src/main/java/edu/harvard/i2b2/fr/delegate/pm/PMResponseMessage.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.fr/src/server/edu/harvard/i2b2/fr/delegate/pm/PMResponseMessage.java rename to edu.harvard.i2b2.fr/src/main/java/edu/harvard/i2b2/fr/delegate/pm/PMResponseMessage.java index 1627de54..62699010 --- a/edu.harvard.i2b2.fr/src/server/edu/harvard/i2b2/fr/delegate/pm/PMResponseMessage.java +++ b/edu.harvard.i2b2.fr/src/main/java/edu/harvard/i2b2/fr/delegate/pm/PMResponseMessage.java @@ -1,77 +1,77 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.fr.delegate.pm; - -import jakarta.xml.bind.JAXBElement; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.fr.datavo.FRJAXBUtil; -import edu.harvard.i2b2.fr.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.fr.datavo.i2b2message.ResponseHeaderType; -import edu.harvard.i2b2.fr.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.fr.datavo.i2b2message.StatusType; -import edu.harvard.i2b2.fr.datavo.pm.ConfigureType; - -public class PMResponseMessage { - - public static final String THIS_CLASS_NAME = PMResponseMessage.class.getName(); - private Log log = LogFactory.getLog(THIS_CLASS_NAME); - private ResponseMessageType pmRespMessageType = null; - - public PMResponseMessage() {} - - public StatusType processResult(String response) throws JAXBUtilException{ - StatusType status = null; - try { - - JAXBElement jaxbElement = FRJAXBUtil.getJAXBUtil().unMashallFromString(response); - pmRespMessageType = (ResponseMessageType) jaxbElement.getValue(); - - // Get response message status - ResponseHeaderType responseHeader = pmRespMessageType.getResponseHeader(); - status = responseHeader.getResultStatus().getStatus(); - String procStatus = status.getType(); - String procMessage = status.getValue(); - - if(procStatus.equals("ERROR")){ - log.error("Error reported by CRC web Service " + procMessage); - } - else if(procStatus.equals("WARNING")){ - log.debug("Warning reported by CRC web Service" + procMessage); - } - - } catch (JAXBUtilException e) { - log.error(e); - throw e; - } - return status; - } - - - public ConfigureType readUserInfo() throws JAXBUtilException { - ConfigureType pmResponse = null; - - BodyType bodyType = pmRespMessageType.getMessageBody(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - pmResponse = (ConfigureType)helper.getObjectByClass(bodyType.getAny(), ConfigureType.class); - - return pmResponse; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.fr.delegate.pm; + +import jakarta.xml.bind.JAXBElement; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.fr.datavo.FRJAXBUtil; +import edu.harvard.i2b2.fr.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.fr.datavo.i2b2message.ResponseHeaderType; +import edu.harvard.i2b2.fr.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.fr.datavo.i2b2message.StatusType; +import edu.harvard.i2b2.fr.datavo.pm.ConfigureType; + +public class PMResponseMessage { + + public static final String THIS_CLASS_NAME = PMResponseMessage.class.getName(); + private Log log = LogFactory.getLog(THIS_CLASS_NAME); + private ResponseMessageType pmRespMessageType = null; + + public PMResponseMessage() {} + + public StatusType processResult(String response) throws JAXBUtilException{ + StatusType status = null; + try { + + JAXBElement jaxbElement = FRJAXBUtil.getJAXBUtil().unMashallFromString(response); + pmRespMessageType = (ResponseMessageType) jaxbElement.getValue(); + + // Get response message status + ResponseHeaderType responseHeader = pmRespMessageType.getResponseHeader(); + status = responseHeader.getResultStatus().getStatus(); + String procStatus = status.getType(); + String procMessage = status.getValue(); + + if(procStatus.equals("ERROR")){ + log.error("Error reported by CRC web Service " + procMessage); + } + else if(procStatus.equals("WARNING")){ + log.debug("Warning reported by CRC web Service" + procMessage); + } + + } catch (JAXBUtilException e) { + log.error(e); + throw e; + } + return status; + } + + + public ConfigureType readUserInfo() throws JAXBUtilException { + ConfigureType pmResponse = null; + + BodyType bodyType = pmRespMessageType.getMessageBody(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + pmResponse = (ConfigureType)helper.getObjectByClass(bodyType.getAny(), ConfigureType.class); + + return pmResponse; + } + +} diff --git a/edu.harvard.i2b2.fr/src/server/edu/harvard/i2b2/fr/delegate/pm/PMServiceClient.java b/edu.harvard.i2b2.fr/src/main/java/edu/harvard/i2b2/fr/delegate/pm/PMServiceClient.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.fr/src/server/edu/harvard/i2b2/fr/delegate/pm/PMServiceClient.java rename to edu.harvard.i2b2.fr/src/main/java/edu/harvard/i2b2/fr/delegate/pm/PMServiceClient.java diff --git a/edu.harvard.i2b2.fr/src/server/edu/harvard/i2b2/fr/delegate/pm/PMServiceDriver.java b/edu.harvard.i2b2.fr/src/main/java/edu/harvard/i2b2/fr/delegate/pm/PMServiceDriver.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.fr/src/server/edu/harvard/i2b2/fr/delegate/pm/PMServiceDriver.java rename to edu.harvard.i2b2.fr/src/main/java/edu/harvard/i2b2/fr/delegate/pm/PMServiceDriver.java diff --git a/edu.harvard.i2b2.fr/src/server/edu/harvard/i2b2/fr/delegate/pm/ProjectManagementRequestData.java b/edu.harvard.i2b2.fr/src/main/java/edu/harvard/i2b2/fr/delegate/pm/ProjectManagementRequestData.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.fr/src/server/edu/harvard/i2b2/fr/delegate/pm/ProjectManagementRequestData.java rename to edu.harvard.i2b2.fr/src/main/java/edu/harvard/i2b2/fr/delegate/pm/ProjectManagementRequestData.java diff --git a/edu.harvard.i2b2.fr/src/server/edu/harvard/i2b2/fr/io/NullOutputStream.java b/edu.harvard.i2b2.fr/src/main/java/edu/harvard/i2b2/fr/io/NullOutputStream.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.fr/src/server/edu/harvard/i2b2/fr/io/NullOutputStream.java rename to edu.harvard.i2b2.fr/src/main/java/edu/harvard/i2b2/fr/io/NullOutputStream.java diff --git a/edu.harvard.i2b2.fr/src/server/edu/harvard/i2b2/fr/util/Base64.java b/edu.harvard.i2b2.fr/src/main/java/edu/harvard/i2b2/fr/util/Base64.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.fr/src/server/edu/harvard/i2b2/fr/util/Base64.java rename to edu.harvard.i2b2.fr/src/main/java/edu/harvard/i2b2/fr/util/Base64.java diff --git a/edu.harvard.i2b2.fr/src/server/edu/harvard/i2b2/fr/util/ConstantUtil.java b/edu.harvard.i2b2.fr/src/main/java/edu/harvard/i2b2/fr/util/ConstantUtil.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.fr/src/server/edu/harvard/i2b2/fr/util/ConstantUtil.java rename to edu.harvard.i2b2.fr/src/main/java/edu/harvard/i2b2/fr/util/ConstantUtil.java diff --git a/edu.harvard.i2b2.fr/src/server/edu/harvard/i2b2/fr/util/FRUtil.java b/edu.harvard.i2b2.fr/src/main/java/edu/harvard/i2b2/fr/util/FRUtil.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.fr/src/server/edu/harvard/i2b2/fr/util/FRUtil.java rename to edu.harvard.i2b2.fr/src/main/java/edu/harvard/i2b2/fr/util/FRUtil.java diff --git a/edu.harvard.i2b2.fr/src/server/edu/harvard/i2b2/fr/util/MD5.java b/edu.harvard.i2b2.fr/src/main/java/edu/harvard/i2b2/fr/util/MD5.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.fr/src/server/edu/harvard/i2b2/fr/util/MD5.java rename to edu.harvard.i2b2.fr/src/main/java/edu/harvard/i2b2/fr/util/MD5.java diff --git a/edu.harvard.i2b2.fr/src/server/edu/harvard/i2b2/fr/util/MD5InputStream.java b/edu.harvard.i2b2.fr/src/main/java/edu/harvard/i2b2/fr/util/MD5InputStream.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.fr/src/server/edu/harvard/i2b2/fr/util/MD5InputStream.java rename to edu.harvard.i2b2.fr/src/main/java/edu/harvard/i2b2/fr/util/MD5InputStream.java diff --git a/edu.harvard.i2b2.fr/src/server/edu/harvard/i2b2/fr/util/MD5OutputStream.java b/edu.harvard.i2b2.fr/src/main/java/edu/harvard/i2b2/fr/util/MD5OutputStream.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.fr/src/server/edu/harvard/i2b2/fr/util/MD5OutputStream.java rename to edu.harvard.i2b2.fr/src/main/java/edu/harvard/i2b2/fr/util/MD5OutputStream.java diff --git a/edu.harvard.i2b2.fr/src/server/edu/harvard/i2b2/fr/util/MD5State.java b/edu.harvard.i2b2.fr/src/main/java/edu/harvard/i2b2/fr/util/MD5State.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.fr/src/server/edu/harvard/i2b2/fr/util/MD5State.java rename to edu.harvard.i2b2.fr/src/main/java/edu/harvard/i2b2/fr/util/MD5State.java diff --git a/edu.harvard.i2b2.fr/src/server/edu/harvard/i2b2/fr/ws/FileRepositoryService.java b/edu.harvard.i2b2.fr/src/main/java/edu/harvard/i2b2/fr/ws/FileRepositoryService.java old mode 100755 new mode 100644 similarity index 98% rename from edu.harvard.i2b2.fr/src/server/edu/harvard/i2b2/fr/ws/FileRepositoryService.java rename to edu.harvard.i2b2.fr/src/main/java/edu/harvard/i2b2/fr/ws/FileRepositoryService.java index 7c81572f..74e181cd --- a/edu.harvard.i2b2.fr/src/server/edu/harvard/i2b2/fr/ws/FileRepositoryService.java +++ b/edu.harvard.i2b2.fr/src/main/java/edu/harvard/i2b2/fr/ws/FileRepositoryService.java @@ -18,8 +18,8 @@ import java.io.StringReader; -import javax.activation.DataHandler; -import javax.activation.FileDataSource; +import jakarta.activation.DataHandler; +import jakarta.activation.FileDataSource; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; diff --git a/edu.harvard.i2b2.fr/src/test/edu/harvard/i2b2/fr/ws/FRAxisAbstract.java b/edu.harvard.i2b2.fr/src/test/java/edu/harvard/i2b2/fr/ws/FRAxisAbstract.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.fr/src/test/edu/harvard/i2b2/fr/ws/FRAxisAbstract.java rename to edu.harvard.i2b2.fr/src/test/java/edu/harvard/i2b2/fr/ws/FRAxisAbstract.java diff --git a/edu.harvard.i2b2.fr/src/test/edu/harvard/i2b2/fr/ws/FRServiceRESTTest.java b/edu.harvard.i2b2.fr/src/test/java/edu/harvard/i2b2/fr/ws/FRServiceRESTTest.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.fr/src/test/edu/harvard/i2b2/fr/ws/FRServiceRESTTest.java rename to edu.harvard.i2b2.fr/src/test/java/edu/harvard/i2b2/fr/ws/FRServiceRESTTest.java index aeb375f6..8bafbea8 --- a/edu.harvard.i2b2.fr/src/test/edu/harvard/i2b2/fr/ws/FRServiceRESTTest.java +++ b/edu.harvard.i2b2.fr/src/test/java/edu/harvard/i2b2/fr/ws/FRServiceRESTTest.java @@ -1,64 +1,64 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Rajesh Kuttan - */ -package edu.harvard.i2b2.fr.ws; - -import static org.junit.Assert.*; - - -import jakarta.xml.bind.JAXBElement; - -import junit.framework.JUnit4TestAdapter; - -import org.apache.axiom.om.OMElement; -import org.junit.BeforeClass; -import org.junit.Test; - -import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; -import edu.harvard.i2b2.fr.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.fr.util.FRUtil; - -public class FRServiceRESTTest extends FRAxisAbstract{ - private static String testFileDir = ""; - - private static String ontologyTargetEPR = null; - // "http://127.0.0.1:8080/i2b2/services/PMService/getServices"; - - public static junit.framework.Test suite() { - return new JUnit4TestAdapter(FRServiceRESTTest.class); - } - - - @BeforeClass - public static void setUp() throws Exception { - String host = (System.getProperty("testhost") == null ? "http://127.0.0.1:9090/i2b2/services" : System.getProperty("testhost") ) ; - ontologyTargetEPR = - host + "/OntologyService/getSchemes"; - testFileDir = "test"; //System.getProperty("testfiledir"); - System.out.println("test file dir " + testFileDir); - - if (!((testFileDir != null) && (testFileDir.trim().length() > 0))) { - throw new Exception( - "please provide test file directory info -Dtestfiledir"); - } - - } - - -} - - - - - +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Rajesh Kuttan + */ +package edu.harvard.i2b2.fr.ws; + +import static org.junit.Assert.*; + + +import jakarta.xml.bind.JAXBElement; + +import junit.framework.JUnit4TestAdapter; + +import org.apache.axiom.om.OMElement; +import org.junit.BeforeClass; +import org.junit.Test; + +import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; +import edu.harvard.i2b2.fr.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.fr.util.FRUtil; + +public class FRServiceRESTTest extends FRAxisAbstract{ + private static String testFileDir = ""; + + private static String ontologyTargetEPR = null; + // "http://127.0.0.1:8080/i2b2/services/PMService/getServices"; + + public static junit.framework.Test suite() { + return new JUnit4TestAdapter(FRServiceRESTTest.class); + } + + + @BeforeClass + public static void setUp() throws Exception { + String host = (System.getProperty("testhost") == null ? "http://127.0.0.1:9090/i2b2/services" : System.getProperty("testhost") ) ; + ontologyTargetEPR = + host + "/OntologyService/getSchemes"; + testFileDir = "test"; //System.getProperty("testfiledir"); + System.out.println("test file dir " + testFileDir); + + if (!((testFileDir != null) && (testFileDir.trim().length() > 0))) { + throw new Exception( + "please provide test file directory info -Dtestfiledir"); + } + + } + + +} + + + + + diff --git a/edu.harvard.i2b2.fr/src/test/edu/harvard/i2b2/fr/ws/GetFilefromFRC_SOAPTest.java b/edu.harvard.i2b2.fr/src/test/java/edu/harvard/i2b2/fr/ws/GetFilefromFRC_SOAPTest.java old mode 100755 new mode 100644 similarity index 99% rename from edu.harvard.i2b2.fr/src/test/edu/harvard/i2b2/fr/ws/GetFilefromFRC_SOAPTest.java rename to edu.harvard.i2b2.fr/src/test/java/edu/harvard/i2b2/fr/ws/GetFilefromFRC_SOAPTest.java index d4293d3e..edd782c6 --- a/edu.harvard.i2b2.fr/src/test/edu/harvard/i2b2/fr/ws/GetFilefromFRC_SOAPTest.java +++ b/edu.harvard.i2b2.fr/src/test/java/edu/harvard/i2b2/fr/ws/GetFilefromFRC_SOAPTest.java @@ -41,7 +41,7 @@ import java.io.InputStreamReader; import java.io.StringReader; -import javax.activation.DataHandler; +import jakarta.activation.DataHandler; import javax.xml.stream.FactoryConfigurationError; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamReader; diff --git a/edu.harvard.i2b2.fr/src/test/edu/harvard/i2b2/fr/ws/PostFiletoFRC_SOAPTest.java b/edu.harvard.i2b2.fr/src/test/java/edu/harvard/i2b2/fr/ws/PostFiletoFRC_SOAPTest.java old mode 100755 new mode 100644 similarity index 98% rename from edu.harvard.i2b2.fr/src/test/edu/harvard/i2b2/fr/ws/PostFiletoFRC_SOAPTest.java rename to edu.harvard.i2b2.fr/src/test/java/edu/harvard/i2b2/fr/ws/PostFiletoFRC_SOAPTest.java index 919a6d86..3fb9437c --- a/edu.harvard.i2b2.fr/src/test/edu/harvard/i2b2/fr/ws/PostFiletoFRC_SOAPTest.java +++ b/edu.harvard.i2b2.fr/src/test/java/edu/harvard/i2b2/fr/ws/PostFiletoFRC_SOAPTest.java @@ -36,8 +36,8 @@ import java.io.InputStreamReader; import java.io.StringReader; -import javax.activation.DataHandler; -import javax.activation.FileDataSource; +import jakarta.activation.DataHandler; +import jakarta.activation.FileDataSource; import javax.xml.stream.FactoryConfigurationError; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamReader; diff --git a/edu.harvard.i2b2.im/${edu.harvard.i2b2.iim.applicationdir}/im.properties b/edu.harvard.i2b2.im/${edu.harvard.i2b2.iim.applicationdir}/im.properties deleted file mode 100755 index 483793fe..00000000 --- a/edu.harvard.i2b2.im/${edu.harvard.i2b2.iim.applicationdir}/im.properties +++ /dev/null @@ -1,24 +0,0 @@ -#------------------------------------------------------------------------------- -# Copyright (c) 2006-2018 Massachusetts General Hospital -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Mozilla Public License, -# v. 2.0. If a copy of the MPL was not distributed with this file, You can -# obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under -# the terms of the Healthcare Disclaimer. -#------------------------------------------------------------------------------- -############################################### -## Application properties for IM Cell ## -############################################### - -####################################### -# Project Management Cell -####################################### -im.ws.pm.url=http://localhost:9090/i2b2/services/PMService/getServices -# Flag to bypass project management cell -im.ws.pm.bypass=false -im.ws.pm.bypass.role=ADMIN -im.ws.pm.bypass.project=Demo - - - - diff --git a/edu.harvard.i2b2.im/${edu.harvard.i2b2.workplace.applicationdir}/im.properties b/edu.harvard.i2b2.im/${edu.harvard.i2b2.workplace.applicationdir}/im.properties deleted file mode 100755 index 4723bea6..00000000 --- a/edu.harvard.i2b2.im/${edu.harvard.i2b2.workplace.applicationdir}/im.properties +++ /dev/null @@ -1,29 +0,0 @@ -#------------------------------------------------------------------------------- -# Copyright (c) 2006-2018 Massachusetts General Hospital -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Mozilla Public License, -# v. 2.0. If a copy of the MPL was not distributed with this file, You can -# obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under -# the terms of the Healthcare Disclaimer. -#------------------------------------------------------------------------------- -############################################### -## Application properties for IM Cell ## -############################################### - -####################################### -# Project Management Cell -####################################### -queryprocessor.ws.pm.url=http://localhost:9090/i2b2/rest/PMService/getServices -# Flag to bypass project management cell -queryprocessor.ws.pm.bypass=false -queryprocessor.ws.pm.bypass.role=ADMIN -queryprocessor.ws.pm.bypass.project=Demo - -####################################### -# Datasource Lookup properties -####################################### -queryprocessor.ds.lookup.datasource=CRCDataSourceLookup -queryprocessor.ds.lookup.servertype=ORACLE -queryprocessor.ds.lookup.schemaname=i2b2hive - - diff --git a/edu.harvard.i2b2.im/.classpath b/edu.harvard.i2b2.im/.classpath index 28aebfe1..b9f6029d 100755 --- a/edu.harvard.i2b2.im/.classpath +++ b/edu.harvard.i2b2.im/.classpath @@ -1,151 +1,46 @@ - - - - - - + - + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/edu.harvard.i2b2.im/.gitignore b/edu.harvard.i2b2.im/.gitignore deleted file mode 100644 index ae3c1726..00000000 --- a/edu.harvard.i2b2.im/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/bin/ diff --git a/edu.harvard.i2b2.im/.project b/edu.harvard.i2b2.im/.project index edf2d25e..119407ff 100755 --- a/edu.harvard.i2b2.im/.project +++ b/edu.harvard.i2b2.im/.project @@ -10,8 +10,14 @@ + + org.eclipse.m2e.core.maven2Builder + + + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature diff --git a/edu.harvard.i2b2.im/LICENSE.txt b/edu.harvard.i2b2.im/LICENSE.txt deleted file mode 100644 index e5a5569a..00000000 --- a/edu.harvard.i2b2.im/LICENSE.txt +++ /dev/null @@ -1,406 +0,0 @@ -#------------------------------------------------------------------------------- -# Copyright (c) 2006-2018 Massachusetts General Hospital -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Mozilla Public License, -# v. 2.0. If a copy of the MPL was not distributed with this file, You can -# obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under -# the terms of the Healthcare Disclaimer. -#------------------------------------------------------------------------------- -Mozilla Public License, version 2.0 - -1. Definitions - -1.1. "Contributor" - - means each individual or legal entity that creates, contributes to the - creation of, or owns Covered Software. - -1.2. "Contributor Version" - - means the combination of the Contributions of others (if any) used by a - Contributor and that particular Contributor's Contribution. - -1.3. "Contribution" - - means Covered Software of a particular Contributor. - -1.4. "Covered Software" - - means Source Code Form to which the initial Contributor has attached the - notice in Exhibit A, the Executable Form of such Source Code Form, and - Modifications of such Source Code Form, in each case including portions - thereof. - -1.5. "Incompatible With Secondary Licenses" - means - - a. that the initial Contributor has attached the notice described in - Exhibit B to the Covered Software; or - - b. that the Covered Software was made available under the terms of - version 1.1 or earlier of the License, but not also under the terms of - a Secondary License. - -1.6. "Executable Form" - - means any form of the work other than Source Code Form. - -1.7. "Larger Work" - - means a work that combines Covered Software with other material, in a - separate file or files, that is not Covered Software. - -1.8. "License" - - means this document. - -1.9. "Licensable" - - means having the right to grant, to the maximum extent possible, whether - at the time of the initial grant or subsequently, any and all of the - rights conveyed by this License. - -1.10. "Modifications" - - means any of the following: - - a. any file in Source Code Form that results from an addition to, - deletion from, or modification of the contents of Covered Software; or - - b. any new file in Source Code Form that contains any Covered Software. - -1.11. "Patent Claims" of a Contributor - - means any patent claim(s), including without limitation, method, - process, and apparatus claims, in any patent Licensable by such - Contributor that would be infringed, but for the grant of the License, - by the making, using, selling, offering for sale, having made, import, - or transfer of either its Contributions or its Contributor Version. - -1.12. "Secondary License" - - means either the GNU General Public License, Version 2.0, the GNU Lesser - General Public License, Version 2.1, the GNU Affero General Public - License, Version 3.0, or any later versions of those licenses. - -1.13. "Source Code Form" - - means the form of the work preferred for making modifications. - -1.14. "You" (or "Your") - - means an individual or a legal entity exercising rights under this - License. For legal entities, "You" includes any entity that controls, is - controlled by, or is under common control with You. For purposes of this - definition, "control" means (a) the power, direct or indirect, to cause - the direction or management of such entity, whether by contract or - otherwise, or (b) ownership of more than fifty percent (50%) of the - outstanding shares or beneficial ownership of such entity. - - -2. License Grants and Conditions - -2.1. Grants - - Each Contributor hereby grants You a world-wide, royalty-free, - non-exclusive license: - - a. under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or - as part of a Larger Work; and - - b. under Patent Claims of such Contributor to make, use, sell, offer for - sale, have made, import, and otherwise transfer either its - Contributions or its Contributor Version. - -2.2. Effective Date - - The licenses granted in Section 2.1 with respect to any Contribution - become effective for each Contribution on the date the Contributor first - distributes such Contribution. - -2.3. Limitations on Grant Scope - - The licenses granted in this Section 2 are the only rights granted under - this License. No additional rights or licenses will be implied from the - distribution or licensing of Covered Software under this License. - Notwithstanding Section 2.1(b) above, no patent license is granted by a - Contributor: - - a. for any code that a Contributor has removed from Covered Software; or - - b. for infringements caused by: (i) Your and any other third party's - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - - c. under Patent Claims infringed by Covered Software in the absence of - its Contributions. - - This License does not grant any rights in the trademarks, service marks, - or logos of any Contributor (except as may be necessary to comply with - the notice requirements in Section 3.4). - -2.4. Subsequent Licenses - - No Contributor makes additional grants as a result of Your choice to - distribute the Covered Software under a subsequent version of this - License (see Section 10.2) or under the terms of a Secondary License (if - permitted under the terms of Section 3.3). - -2.5. Representation - - Each Contributor represents that the Contributor believes its - Contributions are its original creation(s) or it has sufficient rights to - grant the rights to its Contributions conveyed by this License. - -2.6. Fair Use - - This License is not intended to limit any rights You have under - applicable copyright doctrines of fair use, fair dealing, or other - equivalents. - -2.7. Conditions - - Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in - Section 2.1. - - -3. Responsibilities - -3.1. Distribution of Source Form - - All distribution of Covered Software in Source Code Form, including any - Modifications that You create or to which You contribute, must be under - the terms of this License. You must inform recipients that the Source - Code Form of the Covered Software is governed by the terms of this - License, and how they can obtain a copy of this License. You may not - attempt to alter or restrict the recipients' rights in the Source Code - Form. - -3.2. Distribution of Executable Form - - If You distribute Covered Software in Executable Form then: - - a. such Covered Software must also be made available in Source Code Form, - as described in Section 3.1, and You must inform recipients of the - Executable Form how they can obtain a copy of such Source Code Form by - reasonable means in a timely manner, at a charge no more than the cost - of distribution to the recipient; and - - b. You may distribute such Executable Form under the terms of this - License, or sublicense it under different terms, provided that the - license for the Executable Form does not attempt to limit or alter the - recipients' rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - - You may create and distribute a Larger Work under terms of Your choice, - provided that You also comply with the requirements of this License for - the Covered Software. If the Larger Work is a combination of Covered - Software with a work governed by one or more Secondary Licenses, and the - Covered Software is not Incompatible With Secondary Licenses, this - License permits You to additionally distribute such Covered Software - under the terms of such Secondary License(s), so that the recipient of - the Larger Work may, at their option, further distribute the Covered - Software under the terms of either this License or such Secondary - License(s). - -3.4. Notices - - You may not remove or alter the substance of any license notices - (including copyright notices, patent notices, disclaimers of warranty, or - limitations of liability) contained within the Source Code Form of the - Covered Software, except that You may alter any license notices to the - extent required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - - You may choose to offer, and to charge a fee for, warranty, support, - indemnity or liability obligations to one or more recipients of Covered - Software. However, You may do so only on Your own behalf, and not on - behalf of any Contributor. You must make it absolutely clear that any - such warranty, support, indemnity, or liability obligation is offered by - You alone, and You hereby agree to indemnify every Contributor for any - liability incurred by such Contributor as a result of warranty, support, - indemnity or liability terms You offer. You may include additional - disclaimers of warranty and limitations of liability specific to any - jurisdiction. - -4. Inability to Comply Due to Statute or Regulation - - If it is impossible for You to comply with any of the terms of this License - with respect to some or all of the Covered Software due to statute, - judicial order, or regulation then You must: (a) comply with the terms of - this License to the maximum extent possible; and (b) describe the - limitations and the code they affect. Such description must be placed in a - text file included with all distributions of the Covered Software under - this License. Except to the extent prohibited by statute or regulation, - such description must be sufficiently detailed for a recipient of ordinary - skill to be able to understand it. - -5. Termination - -5.1. The rights granted under this License will terminate automatically if You - fail to comply with any of its terms. However, if You become compliant, - then the rights granted under this License from a particular Contributor - are reinstated (a) provisionally, unless and until such Contributor - explicitly and finally terminates Your grants, and (b) on an ongoing - basis, if such Contributor fails to notify You of the non-compliance by - some reasonable means prior to 60 days after You have come back into - compliance. Moreover, Your grants from a particular Contributor are - reinstated on an ongoing basis if such Contributor notifies You of the - non-compliance by some reasonable means, this is the first time You have - received notice of non-compliance with this License from such - Contributor, and You become compliant prior to 30 days after Your receipt - of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent - infringement claim (excluding declaratory judgment actions, - counter-claims, and cross-claims) alleging that a Contributor Version - directly or indirectly infringes any patent, then the rights granted to - You by any and all Contributors for the Covered Software under Section - 2.1 of this License shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user - license agreements (excluding distributors and resellers) which have been - validly granted by You or Your distributors under this License prior to - termination shall survive termination. - -6. Disclaimer of Warranty - - Covered Software is provided under this License on an "as is" basis, - without warranty of any kind, either expressed, implied, or statutory, - including, without limitation, warranties that the Covered Software is free - of defects, merchantable, fit for a particular purpose or non-infringing. - The entire risk as to the quality and performance of the Covered Software - is with You. Should any Covered Software prove defective in any respect, - You (not any Contributor) assume the cost of any necessary servicing, - repair, or correction. This disclaimer of warranty constitutes an essential - part of this License. No use of any Covered Software is authorized under - this License except under this disclaimer. - -7. Limitation of Liability - - Under no circumstances and under no legal theory, whether tort (including - negligence), contract, or otherwise, shall any Contributor, or anyone who - distributes Covered Software as permitted above, be liable to You for any - direct, indirect, special, incidental, or consequential damages of any - character including, without limitation, damages for lost profits, loss of - goodwill, work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses, even if such party shall have been - informed of the possibility of such damages. This limitation of liability - shall not apply to liability for death or personal injury resulting from - such party's negligence to the extent applicable law prohibits such - limitation. Some jurisdictions do not allow the exclusion or limitation of - incidental or consequential damages, so this exclusion and limitation may - not apply to You. - -8. Litigation - - Any litigation relating to this License may be brought only in the courts - of a jurisdiction where the defendant maintains its principal place of - business and such litigation shall be governed by laws of that - jurisdiction, without reference to its conflict-of-law provisions. Nothing - in this Section shall prevent a party's ability to bring cross-claims or - counter-claims. - -9. Miscellaneous - - This License represents the complete agreement concerning the subject - matter hereof. If any provision of this License is held to be - unenforceable, such provision shall be reformed only to the extent - necessary to make it enforceable. Any law or regulation which provides that - the language of a contract shall be construed against the drafter shall not - be used to construe this License against a Contributor. - - -10. Versions of the License - -10.1. New Versions - - Mozilla Foundation is the license steward. Except as provided in Section - 10.3, no one other than the license steward has the right to modify or - publish new versions of this License. Each version will be given a - distinguishing version number. - -10.2. Effect of New Versions - - You may distribute the Covered Software under the terms of the version - of the License under which You originally received the Covered Software, - or under the terms of any subsequent version published by the license - steward. - -10.3. Modified Versions - - If you create software not governed by this License, and you want to - create a new license for such software, you may create and use a - modified version of this License if you rename the license and remove - any references to the name of the license steward (except to note that - such modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary - Licenses If You choose to distribute Source Code Form that is - Incompatible With Secondary Licenses under the terms of this version of - the License, the notice described in Exhibit B of this License must be - attached. - -Exhibit A - Source Code Form License Notice - - This Source Code Form is subject to the - terms of the Mozilla Public License, v. - 2.0. If a copy of the MPL was not - distributed with this file, You can - obtain one at - http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular file, -then You may include the notice in a location (such as a LICENSE file in a -relevant directory) where a recipient would be likely to look for such a -notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - "Incompatible With Secondary Licenses" Notice - - This Source Code Form is "Incompatible - With Secondary Licenses", as defined by - the Mozilla Public License, v. 2.0. - ---------------------- - -Healthcare Disclaimer - -In the United States, or any other jurisdictions where they may apply, the -following additional disclaimer of warranty and limitation of liability are -hereby incorporated into the terms and conditions of MPL 2.0: - -1. No warranties of any kind whatsoever are made as to the results that - You will obtain from relying upon the covered code (or any information - or content obtained by way of the covered code), including but not - limited to compliance with privacy laws or regulations or clinical - care industry standards and protocols. Use of the covered code is not - a substitute for a health care provider’s standard practice or - professional judgment. Any decision with regard to the appropriateness - of treatment, or the validity or reliability of information or content - made available by the covered code, is the sole responsibility of the - health care provider. Consequently, it is incumbent upon each health - care provider to verify all medical history and treatment plans with - each patient. - -2. Under no circumstances and under no legal theory, whether tort - (including negligence), contract, or otherwise, shall any Contributor, - or anyone who distributes Covered Software as permitted by the - license, be liable to You for any indirect, special, incidental, - consequential damages of any character including, without limitation, - damages for loss of goodwill, work stoppage, computer failure or - malfunction, or any and all other damages or losses, of any nature - whatsoever (direct or otherwise) on account of or associated with the - use or inability to use the covered content (including, without - limitation, the use of information or content made available by the - covered code, all documentation associated therewith, and the failure - of the covered code to comply with privacy laws and regulations or - clinical care industry standards and protocols), even if such party - shall have been informed of the possibility of such damages. diff --git a/edu.harvard.i2b2.im/build.properties b/edu.harvard.i2b2.im/build.properties deleted file mode 100755 index f48d1b6f..00000000 --- a/edu.harvard.i2b2.im/build.properties +++ /dev/null @@ -1,10 +0,0 @@ -#Ant build property file - -## JBOSS HOME -jboss.home=/opt/wildfly-17.0.1.Final -axis2.war.name=i2b2.war - -report=test-reports -testfiledir=testfiles -testhost=http://127.0.0.1:9090/i2b2/services - diff --git a/edu.harvard.i2b2.im/build.xml b/edu.harvard.i2b2.im/build.xml deleted file mode 100755 index b7f094c1..00000000 --- a/edu.harvard.i2b2.im/build.xml +++ /dev/null @@ -1,235 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/edu.harvard.i2b2.im/common-build.xml b/edu.harvard.i2b2.im/common-build.xml deleted file mode 100755 index d42db08f..00000000 --- a/edu.harvard.i2b2.im/common-build.xml +++ /dev/null @@ -1,75 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/edu.harvard.i2b2.im/master_build.xml b/edu.harvard.i2b2.im/master_build.xml deleted file mode 100755 index 27f4c9bd..00000000 --- a/edu.harvard.i2b2.im/master_build.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/edu.harvard.i2b2.im/pom.xml b/edu.harvard.i2b2.im/pom.xml new file mode 100644 index 00000000..d015a86c --- /dev/null +++ b/edu.harvard.i2b2.im/pom.xml @@ -0,0 +1,44 @@ + + 4.0.0 + + edu.harvard.i2b2 + i2b2-parent + 2.0.0-SNAPSHOT + + edu.harvard.i2b2.im + jar + IM Module + + + + + org.codehaus.mojo + build-helper-maven-plugin + 3.0.0 + + + generate-sources + + add-source + + + + gensrc + + + + + + + + + + + edu.harvard.i2b2 + edu.harvard.i2b2.server-common + + + + + \ No newline at end of file diff --git a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/dao/DataSourceLookupHelper.java b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/dao/DataSourceLookupHelper.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/dao/DataSourceLookupHelper.java rename to edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/dao/DataSourceLookupHelper.java diff --git a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/dao/DblookupDao.java b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/dao/DblookupDao.java similarity index 100% rename from edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/dao/DblookupDao.java rename to edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/dao/DblookupDao.java diff --git a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/dao/IMDbDao.java b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/dao/IMDbDao.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/dao/IMDbDao.java rename to edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/dao/IMDbDao.java diff --git a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/dao/IMKey.java b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/dao/IMKey.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/dao/IMKey.java rename to edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/dao/IMKey.java index d16e48f4..6293ffa4 --- a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/dao/IMKey.java +++ b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/dao/IMKey.java @@ -1,90 +1,90 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.im.dao; - -import java.io.UnsupportedEncodingException; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.Hashtable; - -//import org.apache.commons.codec.digest.DigestUtils; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.im.datavo.pm.ProjectType; -import edu.harvard.i2b2.im.datavo.wdo.SetKeyType; - -public class IMKey { - - private static Hashtable imkey = new Hashtable(); - - public static String getKey(ProjectType projectInfo) { - return imkey.get(projectInfo.getId()); - } - - - public static int setKey(SetKeyType requestType, ProjectType projectInfo, - String projectID) throws UnsupportedEncodingException, NoSuchAlgorithmException, I2B2Exception { - if (projectInfo == null) return -1; - - if (!projectInfo.getRole().contains("ADMIN") && !projectInfo.getRole().contains("MANAGER")) - return -11111; - if ( (requestType.getKey() == null) || (requestType.getKey().equals(""))) - { - imkey.remove(projectInfo.getId()); - } else { - //MM TODO: FIX - /* - if (projectInfo.getKey() != null) - { - - String key = DigestUtils.sha256Hex(requestType.getKey()).substring(0, 3); - if (!key.equals(projectInfo.getKey())) - return -1; - } - */ - imkey.put(projectInfo.getId(), requestType.getKey()); - } - return 0; - } - - public static int isKeySet( ProjectType projectInfo ) throws UnsupportedEncodingException, NoSuchAlgorithmException, I2B2Exception { - if (projectInfo == null) return -1; - - if (!projectInfo.getRole().contains("ADMIN") && !projectInfo.getRole().contains("MANAGER") - && !projectInfo.getRole().contains("DATA_PROT")) - return -11111; - - if (imkey.containsKey(projectInfo.getId())) - return 1; - else - return 0; - - } - - - public static int isKeySet( ProjectType projectInfo, String projectId) throws UnsupportedEncodingException, NoSuchAlgorithmException, I2B2Exception { - if (projectInfo == null) return -1; - - if (!projectInfo.getRole().contains("ADMIN") && !projectInfo.getRole().contains("MANAGER") - && !projectInfo.getRole().contains("DATA_PROT")) - return -11111; - - if (!projectInfo.getRole().contains("ADMIN") && !projectInfo.getId().equals(projectId)) - return -22222; - - if (imkey.containsKey(projectId)) - return 1; - else - return 0; - - } - - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.im.dao; + +import java.io.UnsupportedEncodingException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Hashtable; + +//import org.apache.commons.codec.digest.DigestUtils; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.im.datavo.pm.ProjectType; +import edu.harvard.i2b2.im.datavo.wdo.SetKeyType; + +public class IMKey { + + private static Hashtable imkey = new Hashtable(); + + public static String getKey(ProjectType projectInfo) { + return imkey.get(projectInfo.getId()); + } + + + public static int setKey(SetKeyType requestType, ProjectType projectInfo, + String projectID) throws UnsupportedEncodingException, NoSuchAlgorithmException, I2B2Exception { + if (projectInfo == null) return -1; + + if (!projectInfo.getRole().contains("ADMIN") && !projectInfo.getRole().contains("MANAGER")) + return -11111; + if ( (requestType.getKey() == null) || (requestType.getKey().equals(""))) + { + imkey.remove(projectInfo.getId()); + } else { + //MM TODO: FIX + /* + if (projectInfo.getKey() != null) + { + + String key = DigestUtils.sha256Hex(requestType.getKey()).substring(0, 3); + if (!key.equals(projectInfo.getKey())) + return -1; + } + */ + imkey.put(projectInfo.getId(), requestType.getKey()); + } + return 0; + } + + public static int isKeySet( ProjectType projectInfo ) throws UnsupportedEncodingException, NoSuchAlgorithmException, I2B2Exception { + if (projectInfo == null) return -1; + + if (!projectInfo.getRole().contains("ADMIN") && !projectInfo.getRole().contains("MANAGER") + && !projectInfo.getRole().contains("DATA_PROT")) + return -11111; + + if (imkey.containsKey(projectInfo.getId())) + return 1; + else + return 0; + + } + + + public static int isKeySet( ProjectType projectInfo, String projectId) throws UnsupportedEncodingException, NoSuchAlgorithmException, I2B2Exception { + if (projectInfo == null) return -1; + + if (!projectInfo.getRole().contains("ADMIN") && !projectInfo.getRole().contains("MANAGER") + && !projectInfo.getRole().contains("DATA_PROT")) + return -11111; + + if (!projectInfo.getRole().contains("ADMIN") && !projectInfo.getId().equals(projectId)) + return -22222; + + if (imkey.containsKey(projectId)) + return 1; + else + return 0; + + } + + + +} diff --git a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/dao/PdoDao.java b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/dao/PdoDao.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/dao/PdoDao.java rename to edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/dao/PdoDao.java diff --git a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/delegate/DeleteDblookupHandler.java b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/delegate/DeleteDblookupHandler.java similarity index 100% rename from edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/delegate/DeleteDblookupHandler.java rename to edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/delegate/DeleteDblookupHandler.java diff --git a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/delegate/GetAllDblookupsHandler.java b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/delegate/GetAllDblookupsHandler.java similarity index 100% rename from edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/delegate/GetAllDblookupsHandler.java rename to edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/delegate/GetAllDblookupsHandler.java diff --git a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/delegate/GetAuditHandlerHandler.java b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/delegate/GetAuditHandlerHandler.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/delegate/GetAuditHandlerHandler.java rename to edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/delegate/GetAuditHandlerHandler.java diff --git a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/delegate/GetDblookupHandler.java b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/delegate/GetDblookupHandler.java similarity index 100% rename from edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/delegate/GetDblookupHandler.java rename to edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/delegate/GetDblookupHandler.java diff --git a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/delegate/IsKeySetHandlerHandler.java b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/delegate/IsKeySetHandlerHandler.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/delegate/IsKeySetHandlerHandler.java rename to edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/delegate/IsKeySetHandlerHandler.java diff --git a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/delegate/PdoHandlerHandler.java b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/delegate/PdoHandlerHandler.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/delegate/PdoHandlerHandler.java rename to edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/delegate/PdoHandlerHandler.java diff --git a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/delegate/RequestHandler.java b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/delegate/RequestHandler.java old mode 100755 new mode 100644 similarity index 95% rename from edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/delegate/RequestHandler.java rename to edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/delegate/RequestHandler.java index 705c6337..ac8a5d1a --- a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/delegate/RequestHandler.java +++ b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/delegate/RequestHandler.java @@ -1,233 +1,233 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Lori Phillips - * Wayne Chan - */ -package edu.harvard.i2b2.im.delegate; - -import java.util.Iterator; - -import org.apache.axis2.AxisFault; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.im.datavo.i2b2message.MessageHeaderType; -import edu.harvard.i2b2.im.datavo.i2b2message.SecurityType; -import edu.harvard.i2b2.pm.ws.PMResponseMessage; -import edu.harvard.i2b2.pm.ws.PMServiceDriver; -import edu.harvard.i2b2.im.dao.DataSourceLookupHelper; -import edu.harvard.i2b2.im.ejb.DBInfoType; -import edu.harvard.i2b2.im.datavo.i2b2message.StatusType; -import edu.harvard.i2b2.im.datavo.pm.CellDataType; -import edu.harvard.i2b2.im.datavo.pm.ConfigureType; -import edu.harvard.i2b2.im.datavo.pm.GetUserConfigurationType; -import edu.harvard.i2b2.im.datavo.pm.ProjectType; -import edu.harvard.i2b2.im.datavo.pm.ProjectsType; -import edu.harvard.i2b2.im.util.IMUtil; - -public abstract class RequestHandler { - protected final Log log = LogFactory.getLog(getClass()); - protected final Log logesapi = LogFactory.getLog(getClass()); - - public abstract String execute() throws I2B2Exception; - private SecurityType securityType = null; - private DBInfoType dbInfo; - private ConfigureType configureType; - - - //swc20160520 - public boolean isAdmin(MessageHeaderType header) { - try { - GetUserConfigurationType userConfigType = new GetUserConfigurationType(); - String response = PMServiceDriver.getRoles(userConfigType, header); - logesapi.debug(response); - PMResponseMessage msg = new PMResponseMessage(); - StatusType procStatus = msg.processResult(response); - if(procStatus.getType().equals("ERROR")) return false; - ConfigureType pmConfigure = msg.readUserInfo(); - if (pmConfigure.getUser().isIsAdmin()) return true; - } catch (AxisFault e) { - log.error("Can't connect to PM service"); - } catch (I2B2Exception e) { - log.error("Problem processing PM service address"); - } catch (Exception e) { - log.error("General PM processing problem: "+ e.getMessage()); - } - return false; - } - - - public ConfigureType getConfigureType() { - return configureType; - } - - public SecurityType getSecurityType() { - return securityType; - } - - public ProjectType getAllProjectsInfo(MessageHeaderType header, String projectId) - { - ProjectType projectType = null; - - // Are we bypassing the PM cell? Look in properties file. - - try { - //GetUserConfigurationType userConfigType = new GetUserConfigurationType(); - - PMResponseMessage msg = new PMResponseMessage(); - StatusType procStatus = null; - String response = PMServiceDriver.getAllProjects(header); - logesapi.debug(response); - procStatus = msg.processResult(response); - if(procStatus.getType().equals("ERROR")) - return null; - // check that user has access to this project. - ProjectsType pmConfigure = msg.readProjectsInfo(); - Iterator it = pmConfigure.getProject().iterator(); - - //Set Security Type - /* - log.debug("Setting security type needed for CRC"); - securityType = new SecurityType(); - securityType.setDomain(pmConfigure.getUser().getDomain()); - securityType.setUsername(pmConfigure.getUser().getUserName()); - edu.harvard.i2b2.im.datavo.i2b2message.PasswordType ptype = new edu.harvard.i2b2.im.datavo.i2b2message.PasswordType(); - ptype.setIsToken(pmConfigure.getUser().getPassword().isIsToken()); - ptype.setTokenMsTimeout(pmConfigure.getUser().getPassword().getTokenMsTimeout()); - ptype.setValue(pmConfigure.getUser().getPassword().getValue()); - securityType.setPassword(ptype); - */ - while (it.hasNext()) - { - projectType = (ProjectType)it.next(); - if (projectType.getId().equals(projectId)) { - // log.info(header.getProjectId()); - // log.info(projectType.getId()); - break; - } - projectType = null; - - } - projectType.getRole().add("ADMIN"); - - // projectType = pmConfigure.getUser().getProject().get(0); - } catch (AxisFault e) { - log.error("Cant connect to PM service"); - } catch (I2B2Exception e) { - log.error("Problem processing PM service address"); - } catch (Exception e) { - log.error("General PM processing problem: "+ e.getMessage()); - } - - return projectType; - } - - public ProjectType getRoleInfo(MessageHeaderType header) - { - ProjectType projectType = null; - - // Are we bypassing the PM cell? Look in properties file. - - try { - GetUserConfigurationType userConfigType = new GetUserConfigurationType(); - - PMResponseMessage msg = new PMResponseMessage(); - StatusType procStatus = null; - String response = PMServiceDriver.getRoles(userConfigType,header); - logesapi.debug(response); - procStatus = msg.processResult(response); - if(procStatus.getType().equals("ERROR")) - return null; - // check that user has access to this project. - configureType = msg.readUserInfo(); - Iterator it = configureType.getUser().getProject().iterator(); - - //Set CRC Cell URL - for (CellDataType cell : configureType.getCellDatas().getCellData()) - { - if (cell.getId().equals("CRC")) - { - IMUtil.getInstance().setCRCEndpointReference(cell.getUrl()); - break; - } - - } - - //Set Security Type - log.debug("Setting security type needed for CRC"); - securityType = new SecurityType(); - securityType.setDomain(configureType.getUser().getDomain()); - securityType.setUsername(configureType.getUser().getUserName()); - edu.harvard.i2b2.im.datavo.i2b2message.PasswordType ptype = new edu.harvard.i2b2.im.datavo.i2b2message.PasswordType(); - ptype.setIsToken(configureType.getUser().getPassword().isIsToken()); - ptype.setTokenMsTimeout(configureType.getUser().getPassword().getTokenMsTimeout()); - ptype.setValue(configureType.getUser().getPassword().getValue()); - securityType.setPassword(ptype); - - while (it.hasNext()) - { - projectType = (ProjectType)it.next(); - if (projectType.getId().equals(header.getProjectId())) { - // log.info(header.getProjectId()); - // log.info(projectType.getId()); - //If admin add role of admin - if (configureType.getUser().isIsAdmin()) - projectType.getRole().add("ADMIN"); - break; - } - projectType = null; - - } - - // projectType = pmConfigure.getUser().getProject().get(0); - } catch (AxisFault e) { - log.error("Cant connect to PM service"); - } catch (I2B2Exception e) { - log.error("Problem processing PM service address"); - } catch (Exception e) { - log.error("General PM processing problem: "+ e.getMessage()); - } - - return projectType; - } - - public void setDbInfo(MessageHeaderType requestMessageHeader) throws I2B2Exception{ - - DataSourceLookupHelper dsHelper = new DataSourceLookupHelper(); - this.dbInfo = - dsHelper.matchDataSource(requestMessageHeader.getSecurity().getDomain(), - requestMessageHeader.getProjectId(), - requestMessageHeader.getSecurity().getUsername()); - } - - - public DBInfoType getDbInfo() { - return this.dbInfo; - } - - public String getMetadata_dataSource() { - return dbInfo.getDb_dataSource(); - } - - - public String getMetadata_fullSchema() { - return dbInfo.getDb_fullSchema(); - } - - public String getMetadata_serverType() { - return dbInfo.getDb_serverType(); - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Lori Phillips + * Wayne Chan + */ +package edu.harvard.i2b2.im.delegate; + +import java.util.Iterator; + +import org.apache.axis2.AxisFault; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.im.datavo.i2b2message.MessageHeaderType; +import edu.harvard.i2b2.im.datavo.i2b2message.SecurityType; +import edu.harvard.i2b2.im.dao.DataSourceLookupHelper; +import edu.harvard.i2b2.im.ejb.DBInfoType; +import edu.harvard.i2b2.im.datavo.i2b2message.StatusType; +import edu.harvard.i2b2.im.datavo.pm.CellDataType; +import edu.harvard.i2b2.im.datavo.pm.ConfigureType; +import edu.harvard.i2b2.im.datavo.pm.GetUserConfigurationType; +import edu.harvard.i2b2.im.datavo.pm.ProjectType; +import edu.harvard.i2b2.im.datavo.pm.ProjectsType; +import edu.harvard.i2b2.im.util.IMUtil; +import edu.harvard.i2b2.impm.ws.PMResponseMessage; +import edu.harvard.i2b2.impm.ws.PMServiceDriver; + +public abstract class RequestHandler { + protected final Log log = LogFactory.getLog(getClass()); + protected final Log logesapi = LogFactory.getLog(getClass()); + + public abstract String execute() throws I2B2Exception; + private SecurityType securityType = null; + private DBInfoType dbInfo; + private ConfigureType configureType; + + + //swc20160520 + public boolean isAdmin(MessageHeaderType header) { + try { + GetUserConfigurationType userConfigType = new GetUserConfigurationType(); + String response = PMServiceDriver.getRoles(userConfigType, header); + logesapi.debug(response); + PMResponseMessage msg = new PMResponseMessage(); + StatusType procStatus = msg.processResult(response); + if(procStatus.getType().equals("ERROR")) return false; + ConfigureType pmConfigure = msg.readUserInfo(); + if (pmConfigure.getUser().isIsAdmin()) return true; + } catch (AxisFault e) { + log.error("Can't connect to PM service"); + } catch (I2B2Exception e) { + log.error("Problem processing PM service address"); + } catch (Exception e) { + log.error("General PM processing problem: "+ e.getMessage()); + } + return false; + } + + + public ConfigureType getConfigureType() { + return configureType; + } + + public SecurityType getSecurityType() { + return securityType; + } + + public ProjectType getAllProjectsInfo(MessageHeaderType header, String projectId) + { + ProjectType projectType = null; + + // Are we bypassing the PM cell? Look in properties file. + + try { + //GetUserConfigurationType userConfigType = new GetUserConfigurationType(); + + PMResponseMessage msg = new PMResponseMessage(); + StatusType procStatus = null; + String response = PMServiceDriver.getAllProjects(header); + logesapi.debug(response); + procStatus = msg.processResult(response); + if(procStatus.getType().equals("ERROR")) + return null; + // check that user has access to this project. + ProjectsType pmConfigure = msg.readProjectsInfo(); + Iterator it = pmConfigure.getProject().iterator(); + + //Set Security Type + /* + log.debug("Setting security type needed for CRC"); + securityType = new SecurityType(); + securityType.setDomain(pmConfigure.getUser().getDomain()); + securityType.setUsername(pmConfigure.getUser().getUserName()); + edu.harvard.i2b2.im.datavo.i2b2message.PasswordType ptype = new edu.harvard.i2b2.im.datavo.i2b2message.PasswordType(); + ptype.setIsToken(pmConfigure.getUser().getPassword().isIsToken()); + ptype.setTokenMsTimeout(pmConfigure.getUser().getPassword().getTokenMsTimeout()); + ptype.setValue(pmConfigure.getUser().getPassword().getValue()); + securityType.setPassword(ptype); + */ + while (it.hasNext()) + { + projectType = (ProjectType)it.next(); + if (projectType.getId().equals(projectId)) { + // log.info(header.getProjectId()); + // log.info(projectType.getId()); + break; + } + projectType = null; + + } + projectType.getRole().add("ADMIN"); + + // projectType = pmConfigure.getUser().getProject().get(0); + } catch (AxisFault e) { + log.error("Cant connect to PM service"); + } catch (I2B2Exception e) { + log.error("Problem processing PM service address"); + } catch (Exception e) { + log.error("General PM processing problem: "+ e.getMessage()); + } + + return projectType; + } + + public ProjectType getRoleInfo(MessageHeaderType header) + { + ProjectType projectType = null; + + // Are we bypassing the PM cell? Look in properties file. + + try { + GetUserConfigurationType userConfigType = new GetUserConfigurationType(); + + PMResponseMessage msg = new PMResponseMessage(); + StatusType procStatus = null; + String response = PMServiceDriver.getRoles(userConfigType,header); + logesapi.debug(response); + procStatus = msg.processResult(response); + if(procStatus.getType().equals("ERROR")) + return null; + // check that user has access to this project. + configureType = msg.readUserInfo(); + Iterator it = configureType.getUser().getProject().iterator(); + + //Set CRC Cell URL + for (CellDataType cell : configureType.getCellDatas().getCellData()) + { + if (cell.getId().equals("CRC")) + { + IMUtil.getInstance().setCRCEndpointReference(cell.getUrl()); + break; + } + + } + + //Set Security Type + log.debug("Setting security type needed for CRC"); + securityType = new SecurityType(); + securityType.setDomain(configureType.getUser().getDomain()); + securityType.setUsername(configureType.getUser().getUserName()); + edu.harvard.i2b2.im.datavo.i2b2message.PasswordType ptype = new edu.harvard.i2b2.im.datavo.i2b2message.PasswordType(); + ptype.setIsToken(configureType.getUser().getPassword().isIsToken()); + ptype.setTokenMsTimeout(configureType.getUser().getPassword().getTokenMsTimeout()); + ptype.setValue(configureType.getUser().getPassword().getValue()); + securityType.setPassword(ptype); + + while (it.hasNext()) + { + projectType = (ProjectType)it.next(); + if (projectType.getId().equals(header.getProjectId())) { + // log.info(header.getProjectId()); + // log.info(projectType.getId()); + //If admin add role of admin + if (configureType.getUser().isIsAdmin()) + projectType.getRole().add("ADMIN"); + break; + } + projectType = null; + + } + + // projectType = pmConfigure.getUser().getProject().get(0); + } catch (AxisFault e) { + log.error("Cant connect to PM service"); + } catch (I2B2Exception e) { + log.error("Problem processing PM service address"); + } catch (Exception e) { + log.error("General PM processing problem: "+ e.getMessage()); + } + + return projectType; + } + + public void setDbInfo(MessageHeaderType requestMessageHeader) throws I2B2Exception{ + + DataSourceLookupHelper dsHelper = new DataSourceLookupHelper(); + this.dbInfo = + dsHelper.matchDataSource(requestMessageHeader.getSecurity().getDomain(), + requestMessageHeader.getProjectId(), + requestMessageHeader.getSecurity().getUsername()); + } + + + public DBInfoType getDbInfo() { + return this.dbInfo; + } + + public String getMetadata_dataSource() { + return dbInfo.getDb_dataSource(); + } + + + public String getMetadata_fullSchema() { + return dbInfo.getDb_fullSchema(); + } + + public String getMetadata_serverType() { + return dbInfo.getDb_serverType(); + } +} diff --git a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/delegate/SetDblookupHandler.java b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/delegate/SetDblookupHandler.java similarity index 100% rename from edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/delegate/SetDblookupHandler.java rename to edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/delegate/SetDblookupHandler.java diff --git a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/delegate/SetKeyHandlerHandler.java b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/delegate/SetKeyHandlerHandler.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/delegate/SetKeyHandlerHandler.java rename to edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/delegate/SetKeyHandlerHandler.java diff --git a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/delegate/ValidationHandlerHandler.java b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/delegate/ValidationHandlerHandler.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/delegate/ValidationHandlerHandler.java rename to edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/delegate/ValidationHandlerHandler.java diff --git a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/delegate/crc/CallCRCUtil.java b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/delegate/crc/CallCRCUtil.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/delegate/crc/CallCRCUtil.java rename to edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/delegate/crc/CallCRCUtil.java index a82d4ab8..b735a1a2 --- a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/delegate/crc/CallCRCUtil.java +++ b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/delegate/crc/CallCRCUtil.java @@ -1,151 +1,151 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.im.delegate.crc; - -import java.io.StringReader; -import java.io.StringWriter; - -import javax.xml.stream.XMLInputFactory; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamReader; - -import org.apache.axiom.om.OMAbstractFactory; -import org.apache.axiom.om.OMElement; -import org.apache.axiom.om.OMFactory; -import org.apache.axiom.om.OMXMLBuilderFactory; - -import edu.harvard.i2b2.common.util.axis2.ServiceClient; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.im.util.IMJAXBUtil; -import edu.harvard.i2b2.im.util.IMUtil; -import edu.harvard.i2b2.im.ws.PDORequestMessage; - - -import edu.harvard.i2b2.im.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.im.datavo.i2b2message.SecurityType; - - -public class CallCRCUtil { - - // private SecurityType securityType = null; - // private String projectId = null; - //private String crcUrl = null; - static IMUtil workplaceUtil = IMUtil.getInstance(); - private static Log log = LogFactory.getLog(CallCRCUtil.class); - protected static final Log logesapi = LogFactory.getLog(CallCRCUtil.class); - - - public static String callCRCPDORequest(PDORequestMessage getFoldersMsg) - throws I2B2Exception { - // ResultResponseType resultResponseType = null; - - String response = null; - try { - log.debug("begin build element"); - RequestMessageType requestMessageType = getFoldersMsg.getRequestMessageType();//getRequestMessageType(); - - // buildResultInstanceRequestXMLRequestMessage(resultInstanceID, securityType, projectId); - OMElement requestElement = buildOMElement(requestMessageType); - log.debug("callCRCQueryRequestXML - CRC setfinder query request XML call's request xml " - + requestElement); - response = getServiceClient("pdorequest", requestElement).toString(); - logesapi.debug("callCRCQueryRequestXML - CRC setfinder query request XML call's response xml " + response.toString()); - //resultResponseType = getResultResponseMessage(response.toString()); - //masterInstanceResultResponseType = getResponseMessage(response - // .toString()); - - } catch (JAXBUtilException jaxbEx) { - log.error(jaxbEx.getLocalizedMessage()); - throw new I2B2Exception("Error in CRC upload ", jaxbEx); - } catch (XMLStreamException e) { - log.error(e.getLocalizedMessage()); - throw new I2B2Exception("Error in CRC upload ", e); - - } catch (Exception e) { - log.error(e.getLocalizedMessage()); - e.printStackTrace(); - throw new I2B2Exception("Error in CRC upload ", e); - } finally { - - } - - return response; - } - - - public static String callCRCQueryRequestXML(String queryMasterId, SecurityType securityType, String projectId) - throws I2B2Exception { - // ResultResponseType resultResponseType = null; - //MasterResponseType masterInstanceResultResponseType = null; - String response = null; - try { - log.debug("begin build element"); - RequestMessageType requestMessageType = null; //buildSetfinderRequestXMLRequestMessage(queryMasterId, securityType, projectId); - OMElement requestElement = buildOMElement(requestMessageType); - log.debug("callCRCQueryRequestXML - CRC setfinder query request XML call's request xml " - + requestElement); - response = getServiceClient("/request", requestElement).toString(); - - //log.debug("callCRCQueryRequestXML - CRC setfinder query request XML call's response xml " + response.toString()); - //resultResponseType = getResultResponseMessage(response.toString()); - //masterInstanceResultResponseType = getMasterInstanceResultResponseMessage(response - // .toString()); - - } catch (JAXBUtilException jaxbEx) { - log.error(jaxbEx.getLocalizedMessage()); - throw new I2B2Exception("Error in CRC upload ", jaxbEx); - } catch (XMLStreamException e) { - log.error(e.getLocalizedMessage()); - throw new I2B2Exception("Error in CRC upload ", e); - - } catch (Exception e) { - log.error(e.getLocalizedMessage()); - throw new I2B2Exception("Error in CRC upload ", e); - } finally { - - } - return response; - } - - - private static OMElement buildOMElement(RequestMessageType requestMessageType) - throws XMLStreamException, JAXBUtilException { - StringWriter strWriter = new StringWriter(); - edu.harvard.i2b2.im.datavo.i2b2message.ObjectFactory hiveof = new edu.harvard.i2b2.im.datavo.i2b2message.ObjectFactory(); - IMJAXBUtil.getJAXBUtil().marshaller( - hiveof.createRequest(requestMessageType), strWriter); - // getOMElement from message - OMFactory fac = OMAbstractFactory.getOMFactory(); - - StringReader strReader = new StringReader(strWriter.toString()); - XMLInputFactory xif = XMLInputFactory.newInstance(); - XMLStreamReader reader = xif.createXMLStreamReader(strReader); - OMElement request = OMXMLBuilderFactory.createStAXOMBuilder(reader).getDocumentElement(); - - return request; - } - - private static String getServiceClient(String operationName, OMElement request) throws Exception { - // call - String response = null; - - - response = ServiceClient.sendREST(workplaceUtil.getCRCUrl() + operationName, request.toString()); - - return response; - - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.im.delegate.crc; + +import java.io.StringReader; +import java.io.StringWriter; + +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import org.apache.axiom.om.OMAbstractFactory; +import org.apache.axiom.om.OMElement; +import org.apache.axiom.om.OMFactory; +import org.apache.axiom.om.OMXMLBuilderFactory; + +import edu.harvard.i2b2.common.util.axis2.ServiceClient; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.im.util.IMJAXBUtil; +import edu.harvard.i2b2.im.util.IMUtil; +import edu.harvard.i2b2.im.ws.PDORequestMessage; + + +import edu.harvard.i2b2.im.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.im.datavo.i2b2message.SecurityType; + + +public class CallCRCUtil { + + // private SecurityType securityType = null; + // private String projectId = null; + //private String crcUrl = null; + static IMUtil workplaceUtil = IMUtil.getInstance(); + private static Log log = LogFactory.getLog(CallCRCUtil.class); + protected static final Log logesapi = LogFactory.getLog(CallCRCUtil.class); + + + public static String callCRCPDORequest(PDORequestMessage getFoldersMsg) + throws I2B2Exception { + // ResultResponseType resultResponseType = null; + + String response = null; + try { + log.debug("begin build element"); + RequestMessageType requestMessageType = getFoldersMsg.getRequestMessageType();//getRequestMessageType(); + + // buildResultInstanceRequestXMLRequestMessage(resultInstanceID, securityType, projectId); + OMElement requestElement = buildOMElement(requestMessageType); + log.debug("callCRCQueryRequestXML - CRC setfinder query request XML call's request xml " + + requestElement); + response = getServiceClient("pdorequest", requestElement).toString(); + logesapi.debug("callCRCQueryRequestXML - CRC setfinder query request XML call's response xml " + response.toString()); + //resultResponseType = getResultResponseMessage(response.toString()); + //masterInstanceResultResponseType = getResponseMessage(response + // .toString()); + + } catch (JAXBUtilException jaxbEx) { + log.error(jaxbEx.getLocalizedMessage()); + throw new I2B2Exception("Error in CRC upload ", jaxbEx); + } catch (XMLStreamException e) { + log.error(e.getLocalizedMessage()); + throw new I2B2Exception("Error in CRC upload ", e); + + } catch (Exception e) { + log.error(e.getLocalizedMessage()); + e.printStackTrace(); + throw new I2B2Exception("Error in CRC upload ", e); + } finally { + + } + + return response; + } + + + public static String callCRCQueryRequestXML(String queryMasterId, SecurityType securityType, String projectId) + throws I2B2Exception { + // ResultResponseType resultResponseType = null; + //MasterResponseType masterInstanceResultResponseType = null; + String response = null; + try { + log.debug("begin build element"); + RequestMessageType requestMessageType = null; //buildSetfinderRequestXMLRequestMessage(queryMasterId, securityType, projectId); + OMElement requestElement = buildOMElement(requestMessageType); + log.debug("callCRCQueryRequestXML - CRC setfinder query request XML call's request xml " + + requestElement); + response = getServiceClient("/request", requestElement).toString(); + + //log.debug("callCRCQueryRequestXML - CRC setfinder query request XML call's response xml " + response.toString()); + //resultResponseType = getResultResponseMessage(response.toString()); + //masterInstanceResultResponseType = getMasterInstanceResultResponseMessage(response + // .toString()); + + } catch (JAXBUtilException jaxbEx) { + log.error(jaxbEx.getLocalizedMessage()); + throw new I2B2Exception("Error in CRC upload ", jaxbEx); + } catch (XMLStreamException e) { + log.error(e.getLocalizedMessage()); + throw new I2B2Exception("Error in CRC upload ", e); + + } catch (Exception e) { + log.error(e.getLocalizedMessage()); + throw new I2B2Exception("Error in CRC upload ", e); + } finally { + + } + return response; + } + + + private static OMElement buildOMElement(RequestMessageType requestMessageType) + throws XMLStreamException, JAXBUtilException { + StringWriter strWriter = new StringWriter(); + edu.harvard.i2b2.im.datavo.i2b2message.ObjectFactory hiveof = new edu.harvard.i2b2.im.datavo.i2b2message.ObjectFactory(); + IMJAXBUtil.getJAXBUtil().marshaller( + hiveof.createRequest(requestMessageType), strWriter); + // getOMElement from message + OMFactory fac = OMAbstractFactory.getOMFactory(); + + StringReader strReader = new StringReader(strWriter.toString()); + XMLInputFactory xif = XMLInputFactory.newInstance(); + XMLStreamReader reader = xif.createXMLStreamReader(strReader); + OMElement request = OMXMLBuilderFactory.createStAXOMBuilder(reader).getDocumentElement(); + + return request; + } + + private static String getServiceClient(String operationName, OMElement request) throws Exception { + // call + String response = null; + + + response = ServiceClient.sendREST(workplaceUtil.getCRCUrl() + operationName, request.toString()); + + return response; + + } + +} diff --git a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/ejb/DBInfoType.java b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/ejb/DBInfoType.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/ejb/DBInfoType.java rename to edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/ejb/DBInfoType.java diff --git a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/ejb/DataSourceLookup.java b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/ejb/DataSourceLookup.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/ejb/DataSourceLookup.java rename to edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/ejb/DataSourceLookup.java diff --git a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/ejb/NodeType.java b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/ejb/NodeType.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/ejb/NodeType.java rename to edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/ejb/NodeType.java diff --git a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/util/CryptUtil.java b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/util/CryptUtil.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/util/CryptUtil.java rename to edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/util/CryptUtil.java diff --git a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/util/DateUtil.java b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/util/DateUtil.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/util/DateUtil.java rename to edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/util/DateUtil.java diff --git a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/util/EMPI.java b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/util/EMPI.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/util/EMPI.java rename to edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/util/EMPI.java diff --git a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/util/EMPIOpenEMPI.java b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/util/EMPIOpenEMPI.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/util/EMPIOpenEMPI.java rename to edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/util/EMPIOpenEMPI.java diff --git a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/util/HighEncryption.java b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/util/HighEncryption.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/util/HighEncryption.java rename to edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/util/HighEncryption.java diff --git a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/util/IMJAXBUtil.java b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/util/IMJAXBUtil.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/util/IMJAXBUtil.java rename to edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/util/IMJAXBUtil.java diff --git a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/util/IMUtil.java b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/util/IMUtil.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/util/IMUtil.java rename to edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/util/IMUtil.java diff --git a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/util/JAXBConstant.java b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/util/JAXBConstant.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/util/JAXBConstant.java rename to edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/util/JAXBConstant.java diff --git a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/util/RijndaelAlgorithm.java b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/util/RijndaelAlgorithm.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/util/RijndaelAlgorithm.java rename to edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/util/RijndaelAlgorithm.java diff --git a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/util/StringUtil.java b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/util/StringUtil.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/util/StringUtil.java rename to edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/util/StringUtil.java diff --git a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/util/UInt.java b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/util/UInt.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/util/UInt.java rename to edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/util/UInt.java diff --git a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/util/UInt64.java b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/util/UInt64.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/util/UInt64.java rename to edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/util/UInt64.java diff --git a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/ws/DeleteDblookupDataMessage.java b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/ws/DeleteDblookupDataMessage.java similarity index 100% rename from edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/ws/DeleteDblookupDataMessage.java rename to edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/ws/DeleteDblookupDataMessage.java diff --git a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/ws/ExecutorRunnable.java b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/ws/ExecutorRunnable.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/ws/ExecutorRunnable.java rename to edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/ws/ExecutorRunnable.java diff --git a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/ws/GetAllDblookupsDataMessage.java b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/ws/GetAllDblookupsDataMessage.java similarity index 100% rename from edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/ws/GetAllDblookupsDataMessage.java rename to edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/ws/GetAllDblookupsDataMessage.java diff --git a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/ws/GetAuditRequestMessage.java b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/ws/GetAuditRequestMessage.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/ws/GetAuditRequestMessage.java rename to edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/ws/GetAuditRequestMessage.java diff --git a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/ws/GetDblookupDataMessage.java b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/ws/GetDblookupDataMessage.java similarity index 100% rename from edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/ws/GetDblookupDataMessage.java rename to edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/ws/GetDblookupDataMessage.java diff --git a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/ws/IMService.java b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/ws/IMService.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/ws/IMService.java rename to edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/ws/IMService.java diff --git a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/ws/IsKeySetRequestMessage.java b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/ws/IsKeySetRequestMessage.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/ws/IsKeySetRequestMessage.java rename to edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/ws/IsKeySetRequestMessage.java diff --git a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/ws/MessageFactory.java b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/ws/MessageFactory.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/ws/MessageFactory.java rename to edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/ws/MessageFactory.java diff --git a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/ws/PDORequestMessage.java b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/ws/PDORequestMessage.java old mode 100755 new mode 100644 similarity index 98% rename from edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/ws/PDORequestMessage.java rename to edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/ws/PDORequestMessage.java index c910122e..3a1f0612 --- a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/ws/PDORequestMessage.java +++ b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/ws/PDORequestMessage.java @@ -30,7 +30,7 @@ import edu.harvard.i2b2.im.datavo.pdo.query.RequestType; import edu.harvard.i2b2.im.datavo.pm.GetUserConfigurationType; import edu.harvard.i2b2.im.util.IMJAXBUtil; -import edu.harvard.i2b2.pm.ws.ProjectManagementRequestData; +import edu.harvard.i2b2.impm.ws.ProjectManagementRequestData; /** diff --git a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/ws/PDOResponseMessage.java b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/ws/PDOResponseMessage.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/ws/PDOResponseMessage.java rename to edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/ws/PDOResponseMessage.java index f05acb06..ef291754 --- a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/ws/PDOResponseMessage.java +++ b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/ws/PDOResponseMessage.java @@ -1,108 +1,108 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * - * Michael Mendis - * - */ - -package edu.harvard.i2b2.im.ws; - -import java.io.StringWriter; -import java.util.List; - -import jakarta.xml.bind.JAXBElement; - -import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.im.util.IMJAXBUtil; -import edu.harvard.i2b2.im.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.im.datavo.i2b2message.MessageHeaderType; -import edu.harvard.i2b2.im.datavo.i2b2message.RequestHeaderType; -import edu.harvard.i2b2.im.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.im.datavo.i2b2message.ResponseHeaderType; -import edu.harvard.i2b2.im.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.im.datavo.i2b2message.StatusType; -import edu.harvard.i2b2.im.datavo.pdo.EventSet; -import edu.harvard.i2b2.im.datavo.pdo.ObservationSet; -import edu.harvard.i2b2.im.datavo.pdo.PatientDataType; -import edu.harvard.i2b2.im.datavo.pdo.PatientSet; -import edu.harvard.i2b2.im.datavo.pdo.PidSet; -import edu.harvard.i2b2.im.datavo.pdo.PidType; -import edu.harvard.i2b2.im.datavo.pdo.query.GetPDOFromInputListRequestType; -import edu.harvard.i2b2.im.datavo.pdo.query.PatientDataResponseType; - -public class PDOResponseMessage extends ResponseDataMessage{ - - public PDOResponseMessage() { - } - - - /** - * Function to build PM Request message type and return it as an XML string - * - * @param GetUserConfigurationType (user config data) - * @return A String data type containing the PM RequestMessage in XML format - */ - public String doBuildXML(PatientDataResponseType userConfig, MessageHeaderType header){ - String requestString = null; - try { - MessageHeaderType messageHeader = getMessageHeader(); - - messageHeader.setSecurity(header.getSecurity()); - messageHeader.setProjectId(header.getProjectId()); - - ResponseHeaderType reqHeader = getResponseHeader(); - BodyType bodyType = getBodyType(userConfig) ; - ResponseMessageType reqMessageType = getResponseMessageType(messageHeader, - reqHeader, bodyType); - - JAXBUtil jaxbUtil = IMJAXBUtil.getJAXBUtil(); - StringWriter strWriter = new StringWriter(); - try { - edu.harvard.i2b2.im.datavo.i2b2message.ObjectFactory of = new edu.harvard.i2b2.im.datavo.i2b2message.ObjectFactory(); - jaxbUtil.marshaller(of.createResponse(reqMessageType), strWriter); - } catch (Exception e) { - log.error(e.getMessage()); - e.printStackTrace(); - } - requestString = strWriter.toString(); - } catch (Exception e) { - log.error(e.getMessage()); - } - return requestString; - } - - public BodyType getBodyType(PatientDataResponseType userConfigurationType) { - edu.harvard.i2b2.im.datavo.pdo.query.ObjectFactory of = new edu.harvard.i2b2.im.datavo.pdo.query.ObjectFactory(); - - BodyType bodyType = new BodyType(); - bodyType.getAny().add(of.createResponse(userConfigurationType)); - return bodyType; - } - - public PatientDataResponseType getPatientDataFromResponseXML(String responseXML) - throws Exception { - - JAXBUtil jaxbUtil = IMJAXBUtil.getJAXBUtil(); - - JAXBElement jaxbElement = jaxbUtil.unMashallFromString(responseXML); - ResponseMessageType messageType = (ResponseMessageType) jaxbElement - .getValue(); - BodyType bodyType = messageType.getMessageBody(); - PatientDataResponseType responseType = (PatientDataResponseType) new JAXBUnWrapHelper() - .getObjectByClass(bodyType.getAny(), - PatientDataResponseType.class); - return responseType; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * + * Michael Mendis + * + */ + +package edu.harvard.i2b2.im.ws; + +import java.io.StringWriter; +import java.util.List; + +import jakarta.xml.bind.JAXBElement; + +import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.im.util.IMJAXBUtil; +import edu.harvard.i2b2.im.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.im.datavo.i2b2message.MessageHeaderType; +import edu.harvard.i2b2.im.datavo.i2b2message.RequestHeaderType; +import edu.harvard.i2b2.im.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.im.datavo.i2b2message.ResponseHeaderType; +import edu.harvard.i2b2.im.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.im.datavo.i2b2message.StatusType; +import edu.harvard.i2b2.im.datavo.pdo.EventSet; +import edu.harvard.i2b2.im.datavo.pdo.ObservationSet; +import edu.harvard.i2b2.im.datavo.pdo.PatientDataType; +import edu.harvard.i2b2.im.datavo.pdo.PatientSet; +import edu.harvard.i2b2.im.datavo.pdo.PidSet; +import edu.harvard.i2b2.im.datavo.pdo.PidType; +import edu.harvard.i2b2.im.datavo.pdo.query.GetPDOFromInputListRequestType; +import edu.harvard.i2b2.im.datavo.pdo.query.PatientDataResponseType; + +public class PDOResponseMessage extends ResponseDataMessage{ + + public PDOResponseMessage() { + } + + + /** + * Function to build PM Request message type and return it as an XML string + * + * @param GetUserConfigurationType (user config data) + * @return A String data type containing the PM RequestMessage in XML format + */ + public String doBuildXML(PatientDataResponseType userConfig, MessageHeaderType header){ + String requestString = null; + try { + MessageHeaderType messageHeader = getMessageHeader(); + + messageHeader.setSecurity(header.getSecurity()); + messageHeader.setProjectId(header.getProjectId()); + + ResponseHeaderType reqHeader = getResponseHeader(); + BodyType bodyType = getBodyType(userConfig) ; + ResponseMessageType reqMessageType = getResponseMessageType(messageHeader, + reqHeader, bodyType); + + JAXBUtil jaxbUtil = IMJAXBUtil.getJAXBUtil(); + StringWriter strWriter = new StringWriter(); + try { + edu.harvard.i2b2.im.datavo.i2b2message.ObjectFactory of = new edu.harvard.i2b2.im.datavo.i2b2message.ObjectFactory(); + jaxbUtil.marshaller(of.createResponse(reqMessageType), strWriter); + } catch (Exception e) { + log.error(e.getMessage()); + e.printStackTrace(); + } + requestString = strWriter.toString(); + } catch (Exception e) { + log.error(e.getMessage()); + } + return requestString; + } + + public BodyType getBodyType(PatientDataResponseType userConfigurationType) { + edu.harvard.i2b2.im.datavo.pdo.query.ObjectFactory of = new edu.harvard.i2b2.im.datavo.pdo.query.ObjectFactory(); + + BodyType bodyType = new BodyType(); + bodyType.getAny().add(of.createResponse(userConfigurationType)); + return bodyType; + } + + public PatientDataResponseType getPatientDataFromResponseXML(String responseXML) + throws Exception { + + JAXBUtil jaxbUtil = IMJAXBUtil.getJAXBUtil(); + + JAXBElement jaxbElement = jaxbUtil.unMashallFromString(responseXML); + ResponseMessageType messageType = (ResponseMessageType) jaxbElement + .getValue(); + BodyType bodyType = messageType.getMessageBody(); + PatientDataResponseType responseType = (PatientDataResponseType) new JAXBUnWrapHelper() + .getObjectByClass(bodyType.getAny(), + PatientDataResponseType.class); + return responseType; + } + +} diff --git a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/ws/RequestDataMessage.java b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/ws/RequestDataMessage.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/ws/RequestDataMessage.java rename to edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/ws/RequestDataMessage.java index 702057c8..d3dfc8d7 --- a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/ws/RequestDataMessage.java +++ b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/ws/RequestDataMessage.java @@ -1,177 +1,177 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Raj Kuttan - * Lori Phillips - */ -package edu.harvard.i2b2.im.ws; - -import java.io.StringWriter; -import java.math.BigDecimal; -import java.util.Date; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.DTOFactory; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.im.util.IMJAXBUtil; -import edu.harvard.i2b2.im.datavo.i2b2message.ApplicationType; -import edu.harvard.i2b2.im.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.im.datavo.i2b2message.FacilityType; -import edu.harvard.i2b2.im.datavo.i2b2message.MessageControlIdType; -import edu.harvard.i2b2.im.datavo.i2b2message.MessageHeaderType; -import edu.harvard.i2b2.im.datavo.i2b2message.ProcessingIdType; -import edu.harvard.i2b2.im.datavo.i2b2message.RequestHeaderType; -import edu.harvard.i2b2.im.datavo.i2b2message.RequestMessageType; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import jakarta.xml.bind.JAXBElement; - - -/** - * The RequestDataMessage class is a helper class to build Workplace messages in the - * i2b2 format - */ -public abstract class RequestDataMessage{ - protected final Log log = LogFactory.getLog(getClass()); - - public RequestMessageType reqMessageType = null; - - public void setRequestMessageType(String requestWdo) throws I2B2Exception { - try { - JAXBElement jaxbElement = IMJAXBUtil.getJAXBUtil().unMashallFromString(requestWdo); - this.reqMessageType = (RequestMessageType) jaxbElement.getValue(); - - } catch (JAXBUtilException e) { - throw new I2B2Exception("Umarshaller error: " + e.getMessage() + - requestWdo, e); - } - } - - - /** - * Function to build i2b2 message header - * - * @return MessageHeader object - */ - public MessageHeaderType getMessageHeader() { - MessageHeaderType messageHeader = new MessageHeaderType(); - - messageHeader.setI2B2VersionCompatible(new BigDecimal("1.1")); - messageHeader.setHl7VersionCompatible(new BigDecimal("2.4")); - - ApplicationType appType = new ApplicationType(); - appType.setApplicationName("IM Cell"); - appType.setApplicationVersion("1.700"); - messageHeader.setSendingApplication(appType); - - FacilityType facility = new FacilityType(); - facility.setFacilityName("i2b2 Hive"); - messageHeader.setSendingFacility(facility); - - ApplicationType appType2 = new ApplicationType(); - appType2.setApplicationVersion("1.700"); - appType2.setApplicationName("Project Management Cell"); - messageHeader.setReceivingApplication(appType2); - - FacilityType facility2 = new FacilityType(); - facility2.setFacilityName("i2b2 Hive"); - messageHeader.setReceivingFacility(facility2); - - Date currentDate = new Date(); - DTOFactory factory = new DTOFactory(); - messageHeader.setDatetimeOfMessage(factory.getXMLGregorianCalendar(currentDate.getTime())); - - MessageControlIdType mcIdType = new MessageControlIdType(); - mcIdType.setInstanceNum(0); - mcIdType.setMessageNum(generateMessageId()); - messageHeader.setMessageControlId(mcIdType); - - ProcessingIdType proc = new ProcessingIdType(); - proc.setProcessingId("P"); - proc.setProcessingMode("I"); - messageHeader.setProcessingId(proc); - - messageHeader.setAcceptAcknowledgementType("AL"); - messageHeader.setApplicationAcknowledgementType("AL"); - messageHeader.setCountryCode("US"); - - return messageHeader; - } - - /** - * Function to generate i2b2 message header message number - * - * @return String - */ - protected String generateMessageId() { - StringWriter strWriter = new StringWriter(); - for(int i=0; i<20; i++) { - int num = getValidAcsiiValue(); - strWriter.append((char)num); - } - return strWriter.toString(); - } - /** - * Function to build i2b2 Request message header - * - * @return RequestHeader object - */ - public RequestHeaderType getRequestHeader() { - RequestHeaderType reqHeader = new RequestHeaderType(); - reqHeader.setResultWaittimeMs(120000); - return reqHeader; - } - - - /** - * Function to build Request message type - * - * @param messageHeader MessageHeader object - * @param reqHeader RequestHeader object - * @param bodyType BodyType object - * @return RequestMessageType object - */ - public RequestMessageType getRequestMessageType(MessageHeaderType messageHeader, - RequestHeaderType reqHeader, BodyType bodyType) { - RequestMessageType reqMsgType = new RequestMessageType(); - reqMsgType.setMessageHeader(messageHeader); - reqMsgType.setMessageBody(bodyType); - reqMsgType.setRequestHeader(reqHeader); - return reqMsgType; - } - - /** - * Function to generate random number used in message number - * - * @return int - */ - private int getValidAcsiiValue() { - int number = 48; - while(true) { - number = 48+(int) Math.round(Math.random() * 74); - if((number > 47 && number < 58) || (number > 64 && number < 91) - || (number > 96 && number < 123)) { - break; - } - } - return number; - } - public RequestMessageType getRequestMessageType() { - return reqMessageType; - } - - public MessageHeaderType getMessageHeaderType() { - return reqMessageType.getMessageHeader(); - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Raj Kuttan + * Lori Phillips + */ +package edu.harvard.i2b2.im.ws; + +import java.io.StringWriter; +import java.math.BigDecimal; +import java.util.Date; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.DTOFactory; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.im.util.IMJAXBUtil; +import edu.harvard.i2b2.im.datavo.i2b2message.ApplicationType; +import edu.harvard.i2b2.im.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.im.datavo.i2b2message.FacilityType; +import edu.harvard.i2b2.im.datavo.i2b2message.MessageControlIdType; +import edu.harvard.i2b2.im.datavo.i2b2message.MessageHeaderType; +import edu.harvard.i2b2.im.datavo.i2b2message.ProcessingIdType; +import edu.harvard.i2b2.im.datavo.i2b2message.RequestHeaderType; +import edu.harvard.i2b2.im.datavo.i2b2message.RequestMessageType; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import jakarta.xml.bind.JAXBElement; + + +/** + * The RequestDataMessage class is a helper class to build Workplace messages in the + * i2b2 format + */ +public abstract class RequestDataMessage{ + protected final Log log = LogFactory.getLog(getClass()); + + public RequestMessageType reqMessageType = null; + + public void setRequestMessageType(String requestWdo) throws I2B2Exception { + try { + JAXBElement jaxbElement = IMJAXBUtil.getJAXBUtil().unMashallFromString(requestWdo); + this.reqMessageType = (RequestMessageType) jaxbElement.getValue(); + + } catch (JAXBUtilException e) { + throw new I2B2Exception("Umarshaller error: " + e.getMessage() + + requestWdo, e); + } + } + + + /** + * Function to build i2b2 message header + * + * @return MessageHeader object + */ + public MessageHeaderType getMessageHeader() { + MessageHeaderType messageHeader = new MessageHeaderType(); + + messageHeader.setI2B2VersionCompatible(new BigDecimal("1.1")); + messageHeader.setHl7VersionCompatible(new BigDecimal("2.4")); + + ApplicationType appType = new ApplicationType(); + appType.setApplicationName("IM Cell"); + appType.setApplicationVersion("1.700"); + messageHeader.setSendingApplication(appType); + + FacilityType facility = new FacilityType(); + facility.setFacilityName("i2b2 Hive"); + messageHeader.setSendingFacility(facility); + + ApplicationType appType2 = new ApplicationType(); + appType2.setApplicationVersion("1.700"); + appType2.setApplicationName("Project Management Cell"); + messageHeader.setReceivingApplication(appType2); + + FacilityType facility2 = new FacilityType(); + facility2.setFacilityName("i2b2 Hive"); + messageHeader.setReceivingFacility(facility2); + + Date currentDate = new Date(); + DTOFactory factory = new DTOFactory(); + messageHeader.setDatetimeOfMessage(factory.getXMLGregorianCalendar(currentDate.getTime())); + + MessageControlIdType mcIdType = new MessageControlIdType(); + mcIdType.setInstanceNum(0); + mcIdType.setMessageNum(generateMessageId()); + messageHeader.setMessageControlId(mcIdType); + + ProcessingIdType proc = new ProcessingIdType(); + proc.setProcessingId("P"); + proc.setProcessingMode("I"); + messageHeader.setProcessingId(proc); + + messageHeader.setAcceptAcknowledgementType("AL"); + messageHeader.setApplicationAcknowledgementType("AL"); + messageHeader.setCountryCode("US"); + + return messageHeader; + } + + /** + * Function to generate i2b2 message header message number + * + * @return String + */ + protected String generateMessageId() { + StringWriter strWriter = new StringWriter(); + for(int i=0; i<20; i++) { + int num = getValidAcsiiValue(); + strWriter.append((char)num); + } + return strWriter.toString(); + } + /** + * Function to build i2b2 Request message header + * + * @return RequestHeader object + */ + public RequestHeaderType getRequestHeader() { + RequestHeaderType reqHeader = new RequestHeaderType(); + reqHeader.setResultWaittimeMs(120000); + return reqHeader; + } + + + /** + * Function to build Request message type + * + * @param messageHeader MessageHeader object + * @param reqHeader RequestHeader object + * @param bodyType BodyType object + * @return RequestMessageType object + */ + public RequestMessageType getRequestMessageType(MessageHeaderType messageHeader, + RequestHeaderType reqHeader, BodyType bodyType) { + RequestMessageType reqMsgType = new RequestMessageType(); + reqMsgType.setMessageHeader(messageHeader); + reqMsgType.setMessageBody(bodyType); + reqMsgType.setRequestHeader(reqHeader); + return reqMsgType; + } + + /** + * Function to generate random number used in message number + * + * @return int + */ + private int getValidAcsiiValue() { + int number = 48; + while(true) { + number = 48+(int) Math.round(Math.random() * 74); + if((number > 47 && number < 58) || (number > 64 && number < 91) + || (number > 96 && number < 123)) { + break; + } + } + return number; + } + public RequestMessageType getRequestMessageType() { + return reqMessageType; + } + + public MessageHeaderType getMessageHeaderType() { + return reqMessageType.getMessageHeader(); + } + +} diff --git a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/ws/ResponseDataMessage.java b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/ws/ResponseDataMessage.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/ws/ResponseDataMessage.java rename to edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/ws/ResponseDataMessage.java index b9b3173c..42b18525 --- a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/ws/ResponseDataMessage.java +++ b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/ws/ResponseDataMessage.java @@ -1,189 +1,189 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Raj Kuttan - * Lori Phillips - */ -package edu.harvard.i2b2.im.ws; - -import java.io.StringWriter; -import java.math.BigDecimal; -import java.security.SecureRandom; -import java.util.Date; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.DTOFactory; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.im.util.IMJAXBUtil; -import edu.harvard.i2b2.im.datavo.i2b2message.ApplicationType; -import edu.harvard.i2b2.im.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.im.datavo.i2b2message.FacilityType; -import edu.harvard.i2b2.im.datavo.i2b2message.MessageControlIdType; -import edu.harvard.i2b2.im.datavo.i2b2message.MessageHeaderType; -import edu.harvard.i2b2.im.datavo.i2b2message.ProcessingIdType; -import edu.harvard.i2b2.im.datavo.i2b2message.ResponseHeaderType; -import edu.harvard.i2b2.im.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.im.datavo.i2b2message.ResultStatusType; -import edu.harvard.i2b2.im.datavo.i2b2message.StatusType; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import jakarta.xml.bind.JAXBElement; - - -/** - * The ResponseDataMessage class is a helper class to build Workplace messages in the - * i2b2 format - */ -public abstract class ResponseDataMessage{ - protected final Log log = LogFactory.getLog(getClass()); - - public ResponseMessageType reqMessageType = null; - - public void setResponseMessageType(String responseWdo) throws I2B2Exception { - try { - JAXBElement jaxbElement = IMJAXBUtil.getJAXBUtil().unMashallFromString(responseWdo); - this.reqMessageType = (ResponseMessageType) jaxbElement.getValue(); - - } catch (JAXBUtilException e) { - throw new I2B2Exception("Umarshaller error: " + e.getMessage() + - responseWdo, e); - } - } - - - /** - * Function to build i2b2 message header - * - * @return MessageHeader object - */ - public MessageHeaderType getMessageHeader() { - MessageHeaderType messageHeader = new MessageHeaderType(); - - messageHeader.setI2B2VersionCompatible(new BigDecimal("1.1")); - messageHeader.setHl7VersionCompatible(new BigDecimal("2.4")); - - ApplicationType appType = new ApplicationType(); - appType.setApplicationName("IM Cell"); - appType.setApplicationVersion("1.700"); - messageHeader.setSendingApplication(appType); - - FacilityType facility = new FacilityType(); - facility.setFacilityName("i2b2 Hive"); - messageHeader.setSendingFacility(facility); - - ApplicationType appType2 = new ApplicationType(); - appType2.setApplicationVersion("1.700"); - appType2.setApplicationName("Project Management Cell"); - messageHeader.setReceivingApplication(appType2); - - FacilityType facility2 = new FacilityType(); - facility2.setFacilityName("i2b2 Hive"); - messageHeader.setReceivingFacility(facility2); - - Date currentDate = new Date(); - DTOFactory factory = new DTOFactory(); - messageHeader.setDatetimeOfMessage(factory.getXMLGregorianCalendar(currentDate.getTime())); - - MessageControlIdType mcIdType = new MessageControlIdType(); - mcIdType.setInstanceNum(0); - mcIdType.setMessageNum(generateMessageId()); - messageHeader.setMessageControlId(mcIdType); - - ProcessingIdType proc = new ProcessingIdType(); - proc.setProcessingId("P"); - proc.setProcessingMode("I"); - messageHeader.setProcessingId(proc); - - messageHeader.setAcceptAcknowledgementType("AL"); - messageHeader.setApplicationAcknowledgementType("AL"); - messageHeader.setCountryCode("US"); - - return messageHeader; - } - - /** - * Function to generate i2b2 message header message number - * - * @return String - */ - protected String generateMessageId() { - StringWriter strWriter = new StringWriter(); - for(int i=0; i<20; i++) { - int num = getValidAcsiiValue(); - strWriter.append((char)num); - } - return strWriter.toString(); - } - /** - * Function to build i2b2 Response message header - * - * @return ResponseHeader object - */ - public ResponseHeaderType getResponseHeader() { - ResponseHeaderType reqHeader = new ResponseHeaderType(); - - StatusType status = new StatusType(); - status.setType("DONE"); - status.setValue("DONE"); - - ResultStatusType resStat = new ResultStatusType(); - resStat.setStatus(status); - reqHeader.setResultStatus(resStat); - return reqHeader; - } - - - /** - * Function to build Response message type - * - * @param messageHeader MessageHeader object - * @param reqHeader ResponseHeader object - * @param bodyType BodyType object - * @return ResponseMessageType object - */ - public ResponseMessageType getResponseMessageType(MessageHeaderType messageHeader, - ResponseHeaderType reqHeader, BodyType bodyType) { - ResponseMessageType reqMsgType = new ResponseMessageType(); - reqMsgType.setMessageHeader(messageHeader); - reqMsgType.setMessageBody(bodyType); - reqMsgType.setResponseHeader(reqHeader); - return reqMsgType; - } - - /** - * Function to generate random number used in message number - * - * @return int - */ - private int getValidAcsiiValue() { - int number = 48; - while(true) { - SecureRandom random = new SecureRandom(); - - number = 48+(int) Math.round(random.nextDouble() * 74); - if((number > 47 && number < 58) || (number > 64 && number < 91) - || (number > 96 && number < 123)) { - break; - } - } - return number; - } - public ResponseMessageType getResponseMessageType() { - return reqMessageType; - } - - public MessageHeaderType getMessageHeaderType() { - return reqMessageType.getMessageHeader(); - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Raj Kuttan + * Lori Phillips + */ +package edu.harvard.i2b2.im.ws; + +import java.io.StringWriter; +import java.math.BigDecimal; +import java.security.SecureRandom; +import java.util.Date; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.DTOFactory; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.im.util.IMJAXBUtil; +import edu.harvard.i2b2.im.datavo.i2b2message.ApplicationType; +import edu.harvard.i2b2.im.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.im.datavo.i2b2message.FacilityType; +import edu.harvard.i2b2.im.datavo.i2b2message.MessageControlIdType; +import edu.harvard.i2b2.im.datavo.i2b2message.MessageHeaderType; +import edu.harvard.i2b2.im.datavo.i2b2message.ProcessingIdType; +import edu.harvard.i2b2.im.datavo.i2b2message.ResponseHeaderType; +import edu.harvard.i2b2.im.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.im.datavo.i2b2message.ResultStatusType; +import edu.harvard.i2b2.im.datavo.i2b2message.StatusType; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import jakarta.xml.bind.JAXBElement; + + +/** + * The ResponseDataMessage class is a helper class to build Workplace messages in the + * i2b2 format + */ +public abstract class ResponseDataMessage{ + protected final Log log = LogFactory.getLog(getClass()); + + public ResponseMessageType reqMessageType = null; + + public void setResponseMessageType(String responseWdo) throws I2B2Exception { + try { + JAXBElement jaxbElement = IMJAXBUtil.getJAXBUtil().unMashallFromString(responseWdo); + this.reqMessageType = (ResponseMessageType) jaxbElement.getValue(); + + } catch (JAXBUtilException e) { + throw new I2B2Exception("Umarshaller error: " + e.getMessage() + + responseWdo, e); + } + } + + + /** + * Function to build i2b2 message header + * + * @return MessageHeader object + */ + public MessageHeaderType getMessageHeader() { + MessageHeaderType messageHeader = new MessageHeaderType(); + + messageHeader.setI2B2VersionCompatible(new BigDecimal("1.1")); + messageHeader.setHl7VersionCompatible(new BigDecimal("2.4")); + + ApplicationType appType = new ApplicationType(); + appType.setApplicationName("IM Cell"); + appType.setApplicationVersion("1.700"); + messageHeader.setSendingApplication(appType); + + FacilityType facility = new FacilityType(); + facility.setFacilityName("i2b2 Hive"); + messageHeader.setSendingFacility(facility); + + ApplicationType appType2 = new ApplicationType(); + appType2.setApplicationVersion("1.700"); + appType2.setApplicationName("Project Management Cell"); + messageHeader.setReceivingApplication(appType2); + + FacilityType facility2 = new FacilityType(); + facility2.setFacilityName("i2b2 Hive"); + messageHeader.setReceivingFacility(facility2); + + Date currentDate = new Date(); + DTOFactory factory = new DTOFactory(); + messageHeader.setDatetimeOfMessage(factory.getXMLGregorianCalendar(currentDate.getTime())); + + MessageControlIdType mcIdType = new MessageControlIdType(); + mcIdType.setInstanceNum(0); + mcIdType.setMessageNum(generateMessageId()); + messageHeader.setMessageControlId(mcIdType); + + ProcessingIdType proc = new ProcessingIdType(); + proc.setProcessingId("P"); + proc.setProcessingMode("I"); + messageHeader.setProcessingId(proc); + + messageHeader.setAcceptAcknowledgementType("AL"); + messageHeader.setApplicationAcknowledgementType("AL"); + messageHeader.setCountryCode("US"); + + return messageHeader; + } + + /** + * Function to generate i2b2 message header message number + * + * @return String + */ + protected String generateMessageId() { + StringWriter strWriter = new StringWriter(); + for(int i=0; i<20; i++) { + int num = getValidAcsiiValue(); + strWriter.append((char)num); + } + return strWriter.toString(); + } + /** + * Function to build i2b2 Response message header + * + * @return ResponseHeader object + */ + public ResponseHeaderType getResponseHeader() { + ResponseHeaderType reqHeader = new ResponseHeaderType(); + + StatusType status = new StatusType(); + status.setType("DONE"); + status.setValue("DONE"); + + ResultStatusType resStat = new ResultStatusType(); + resStat.setStatus(status); + reqHeader.setResultStatus(resStat); + return reqHeader; + } + + + /** + * Function to build Response message type + * + * @param messageHeader MessageHeader object + * @param reqHeader ResponseHeader object + * @param bodyType BodyType object + * @return ResponseMessageType object + */ + public ResponseMessageType getResponseMessageType(MessageHeaderType messageHeader, + ResponseHeaderType reqHeader, BodyType bodyType) { + ResponseMessageType reqMsgType = new ResponseMessageType(); + reqMsgType.setMessageHeader(messageHeader); + reqMsgType.setMessageBody(bodyType); + reqMsgType.setResponseHeader(reqHeader); + return reqMsgType; + } + + /** + * Function to generate random number used in message number + * + * @return int + */ + private int getValidAcsiiValue() { + int number = 48; + while(true) { + SecureRandom random = new SecureRandom(); + + number = 48+(int) Math.round(random.nextDouble() * 74); + if((number > 47 && number < 58) || (number > 64 && number < 91) + || (number > 96 && number < 123)) { + break; + } + } + return number; + } + public ResponseMessageType getResponseMessageType() { + return reqMessageType; + } + + public MessageHeaderType getMessageHeaderType() { + return reqMessageType.getMessageHeader(); + } + +} diff --git a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/ws/SetDblookupDataMessage.java b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/ws/SetDblookupDataMessage.java similarity index 100% rename from edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/ws/SetDblookupDataMessage.java rename to edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/ws/SetDblookupDataMessage.java diff --git a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/ws/SetKeyRequestMessage.java b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/ws/SetKeyRequestMessage.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.im/src/edu/harvard/i2b2/im/ws/SetKeyRequestMessage.java rename to edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/im/ws/SetKeyRequestMessage.java diff --git a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/pm/ws/GetAllProjectRequestMessage.java b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/impm/ws/GetAllProjectRequestMessage.java old mode 100755 new mode 100644 similarity index 99% rename from edu.harvard.i2b2.im/src/edu/harvard/i2b2/pm/ws/GetAllProjectRequestMessage.java rename to edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/impm/ws/GetAllProjectRequestMessage.java index 401fdfdd..671478f5 --- a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/pm/ws/GetAllProjectRequestMessage.java +++ b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/impm/ws/GetAllProjectRequestMessage.java @@ -13,7 +13,7 @@ * Mike Mendis * Raj Kuttan */ -package edu.harvard.i2b2.pm.ws; +package edu.harvard.i2b2.impm.ws; import java.io.StringWriter; diff --git a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/pm/ws/GetUserConfigurationRequestMessage.java b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/impm/ws/GetUserConfigurationRequestMessage.java old mode 100755 new mode 100644 similarity index 99% rename from edu.harvard.i2b2.im/src/edu/harvard/i2b2/pm/ws/GetUserConfigurationRequestMessage.java rename to edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/impm/ws/GetUserConfigurationRequestMessage.java index 508d5cfc..a8866182 --- a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/pm/ws/GetUserConfigurationRequestMessage.java +++ b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/impm/ws/GetUserConfigurationRequestMessage.java @@ -13,7 +13,7 @@ * Mike Mendis * Raj Kuttan */ -package edu.harvard.i2b2.pm.ws; +package edu.harvard.i2b2.impm.ws; import java.io.StringWriter; diff --git a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/pm/ws/PMResponseMessage.java b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/impm/ws/PMResponseMessage.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.im/src/edu/harvard/i2b2/pm/ws/PMResponseMessage.java rename to edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/impm/ws/PMResponseMessage.java index 46299600..e62b90e3 --- a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/pm/ws/PMResponseMessage.java +++ b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/impm/ws/PMResponseMessage.java @@ -1,82 +1,82 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Mike Mendis - * Raj Kuttan - */ -package edu.harvard.i2b2.pm.ws; - -import jakarta.xml.bind.JAXBElement; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.im.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.im.datavo.i2b2message.ResponseHeaderType; -import edu.harvard.i2b2.im.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.im.datavo.i2b2message.StatusType; -import edu.harvard.i2b2.im.datavo.pm.ConfigureType; -import edu.harvard.i2b2.im.datavo.pm.ProjectType; -import edu.harvard.i2b2.im.datavo.pm.ProjectsType; -import edu.harvard.i2b2.im.util.IMJAXBUtil; - - -public class PMResponseMessage { - - public static final String THIS_CLASS_NAME = PMResponseMessage.class.getName(); - private Log log = LogFactory.getLog(THIS_CLASS_NAME); - private ResponseMessageType pmRespMessageType = null; - - public PMResponseMessage() {} - - public StatusType processResult(String response) { - StatusType status = null; - - JAXBElement jaxbElement; - try { - jaxbElement = IMJAXBUtil.getJAXBUtil().unMashallFromString(response); - } catch (JAXBUtilException e) { - return status; - } - - pmRespMessageType = (ResponseMessageType) jaxbElement.getValue(); - - // Get response message status - ResponseHeaderType responseHeader = pmRespMessageType.getResponseHeader(); - status = responseHeader.getResultStatus().getStatus(); - - return status; - } - - public ProjectsType readProjectsInfo() throws Exception { - ProjectsType pmResponse = null; - - BodyType bodyType = pmRespMessageType.getMessageBody(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - pmResponse = (ProjectsType)helper.getObjectByClass(bodyType.getAny(), ProjectsType.class); - - return pmResponse; - } - - public ConfigureType readUserInfo() throws Exception { - ConfigureType pmResponse = null; - - BodyType bodyType = pmRespMessageType.getMessageBody(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - pmResponse = (ConfigureType)helper.getObjectByClass(bodyType.getAny(), ConfigureType.class); - - return pmResponse; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Mike Mendis + * Raj Kuttan + */ +package edu.harvard.i2b2.impm.ws; + +import jakarta.xml.bind.JAXBElement; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.im.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.im.datavo.i2b2message.ResponseHeaderType; +import edu.harvard.i2b2.im.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.im.datavo.i2b2message.StatusType; +import edu.harvard.i2b2.im.datavo.pm.ConfigureType; +import edu.harvard.i2b2.im.datavo.pm.ProjectType; +import edu.harvard.i2b2.im.datavo.pm.ProjectsType; +import edu.harvard.i2b2.im.util.IMJAXBUtil; + + +public class PMResponseMessage { + + public static final String THIS_CLASS_NAME = PMResponseMessage.class.getName(); + private Log log = LogFactory.getLog(THIS_CLASS_NAME); + private ResponseMessageType pmRespMessageType = null; + + public PMResponseMessage() {} + + public StatusType processResult(String response) { + StatusType status = null; + + JAXBElement jaxbElement; + try { + jaxbElement = IMJAXBUtil.getJAXBUtil().unMashallFromString(response); + } catch (JAXBUtilException e) { + return status; + } + + pmRespMessageType = (ResponseMessageType) jaxbElement.getValue(); + + // Get response message status + ResponseHeaderType responseHeader = pmRespMessageType.getResponseHeader(); + status = responseHeader.getResultStatus().getStatus(); + + return status; + } + + public ProjectsType readProjectsInfo() throws Exception { + ProjectsType pmResponse = null; + + BodyType bodyType = pmRespMessageType.getMessageBody(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + pmResponse = (ProjectsType)helper.getObjectByClass(bodyType.getAny(), ProjectsType.class); + + return pmResponse; + } + + public ConfigureType readUserInfo() throws Exception { + ConfigureType pmResponse = null; + + BodyType bodyType = pmRespMessageType.getMessageBody(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + pmResponse = (ConfigureType)helper.getObjectByClass(bodyType.getAny(), ConfigureType.class); + + return pmResponse; + } + +} diff --git a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/pm/ws/PMServiceDriver.java b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/impm/ws/PMServiceDriver.java old mode 100755 new mode 100644 similarity index 99% rename from edu.harvard.i2b2.im/src/edu/harvard/i2b2/pm/ws/PMServiceDriver.java rename to edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/impm/ws/PMServiceDriver.java index 193eebb0..ae254fc7 --- a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/pm/ws/PMServiceDriver.java +++ b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/impm/ws/PMServiceDriver.java @@ -14,7 +14,7 @@ * Raj Kuttan * Lori Phillips */ -package edu.harvard.i2b2.pm.ws; +package edu.harvard.i2b2.impm.ws; import java.io.StringReader; diff --git a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/pm/ws/ProjectManagementRequestData.java b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/impm/ws/ProjectManagementRequestData.java old mode 100755 new mode 100644 similarity index 99% rename from edu.harvard.i2b2.im/src/edu/harvard/i2b2/pm/ws/ProjectManagementRequestData.java rename to edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/impm/ws/ProjectManagementRequestData.java index 922fca1e..3d486da4 --- a/edu.harvard.i2b2.im/src/edu/harvard/i2b2/pm/ws/ProjectManagementRequestData.java +++ b/edu.harvard.i2b2.im/src/main/java/edu/harvard/i2b2/impm/ws/ProjectManagementRequestData.java @@ -13,7 +13,7 @@ * Mike Mendis * Raj Kuttan */ -package edu.harvard.i2b2.pm.ws; +package edu.harvard.i2b2.impm.ws; import java.io.StringWriter; import java.math.BigDecimal; diff --git a/edu.harvard.i2b2.ontology/.classpath b/edu.harvard.i2b2.ontology/.classpath index b8ca79db..b9f6029d 100755 --- a/edu.harvard.i2b2.ontology/.classpath +++ b/edu.harvard.i2b2.ontology/.classpath @@ -1,152 +1,46 @@ - - - - - - - + - + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/edu.harvard.i2b2.ontology/.cvsignore b/edu.harvard.i2b2.ontology/.cvsignore deleted file mode 100755 index a1c59fed..00000000 --- a/edu.harvard.i2b2.ontology/.cvsignore +++ /dev/null @@ -1,4 +0,0 @@ -classes -gensrc -dist - diff --git a/edu.harvard.i2b2.ontology/.gitignore b/edu.harvard.i2b2.ontology/.gitignore deleted file mode 100644 index 840e7d31..00000000 --- a/edu.harvard.i2b2.ontology/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/classes/ diff --git a/edu.harvard.i2b2.ontology/.project b/edu.harvard.i2b2.ontology/.project index bd232686..3e02b58a 100755 --- a/edu.harvard.i2b2.ontology/.project +++ b/edu.harvard.i2b2.ontology/.project @@ -10,10 +10,14 @@ + + org.eclipse.m2e.core.maven2Builder + + + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature - - diff --git a/edu.harvard.i2b2.ontology/.settings/org.eclipse.jdt.core.prefs b/edu.harvard.i2b2.ontology/.settings/org.eclipse.jdt.core.prefs index c59d0c6a..cb635b1c 100644 --- a/edu.harvard.i2b2.ontology/.settings/org.eclipse.jdt.core.prefs +++ b/edu.harvard.i2b2.ontology/.settings/org.eclipse.jdt.core.prefs @@ -1,15 +1,8 @@ eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 -org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve org.eclipse.jdt.core.compiler.compliance=1.8 -org.eclipse.jdt.core.compiler.debug.lineNumber=generate -org.eclipse.jdt.core.compiler.debug.localVariable=generate -org.eclipse.jdt.core.compiler.debug.sourceFile=generate -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=warning +org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning +org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=ignore org.eclipse.jdt.core.compiler.release=disabled org.eclipse.jdt.core.compiler.source=1.8 diff --git a/edu.harvard.i2b2.ontology/.settings/org.hibernate.eclipse.console.prefs b/edu.harvard.i2b2.ontology/.settings/org.hibernate.eclipse.console.prefs deleted file mode 100644 index 21fefffa..00000000 --- a/edu.harvard.i2b2.ontology/.settings/org.hibernate.eclipse.console.prefs +++ /dev/null @@ -1,3 +0,0 @@ -default.configuration= -eclipse.preferences.version=1 -hibernate3.enabled=false diff --git a/edu.harvard.i2b2.ontology/LICENSE.txt b/edu.harvard.i2b2.ontology/LICENSE.txt deleted file mode 100644 index e5a5569a..00000000 --- a/edu.harvard.i2b2.ontology/LICENSE.txt +++ /dev/null @@ -1,406 +0,0 @@ -#------------------------------------------------------------------------------- -# Copyright (c) 2006-2018 Massachusetts General Hospital -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Mozilla Public License, -# v. 2.0. If a copy of the MPL was not distributed with this file, You can -# obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under -# the terms of the Healthcare Disclaimer. -#------------------------------------------------------------------------------- -Mozilla Public License, version 2.0 - -1. Definitions - -1.1. "Contributor" - - means each individual or legal entity that creates, contributes to the - creation of, or owns Covered Software. - -1.2. "Contributor Version" - - means the combination of the Contributions of others (if any) used by a - Contributor and that particular Contributor's Contribution. - -1.3. "Contribution" - - means Covered Software of a particular Contributor. - -1.4. "Covered Software" - - means Source Code Form to which the initial Contributor has attached the - notice in Exhibit A, the Executable Form of such Source Code Form, and - Modifications of such Source Code Form, in each case including portions - thereof. - -1.5. "Incompatible With Secondary Licenses" - means - - a. that the initial Contributor has attached the notice described in - Exhibit B to the Covered Software; or - - b. that the Covered Software was made available under the terms of - version 1.1 or earlier of the License, but not also under the terms of - a Secondary License. - -1.6. "Executable Form" - - means any form of the work other than Source Code Form. - -1.7. "Larger Work" - - means a work that combines Covered Software with other material, in a - separate file or files, that is not Covered Software. - -1.8. "License" - - means this document. - -1.9. "Licensable" - - means having the right to grant, to the maximum extent possible, whether - at the time of the initial grant or subsequently, any and all of the - rights conveyed by this License. - -1.10. "Modifications" - - means any of the following: - - a. any file in Source Code Form that results from an addition to, - deletion from, or modification of the contents of Covered Software; or - - b. any new file in Source Code Form that contains any Covered Software. - -1.11. "Patent Claims" of a Contributor - - means any patent claim(s), including without limitation, method, - process, and apparatus claims, in any patent Licensable by such - Contributor that would be infringed, but for the grant of the License, - by the making, using, selling, offering for sale, having made, import, - or transfer of either its Contributions or its Contributor Version. - -1.12. "Secondary License" - - means either the GNU General Public License, Version 2.0, the GNU Lesser - General Public License, Version 2.1, the GNU Affero General Public - License, Version 3.0, or any later versions of those licenses. - -1.13. "Source Code Form" - - means the form of the work preferred for making modifications. - -1.14. "You" (or "Your") - - means an individual or a legal entity exercising rights under this - License. For legal entities, "You" includes any entity that controls, is - controlled by, or is under common control with You. For purposes of this - definition, "control" means (a) the power, direct or indirect, to cause - the direction or management of such entity, whether by contract or - otherwise, or (b) ownership of more than fifty percent (50%) of the - outstanding shares or beneficial ownership of such entity. - - -2. License Grants and Conditions - -2.1. Grants - - Each Contributor hereby grants You a world-wide, royalty-free, - non-exclusive license: - - a. under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or - as part of a Larger Work; and - - b. under Patent Claims of such Contributor to make, use, sell, offer for - sale, have made, import, and otherwise transfer either its - Contributions or its Contributor Version. - -2.2. Effective Date - - The licenses granted in Section 2.1 with respect to any Contribution - become effective for each Contribution on the date the Contributor first - distributes such Contribution. - -2.3. Limitations on Grant Scope - - The licenses granted in this Section 2 are the only rights granted under - this License. No additional rights or licenses will be implied from the - distribution or licensing of Covered Software under this License. - Notwithstanding Section 2.1(b) above, no patent license is granted by a - Contributor: - - a. for any code that a Contributor has removed from Covered Software; or - - b. for infringements caused by: (i) Your and any other third party's - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - - c. under Patent Claims infringed by Covered Software in the absence of - its Contributions. - - This License does not grant any rights in the trademarks, service marks, - or logos of any Contributor (except as may be necessary to comply with - the notice requirements in Section 3.4). - -2.4. Subsequent Licenses - - No Contributor makes additional grants as a result of Your choice to - distribute the Covered Software under a subsequent version of this - License (see Section 10.2) or under the terms of a Secondary License (if - permitted under the terms of Section 3.3). - -2.5. Representation - - Each Contributor represents that the Contributor believes its - Contributions are its original creation(s) or it has sufficient rights to - grant the rights to its Contributions conveyed by this License. - -2.6. Fair Use - - This License is not intended to limit any rights You have under - applicable copyright doctrines of fair use, fair dealing, or other - equivalents. - -2.7. Conditions - - Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in - Section 2.1. - - -3. Responsibilities - -3.1. Distribution of Source Form - - All distribution of Covered Software in Source Code Form, including any - Modifications that You create or to which You contribute, must be under - the terms of this License. You must inform recipients that the Source - Code Form of the Covered Software is governed by the terms of this - License, and how they can obtain a copy of this License. You may not - attempt to alter or restrict the recipients' rights in the Source Code - Form. - -3.2. Distribution of Executable Form - - If You distribute Covered Software in Executable Form then: - - a. such Covered Software must also be made available in Source Code Form, - as described in Section 3.1, and You must inform recipients of the - Executable Form how they can obtain a copy of such Source Code Form by - reasonable means in a timely manner, at a charge no more than the cost - of distribution to the recipient; and - - b. You may distribute such Executable Form under the terms of this - License, or sublicense it under different terms, provided that the - license for the Executable Form does not attempt to limit or alter the - recipients' rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - - You may create and distribute a Larger Work under terms of Your choice, - provided that You also comply with the requirements of this License for - the Covered Software. If the Larger Work is a combination of Covered - Software with a work governed by one or more Secondary Licenses, and the - Covered Software is not Incompatible With Secondary Licenses, this - License permits You to additionally distribute such Covered Software - under the terms of such Secondary License(s), so that the recipient of - the Larger Work may, at their option, further distribute the Covered - Software under the terms of either this License or such Secondary - License(s). - -3.4. Notices - - You may not remove or alter the substance of any license notices - (including copyright notices, patent notices, disclaimers of warranty, or - limitations of liability) contained within the Source Code Form of the - Covered Software, except that You may alter any license notices to the - extent required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - - You may choose to offer, and to charge a fee for, warranty, support, - indemnity or liability obligations to one or more recipients of Covered - Software. However, You may do so only on Your own behalf, and not on - behalf of any Contributor. You must make it absolutely clear that any - such warranty, support, indemnity, or liability obligation is offered by - You alone, and You hereby agree to indemnify every Contributor for any - liability incurred by such Contributor as a result of warranty, support, - indemnity or liability terms You offer. You may include additional - disclaimers of warranty and limitations of liability specific to any - jurisdiction. - -4. Inability to Comply Due to Statute or Regulation - - If it is impossible for You to comply with any of the terms of this License - with respect to some or all of the Covered Software due to statute, - judicial order, or regulation then You must: (a) comply with the terms of - this License to the maximum extent possible; and (b) describe the - limitations and the code they affect. Such description must be placed in a - text file included with all distributions of the Covered Software under - this License. Except to the extent prohibited by statute or regulation, - such description must be sufficiently detailed for a recipient of ordinary - skill to be able to understand it. - -5. Termination - -5.1. The rights granted under this License will terminate automatically if You - fail to comply with any of its terms. However, if You become compliant, - then the rights granted under this License from a particular Contributor - are reinstated (a) provisionally, unless and until such Contributor - explicitly and finally terminates Your grants, and (b) on an ongoing - basis, if such Contributor fails to notify You of the non-compliance by - some reasonable means prior to 60 days after You have come back into - compliance. Moreover, Your grants from a particular Contributor are - reinstated on an ongoing basis if such Contributor notifies You of the - non-compliance by some reasonable means, this is the first time You have - received notice of non-compliance with this License from such - Contributor, and You become compliant prior to 30 days after Your receipt - of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent - infringement claim (excluding declaratory judgment actions, - counter-claims, and cross-claims) alleging that a Contributor Version - directly or indirectly infringes any patent, then the rights granted to - You by any and all Contributors for the Covered Software under Section - 2.1 of this License shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user - license agreements (excluding distributors and resellers) which have been - validly granted by You or Your distributors under this License prior to - termination shall survive termination. - -6. Disclaimer of Warranty - - Covered Software is provided under this License on an "as is" basis, - without warranty of any kind, either expressed, implied, or statutory, - including, without limitation, warranties that the Covered Software is free - of defects, merchantable, fit for a particular purpose or non-infringing. - The entire risk as to the quality and performance of the Covered Software - is with You. Should any Covered Software prove defective in any respect, - You (not any Contributor) assume the cost of any necessary servicing, - repair, or correction. This disclaimer of warranty constitutes an essential - part of this License. No use of any Covered Software is authorized under - this License except under this disclaimer. - -7. Limitation of Liability - - Under no circumstances and under no legal theory, whether tort (including - negligence), contract, or otherwise, shall any Contributor, or anyone who - distributes Covered Software as permitted above, be liable to You for any - direct, indirect, special, incidental, or consequential damages of any - character including, without limitation, damages for lost profits, loss of - goodwill, work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses, even if such party shall have been - informed of the possibility of such damages. This limitation of liability - shall not apply to liability for death or personal injury resulting from - such party's negligence to the extent applicable law prohibits such - limitation. Some jurisdictions do not allow the exclusion or limitation of - incidental or consequential damages, so this exclusion and limitation may - not apply to You. - -8. Litigation - - Any litigation relating to this License may be brought only in the courts - of a jurisdiction where the defendant maintains its principal place of - business and such litigation shall be governed by laws of that - jurisdiction, without reference to its conflict-of-law provisions. Nothing - in this Section shall prevent a party's ability to bring cross-claims or - counter-claims. - -9. Miscellaneous - - This License represents the complete agreement concerning the subject - matter hereof. If any provision of this License is held to be - unenforceable, such provision shall be reformed only to the extent - necessary to make it enforceable. Any law or regulation which provides that - the language of a contract shall be construed against the drafter shall not - be used to construe this License against a Contributor. - - -10. Versions of the License - -10.1. New Versions - - Mozilla Foundation is the license steward. Except as provided in Section - 10.3, no one other than the license steward has the right to modify or - publish new versions of this License. Each version will be given a - distinguishing version number. - -10.2. Effect of New Versions - - You may distribute the Covered Software under the terms of the version - of the License under which You originally received the Covered Software, - or under the terms of any subsequent version published by the license - steward. - -10.3. Modified Versions - - If you create software not governed by this License, and you want to - create a new license for such software, you may create and use a - modified version of this License if you rename the license and remove - any references to the name of the license steward (except to note that - such modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary - Licenses If You choose to distribute Source Code Form that is - Incompatible With Secondary Licenses under the terms of this version of - the License, the notice described in Exhibit B of this License must be - attached. - -Exhibit A - Source Code Form License Notice - - This Source Code Form is subject to the - terms of the Mozilla Public License, v. - 2.0. If a copy of the MPL was not - distributed with this file, You can - obtain one at - http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular file, -then You may include the notice in a location (such as a LICENSE file in a -relevant directory) where a recipient would be likely to look for such a -notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - "Incompatible With Secondary Licenses" Notice - - This Source Code Form is "Incompatible - With Secondary Licenses", as defined by - the Mozilla Public License, v. 2.0. - ---------------------- - -Healthcare Disclaimer - -In the United States, or any other jurisdictions where they may apply, the -following additional disclaimer of warranty and limitation of liability are -hereby incorporated into the terms and conditions of MPL 2.0: - -1. No warranties of any kind whatsoever are made as to the results that - You will obtain from relying upon the covered code (or any information - or content obtained by way of the covered code), including but not - limited to compliance with privacy laws or regulations or clinical - care industry standards and protocols. Use of the covered code is not - a substitute for a health care provider’s standard practice or - professional judgment. Any decision with regard to the appropriateness - of treatment, or the validity or reliability of information or content - made available by the covered code, is the sole responsibility of the - health care provider. Consequently, it is incumbent upon each health - care provider to verify all medical history and treatment plans with - each patient. - -2. Under no circumstances and under no legal theory, whether tort - (including negligence), contract, or otherwise, shall any Contributor, - or anyone who distributes Covered Software as permitted by the - license, be liable to You for any indirect, special, incidental, - consequential damages of any character including, without limitation, - damages for loss of goodwill, work stoppage, computer failure or - malfunction, or any and all other damages or losses, of any nature - whatsoever (direct or otherwise) on account of or associated with the - use or inability to use the covered content (including, without - limitation, the use of information or content made available by the - covered code, all documentation associated therewith, and the failure - of the covered code to comply with privacy laws and regulations or - clinical care industry standards and protocols), even if such party - shall have been informed of the possibility of such damages. diff --git a/edu.harvard.i2b2.ontology/build.properties b/edu.harvard.i2b2.ontology/build.properties deleted file mode 100755 index 3f3edf40..00000000 --- a/edu.harvard.i2b2.ontology/build.properties +++ /dev/null @@ -1,10 +0,0 @@ -#Ant build property file - -## TOMCAT HOME /opt/wildfly-33.0.2.Final/standalone/configuration/workplaceapp -jboss.home=/opt/wildfly-33.0.2.Final -axis2.war.name=i2b2.war - -report=test-reports -testfiledir=testfiles -testhost=http://127.0.0.1:9090/i2b2/services - diff --git a/edu.harvard.i2b2.ontology/build.xml b/edu.harvard.i2b2.ontology/build.xml deleted file mode 100755 index 1b743159..00000000 --- a/edu.harvard.i2b2.ontology/build.xml +++ /dev/null @@ -1,291 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/edu.harvard.i2b2.ontology/data_build.xml b/edu.harvard.i2b2.ontology/data_build.xml deleted file mode 100755 index 2e20ab64..00000000 --- a/edu.harvard.i2b2.ontology/data_build.xml +++ /dev/null @@ -1,55 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - CREATE USER i2b2metadata IDENTIFIED BY i2b2metadata; - - - - - - - - - - - - - - - - - - GRANT SELECT ON i2b2 to i2b2demodata ; - GRANT SELECT ON labs to i2b2demodata ; - GRANT SELECT ON schemes to i2b2demodata ; - GRANT SELECT ON table_access to i2b2demodata ; - - - - - - diff --git a/edu.harvard.i2b2.ontology/master_build.xml b/edu.harvard.i2b2.ontology/master_build.xml deleted file mode 100755 index a9ac043d..00000000 --- a/edu.harvard.i2b2.ontology/master_build.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/edu.harvard.i2b2.ontology/pom.xml b/edu.harvard.i2b2.ontology/pom.xml new file mode 100644 index 00000000..bf7817fe --- /dev/null +++ b/edu.harvard.i2b2.ontology/pom.xml @@ -0,0 +1,43 @@ + + 4.0.0 + + edu.harvard.i2b2 + i2b2-parent + 2.0.0-SNAPSHOT + + edu.harvard.i2b2.ontology + jar + Ontology Module + + + + + org.codehaus.mojo + build-helper-maven-plugin + 3.0.0 + + + generate-sources + + add-source + + + + gensrc + + + + + + + + + + + edu.harvard.i2b2 + edu.harvard.i2b2.server-common + + + + \ No newline at end of file diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/dao/CRCConceptTotalNumUpdateDao.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/dao/CRCConceptTotalNumUpdateDao.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/dao/CRCConceptTotalNumUpdateDao.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/dao/CRCConceptTotalNumUpdateDao.java index 8b16906c..22cef145 --- a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/dao/CRCConceptTotalNumUpdateDao.java +++ b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/dao/CRCConceptTotalNumUpdateDao.java @@ -1,282 +1,282 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.ontology.dao; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Date; -import java.util.Iterator; -import java.util.List; - -import javax.sql.DataSource; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.jdbc.core.support.JdbcDaoSupport; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.exception.StackTraceUtil; -import edu.harvard.i2b2.common.util.db.JDBCUtil; -import edu.harvard.i2b2.ontology.datavo.crc.setfinder.query.MasterInstanceResultResponseType; -import edu.harvard.i2b2.ontology.datavo.crc.setfinder.query.MasterResponseType; -import edu.harvard.i2b2.ontology.datavo.crc.setfinder.query.QueryStatusTypeType; -import edu.harvard.i2b2.ontology.datavo.crc.setfinder.query.ResultResponseType; -import edu.harvard.i2b2.ontology.datavo.i2b2message.MessageHeaderType; -import edu.harvard.i2b2.ontology.datavo.i2b2message.PasswordType; -import edu.harvard.i2b2.ontology.datavo.i2b2message.SecurityType; -import edu.harvard.i2b2.ontology.datavo.pm.ProjectType; -import edu.harvard.i2b2.ontology.datavo.vdo.OntologyProcessStatusType; -import edu.harvard.i2b2.ontology.delegate.crc.CallCRCUtil; -import edu.harvard.i2b2.ontology.ejb.DBInfoType; -import edu.harvard.i2b2.ontology.ejb.TableAccessType; -import edu.harvard.i2b2.ontology.util.OntologyUtil; - -public class CRCConceptTotalNumUpdateDao extends JdbcDaoSupport { - - private static Log log = LogFactory.getLog(CRCConceptTotalNumUpdateDao.class); - protected static Log logesapi = LogFactory.getLog(CRCConceptTotalNumUpdateDao.class); - - private DataSource dataSource = null; - - OntologyUtil ontUtil = OntologyUtil.getInstance(); - - public void setDataSourceObject(DataSource dataSource) { - this.dataSource = dataSource; - } - - private void setDataSource(String dataSourceName) { - DataSource ds = null; - try { - ds = OntologyUtil.getInstance().getDataSource(dataSourceName); - } catch (I2B2Exception e2) { - log.error(e2.getMessage()); - ; - } - dataSource = ds; - } - - public OntologyProcessStatusType updateConceptTotalNum(ProjectType projectInfo, - DBInfoType dbInfo, int processId, - MessageHeaderType messageHeaderType, boolean synchronizeAllFlag) - throws I2B2Exception { - OntologyProcessStatusType ontProcessStatusType = null; - OntProcessStatusDao ontProcessStatusDao = null; - - - Connection conn = null; - boolean killedFlag = false; - ResultSet resultSet = null; - QueryStatusTypeType queryStatusType = null; - MasterInstanceResultResponseType masterInstanceResultResponse = null; - MasterResponseType masterResponseType = null; - ResultResponseType resultResponse = null; - TableAccessType tableAccessType = null; - int totalRecordToUpdate = 0, totalProcessedRecord = 0 ; - PreparedStatement pStmt = null, updatePStmt = null; - try { - String metadataSchema = dbInfo.getDb_fullSchema(); - TableAccessDao tableAccessDao = new TableAccessDao(); - if (this.dataSource == null) { - setDataSource(dbInfo.getDb_dataSource()); - } else { - tableAccessDao.setDataSourceObject(this.dataSource); - } - - SecurityType securityType = getServiceAccountSecurityType(messageHeaderType); - String projectId = getProjectId(messageHeaderType); - - // update the process status - ontProcessStatusDao = new OntProcessStatusDao(dataSource, - projectInfo, dbInfo); - - conn = this.dataSource.getConnection(); - - //read the list of metadata - //for each of metadata table select c_fullpath order by c_fullpath - List tableAccessTypeList = tableAccessDao.getAllTableAccess(projectInfo, dbInfo); - log.debug("Table access List size [ " + tableAccessTypeList.size() + " ]"); - List tableNameList = new ArrayList(); - - - for (Iterator tableAccess = tableAccessTypeList.iterator(); tableAccess.hasNext();) { - tableAccessType = tableAccess.next(); - - String updateStmtStr = " update " + metadataSchema + tableAccessType.getTableName().trim() + " set c_totalnum = null where c_fullname like ? "; - log.debug("Executing sql [" + updateStmtStr + "] c_fullname [" + tableAccessType.getFullName() + " ]"); - if (synchronizeAllFlag) { - pStmt = conn.prepareStatement(updateStmtStr); - pStmt.setString(1, tableAccessType.getFullName() + "%"); - pStmt.executeUpdate(); - pStmt.close(); - } - - - - String selectStmt = "select count(1) from " + metadataSchema + tableAccessType.getTableName().trim() + " where c_fullname like ? "; - if (synchronizeAllFlag == false) { - selectStmt += " and c_totalnum is null "; - } - - pStmt = conn.prepareStatement(selectStmt); - pStmt.setString(1, tableAccessType.getFullName() + "%"); - resultSet = pStmt.executeQuery(); - resultSet.next(); - totalRecordToUpdate += resultSet.getInt(1); - resultSet.close(); - pStmt.close(); - log.debug("Executing sql [" + selectStmt + "] c_fullname [" + tableAccessType.getFullName() + " ] totalCount" + totalRecordToUpdate ); - } - - - - //update the step field (PROCESSED updatedrecord/totalrecordtoupdate format) - ontProcessStatusDao.updateStatus(processId, new Date(System - .currentTimeMillis()), "PROCESSED 0/"+totalRecordToUpdate, "PROCESSING"); - - for (Iterator tableAccess = tableAccessTypeList.iterator(); tableAccess.hasNext();) { - tableAccessType = tableAccess.next(); - String selectStmt = "select * from " + metadataSchema + tableAccessType.getTableName().trim() + " where c_fullname like ? and c_visualattributes not like 'C%' and c_visualattributes not like 'O%' " + - " and c_visualattributes not like 'D%' and c_visualattributes not like 'R%' "; - if (synchronizeAllFlag == false) { - selectStmt += " and c_totalnum is null "; - } - selectStmt += " order by c_fullname"; - pStmt = conn.prepareStatement(selectStmt); - pStmt.setString(1, tableAccessType.getFullName() + "%"); - resultSet = pStmt.executeQuery(); - - updatePStmt = conn.prepareStatement("update "+ metadataSchema + tableAccessType.getTableName().trim() +" set c_totalnum = ? where c_fullname = ? "); - // CallCRCUtil crcUtil = new CallCRCUtil( - // securityType, projectId); - String cFullName = ""; - boolean conceptSkipFlag = false; - while (resultSet.next()) { - - cFullName = resultSet.getString("c_fullname"); - //check for status of ont_process_status giving the process id - //if the status is "aborted", then exit - ontProcessStatusType = ontProcessStatusDao.findById(processId); - if (ontProcessStatusType.getProcessStatusCd().equalsIgnoreCase("ABORT")) { - killedFlag = true; - break; - } - //pass c_fullname to crc setfinder util class - // call frc - logesapi.debug("Begin Setfinder query to CRC [" + cFullName + "]"); - conceptSkipFlag = false; - try { - masterInstanceResultResponse = CallCRCUtil.callSetfinderQuery("\\\\" + tableAccessType.getTableCd().trim() + cFullName, securityType, projectId); - } catch (Throwable i2b2Ex) { - logesapi.info("Patient count caught the exception " + i2b2Ex.getMessage()); - i2b2Ex.printStackTrace(); - conceptSkipFlag = true; - } - - if (conceptSkipFlag == false) { - String queryInstanceId = masterInstanceResultResponse.getQueryInstance().getQueryInstanceId(); - queryStatusType = masterInstanceResultResponse.getQueryInstance().getQueryStatusType(); - logesapi.debug("End Setfinder query to CRC[" + cFullName + "]"); - int totalNum = 0; - if (queryStatusType.getName().equalsIgnoreCase("PROCESSING")) { - log.info("Setfinder request status is processing query instance id [ " + queryInstanceId + " ]"); - resultResponse = CallCRCUtil.pollQueryStatus(queryInstanceId, securityType, projectId); - totalNum = resultResponse.getQueryResultInstance().get(0).getSetSize(); - } else { - totalNum = masterInstanceResultResponse.getQueryResultInstance().get(0).getSetSize(); - } - //update total_num column - updatePStmt.setInt(1,totalNum); - updatePStmt.setString(2,cFullName); - updatePStmt.executeUpdate(); - - } - - //delete the setfinder query - log.debug("Delete query for master id [ " + masterInstanceResultResponse.getQueryMaster().getQueryMasterId() + " ]"); - masterResponseType =CallCRCUtil.callDeleteMasterQuery(securityType.getUsername(), masterInstanceResultResponse.getQueryMaster().getQueryMasterId(), securityType, projectId); - log.debug("Deleted query for master id [ " + masterInstanceResultResponse.getQueryMaster().getQueryMasterId() + " ]"); - - //update processed record count - totalProcessedRecord++; - if (totalProcessedRecord % 10 == 0) { - ontProcessStatusDao.updateStatus(processId, new Date(System - .currentTimeMillis()), "PROCESSED "+ totalProcessedRecord +"/"+totalRecordToUpdate, "PROCESSING"); - } - - } - if (killedFlag) { - break; - } - resultSet.close(); - pStmt.close(); - } - - if (killedFlag == false) { - ontProcessStatusDao.updateStatus(processId, new Date(System - .currentTimeMillis()), "PROCESSED "+ totalProcessedRecord +"/"+totalRecordToUpdate, "COMPLETED"); - } else { - ontProcessStatusDao.updateStatus(processId, new Date(System - .currentTimeMillis()), "PROCESSED "+ totalProcessedRecord +"/"+totalRecordToUpdate, "KILLED"); - } - return ontProcessStatusType; - } catch (Throwable t) { - t.printStackTrace(); - String stackTrace = StackTraceUtil.getStackTrace(t); - if (ontProcessStatusDao != null && processId > 0) { - ontProcessStatusDao.updateStatus(processId, new Date(System - .currentTimeMillis()), "PROCESSED "+ totalProcessedRecord +"/"+totalRecordToUpdate, "ERROR"); - ontProcessStatusDao.updateStatusMessage(processId, - stackTrace.substring(0, (stackTrace.length()>1900)?1900:stackTrace.length())); - } - throw new I2B2Exception(stackTrace); - } finally { - try { - if (resultSet != null) { - - resultSet.close(); - - } - if (conn != null) { - - JDBCUtil.closeJdbcResource(null, pStmt, conn); - - JDBCUtil.closeJdbcResource(null, updatePStmt, null); - } - } catch (SQLException e) { - e.printStackTrace(); - } - } - } - - private SecurityType getServiceAccountSecurityType(MessageHeaderType messageHeaderType) throws I2B2Exception { - SecurityType securityType = new SecurityType(); - String serviceAccountUser = ontUtil.getServiceAccountUser(); - String serviceAccountPassword = ontUtil.getServiceAccountPassword(); - if (serviceAccountUser == null || serviceAccountPassword == null) { - throw new I2B2Exception("Service account user/password not set in ontology.properties file"); - } - securityType.setUsername(serviceAccountUser); - PasswordType password = new PasswordType(); - password.setValue(ontUtil.getServiceAccountPassword()); - securityType.setPassword(password); - securityType.setDomain(messageHeaderType.getSecurity().getDomain()); - - return securityType; - } - - private String getProjectId(MessageHeaderType messageHeaderType) { - return messageHeaderType.getProjectId(); - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.ontology.dao; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Date; +import java.util.Iterator; +import java.util.List; + +import javax.sql.DataSource; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.jdbc.core.support.JdbcDaoSupport; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.exception.StackTraceUtil; +import edu.harvard.i2b2.common.util.db.JDBCUtil; +import edu.harvard.i2b2.ontology.datavo.crc.setfinder.query.MasterInstanceResultResponseType; +import edu.harvard.i2b2.ontology.datavo.crc.setfinder.query.MasterResponseType; +import edu.harvard.i2b2.ontology.datavo.crc.setfinder.query.QueryStatusTypeType; +import edu.harvard.i2b2.ontology.datavo.crc.setfinder.query.ResultResponseType; +import edu.harvard.i2b2.ontology.datavo.i2b2message.MessageHeaderType; +import edu.harvard.i2b2.ontology.datavo.i2b2message.PasswordType; +import edu.harvard.i2b2.ontology.datavo.i2b2message.SecurityType; +import edu.harvard.i2b2.ontology.datavo.pm.ProjectType; +import edu.harvard.i2b2.ontology.datavo.vdo.OntologyProcessStatusType; +import edu.harvard.i2b2.ontology.delegate.crc.CallCRCUtil; +import edu.harvard.i2b2.ontology.ejb.DBInfoType; +import edu.harvard.i2b2.ontology.ejb.TableAccessType; +import edu.harvard.i2b2.ontology.util.OntologyUtil; + +public class CRCConceptTotalNumUpdateDao extends JdbcDaoSupport { + + private static Log log = LogFactory.getLog(CRCConceptTotalNumUpdateDao.class); + protected static Log logesapi = LogFactory.getLog(CRCConceptTotalNumUpdateDao.class); + + private DataSource dataSource = null; + + OntologyUtil ontUtil = OntologyUtil.getInstance(); + + public void setDataSourceObject(DataSource dataSource) { + this.dataSource = dataSource; + } + + private void setDataSource(String dataSourceName) { + DataSource ds = null; + try { + ds = OntologyUtil.getInstance().getDataSource(dataSourceName); + } catch (I2B2Exception e2) { + log.error(e2.getMessage()); + ; + } + dataSource = ds; + } + + public OntologyProcessStatusType updateConceptTotalNum(ProjectType projectInfo, + DBInfoType dbInfo, int processId, + MessageHeaderType messageHeaderType, boolean synchronizeAllFlag) + throws I2B2Exception { + OntologyProcessStatusType ontProcessStatusType = null; + OntProcessStatusDao ontProcessStatusDao = null; + + + Connection conn = null; + boolean killedFlag = false; + ResultSet resultSet = null; + QueryStatusTypeType queryStatusType = null; + MasterInstanceResultResponseType masterInstanceResultResponse = null; + MasterResponseType masterResponseType = null; + ResultResponseType resultResponse = null; + TableAccessType tableAccessType = null; + int totalRecordToUpdate = 0, totalProcessedRecord = 0 ; + PreparedStatement pStmt = null, updatePStmt = null; + try { + String metadataSchema = dbInfo.getDb_fullSchema(); + TableAccessDao tableAccessDao = new TableAccessDao(); + if (this.dataSource == null) { + setDataSource(dbInfo.getDb_dataSource()); + } else { + tableAccessDao.setDataSourceObject(this.dataSource); + } + + SecurityType securityType = getServiceAccountSecurityType(messageHeaderType); + String projectId = getProjectId(messageHeaderType); + + // update the process status + ontProcessStatusDao = new OntProcessStatusDao(dataSource, + projectInfo, dbInfo); + + conn = this.dataSource.getConnection(); + + //read the list of metadata + //for each of metadata table select c_fullpath order by c_fullpath + List tableAccessTypeList = tableAccessDao.getAllTableAccess(projectInfo, dbInfo); + log.debug("Table access List size [ " + tableAccessTypeList.size() + " ]"); + List tableNameList = new ArrayList(); + + + for (Iterator tableAccess = tableAccessTypeList.iterator(); tableAccess.hasNext();) { + tableAccessType = tableAccess.next(); + + String updateStmtStr = " update " + metadataSchema + tableAccessType.getTableName().trim() + " set c_totalnum = null where c_fullname like ? "; + log.debug("Executing sql [" + updateStmtStr + "] c_fullname [" + tableAccessType.getFullName() + " ]"); + if (synchronizeAllFlag) { + pStmt = conn.prepareStatement(updateStmtStr); + pStmt.setString(1, tableAccessType.getFullName() + "%"); + pStmt.executeUpdate(); + pStmt.close(); + } + + + + String selectStmt = "select count(1) from " + metadataSchema + tableAccessType.getTableName().trim() + " where c_fullname like ? "; + if (synchronizeAllFlag == false) { + selectStmt += " and c_totalnum is null "; + } + + pStmt = conn.prepareStatement(selectStmt); + pStmt.setString(1, tableAccessType.getFullName() + "%"); + resultSet = pStmt.executeQuery(); + resultSet.next(); + totalRecordToUpdate += resultSet.getInt(1); + resultSet.close(); + pStmt.close(); + log.debug("Executing sql [" + selectStmt + "] c_fullname [" + tableAccessType.getFullName() + " ] totalCount" + totalRecordToUpdate ); + } + + + + //update the step field (PROCESSED updatedrecord/totalrecordtoupdate format) + ontProcessStatusDao.updateStatus(processId, new Date(System + .currentTimeMillis()), "PROCESSED 0/"+totalRecordToUpdate, "PROCESSING"); + + for (Iterator tableAccess = tableAccessTypeList.iterator(); tableAccess.hasNext();) { + tableAccessType = tableAccess.next(); + String selectStmt = "select * from " + metadataSchema + tableAccessType.getTableName().trim() + " where c_fullname like ? and c_visualattributes not like 'C%' and c_visualattributes not like 'O%' " + + " and c_visualattributes not like 'D%' and c_visualattributes not like 'R%' "; + if (synchronizeAllFlag == false) { + selectStmt += " and c_totalnum is null "; + } + selectStmt += " order by c_fullname"; + pStmt = conn.prepareStatement(selectStmt); + pStmt.setString(1, tableAccessType.getFullName() + "%"); + resultSet = pStmt.executeQuery(); + + updatePStmt = conn.prepareStatement("update "+ metadataSchema + tableAccessType.getTableName().trim() +" set c_totalnum = ? where c_fullname = ? "); + // CallCRCUtil crcUtil = new CallCRCUtil( + // securityType, projectId); + String cFullName = ""; + boolean conceptSkipFlag = false; + while (resultSet.next()) { + + cFullName = resultSet.getString("c_fullname"); + //check for status of ont_process_status giving the process id + //if the status is "aborted", then exit + ontProcessStatusType = ontProcessStatusDao.findById(processId); + if (ontProcessStatusType.getProcessStatusCd().equalsIgnoreCase("ABORT")) { + killedFlag = true; + break; + } + //pass c_fullname to crc setfinder util class + // call frc + logesapi.debug("Begin Setfinder query to CRC [" + cFullName + "]"); + conceptSkipFlag = false; + try { + masterInstanceResultResponse = CallCRCUtil.callSetfinderQuery("\\\\" + tableAccessType.getTableCd().trim() + cFullName, securityType, projectId); + } catch (Throwable i2b2Ex) { + logesapi.info("Patient count caught the exception " + i2b2Ex.getMessage()); + i2b2Ex.printStackTrace(); + conceptSkipFlag = true; + } + + if (conceptSkipFlag == false) { + String queryInstanceId = masterInstanceResultResponse.getQueryInstance().getQueryInstanceId(); + queryStatusType = masterInstanceResultResponse.getQueryInstance().getQueryStatusType(); + logesapi.debug("End Setfinder query to CRC[" + cFullName + "]"); + int totalNum = 0; + if (queryStatusType.getName().equalsIgnoreCase("PROCESSING")) { + log.info("Setfinder request status is processing query instance id [ " + queryInstanceId + " ]"); + resultResponse = CallCRCUtil.pollQueryStatus(queryInstanceId, securityType, projectId); + totalNum = resultResponse.getQueryResultInstance().get(0).getSetSize(); + } else { + totalNum = masterInstanceResultResponse.getQueryResultInstance().get(0).getSetSize(); + } + //update total_num column + updatePStmt.setInt(1,totalNum); + updatePStmt.setString(2,cFullName); + updatePStmt.executeUpdate(); + + } + + //delete the setfinder query + log.debug("Delete query for master id [ " + masterInstanceResultResponse.getQueryMaster().getQueryMasterId() + " ]"); + masterResponseType =CallCRCUtil.callDeleteMasterQuery(securityType.getUsername(), masterInstanceResultResponse.getQueryMaster().getQueryMasterId(), securityType, projectId); + log.debug("Deleted query for master id [ " + masterInstanceResultResponse.getQueryMaster().getQueryMasterId() + " ]"); + + //update processed record count + totalProcessedRecord++; + if (totalProcessedRecord % 10 == 0) { + ontProcessStatusDao.updateStatus(processId, new Date(System + .currentTimeMillis()), "PROCESSED "+ totalProcessedRecord +"/"+totalRecordToUpdate, "PROCESSING"); + } + + } + if (killedFlag) { + break; + } + resultSet.close(); + pStmt.close(); + } + + if (killedFlag == false) { + ontProcessStatusDao.updateStatus(processId, new Date(System + .currentTimeMillis()), "PROCESSED "+ totalProcessedRecord +"/"+totalRecordToUpdate, "COMPLETED"); + } else { + ontProcessStatusDao.updateStatus(processId, new Date(System + .currentTimeMillis()), "PROCESSED "+ totalProcessedRecord +"/"+totalRecordToUpdate, "KILLED"); + } + return ontProcessStatusType; + } catch (Throwable t) { + t.printStackTrace(); + String stackTrace = StackTraceUtil.getStackTrace(t); + if (ontProcessStatusDao != null && processId > 0) { + ontProcessStatusDao.updateStatus(processId, new Date(System + .currentTimeMillis()), "PROCESSED "+ totalProcessedRecord +"/"+totalRecordToUpdate, "ERROR"); + ontProcessStatusDao.updateStatusMessage(processId, + stackTrace.substring(0, (stackTrace.length()>1900)?1900:stackTrace.length())); + } + throw new I2B2Exception(stackTrace); + } finally { + try { + if (resultSet != null) { + + resultSet.close(); + + } + if (conn != null) { + + JDBCUtil.closeJdbcResource(null, pStmt, conn); + + JDBCUtil.closeJdbcResource(null, updatePStmt, null); + } + } catch (SQLException e) { + e.printStackTrace(); + } + } + } + + private SecurityType getServiceAccountSecurityType(MessageHeaderType messageHeaderType) throws I2B2Exception { + SecurityType securityType = new SecurityType(); + String serviceAccountUser = ontUtil.getServiceAccountUser(); + String serviceAccountPassword = ontUtil.getServiceAccountPassword(); + if (serviceAccountUser == null || serviceAccountPassword == null) { + throw new I2B2Exception("Service account user/password not set in ontology.properties file"); + } + securityType.setUsername(serviceAccountUser); + PasswordType password = new PasswordType(); + password.setValue(ontUtil.getServiceAccountPassword()); + securityType.setPassword(password); + securityType.setDomain(messageHeaderType.getSecurity().getDomain()); + + return securityType; + } + + private String getProjectId(MessageHeaderType messageHeaderType) { + return messageHeaderType.getProjectId(); + } + +} diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/dao/CRCConceptUpdateDao.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/dao/CRCConceptUpdateDao.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/dao/CRCConceptUpdateDao.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/dao/CRCConceptUpdateDao.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/dao/ConceptDao.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/dao/ConceptDao.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/dao/ConceptDao.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/dao/ConceptDao.java index 91ba6e87..ad921719 --- a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/dao/ConceptDao.java +++ b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/dao/ConceptDao.java @@ -1,2517 +1,2516 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Lori Phillips - */ -package edu.harvard.i2b2.ontology.dao; - -import java.io.IOException; -import java.sql.Date; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import javax.sql.DataSource; - -import org.apache.commons.lang3.StringEscapeUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.dao.DataAccessException; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.RowCallbackHandler; -import org.springframework.jdbc.core.RowMapper; -import org.springframework.jdbc.core.support.JdbcDaoSupport; -import org.w3c.dom.Document; -import org.w3c.dom.Element; - -import antlr.StringUtils; -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.db.JDBCUtil; -import edu.harvard.i2b2.common.util.jaxb.DTOFactory; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.common.util.xml.XMLUtil; -import edu.harvard.i2b2.ontology.datavo.pm.ProjectType; -import edu.harvard.i2b2.ontology.datavo.vdo.ConceptType; -import edu.harvard.i2b2.ontology.datavo.vdo.GetCategoriesType; -import edu.harvard.i2b2.ontology.datavo.vdo.GetChildrenType; -import edu.harvard.i2b2.ontology.datavo.vdo.GetModifierChildrenType; -import edu.harvard.i2b2.ontology.datavo.vdo.GetModifierInfoType; - -import edu.harvard.i2b2.ontology.datavo.vdo.GetTermInfoType; -import edu.harvard.i2b2.ontology.datavo.vdo.VocabRequestType; -import edu.harvard.i2b2.ontology.datavo.vdo.ModifierType; -import edu.harvard.i2b2.ontology.datavo.vdo.GetModifiersType; -import edu.harvard.i2b2.ontology.datavo.vdo.XmlValueType; -import edu.harvard.i2b2.ontology.ejb.DBInfoType; -import edu.harvard.i2b2.ontology.ejb.NodeType; -import edu.harvard.i2b2.ontology.util.OntologyUtil; -import edu.harvard.i2b2.ontology.util.Roles; -import edu.harvard.i2b2.ontology.util.StringUtil; -import edu.harvard.i2b2.ontology.ws.GetChildrenDataMessage; - -public class ConceptDao extends JdbcDaoSupport { - - private static Log log = LogFactory.getLog(ConceptDao.class); - final static String CAT_CORE = " c_hlevel, c_fullname, c_name, c_synonym_cd, c_visualattributes, c_totalnum, c_basecode, c_facttablecolumn, c_dimtablename, c_columnname, c_columndatatype, c_operator, c_dimcode, c_tooltip, valuetype_cd, c_protected_access, c_ontology_protection "; - final static String CAT_DEFAULT = " c_fullname, c_name "; - final static String CAT_LIMITED = " c_hlevel, c_fullname, c_name, c_synonym_cd, c_visualattributes, c_totalnum, c_basecode, c_tooltip, valuetype_cd, c_protected_access, c_ontology_protection "; - - final static String MOD_DEFAULT = " c_hlevel, c_fullname, c_name, c_synonym_cd, c_visualattributes, c_totalnum, c_basecode, c_facttablecolumn, c_tablename, c_columnname, c_columndatatype, c_operator, c_dimcode, c_tooltip, m_applied_path "; - final static String MOD_CORE = MOD_DEFAULT; - final static String MOD_LIMITED = " c_hlevel, c_fullname, c_name, c_synonym_cd, c_visualattributes, c_totalnum, c_basecode, c_tooltip, m_applied_path "; - - - final static String DEFAULT = " c_hlevel, c_fullname, c_name, c_synonym_cd, c_visualattributes, c_totalnum, c_basecode, c_facttablecolumn, c_tablename, c_columnname, c_columndatatype, c_operator, c_dimcode, c_tooltip, valuetype_cd "; - final static String CORE = DEFAULT; - final static String LIMITED = " c_hlevel, c_fullname, c_name, c_synonym_cd, c_visualattributes, c_totalnum, c_basecode, c_tooltip, valuetype_cd "; - - final static String ALL = ", update_date, download_date, import_date, sourcesystem_cd "; - final static String BLOB = ", c_metadataxml, c_comment "; - - final static String NAME_DEFAULT = " c_name "; - - private JdbcTemplate jt; - - private void setDataSource(String dataSource) { - DataSource ds = null; - try { - ds = OntologyUtil.getInstance().getDataSource(dataSource); - } catch (I2B2Exception e2) { - log.error(e2.getMessage());; - } - this.jt = new JdbcTemplate(ds); - - } - - private String getMetadataSchema() throws I2B2Exception{ - - return OntologyUtil.getInstance().getMetaDataSchemaName(); - } - - public List findRootCategories(final GetCategoriesType returnType, final ProjectType projectInfo, final DBInfoType dbInfo) throws I2B2Exception, I2B2DAOException{ - - // find return parameters - String parameters = CAT_DEFAULT; - if (returnType.getType().equals("limited")){ - parameters = CAT_LIMITED; - } - else if(returnType.getType().equals("core")){ - parameters = CAT_CORE; - } - - /* else if (returnType.getType().equals("all")){ - parameters = ALL; - } - */ - String metadataSchema = dbInfo.getDb_fullSchema(); - setDataSource(dbInfo.getDb_dataSource()); - - - // First step is to call PM to see what roles user belongs to. - - if (projectInfo.getRole().size() == 0) - { - log.error("no role found for this user in project: " + projectInfo.getName()); - I2B2Exception e = new I2B2Exception("No role found for user"); - throw e; - } - - /* - Boolean protectedAccess = false; - Iterator it = projectInfo.getRole().iterator(); - while (it.hasNext()){ - String role = (String) it.next(); - if(role.toUpperCase().equals("DATA_PROT")) { - protectedAccess = true; - break; - } - } - */ - - final boolean obfuscatedUserFlag = Roles.getInstance().isRoleOfuscated(projectInfo); - - - List queryResult = null; - - - String categoriesSql = "select c_table_cd, " + parameters + " from " + metadataSchema + "table_access "; - - String hidden = ""; - if(returnType.isHiddens() == false) - hidden = " where c_visualattributes not like '_H%'"; - - String synonym = ""; - if(returnType.isSynonyms() == false) - synonym = " c_synonym_cd = 'N'"; - - String whereClause = hidden; - if((whereClause.length() > 2) && (synonym.length() > 2)) - whereClause = whereClause + " and " + synonym; - - else if (synonym.length() > 2) - whereClause = " where " + synonym; - - categoriesSql = categoriesSql + whereClause + " order by upper(c_name)"; - log.debug(categoriesSql); - - try { - queryResult = jt.query(categoriesSql, getConceptFullNameMapper(returnType, projectInfo, obfuscatedUserFlag)); - } catch (DataAccessException e) { - log.error("Get Categories " +e.getMessage()); - throw new I2B2DAOException("Database Error"); - } - //} - log.debug("result size = " + queryResult.size()); - - if (returnType.isBlob() == true && queryResult != null){ - Iterator itr = queryResult.iterator(); - while (itr.hasNext()){ - ConceptType child = (ConceptType) itr.next(); - String clobSql = "select c_metadataxml, c_comment from "+ metadataSchema + "table_access where c_table_cd = ?"; - - List clobResult = null; - try { - clobResult = jt.query(clobSql, getConceptXMLMapper(dbInfo), StringUtil.getTableCd(child.getKey())); - } catch (DataAccessException e) { - log.error(e.getMessage()); - throw new I2B2DAOException("Database Error"); - } - if(clobResult != null) { - child.setMetadataxml(((ConceptType)(clobResult.get(0))).getMetadataxml()); - child.setComment(((ConceptType)(clobResult.get(0))).getComment()); - } - else { - child.setMetadataxml(null); - child.setComment(null); - } - - } - } - return queryResult; - } - - - - public List findChildrenByParent(final GetChildrenDataMessage childrenMsg, ProjectType projectInfo, DBInfoType dbInfo) throws I2B2DAOException, I2B2Exception, JAXBUtilException{ - - final GetChildrenType childrenType = childrenMsg.getChildrenType(); - - // find return parameters - String parameters = DEFAULT; - if (childrenType.getType().equals("limited")){ - parameters = LIMITED; - } - - else if (childrenType.getType().equals("core")){ - parameters = CORE; - } - else if (childrenType.getType().equals("all")){ - parameters = CORE + ALL; - } - if(childrenType.isBlob() == true) - parameters = parameters + BLOB; - - String metadataSchema = dbInfo.getDb_fullSchema(); - setDataSource(dbInfo.getDb_dataSource()); - - if (projectInfo.getRole().size() == 0) - { - log.error("no role found for this user in project: " + projectInfo.getName()); - I2B2Exception e = new I2B2Exception("No role found for user"); - throw e; - } - - /* - Boolean protectedAccess = false; - Iterator it = projectInfo.getRole().iterator(); - while (it.hasNext()){ - String role = (String) it.next(); - if(role.toUpperCase().equals("DATA_PROT")) { - protectedAccess = true; - break; - } - } - */ - - - //extract table code - String tableCd = StringUtil.getTableCd(childrenType.getParent()); - String tableName=null; - String tableSql = "select distinct(c_table_name) from " + metadataSchema + "table_access where c_table_cd = ?"; - try { - tableName = jt.queryForObject(tableSql, String.class, tableCd); - } catch (DataAccessException e) { - log.error("Get Children " + e.getMessage()); - throw new I2B2DAOException("Database Error"); - } - - String path = StringUtil.getPath(childrenType.getParent()); - String searchPath = path + "%"; - - // Lookup to get chlevel + 1 --- dont allow synonyms so we only get one result back - - String levelSql = "select c_hlevel from " + metadataSchema+tableName + " where c_fullname = ? and c_synonym_cd = 'N'"; - - int level = 0; - try { - level = jt.queryForObject(levelSql, Integer.class, path); - } catch (DataAccessException e1) { - // should only get 1 result back (path == c_fullname which should be unique) - log.error("Get Children " + e1.getMessage()); - throw new I2B2DAOException("Database Error"); - } - - String hidden = ""; - if(childrenType.isHiddens() == false) - hidden = " and c_visualattributes not like '_H%'"; - - String synonym = ""; - if(childrenType.isSynonyms() == false) - synonym = " and c_synonym_cd = 'N'"; - - // get all children if the numLevel is less then zero - int numLevel = childrenType.getNumLevel(); - String sql = "select " + parameters + " from " + metadataSchema + tableName + " where c_fullname like ? " + (!dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL") ? "{ESCAPE '?'}" : ""); - sql += (numLevel >= 0) ? " and c_hlevel > ? and c_hlevel <= ? " : " and c_hlevel > ? "; - sql = sql + hidden + synonym + " order by c_hlevel,upper(c_name) "; - - //log.info(sql + " " + path + " " + level); - boolean obfuscatedUserFlag = Roles.getInstance().isRoleOfuscated(projectInfo); - //ParameterizedRowMapper mapper = getMapper(new NodeType(childrenType),obfuscatedUserFlag, dbInfo.getDb_serverType()); - - if(dbInfo.getDb_serverType().toUpperCase().equals("SQLSERVER")){ - searchPath = StringUtil.escapeSQLSERVER(path); - searchPath += "%"; - // log.info("escaped searchPath is " + searchPath); - } - - else if(dbInfo.getDb_serverType().toUpperCase().equals("ORACLE")){ - searchPath = StringUtil.escapeORACLE(path); - searchPath += "%"; - } - else if(dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL")){ - searchPath = StringUtil.escapePOSTGRESQL(path); - searchPath += "%"; - } - - List queryResult = null; - try { - queryResult = (numLevel >= 0) - ? jt.query(sql, getConceptNodeMapper(new NodeType(childrenType), obfuscatedUserFlag, dbInfo.getDb_serverType()), searchPath, level, (level + numLevel)) - : jt.query(sql, getConceptNodeMapper(new NodeType(childrenType), obfuscatedUserFlag, dbInfo.getDb_serverType()), searchPath, level); - } catch (Exception e) { - log.error("Get Children " + e.getMessage()); - throw new I2B2DAOException("Database Error"); - } - - - if ((Float.parseFloat( - childrenMsg.getMessageHeaderType().getSendingApplication().getApplicationVersion()) > 1.5) && - (queryResult.size() > 0)) { - Iterator it2 = queryResult.iterator(); - while (it2.hasNext()){ - ConceptType concept = it2.next(); - // if a leaf has modifiers report it with visAttrib == F - if(concept.getVisualattributes().startsWith("L")){ - String modPath = StringUtil.getPath(concept.getKey()); - // I have to do this the hard way because there are a dynamic number of applied paths to check - // prevent SQL injection - if(modPath.contains("'")){ - modPath = modPath.replaceAll("'", "''"); - } - String sqlCount = "select count(*) from " + metadataSchema+ tableName + " where m_exclusion_cd is null and c_fullname in"; - int queryCount = 0; - // build m_applied_path sub-query - String m_applied_pathSql = "(m_applied_path = '" + modPath +"'"; - while (modPath.length() > 3) { - if(modPath.endsWith("%")){ - modPath = modPath.substring(0, modPath.length()-2); - modPath = modPath.substring(0, modPath.lastIndexOf("\\") + 1) + "%"; - } - else - modPath = modPath + "%"; - m_applied_pathSql = m_applied_pathSql + " or m_applied_path = '" + modPath + "'" ; - } - sqlCount = sqlCount + "(select c_fullname from " + metadataSchema+ tableName + " where c_hlevel = 1 and m_exclusion_cd is null and " + m_applied_pathSql + " )"; - - if(dbInfo.getDb_serverType().toUpperCase().equals("ORACLE")) - sqlCount = sqlCount + " MINUS "; - else - sqlCount = sqlCount + " EXCEPT "; - - sqlCount = sqlCount+ " (select c_fullname from " + metadataSchema+ tableName + " where m_exclusion_cd is not null and " + m_applied_pathSql + " )))"; - - - try { - queryCount = jt.queryForObject(sqlCount, Integer.class); - } catch (DataAccessException e) { - log.error("Get Children " + e.getMessage()); - throw new I2B2DAOException("Database Error"); - } - // log.debug("COUNT " + queryCount + " for " +sqlCount); - - - if(queryCount > 0){ - concept.setVisualattributes(concept.getVisualattributes().replace('L', 'F')); - log.debug("changed " + concept.getName() + " from leaf to folder: modCount > 0"); - } - } - } - } - // log.debug("Find Children By Parent " + sql); - log.debug("get_children result size = " + queryResult.size()); - return queryResult; - // tested statement with aqua data studio verified output from above against this. - // select c_fullname, c_name, c_synonym_cd, c_visualattributes from metadata.testrpdr - // where c_fullname like '\RPDR\Diagnoses\Circulatory system (390-459)\Arterial vascular disease (440-447)\(446) Polyarteritis nodosa and al%' - // and c_hlevel = 5 and c_visualattributes not like '_H%' and c_synonym_cd = 'N' - - // verified both with and without hiddens and synonyms. - - // clob test level = 4 - // \\testrpdr\RPDR\HealthHistory\PHY\Health Maintenance\Mammogram\Mammogram - Deferred - } - - public List findByFullname(final GetTermInfoType termInfoType, ProjectType projectInfo, DBInfoType dbInfo) throws I2B2DAOException, I2B2Exception{ - - // find return parameters - String parameters = DEFAULT; - if (termInfoType.getType().equals("limited")){ - parameters = LIMITED; - } - - else if (termInfoType.getType().equals("core")){ - parameters = CORE; - } - else if (termInfoType.getType().equals("all")){ - parameters = CORE + ALL; - } - if(termInfoType.isBlob() == true) - parameters = parameters + BLOB; - - String metadataSchema = dbInfo.getDb_fullSchema(); - setDataSource(dbInfo.getDb_dataSource()); - - if (projectInfo.getRole().size() == 0) - { - log.error("no role found for this user in project: " + projectInfo.getName()); - I2B2DAOException e = new I2B2DAOException("No role found for user"); - throw e; - } - - - boolean ofuscatedUserFlag = Roles.getInstance().isRoleOfuscated(projectInfo); - - //tableCd to table name conversion - - - String hidden = ""; - if(termInfoType.isHiddens() == false) - hidden = " and c_visualattributes not like '_H%'"; - - //extract table code - String tableCd = StringUtil.getTableCd(termInfoType.getSelf()); - String tableName=null; - String protectedAccess=null; - String ontologyProtection = null; - String tableSql = "select distinct(c_table_name) from " + metadataSchema + "table_access where c_table_cd = ?" + hidden; - try { - tableName = jt.queryForObject(tableSql, String.class, tableCd); - } catch (DataAccessException e) { - log.error("Get Term Info " + e.getMessage()); - throw new I2B2DAOException("Database Error"); - } - tableSql = "select distinct(c_protected_access) from " + metadataSchema + "table_access where c_table_cd = ?" + hidden; - try { - protectedAccess = jt.queryForObject(tableSql, String.class, tableCd); - } catch (DataAccessException e) { - log.error("Get Term Info " + e.getMessage()); - throw new I2B2DAOException("Database Error"); - } - tableSql = "select c_ontology_protection from " + metadataSchema + "table_access where c_table_cd = ?" + hidden; - try { - ontologyProtection = jt.queryForObject(tableSql, String.class, tableCd); - } catch (DataAccessException e) { - log.error("Get Term Info " + e.getMessage()); - throw new I2B2DAOException("Database Error"); - } - - String path = StringUtil.getPath(termInfoType.getSelf()); - /* - if(dbInfo.getDb_serverType().toUpperCase().equals("SQLSERVER")){ - //path = path.replaceAll("\\[", "[[]"); - path = StringUtil.escapeSQLSERVER(path); - } - else if(dbInfo.getDb_serverType().toUpperCase().equals("ORACLE")){ - path = StringUtil.escapeORACLE(path); - } - else if(dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL")){ - path = StringUtil.escapePOSTGRESQL(path); - } - */ - - String searchPath = path; - - String synonym = ""; - if(termInfoType.isSynonyms() == false) - synonym = " and c_synonym_cd = 'N'"; - - // String sql = "select " + parameters +" from " + metadataSchema+tableName + " where c_fullname like ? " + (!dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL") ? "{ESCAPE '?'}" : "" ) + ""; - String sql = "select '" + protectedAccess + "' as c_protected_access, '" + ontologyProtection + "' as c_ontology_protection, " + parameters +" from " + metadataSchema+tableName + " where c_fullname = ? "; - sql = sql + hidden + synonym + " order by upper(c_name) "; - - //log.info(sql + " " + path + " " + level); - - //ParameterizedRowMapper mapper = getMapper(new NodeType(termInfoType), ofuscatedUserFlag, dbInfo.getDb_serverType()); - - List queryResult = null; - try { - queryResult = jt.query(sql, getConceptNodeMapper(new NodeType(termInfoType), ofuscatedUserFlag, dbInfo.getDb_serverType()), searchPath ); - } catch (DataAccessException e) { - log.error("Get Term Info " + e.getMessage()); - throw new I2B2DAOException("Database Error"); - } - - log.debug("Term Info result size = " + queryResult.size()); - - - return queryResult; - - } - - - - public List findNameInfo(final VocabRequestType vocabType, ProjectType projectInfo, DBInfoType dbInfo) throws I2B2DAOException, I2B2Exception{ - - // find return parameters - String parameters = NAME_DEFAULT; - - if (vocabType.getType().equals("limited")){ - parameters = LIMITED; - } - - else if (vocabType.getType().equals("core")){ - parameters = CORE; - } - - else if (vocabType.getType().equals("all")){ - parameters = CORE + ALL; - } - if(vocabType.isBlob() == true) - parameters = parameters + BLOB; - - String metadataSchema = dbInfo.getDb_fullSchema(); - setDataSource(dbInfo.getDb_dataSource()); - - // log.info(metadataSchema); - - if (projectInfo.getRole().size() == 0) - { - log.error("no role found for this user in project: " + projectInfo.getName()); - I2B2Exception e = new I2B2Exception("No role found for user"); - throw e; - } - - - - //tableCd to table name + fullname conversion - - - - //extract table code - String tableCd = vocabType.getCategory(); - List categoryResult; - - List queryResult = null; - if (tableCd.equals("@")) - { - String tableSql = "select distinct(c_table_name), c_fullname, c_name, c_table_cd from " + metadataSchema + "table_access where c_visualattributes not like '_H%'" ; - try { - categoryResult = jt.query(tableSql, new GetConceptNameMapper()); - } catch (DataAccessException e) { - log.error("Search by Name " + e.getMessage()); - throw new I2B2DAOException("Database Error"); - } - - - } else { - String tableSql = "select distinct(c_table_name), c_fullname, c_name, c_table_cd from " + metadataSchema + "table_access where upper(c_table_cd) = ? " ; - try { - categoryResult = jt.query(tableSql, new GetConceptNameMapper(), tableCd.toUpperCase()); - } catch (DataAccessException e) { - log.error("Search by Name " + e.getMessage()); - throw new I2B2DAOException("Database Error"); - } - } - - String nameInfoSql = null; - String compareName = null; - - String value = vocabType.getMatchStr().getValue(); - // using JDBCtemplate so dont need to do apostrophe replace - // if(value.contains("'")){ - // value = value.replaceAll("'", "''"); - // } - - if (categoryResult.size() == 0){ - log.error("Non existent tableCd category passed in getNameInfo request " + tableCd); - return null; - } - - - - for (int i=0; i < categoryResult.size(); i++) { - String category = categoryResult.get(i).getKey(); - if(category.contains("'")){ - category = category.replaceAll("'", "''"); - } - - if(dbInfo.getDb_serverType().toUpperCase().equals("SQLSERVER")){ - category = StringUtil.escapeSQLSERVER(category); - } - else if(dbInfo.getDb_serverType().toUpperCase().equals("ORACLE")){ - category = StringUtil.escapeORACLE(category); - } - else if(dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL")){ - category = StringUtil.escapePOSTGRESQL(category); - } - - - // dont do the sql injection replace; it breaks the service. - if(vocabType.getMatchStr().getStrategy().equals("exact")) { - nameInfoSql = "select " + parameters + " from " + metadataSchema+categoryResult.get(i).getTablename() + " where upper(c_name) = ? and c_fullname like '" + category + "%' " + (!dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL") ? "{ESCAPE '?'}" : "" ) ; //{ESCAPE '?'}"; - compareName = value.toUpperCase(); - } - - else if(vocabType.getMatchStr().getStrategy().equals("left")){ - nameInfoSql = "select " + parameters + " from " + metadataSchema+categoryResult.get(i).getTablename() +" where upper(c_name) like ? " + (!dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL") ? "{ESCAPE '?'}" : "" ) + " and c_fullname like '" + category +"%' " + (!dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL") ? "{ESCAPE '?'}" : "" ) ; //{ESCAPE '?'}"; - if(dbInfo.getDb_serverType().toUpperCase().equals("SQLSERVER")){ - compareName = StringUtil.escapeSQLSERVER(vocabType.getMatchStr().getValue().toUpperCase()); - //compareName = compareName.replaceAll("\\[", "[[]"); - } - else if(dbInfo.getDb_serverType().toUpperCase().equals("ORACLE")){ - compareName = StringUtil.escapeORACLE(vocabType.getMatchStr().getValue().toUpperCase()); - //compareName = compareName.replaceAll("\\[", "[[]"); - } - else if(dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL")){ - compareName = StringUtil.escapePOSTGRESQL(vocabType.getMatchStr().getValue().toUpperCase()); - //compareName = compareName.replaceAll("\\[", "[[]"); - } - compareName = compareName + "%"; - - } - - else if(vocabType.getMatchStr().getStrategy().equals("right")) { - nameInfoSql = "select " + parameters + " from " + metadataSchema+categoryResult.get(i).getTablename() +" where upper(c_name) like ? " + (!dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL") ? "{ESCAPE '?'}" : "" ) + " and c_fullname like '" + category +"%' " + (!dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL") ? "{ESCAPE '?'}" : "" ) ; //{ESCAPE '?'}"; {ESCAPE '?'}"; - if(dbInfo.getDb_serverType().toUpperCase().equals("SQLSERVER")){ - compareName = StringUtil.escapeSQLSERVER(vocabType.getMatchStr().getValue().toUpperCase()); - } - else if(dbInfo.getDb_serverType().toUpperCase().equals("ORACLE")){ - compareName = StringUtil.escapeORACLE(vocabType.getMatchStr().getValue().toUpperCase()); - } - else if(dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL")){ - compareName = StringUtil.escapePOSTGRESQL(vocabType.getMatchStr().getValue().toUpperCase()); - } - - compareName = "%" + compareName; - // if(dbInfo.getDb_serverType().toUpperCase().equals("SQLSERVER")){ - // compareName = compareName.replaceAll("\\[", "[[]"); - // } - } - - else if(vocabType.getMatchStr().getStrategy().equals("contains")) { - if(!(value.contains(" "))){ - nameInfoSql = "select " + parameters + " from " + metadataSchema+categoryResult.get(i).getTablename() +" where upper(c_name) like ? " + (!dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL") ? "{ESCAPE '?'}" : "" ) + " and c_fullname like '" + category +"%' " + (!dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL") ? "{ESCAPE '?'}" : "" ) + ""; - if(dbInfo.getDb_serverType().toUpperCase().equals("SQLSERVER")){ - compareName = StringUtil.escapeSQLSERVER(vocabType.getMatchStr().getValue().toUpperCase()); - } - else if(dbInfo.getDb_serverType().toUpperCase().equals("ORACLE")){ - compareName = StringUtil.escapeORACLE(vocabType.getMatchStr().getValue().toUpperCase()); - } - else if(dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL")){ - compareName = StringUtil.escapePOSTGRESQL(vocabType.getMatchStr().getValue().toUpperCase()); - } - compareName = "%" + compareName + "%"; - //if(dbInfo.getDb_serverType().toUpperCase().equals("SQLSERVER")){ - // compareName = compareName.replaceAll("\\[", "[[]"); - // } - }else{ - nameInfoSql = "select " + parameters + " from " + metadataSchema+categoryResult.get(i).getTablename(); - if(dbInfo.getDb_serverType().toUpperCase().equals("SQLSERVER")){ - compareName = StringUtil.escapeSQLSERVER(vocabType.getMatchStr().getValue().toUpperCase()); - } - else if(dbInfo.getDb_serverType().toUpperCase().equals("ORACLE")){ - compareName = StringUtil.escapeORACLE(vocabType.getMatchStr().getValue().toUpperCase()); - } - else if(dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL")){ - compareName = StringUtil.escapePOSTGRESQL(vocabType.getMatchStr().getValue().toUpperCase()); - } - - // if(dbInfo.getDb_serverType().toUpperCase().equals("SQLSERVER")){ - // value = value.replaceAll("\\[", "[[]"); - // } - // WAS - // nameInfoSql = nameInfoSql + parseMatchString(value)+ " and c_fullname like '" + category +"%'" + (!dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL") ? "{ESCAPE '?'}" : "" ) + "";; - // !dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL") ? compareName.replaceAll("'", "''") : compareName - nameInfoSql = nameInfoSql + parseMatchString((compareName.replaceAll("'", "''")), dbInfo)+ " and c_fullname like '" + category +"%' " + (!dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL") ? "{ESCAPE '?'}" : "" ) + " ";; - - compareName = null; - } - } - - - String hidden = "";// and c_totalnum != 0 "; - if(vocabType.isHiddens() == false) - hidden += " and c_visualattributes not like '_H%'"; - - - String synonym = ""; - if(vocabType.isSynonyms() == false) - synonym = " and c_synonym_cd = 'N'"; - - nameInfoSql = nameInfoSql + hidden + synonym + " order by c_hlevel, c_totalnum, upper(c_name) asc "; - - log.info("nameInfoSql:" + nameInfoSql + " " +compareName); - boolean obfuscatedUserFlag = Roles.getInstance().isRoleOfuscated(projectInfo); - //ParameterizedRowMapper mapper = getMapper(new NodeType(vocabType),obfuscatedUserFlag, dbInfo.getDb_serverType()); - - - try { - List list = null; - if(compareName != null) { - list = jt.query(nameInfoSql, getConceptNodeMapper(new NodeType(vocabType),obfuscatedUserFlag, dbInfo.getDb_serverType()), compareName); - //queryResult.addAll(list); - } else { - vocabType.setCategory(categoryResult.get(i).getTooltip()); - list = jt.query(nameInfoSql, getConceptNodeMapper(new NodeType(vocabType),obfuscatedUserFlag, dbInfo.getDb_serverType())); - //queryResult.addAll(list); - } - - - // Add parent poaths - - String tableName=categoryResult.get(i).getTablename(); - String name = categoryResult.get(i).getName(); - /* - String tableSql = "select distinct(c_table_name) from " + metadataSchema + "table_access where c_table_cd = ?"; - try { - tableName = jt.queryForObject(tableSql, String.class, tableCd); - } catch (DataAccessException e) { - log.error("Get Children " + e.getMessage()); - throw new I2B2DAOException("Database Error"); - } - */ - - //jgk - // This does a linear search through fullnames for each previous fullname, O(n^2) :( - // BUT it assumes its sorted by hlevel so it only has to search through whats already seen - n(n+1)/2 operations - if (list.size()>0 && vocabType.isReducedResults()!=null && vocabType.isReducedResults()) { - ArrayList seen = new ArrayList(); - ArrayList keep = new ArrayList(); - Iterator it = list.iterator(); - while (it.hasNext()) - { - ConceptType node = (ConceptType)it.next(); - String key = node.getKey(); - boolean bAbort = false; - for (String k : seen) { - if(key.startsWith(k) && !key.equals(k) /* <-- don't kill the synonyms */ ) { - bAbort = true; - break; - } - } - if (vocabType.getMax() == 0) { - if (node.getTotalnum() != null && node.getTotalnum() > 0) { - keep.add(node); - } - } - else if (!bAbort) { - // Add nodes that were not subsumed to the keep list - keep.add(node); - } - // Hidden and inactive should not subsume other nodes - exclude them - if (node.getVisualattributes().contains("A")) - seen.add(node.getKey()); - } - log.debug("Reduced find terms from "+list.size()+" to "+keep.size()); - list = keep; - } - - if (vocabType.isKeyname()!=null && vocabType.isKeyname()) { - // Only do keyname lookups if we haven't exceeded the max - HashMap KeynameCache = new HashMap(); - int skipCount = 0; // for debug, number of cache hits - //int skipPathCount = category.split("\\\\").length -2; // preamble elements in path, not to be output in key name (everything but final element in category path) - - // A little code to ignore a path in the category name, if there is more than one element. - // e.g., \\i2b2_MED\Medications\ will ignore i2b2_MED - String[] skipPaths = category.split("\\\\"); - String skipPath = ""; - for (int j=1;jvocabType.getMax()) break; - - if (KeynameCache.containsKey(parentPath)) { - cType.setKeyName(KeynameCache.get(parentPath)); - skipCount++; - } - else { - if(dbInfo.getDb_serverType().toUpperCase().equals("SQLSERVER")){ - sql = "WITH pathnames "; - sql += " AS"; - sql += " ("; - sql += " select c_name, c_fullname,"; - sql += " substring(c_fullname, 1, len(c_fullname) - charindex('\\', reverse(c_fullname), 2) + 1) as c_path,"; - sql += " 1 as c_pathorder"; - sql += " from " + metadataSchema+tableName + " where c_fullname = ? and c_synonym_cd='N'"; - sql += " UNION ALL"; - sql += " select m.c_name, m.c_fullname, substring(m.c_fullname, 1, len(m.c_fullname) - charindex('\\', reverse(m.c_fullname), 2) + 1) as c_path, c_pathorder + 1 as c_pathorder"; - sql += " from " + metadataSchema+tableName + " m"; - sql += " inner join pathnames p on m.c_fullname = p.c_path where c_synonym_cd='N'"; - sql += " )"; - sql += " SELECT distinct c_name, c_fullname, c_pathorder as c_hlevel"; - sql += " FROM pathnames"; - sql += " order by c_pathorder desc "; - - } - - else if(dbInfo.getDb_serverType().toUpperCase().equals("ORACLE")){ - - - sql = "WITH pathnames (c_name, c_fullname, c_path, c_pathorder) "; - sql += " AS "; - sql += " ( "; - sql += " select c_name, c_fullname, "; - sql += " substr(c_fullname, 1, length(c_fullname) - instr(reverse(c_fullname),'\\', 2) + 1) as c_path,"; - sql += " 1 as c_pathorder"; - sql += " from " + metadataSchema+tableName + " where c_fullname = ? and c_synonym_cd='N'"; - sql += " UNION ALL"; - sql += " select m.c_name, m.c_fullname, substr(m.c_fullname, 1, length(m.c_fullname) - instr(reverse(m.c_fullname), '\\', 2) + 1) as c_path, c_pathorder + 1 as c_pathorder"; - sql += " from " + metadataSchema+tableName + " m"; - sql += " inner join pathnames p on m.c_fullname = p.c_path where c_synonym_cd='N'"; - - sql += " )"; - sql += " SELECT distinct c_name, c_fullname, c_pathorder as c_hlevel"; - sql += " FROM pathnames"; - sql += " order by c_pathorder desc "; - } else if(dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL")){ - - sql = "WITH RECURSIVE pathnames "; - sql += " AS"; - sql += " ("; - sql += " select c_name, c_fullname,"; - sql += " substr(c_fullname, 1, length(c_fullname) - strpos(substr(reverse(c_fullname), 2), '\\') ) as c_path,"; - sql += " 1 as c_pathorder"; - sql += " from " + metadataSchema+tableName + " where c_fullname = ? and c_synonym_cd='N'"; - sql += " UNION ALL"; - sql += " select m.c_name, m.c_fullname, "; - sql += " substr(m.c_fullname, 1, length(m.c_fullname) - strpos(substr(reverse(m.c_fullname), 2), '\\') ) as c_path, c_pathorder + 1 as c_pathorder"; - - sql += " from " + metadataSchema+tableName + " m"; - sql += " inner join pathnames p on m.c_fullname = p.c_path where c_synonym_cd='N'"; - - sql += " ) "; - sql += " SELECT distinct c_name, c_fullname, c_pathorder as c_hlevel"; - sql += " FROM pathnames"; - sql += " order by c_pathorder desc"; - } - - - //List rows = jt.queryForList(sql, path); - - /* - * List names = jt.query(sql, new RowMapper() { - public Object mapRow(ResultSet resultSet, int i) throws SQLException { - return resultSet.getString(1); - } - }, path); - */ - List names = jt.query(sql, new RowMapper() { - public ConceptType mapRow(ResultSet rs, int rowNum) throws SQLException { - ConceptType category = new ConceptType(); - - category.setKey(rs.getString("c_fullname")); - category.setLevel(rs.getInt("c_hlevel")); - category.setName(rs.getString("c_name")); - return category; - } - }/*new GetConceptParentMapper()*/, parentPath); - - cType.setKeyName("\\"); - for (int y=0; y< names.size(); y++) { - if(names.get(y).getKey().equals(skipPath)) continue; // only one path component for the category is ever included - if(names.get(y).getKey().equals(category)) - cType.setKeyName(cType.getKeyName() + name); // Use the category name instead of the db row name, for clarity - else cType.setKeyName(cType.getKeyName() + names.get(y).getName()); - if ((y + 1) < names.size()) - cType.setKeyName(cType.getKeyName() + "\\" ); - //+ \\ "); - - } - // In the event that the category does not have a row in the ontology, insert an entry for it manually - // TODO: Is the actual category name anywhere? (Currently using the code) - if (names.size()+skipPaths.length-20) log.debug("Skipped keyname lookups due to caching ="+skipCount); - } - - // Add list to results after adding parent list names - if (queryResult == null) - queryResult = list; - else - queryResult.addAll(list); - - } catch (DataAccessException e) { - log.error("Search by Name " + e.getMessage()); - e.printStackTrace(); - throw new I2B2DAOException("Database Error"); - } - } - log.debug("search by NameInfo result size = " + queryResult.size()); - - - return queryResult; - - } - - public List findCodeInfo(final VocabRequestType vocabType, ProjectType projectInfo, DBInfoType dbInfo) throws I2B2DAOException, I2B2Exception{ - - // find return parameters - String parameters = NAME_DEFAULT; - - if (vocabType.getType().equals("limited")){ - parameters = LIMITED; - } - - else if (vocabType.getType().equals("core")){ - parameters = CORE; - } - - else if (vocabType.getType().equals("all")){ - parameters = CORE + ALL; - } - if(vocabType.isBlob() == true) - parameters = parameters + BLOB; - - String metadataSchema = dbInfo.getDb_fullSchema(); - setDataSource(dbInfo.getDb_dataSource()); - - String dbType = dbInfo.getDb_serverType(); - - // log.info(metadataSchema); - - if (projectInfo.getRole().size() == 0) - { - log.error("no role found for this user in project: " + projectInfo.getName()); - I2B2Exception e = new I2B2Exception("No role found for user"); - throw e; - } - - - - - String hidden = ""; - String whereHidden = ""; - if(vocabType.isHiddens() == false) { - hidden = " and c_visualattributes not like '_H%'"; - whereHidden = " where c_visualattributes not like '_H%'"; - } - //no table code provided so check all tables user has access to - List tableNames=null; - String tableSql = "select distinct(c_table_name) from " + metadataSchema + "table_access " + whereHidden; - try { - tableNames = jt.queryForList(tableSql, String.class); - } catch (DataAccessException e) { - log.error("Search by Code " + e.getMessage()); - throw new I2B2DAOException("Database Error"); - } - - String synonym = ""; - if(vocabType.isSynonyms() == false) - synonym = " and c_synonym_cd = 'N'"; - - // I have to do this the hard way because there are a dynamic number of codes to pass in - // prevent SQL injection - String value = vocabType.getMatchStr().getValue(); - if(value.contains("'")){ - value = vocabType.getMatchStr().getValue().replaceAll("'", "''"); - } - String whereClause = null; - - String compareCode = value.toUpperCase(); - - if(vocabType.getMatchStr().getStrategy().equals("exact")) { - whereClause = " where upper(c_basecode) = '" + compareCode+ "'"; - } - - else { // need escape logic for like operator - - if(dbType.toUpperCase().equals("SQLSERVER")){ - compareCode = StringUtil.escapeSQLSERVER(compareCode); - } - else if(dbType.toUpperCase().equals("ORACLE")){ - compareCode = StringUtil.escapeORACLE(compareCode); - } - else if(dbType.toUpperCase().equals("POSTGRESQL")){ - compareCode = StringUtil.escapePOSTGRESQL(compareCode); - } - - if(vocabType.getMatchStr().getStrategy().equals("left")){ - whereClause = " where upper(c_basecode) like '" + compareCode + "%' " + (!dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL") ? "{ESCAPE '?'}" : "" ) ; //{ESCAPE '?'}"; - } - - else if(vocabType.getMatchStr().getStrategy().equals("right")) { - compareCode = compareCode.replaceFirst(":", ":%"); - whereClause = " where upper(c_basecode) like '" + compareCode + "' " + (!dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL") ? "{ESCAPE '?'}" : "" ) ; //{ESCAPE '?'}"; - } - - else if(vocabType.getMatchStr().getStrategy().equals("contains")) { - compareCode = compareCode.replaceFirst(":", ":%"); - whereClause = " where upper(c_basecode) like '" + compareCode + "%' " + (!dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL") ? "{ESCAPE '?'}" : "" ) ; //{ESCAPE '?'}"; - } - } - // log.debug(vocabType.getMatchStr().getStrategy() + whereClause); - - String codeInfoSql = null; - if(tableNames != null){ - Iterator itTn = tableNames.iterator(); - String table = (String)itTn.next(); - // the following (distinct) doesnt work for a flattened hierarchy but is left for - // dbs other than sqlserver or oracle. [c_table_cd is needed for key] - String tableCdSql = ", (select distinct(c_table_cd) from "+ metadataSchema + "TABLE_ACCESS where c_table_name = '"+ table+ "') as tableCd"; - if(dbType.toUpperCase().equals("SQLSERVER")) - tableCdSql = ", (select top 1(c_table_cd) from "+ metadataSchema + "TABLE_ACCESS where c_table_name = '"+ table+ "') as tableCd"; - else if (dbType.toUpperCase().equals("ORACLE")) - tableCdSql = ", (select c_table_cd from "+ metadataSchema + "TABLE_ACCESS where c_table_name = '"+ table+ "' and rownum <= 1) as tableCd"; - else if(dbType.toUpperCase().equals("POSTGRESQL")) - tableCdSql = ", (select c_table_cd from "+ metadataSchema + "TABLE_ACCESS where c_table_name = '"+ table+ "' limit 1) as tableCd"; - codeInfoSql = "select " + parameters + tableCdSql + " from " + metadataSchema + table + whereClause + hidden + synonym;; - while(itTn.hasNext()){ - table = (String)itTn.next(); - // the following (distinct) doesnt work for a flattened hierarchy but is left for - // dbs other than sqlserver or oracle. [c_table_cd is needed for key] - tableCdSql = ", (select distinct(c_table_cd) from "+ metadataSchema + "TABLE_ACCESS where c_table_name = '"+ table+ "') as tableCd"; - if(dbType.toUpperCase().equals("SQLSERVER")) - tableCdSql = ", (select top 1(c_table_cd) from "+ metadataSchema + "TABLE_ACCESS where c_table_name = '"+ table+ "') as tableCd"; - else if (dbType.toUpperCase().equals("ORACLE")) - tableCdSql = ", (select c_table_cd from "+ metadataSchema + "TABLE_ACCESS where c_table_name = '"+ table+ "' and rownum <= 1) as tableCd"; - else if(dbType.toUpperCase().equals("POSTGRESQL")) - tableCdSql = ", (select c_table_cd from "+ metadataSchema + "TABLE_ACCESS where c_table_name = '"+ table+ "' limit 1) as tableCd"; - - codeInfoSql = codeInfoSql + " union all (select "+ parameters + tableCdSql + " from " + metadataSchema + table + whereClause - + hidden + synonym + ")"; - } - codeInfoSql = codeInfoSql + " order by (c_name) "; - } - else - return null; - - boolean obfuscatedUserFlag = Roles.getInstance().isRoleOfuscated(projectInfo); - // ParameterizedRowMapper mapper = getMapper(new NodeType(vocabType),obfuscatedUserFlag, dbInfo.getDb_serverType()); - - List queryResult = null; - try { - String sqlFinal = codeInfoSql; - queryResult = jt.query(sqlFinal, getConceptNodeMapper(new NodeType(vocabType),obfuscatedUserFlag, dbInfo.getDb_serverType())); - } catch (DataAccessException e) { - log.error("Search by Code " + e.getMessage()); - throw new I2B2DAOException("Database Error"); - } - - log.debug("searchByCodeInfo result size = " + queryResult.size()); - - - return queryResult; - - } - - - /* - private ParameterizedRowMapper getColumnMapper() { - - ParameterizedRowMapper mapper = new ParameterizedRowMapper() { - public String mapRow(ResultSet rs, int rowNum) throws SQLException { - String derivedFactTableColumn; - derivedFactTableColumn=(rs.getString("c_facttablecolumn")); - return derivedFactTableColumn; - } - }; - return mapper; - } - */ - - - - private String parseMatchString(String match, DBInfoType dbInfo){ - String whereClause = null; - - String[] terms = match.split(" "); - ArrayList goodWords = new ArrayList(); - - String word = getStopWords(); - for(int i=0; i< terms.length; i++){ - if(word.contains(terms[i])) - ; - else{ - goodWords.add(terms[i]); - } - } - - if(goodWords.isEmpty()) - return null; - - Iterator it = goodWords.iterator(); - while(it.hasNext()){ - if(whereClause == null) - whereClause = " where upper(c_name) like " + "'%" + ((String)it.next()).toUpperCase() + "%' " + (!dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL") ? "{ESCAPE '?'}" : "" ) ; //{ESCAPE '?'}"; - else - whereClause = whereClause + " AND upper(c_name) like " + "'% " + ((String)it.next()).toUpperCase() + "%' " + (!dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL") ? "{ESCAPE '?'}" : "" ) ; //{ESCAPE '?'}"; - } - return whereClause; - } - - private String getStopWords(){ - - String stopWord = null; - try { - stopWord = OntologyUtil.getInstance().getStopWord(); - } catch (I2B2Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - //"a,able,about,across,after,all,almost,also,am,among,an,and,any,are,as,at,be,because,been,but,by,can,cannot,could,dear,did,do,does,either,else,ever,every,for,from,get,got,had,has,have,he,her,hers,him,his,how,however,i,if,in,into,is,it,its,just,least,let,like,likely,may,me,might,most,must,my,neither,no,nor,not,of,off,often,on,only,or,other,our,own,rather,said,say,says,she,should,since,so,some,than,that,the,their,them,then,there,these,they,this,tis,to,too,twas,us,wants,was,we,were,what,when,where,which,while,who,whom,why,will,with,would,yet,you,your"; - // String[] stopWords = stopWord.split("'"); - return stopWord; - } - - public List findModifiers(final GetModifiersType modifierType, ProjectType projectInfo, DBInfoType dbInfo) throws I2B2DAOException, I2B2Exception{ - - // find return parameters - String parameters = MOD_DEFAULT; - if (modifierType.getType().equals("limited")){ - parameters = MOD_LIMITED; - } - else if (modifierType.getType().equals("core")){ - parameters = MOD_CORE; - } - else if (modifierType.getType().equals("all")){ - parameters = MOD_CORE + ALL; - } - if(modifierType.isBlob() == true) - parameters = parameters + BLOB; - - String metadataSchema = dbInfo.getDb_fullSchema(); - setDataSource(dbInfo.getDb_dataSource()); - - if (projectInfo.getRole().size() == 0) - { - log.error("no role found for this user in project: " + projectInfo.getName()); - I2B2Exception e = new I2B2Exception("No role found for user"); - throw e; - } - - - - - - String hidden = ""; - if(modifierType.isHiddens() == false) - hidden = " and c_visualattributes not like '_H%'"; - - //extract table code - String tableCd = StringUtil.getTableCd(modifierType.getSelf()); - String tableName=null; - String tableSql = "select distinct(c_table_name) from " + metadataSchema + "table_access where c_table_cd = ? " + hidden; - try { - tableName = jt.queryForObject(tableSql, String.class, tableCd); - } catch (DataAccessException e) { - log.error("Find Modifiers " + e.getMessage()); - throw new I2B2DAOException("Database Error"); - } - - - - - // Original sql before exclusions - // String path = StringUtil.getLiteralPath(modifierType.getSelf()); - /* String sql = "select " + parameters +" from " + metadataSchema+ tableName + " where m_applied_path = '" + path + "' and c_hlevel = 1"; - while (path.length() > 2) { - if(path.endsWith("%")){ - path = path.substring(0, path.length()-2); - path = path.substring(0, path.lastIndexOf("\\") + 1) + "%"; - } - else - path = path + "%"; - sql = sql + " union all (select " + parameters +" from " + metadataSchema+ tableName + " where m_applied_path = '" + path + "' and c_hlevel = 1)"; - } - */ - String path = StringUtil.getLiteralPath(modifierType.getSelf()); - // I have to do this the hard way because there are a dynamic number of applied paths to check - // prevent SQL injection - if(path.contains("'")){ - path = path.replaceAll("'", "''"); - } - - String synonym = ""; - if(modifierType.isSynonyms() == false) - synonym = " and c_synonym_cd = 'N'"; - - - // String sql = "select " + parameters + " from "+ metadataSchema+ tableName + " where m_exclusion_cd is null and c_fullname in ("; - String inclusionSql = "select c_fullname from " + metadataSchema+ tableName + " where m_applied_path = '" + path + "' and c_hlevel = 1 and m_exclusion_cd is null " + hidden + synonym; - String modifier_select = " and m_applied_path in ('" + path + "'"; - while (path.length() > 2) { - if(path.endsWith("%")){ - path = path.substring(0, path.length()-2); - path = path.substring(0, path.lastIndexOf("\\") + 1) + "%"; - } - else - path = path + "%"; - inclusionSql = inclusionSql + " union all (select c_fullname from " + metadataSchema+ tableName + " where m_applied_path = '" + path + "' and c_hlevel = 1 and m_exclusion_cd is null " + hidden + synonym +")"; - modifier_select = modifier_select + ", '" + path + "'"; - } - - String sql = "select " + parameters + " from "+ metadataSchema+ tableName + " where m_exclusion_cd is null " + synonym + modifier_select +") and c_fullname in ("; - - if(dbInfo.getDb_serverType().toUpperCase().equals("ORACLE")) - sql = sql + inclusionSql + " MINUS ("; - else - sql = sql + inclusionSql + " EXCEPT ("; - - path = StringUtil.getLiteralPath(modifierType.getSelf()); - // I have to do this the hard way because there are a dynamic number of applied paths to check - // prevent SQL injection - if(path.contains("'")){ - path = path.replaceAll("'", "''"); - } - String exclusionSql = "select c_fullname from " + metadataSchema+ tableName + " where m_applied_path = '" + path + "' and m_exclusion_cd is not null"; - while (path.length() > 2) { - if(path.endsWith("%")){ - path = path.substring(0, path.length()-2); - path = path.substring(0, path.lastIndexOf("\\") + 1) + "%"; - } - else - path = path + "%"; - exclusionSql = exclusionSql + " union all (select c_fullname from " + metadataSchema+ tableName + " where m_applied_path = '" + path + "' and m_exclusion_cd is not null)"; - } - /* // applied paths on exclusions dont end in % - while (path.length() > 2) { - path = path.substring(0, path.length()-2); - path = path.substring(0, path.lastIndexOf("\\") +1) ; - exclusionSql = exclusionSql + " union all (select c_fullname from " + metadataSchema+ tableName + " where m_applied_path = '" + path + "' and m_exclusion_cd = 'X')"; - } - */ - sql = sql + exclusionSql + "))"; - - sql = sql + " order by (c_name) "; - - // ("findMods: " + sql ); - final boolean ofuscatedUserFlag = Roles.getInstance().isRoleOfuscated(projectInfo); - - // ParameterizedRowMapper modMapper = getModMapper(new NodeType (modifierType), ofuscatedUserFlag, dbInfo.getDb_serverType()); - - List queryResult = null; - - try { - // queryResult = jt.query(sql, modMapper, path ); - queryResult = jt.query(sql, getModNodeMapper(new NodeType(modifierType),ofuscatedUserFlag, dbInfo.getDb_serverType())); - } catch (DataAccessException e) { - log.error("Find Modifiers " + e.getMessage()); - throw new I2B2DAOException("Database Error"); - } - log.debug("findModifiers result size " + queryResult.size()); - return queryResult; - } - - - public List findChildrenByParent(final GetModifierChildrenType modifierChildrenType, ProjectType projectInfo, DBInfoType dbInfo) throws I2B2DAOException, I2B2Exception{ - - // ("MOD: " + modifierChildrenType.getParent()); - // log.debug("MOD: " + modifierChildrenType.getAppliedPath()); - - // find return parameters - String parameters = MOD_DEFAULT; - if (modifierChildrenType.getType().equals("limited")){ - parameters = MOD_LIMITED; - } - else if (modifierChildrenType.getType().equals("core")){ - parameters = MOD_CORE; - } - else if (modifierChildrenType.getType().equals("all")){ - parameters = MOD_CORE + ALL; - } - if(modifierChildrenType.isBlob() == true) - parameters = parameters + BLOB; - - String metadataSchema = dbInfo.getDb_fullSchema(); - setDataSource(dbInfo.getDb_dataSource()); - - if (projectInfo.getRole().size() == 0) - { - log.error("no role found for this user in project: " + projectInfo.getName()); - I2B2Exception e = new I2B2Exception("No role found for user"); - throw e; - } - - - - String hidden = ""; - if(modifierChildrenType.isHiddens() == false) - hidden = " and c_visualattributes not like '_H%'"; - - //extract table code - String tableCd = StringUtil.getTableCd(modifierChildrenType.getParent()); - String tableName=null; - String tableSql = "select distinct(c_table_name) from " + metadataSchema + "table_access where c_table_cd = ? " + hidden; - try { - tableName = jt.queryForObject(tableSql, String.class, tableCd); - } catch (DataAccessException e) { - log.error("Get Modifier Children " + e.getMessage()); - throw new I2B2DAOException("Database Error"); - } - - String path = StringUtil.getPath(modifierChildrenType.getParent()); - - String searchPath = path; - if(dbInfo.getDb_serverType().toUpperCase().equals("SQLSERVER")){ - searchPath = StringUtil.escapeSQLSERVER(searchPath); - } - else if(dbInfo.getDb_serverType().toUpperCase().equals("ORACLE")){ - searchPath = StringUtil.escapeORACLE(searchPath); - } - else if(dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL")){ - searchPath = StringUtil.escapePOSTGRESQL(searchPath); - } - - searchPath = searchPath + "%"; - - String levelSql = "select c_hlevel from " + metadataSchema+tableName + " where c_fullname = ? and c_synonym_cd = 'N' and m_applied_path = ? and m_exclusion_cd is null"; - - int level = 0; - try { - level = jt.queryForObject(levelSql, Integer.class, path, modifierChildrenType.getAppliedPath()); - } catch (DataAccessException e1) { - // should only get 1 result back (path == c_fullname which should be unique) - log.error("Get Modifier Children " + e1.getMessage()); - throw new I2B2DAOException("Database Error"); - } - - String synonym = ""; - if(modifierChildrenType.isSynonyms() == false) - synonym = " and c_synonym_cd = 'N'"; - - String appliedConcept = StringUtil.getLiteralPath(modifierChildrenType.getAppliedConcept()); - // I have to do this the hard way because there are a dynamic number of applied paths to check - // prevent SQL injection - if(appliedConcept.contains("'")){ - appliedConcept = appliedConcept.replaceAll("'", "''"); - } - - String inclusionSql = "select c_fullname from " + metadataSchema+ tableName + " where m_applied_path = ? and c_hlevel = " + (level+1) + " and m_exclusion_cd is null"; - String modifier_select = " and m_applied_path in ('" + appliedConcept + "'"; - while (appliedConcept.length() > 2) { - if(appliedConcept.endsWith("%")){ - appliedConcept = appliedConcept.substring(0, appliedConcept.length()-2); - appliedConcept = appliedConcept.substring(0, appliedConcept.lastIndexOf("\\") + 1) + "%"; - } - else - appliedConcept = appliedConcept + "%"; - inclusionSql = inclusionSql + " union all (select c_fullname from " + metadataSchema+ tableName + " where m_applied_path = '" + appliedConcept + "' and c_hlevel = " + (level+1) + " and m_exclusion_cd is null)"; - modifier_select = modifier_select + ", '" + appliedConcept + "'"; - } - - String sql = "select " + parameters + " from "+ metadataSchema+ tableName + " where m_exclusion_cd is null and c_hlevel = ? and c_fullname like ? " + (!dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL") ? "{ESCAPE '?'}" : "" ) + hidden + synonym - + modifier_select +") and c_fullname in ("; - - - if(dbInfo.getDb_serverType().toUpperCase().equals("ORACLE")) - sql = sql + inclusionSql + " MINUS ("; - else - sql = sql + inclusionSql + " EXCEPT ("; - - String exclusionSql = "select c_fullname from " + metadataSchema+ tableName + " where m_applied_path = ? and m_exclusion_cd is not null"; - String appliedExclConcept = StringUtil.getLiteralPath(modifierChildrenType.getAppliedConcept()); - // I have to do this the hard way because there are a dynamic number of applied paths to check - // prevent SQL injection - if(appliedExclConcept.contains("'")){ - appliedExclConcept = appliedExclConcept.replaceAll("'", "''"); - } - while (appliedExclConcept.length() > 2) { - if(appliedExclConcept.endsWith("%")){ - appliedExclConcept = appliedExclConcept.substring(0, appliedExclConcept.length()-2); - appliedExclConcept = appliedExclConcept.substring(0, appliedExclConcept.lastIndexOf("\\") + 1) + "%"; - } - else - appliedExclConcept = appliedExclConcept + "%"; - exclusionSql = exclusionSql + " union all (select c_fullname from " + metadataSchema+ tableName + " where m_applied_path = '" + appliedExclConcept + "' and m_exclusion_cd is not null)"; - } - - sql = sql + exclusionSql + "))"; - - sql = sql + " order by (c_name) "; - - // log.debug("findModChildren: " + sql + (level+1) + searchPath + StringUtil.getLiteralPath(modifierChildrenType.getAppliedConcept())); - - - final boolean ofuscatedUserFlag = Roles.getInstance().isRoleOfuscated(projectInfo); - - //ParameterizedRowMapper modMapper = getModMapper(new NodeType (modifierChildrenType), ofuscatedUserFlag, dbInfo.getDb_serverType()); - - List queryResult = null; - - try { - queryResult = jt.query(sql, getModNodeMapper(new NodeType(modifierChildrenType),ofuscatedUserFlag, dbInfo.getDb_serverType()), (level+1), searchPath, StringUtil.getLiteralPath(modifierChildrenType.getAppliedConcept()), - StringUtil.getLiteralPath(modifierChildrenType.getAppliedConcept())); - } catch (DataAccessException e) { - log.error("Get Modifier Children " + e.getMessage()); - throw new I2B2DAOException("Database Error"); - } - - - log.debug("Get Mod children result size = " + queryResult.size()); - - - return queryResult; - - } - - - - public List findByFullname(final GetModifierInfoType modifierInfoType, ProjectType projectInfo, DBInfoType dbInfo) throws I2B2DAOException, I2B2Exception{ - - // find return parameters - String parameters = MOD_DEFAULT; - if (modifierInfoType.getType().equals("limited")){ - parameters = MOD_LIMITED; - } - else if (modifierInfoType.getType().equals("core")){ - parameters = MOD_CORE; - } - else if (modifierInfoType.getType().equals("all")){ - parameters = MOD_CORE + ALL; - } - if(modifierInfoType.isBlob() == true) - parameters = parameters + BLOB; - - String metadataSchema = dbInfo.getDb_fullSchema(); - setDataSource(dbInfo.getDb_dataSource()); - - if (projectInfo.getRole().size() == 0) - { - log.error("no role found for this user in project: " + projectInfo.getName()); - I2B2DAOException e = new I2B2DAOException("No role found for user"); - throw e; - } - - //tableCd to table name conversion - - - String hidden = ""; - if(modifierInfoType.isHiddens() == false) - hidden = " and c_visualattributes not like '_H%'"; - - - //extract table code - String tableCd = StringUtil.getTableCd(modifierInfoType.getSelf()); - String tableName=null; - String tableSql = "select distinct(c_table_name) from " + metadataSchema + "table_access where c_table_cd = ? " + hidden; - try { - tableName = jt.queryForObject(tableSql, String.class, tableCd); - } catch (DataAccessException e) { - log.error("Get Modifier " + e.getMessage()); - throw new I2B2DAOException("Database Error"); - } - - String path = StringUtil.getPath(modifierInfoType.getSelf()); - String searchPath = path; - - - String synonym = ""; - if(modifierInfoType.isSynonyms() == false) - synonym = " and c_synonym_cd = 'N'"; - - // Removed dependency on m_applied_path 8/4/14 lcp - String sqlWpath = "select " + parameters +" from " + metadataSchema+tableName + " where c_fullname = ? and m_applied_path = ?"; - String sql = "select " + parameters +" from " + metadataSchema+tableName + " where c_fullname = ? "; - - // Putting applied path back.. 1/4/16 CORE-203 - // Was originally omitted for SHRINE (paths would be invalid) but result is that MANY modifiers return and messes up i2b2 - // So first search via applied path; if that returns zero then search w/o applied path - - - sqlWpath = sqlWpath + hidden + synonym + " order by upper(c_name) "; - - //log.info(sql + " " + path + " " + level); - - final boolean ofuscatedUserFlag = Roles.getInstance().isRoleOfuscated(projectInfo); - - // ParameterizedRowMapper modMapper = getModMapper(new NodeType (modifierInfoType), ofuscatedUserFlag, dbInfo.getDb_serverType()); - - List queryResult = null; - try { - queryResult = jt.query(sqlWpath, getModNodeMapper(new NodeType(modifierInfoType),ofuscatedUserFlag, dbInfo.getDb_serverType()), searchPath, modifierInfoType.getAppliedPath()); - - } catch (DataAccessException e) { - log.error("Get Modifier " + e.getMessage()); - throw new I2B2DAOException("Database Error"); - } - - if(queryResult.size() == 0){ - sql = sql + hidden + synonym + " order by upper(c_name) "; - - try { - queryResult = jt.query(sql, getModNodeMapper(new NodeType(modifierInfoType),ofuscatedUserFlag, dbInfo.getDb_serverType()), searchPath); - - } catch (DataAccessException e) { - log.error("Get Modifier " + e.getMessage()); - throw new I2B2DAOException("Database Error"); - } - } - - log.debug("Get ModInfo result size = " + queryResult.size()); - - - return queryResult; - - } - - public List findModifierNameInfo(final VocabRequestType vocabType, ProjectType projectInfo, DBInfoType dbInfo) throws I2B2DAOException, I2B2Exception{ - - // find return parameters - String parameters = NAME_DEFAULT; - - if (vocabType.getType().equals("limited")){ - parameters = MOD_LIMITED; - } - - else if (vocabType.getType().equals("core")){ - parameters = MOD_CORE; - } - - else if (vocabType.getType().equals("all")){ - parameters = MOD_CORE + ALL; - } - if(vocabType.isBlob() == true) - parameters = parameters + BLOB; - - String metadataSchema = dbInfo.getDb_fullSchema(); - setDataSource(dbInfo.getDb_dataSource()); - - // log.info(metadataSchema); - - if (projectInfo.getRole().size() == 0) - { - log.error("no role found for this user in project: " + projectInfo.getName()); - I2B2Exception e = new I2B2Exception("No role found for user"); - throw e; - } - - //tableCd to table name conversion - - - //extract table code - String tableCd = StringUtil.getTableCd(vocabType.getSelf()); - String tableName=null; - String tableSql = "select distinct(c_table_name) from " + metadataSchema + "table_access where c_table_cd = ? " ; - try { - tableName = jt.queryForObject(tableSql, String.class, tableCd); - } catch (DataAccessException e) { - log.error("Get Modifier by name " + e.getMessage()); - throw new I2B2DAOException("Database Error"); - } - - // prevent SQL injection and also catch case where the value contains an (') - String value = vocabType.getMatchStr().getValue(); - if(value.contains("'")){ - value = vocabType.getMatchStr().getValue().replaceAll("'", "''"); - } - String nameInfoSql = null; - String compareName = null; - String modifierPath = StringUtil.getLiteralPath(vocabType.getSelf()); - if(modifierPath.contains("'")){ - modifierPath = modifierPath.replaceAll("'", "''"); - } - - if(vocabType.getMatchStr().getStrategy().equals("exact")) { - compareName = value.toUpperCase(); - nameInfoSql = "select c_fullname from " + metadataSchema + tableName + " where upper(c_name) = '" + compareName + "'" ;//and m_applied_path = '" + path + "'"; - } - - else if(vocabType.getMatchStr().getStrategy().equals("left")){ - compareName = value.toUpperCase(); - if(dbInfo.getDb_serverType().toUpperCase().equals("SQLSERVER")){ - //compareName = compareName.replaceAll("\\[", "[[]"); - compareName = StringUtil.escapeSQLSERVER(compareName); - } - else if(dbInfo.getDb_serverType().toUpperCase().equals("ORACLE")){ - compareName = StringUtil.escapeORACLE(compareName); - } - else if(dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL")){ - compareName = StringUtil.escapePOSTGRESQL(compareName); - } - compareName += "%"; - nameInfoSql = "select c_fullname from " + metadataSchema + tableName +" where upper(c_name) like '" + compareName + "' " + (!dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL") ? "{ESCAPE '?'}" : "" ) ; //{ESCAPE '?'}"; and m_applied_path = '" + path + "'"; - } - - else if(vocabType.getMatchStr().getStrategy().equals("right")) { - compareName = value.toUpperCase(); - if(dbInfo.getDb_serverType().toUpperCase().equals("SQLSERVER")){ - //compareName = compareName.replaceAll("\\[", "[[]"); - compareName = StringUtil.escapeSQLSERVER(compareName); - } - else if(dbInfo.getDb_serverType().toUpperCase().equals("ORACLE")){ - compareName = StringUtil.escapeORACLE(compareName); - } - else if(dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL")){ - compareName = StringUtil.escapePOSTGRESQL(compareName); - } - compareName = "%" + compareName; - nameInfoSql = "select c_fullname from " + metadataSchema + tableName +" where upper(c_name) like '" + compareName + "' " + (!dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL") ? "{ESCAPE '?'}" : "" ) ; //{ESCAPE '?'}"; {ESCAPE '?'}";//and m_applied_path = '" + path + "'"; - } - - else if(vocabType.getMatchStr().getStrategy().equals("contains")) { - if(!(value.contains(" "))){ - // compareName = "%" + value.toUpperCase() + "%"; - compareName = value.toUpperCase(); - if(dbInfo.getDb_serverType().toUpperCase().equals("SQLSERVER")){ - //compareName = compareName.replaceAll("\\[", "[[]"); - compareName = StringUtil.escapeSQLSERVER(compareName); - } - else if(dbInfo.getDb_serverType().toUpperCase().equals("ORACLE")){ - compareName = StringUtil.escapeORACLE(compareName); - } - else if(dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL")){ - compareName = StringUtil.escapePOSTGRESQL(compareName); - } - compareName = "%" + compareName + "%"; - nameInfoSql = "select c_fullname from " + metadataSchema + tableName +" where upper(c_name) like '" + compareName + "' " + (!dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL") ? "{ESCAPE '?'}" : "" ) ; //{ESCAPE '?'}"; {ESCAPE '?'}"; //and m_applied_path = '" + path + "'"; - - }else{ - nameInfoSql = "select c_fullname from " + metadataSchema + tableName ; - // if(dbInfo.getDb_serverType().toUpperCase().equals("SQLSERVER")){ - // value = value.replaceAll("\\[", "[[]"); - // } - if(dbInfo.getDb_serverType().toUpperCase().equals("SQLSERVER")){ - value = StringUtil.escapeSQLSERVER(value); - } - else if(dbInfo.getDb_serverType().toUpperCase().equals("ORACLE")){ - value = StringUtil.escapeORACLE(value); - } - else if(dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL")){ - value = StringUtil.escapePOSTGRESQL(value); - } - nameInfoSql = nameInfoSql + parseMatchString(value, dbInfo);// + "and m_applied_path = '" + path + "'"; - compareName = null; - } - } - - String appliedPath = " and m_applied_path = '" + modifierPath + "' "; - - String hidden = ""; - if(vocabType.isHiddens() == false) - hidden = " and c_visualattributes not like '_H%' "; - - String synonym = ""; - if(vocabType.isSynonyms() == false) - synonym = " and c_synonym_cd = 'N' "; - - String inclusionSql = nameInfoSql + appliedPath + hidden + synonym + " and m_exclusion_cd is null "; - String modifierSelect = "'" + modifierPath + "'"; - while (modifierPath.length() > 3) { - if(modifierPath.endsWith("%")){ - modifierPath = modifierPath.substring(0, modifierPath.length()-2); - modifierPath = modifierPath.substring(0, modifierPath.lastIndexOf("\\") + 1) + "%"; - } - else - modifierPath = modifierPath + "%"; - modifierSelect = modifierSelect + ", '" + modifierPath + "'"; - appliedPath = " and m_applied_path = '" + modifierPath + "' "; - inclusionSql = inclusionSql + " union all " + nameInfoSql + appliedPath + hidden + synonym + " and m_exclusion_cd is null "; - } - - String exclusionSql = nameInfoSql + appliedPath + hidden + synonym + " and m_exclusion_cd is not null"; - modifierPath = StringUtil.getLiteralPath(vocabType.getSelf()); - if(modifierPath.contains("'")){ - modifierPath = modifierPath.replaceAll("'", "''"); - } - while (modifierPath.length() > 3) { - if(modifierPath.endsWith("%")){ - modifierPath = modifierPath.substring(0, modifierPath.length()-2); - modifierPath = modifierPath.substring(0, modifierPath.lastIndexOf("\\") + 1) + "%"; - } - else - modifierPath = modifierPath + "%"; - appliedPath = " and m_applied_path = '" + modifierPath + "' "; - exclusionSql = exclusionSql + " union all " + nameInfoSql + appliedPath + hidden + synonym + " and m_exclusion_cd is not null "; - } - - String exceptSql = " EXCEPT ("; - if(dbInfo.getDb_serverType().toUpperCase().equals("ORACLE")) - exceptSql = " MINUS ("; - - - String modNameInfoSql = " select " + parameters + " from " + metadataSchema + tableName + " where m_exclusion_cd is null and m_applied_path in (" - + modifierSelect +") and c_fullname in (" + inclusionSql + exceptSql + exclusionSql + ")) order by (c_name) "; - - // log.debug("MODnameInfo: " + modNameInfoSql + " " +compareName); - boolean obfuscatedUserFlag = Roles.getInstance().isRoleOfuscated(projectInfo); - - // ParameterizedRowMapper modMapper = getModMapper(new NodeType(vocabType), obfuscatedUserFlag, dbInfo.getDb_serverType()); - - List queryResult = null; - try { - if(compareName != null) - queryResult = jt.query(modNameInfoSql, getModNodeMapper(new NodeType(vocabType),obfuscatedUserFlag, dbInfo.getDb_serverType())); - else - queryResult = jt.query(modNameInfoSql, getModNodeMapper(new NodeType(vocabType),obfuscatedUserFlag, dbInfo.getDb_serverType())); - } catch (DataAccessException e) { - log.error("Get Modifier by name " + e.getMessage()); - throw new I2B2DAOException("Database Error"); - } - - log.debug("Mod search by name result size = " + queryResult.size()); - - - return queryResult; - - } - - public List findModifierCodeInfo(final VocabRequestType vocabType, ProjectType projectInfo, DBInfoType dbInfo) throws I2B2DAOException, I2B2Exception{ - - // find return parameters - String parameters = NAME_DEFAULT; - - if (vocabType.getType().equals("limited")){ - parameters = MOD_LIMITED; - } - - else if (vocabType.getType().equals("core")){ - parameters = MOD_CORE; - } - - else if (vocabType.getType().equals("all")){ - parameters = MOD_CORE + ALL; - } - if(vocabType.isBlob() == true) - parameters = parameters + BLOB; - - String metadataSchema = dbInfo.getDb_fullSchema(); - setDataSource(dbInfo.getDb_dataSource()); - - String dbType = dbInfo.getDb_serverType(); - - // log.info(metadataSchema); - - if (projectInfo.getRole().size() == 0) - { - log.error("no role found for this user in project: " + projectInfo.getName()); - I2B2Exception e = new I2B2Exception("No role found for user"); - throw e; - } - - //tableCd to table name conversion - - - String hidden = ""; - if(vocabType.isHiddens() == false) - hidden = " and c_visualattributes not like '_H%'"; - - //extract table code - String tableCd = StringUtil.getTableCd(vocabType.getSelf()); - String tableName=null; - String tableSql = "select distinct(c_table_name) from " + metadataSchema + "table_access where c_table_cd = ? " + hidden; - try { - tableName = jt.queryForObject(tableSql, String.class, tableCd); - } catch (DataAccessException e) { - log.error("Get Modifier by Code " + e.getMessage()); - throw new I2B2DAOException("Database Error"); - } - - String synonym = ""; - if(vocabType.isSynonyms() == false) - synonym = " and c_synonym_cd = 'N'"; - - // I have to do this the hard way because there are a dynamic number of codes to pass in - // prevent SQL injection - String value = vocabType.getMatchStr().getValue(); - if(value.contains("'")){ - value = vocabType.getMatchStr().getValue().replaceAll("'", "''"); - } - String whereClause = null; - - if(vocabType.getMatchStr().getStrategy().equals("exact")) { - whereClause = " where upper(c_basecode) = '" + value.toUpperCase()+ "'"; - } - - else if(vocabType.getMatchStr().getStrategy().equals("left")){ - if(dbInfo.getDb_serverType().toUpperCase().equals("SQLSERVER")){ - value = StringUtil.escapeSQLSERVER(value); - } - else if(dbInfo.getDb_serverType().toUpperCase().equals("ORACLE")){ - value = StringUtil.escapeORACLE(value); - } - else if(dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL")){ - value = StringUtil.escapePOSTGRESQL(value); - } - whereClause = " where upper(c_basecode) like '" + value.toUpperCase() + "%' " + (!dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL") ? "{ESCAPE '?'}" : "" ) ; //{ESCAPE '?'}"; {ESCAPE '?'}"; - } - - else if(vocabType.getMatchStr().getStrategy().equals("right")) { - if(dbInfo.getDb_serverType().toUpperCase().equals("SQLSERVER")){ - value = StringUtil.escapeSQLSERVER(value); - } - else if(dbInfo.getDb_serverType().toUpperCase().equals("ORACLE")){ - value = StringUtil.escapeORACLE(value); - } - value = value.replaceFirst(":", ":%"); - whereClause = " where upper(c_basecode) like '%" + value.toUpperCase() + "' " + (!dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL") ? "{ESCAPE '?'}" : "" ) ; //{ESCAPE '?'}"; {ESCAPE '?'}"; - - } - - else if(vocabType.getMatchStr().getStrategy().equals("contains")) { - if(dbInfo.getDb_serverType().toUpperCase().equals("SQLSERVER")){ - value = StringUtil.escapeSQLSERVER(value); - } - else if(dbInfo.getDb_serverType().toUpperCase().equals("ORACLE")){ - value = StringUtil.escapeORACLE(value); - } - else if(dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL")){ - value = StringUtil.escapePOSTGRESQL(value); - } - value = value.replaceFirst(":", ":%"); - whereClause = " where upper(c_basecode) like '%" + value.toUpperCase() + "%' " + (!dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL") ? "{ESCAPE '?'}" : "" ) ; //{ESCAPE '?'}"; {ESCAPE '?'}"; - } - - String codeInfoSql = "select c_fullname from " + metadataSchema + tableName + whereClause; - - - String modifierPath = StringUtil.getLiteralPath(vocabType.getSelf()); - if(modifierPath.contains("'")){ - modifierPath = modifierPath.replaceAll("'", "''"); - } - String appliedPath = " and m_applied_path = '" + modifierPath + "' "; - String inclusionSql = codeInfoSql + appliedPath + hidden + synonym + " and m_exclusion_cd is null "; - String modifierSelect = "'" + modifierPath + "'"; - while (modifierPath.length() > 3) { - if(modifierPath.endsWith("%")){ - modifierPath = modifierPath.substring(0, modifierPath.length()-2); - modifierPath = modifierPath.substring(0, modifierPath.lastIndexOf("\\") + 1) + "%"; - } - else - modifierPath = modifierPath + "%"; - modifierSelect = modifierSelect + ", '" + modifierPath + "'"; - appliedPath = " and m_applied_path = '" + modifierPath + "' "; - inclusionSql = inclusionSql + " union all " + codeInfoSql + appliedPath + hidden + synonym + " and m_exclusion_cd is null "; - } - - String exclusionSql = codeInfoSql + appliedPath + hidden + synonym + " and m_exclusion_cd is not null"; - modifierPath = StringUtil.getLiteralPath(vocabType.getSelf()); - if(modifierPath.contains("'")){ - modifierPath = modifierPath.replaceAll("'", "''"); - } - while (modifierPath.length() > 3) { - if(modifierPath.endsWith("%")){ - modifierPath = modifierPath.substring(0, modifierPath.length()-2); - modifierPath = modifierPath.substring(0, modifierPath.lastIndexOf("\\") + 1) + "%"; - } - else - modifierPath = modifierPath + "%"; - appliedPath = " and m_applied_path = '" + modifierPath + "' "; - exclusionSql = exclusionSql + " union all " + codeInfoSql + appliedPath + hidden + synonym + " and m_exclusion_cd is not null "; - } - - String exceptSql = " EXCEPT ("; - if(dbInfo.getDb_serverType().toUpperCase().equals("ORACLE")) - exceptSql = " MINUS ("; - - - String modCodeInfoSql = " select " + parameters + " from " + metadataSchema + tableName + " where m_exclusion_cd is null and m_applied_path in (" - + modifierSelect +") and c_fullname in (" + inclusionSql + exceptSql + exclusionSql + ")) order by (c_name) "; - - - // log.debug("MODCodeInfo " + modCodeInfoSql); - boolean obfuscatedUserFlag = Roles.getInstance().isRoleOfuscated(projectInfo); - //ParameterizedRowMapper modMapper = getModMapper(new NodeType(vocabType),obfuscatedUserFlag, dbInfo.getDb_serverType()); - - List queryResult = null; - try { - queryResult = jt.query(modCodeInfoSql, getModNodeMapper(new NodeType(vocabType),obfuscatedUserFlag, dbInfo.getDb_serverType())); - } catch (DataAccessException e) { - log.error("Get Modifier by Code " + e.getMessage()); - throw new I2B2DAOException("Database Error"); - } - - - log.debug("Mod search by code result size = " + queryResult.size()); - - return queryResult; - - } - - public List findDerivedFactColumns(final GetTermInfoType termInfoType, ProjectType projectInfo, DBInfoType dbInfo) throws I2B2DAOException, I2B2Exception{ - - String metadataSchema = dbInfo.getDb_fullSchema(); - setDataSource(dbInfo.getDb_dataSource()); - - if (projectInfo.getRole().size() == 0) - { - log.error("no role found for this user in project: " + projectInfo.getName()); - I2B2DAOException e = new I2B2DAOException("No role found for user"); - throw e; - } - - Boolean protectedAccess = false; - Iterator it = projectInfo.getRole().iterator(); - while (it.hasNext()){ - String role = (String) it.next(); - if(role.toUpperCase().equals("DATA_PROT")) { - protectedAccess = true; - break; - } - } - boolean ofuscatedUserFlag = Roles.getInstance().isRoleOfuscated(projectInfo); - - //tableCd to table name conversion - - - - String hidden = ""; - if(termInfoType.isHiddens() == false) - hidden = " and c_visualattributes not like '_H%'"; - - //extract table code - String tableCd = StringUtil.getTableCd(termInfoType.getSelf()); - String tableName=null; - if (!protectedAccess){ - String tableSql = "select distinct(c_table_name) from " + metadataSchema + "table_access where c_table_cd = ? and c_protected_access = ? " + hidden; - try { - tableName = jt.queryForObject(tableSql, String.class, tableCd, "N"); - } catch (DataAccessException e) { - log.error("Get Derived Fact Columns " + e.getMessage()); - throw new I2B2DAOException("Database Error"); - } - }else { - String tableSql = "select distinct(c_table_name) from " + metadataSchema + "table_access where c_table_cd = ? " + hidden; - try { - tableName = jt.queryForObject(tableSql, String.class, tableCd); - } catch (DataAccessException e) { - log.error("Get Derived Fact Columns " + e.getMessage()); - throw new I2B2DAOException("Database Error"); - } - } - - String path = StringUtil.getPath(termInfoType.getSelf()); - /* - if(dbInfo.getDb_serverType().toUpperCase().equals("SQLSERVER")){ - //path = path.replaceAll("\\[", "[[]"); - path = StringUtil.escapeSQLSERVER(path); - } - else if(dbInfo.getDb_serverType().toUpperCase().equals("ORACLE")){ - path = StringUtil.escapeORACLE(path); - } - else if(dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL")){ - path = StringUtil.escapePOSTGRESQL(path); - } - */ - - String searchPath = path; - - - String synonym = ""; - if(termInfoType.isSynonyms() == false) - synonym = " and c_synonym_cd = 'N'"; - - String sql = "select distinct(c_facttablecolumn) from " + metadataSchema+tableName + " where c_facttablecolumn is not null and c_fullname like ? "; - if (!dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL")) - sql += "{ESCAPE '?'}" ; - sql = sql + hidden + synonym ; - - if(dbInfo.getDb_serverType().toUpperCase().equals("SQLSERVER")){ - searchPath = StringUtil.escapeSQLSERVER(path); - searchPath += "%"; - } - - else if(dbInfo.getDb_serverType().toUpperCase().equals("ORACLE")){ - searchPath = StringUtil.escapeORACLE(path); - searchPath += "%"; - } - else if(dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL")){ - searchPath = StringUtil.escapePOSTGRESQL(path); - searchPath += "%"; - } - - //ParameterizedRowMapper columnMapper = getColumnMapper(); - - List queryResult = null; - try { - queryResult = jt.queryForList(sql, String.class, searchPath ); - } catch (DataAccessException e) { - log.error("Get Derived Fact Columna " + e.getMessage()); - throw new I2B2DAOException("Database Error"); - } - - log.debug("Derived Fact columns result size = " + queryResult.size()); - - - return queryResult; - - } - - - private GetConceptXMLMapper getConceptXMLMapper(DBInfoType dbInfo) { - GetConceptXMLMapper mapper= new GetConceptXMLMapper(); - mapper.setdbInfo(dbInfo); - return mapper; - } - - - private GetModNodeMapper getModNodeMapper(NodeType nodeType, boolean obfuscatedUserFlag, - String db_serverType) { - // TODO Auto-generated method stub - GetModNodeMapper mapper = new GetModNodeMapper(); - mapper.setDbType(db_serverType); - mapper.setNodeType(nodeType); - mapper.setObfuscatedUserFlag(obfuscatedUserFlag); - return mapper; - } - - - private GetConceptNodeMapper getConceptNodeMapper(NodeType nodeType, boolean obfuscatedUserFlag, - String db_serverType) { - // TODO Auto-generated method stub - GetConceptNodeMapper mapper = new GetConceptNodeMapper(); - mapper.setDbType(db_serverType); - mapper.setNodeType(nodeType); - mapper.setObfuscatedUserFlag(obfuscatedUserFlag); - return mapper; - } - - private GetConceptFullNameMapper getConceptFullNameMapper(GetCategoriesType returnType, ProjectType projectInfo, - boolean obfuscatedUserFlag) { - GetConceptFullNameMapper mapper = new GetConceptFullNameMapper(); - mapper.setObfuscatedUserFlag(obfuscatedUserFlag); - mapper.setProjectInfo(projectInfo); - mapper.setReturnType(returnType); - return mapper; - } - - -} - - -class GetConceptNodeMapper implements RowMapper { - - boolean ofuscatedUserFlag; - NodeType node; - String dbType; - - - public void setObfuscatedUserFlag(boolean obfuscatedUserFlag) { - this.ofuscatedUserFlag = obfuscatedUserFlag; - } - - - public void setNodeType(NodeType nodeType) { - this.node = nodeType; - } - - - public void setDbType(String dbType) { - this.dbType = dbType; - } - - - @Override - public ConceptType mapRow(ResultSet rs, int rowNum) throws SQLException { - ConceptType child = new ConceptType(); - child.setName(rs.getString("c_name")); - if(!(node.getType().equals("default"))){ - child.setBasecode(rs.getString("c_basecode")); - child.setLevel(rs.getInt("c_hlevel")); - if (node.getParent().equals("terminfo")) { - child.setProtectedAccess(rs.getString("c_protected_access")); - child.setOntologyProtection(rs.getString("c_ontology_protection")); - } - // cover get Code Info case where we dont know the vocabType.category apriori - if ((node.getNode() != null) && !node.getNode().equals("@")) - child.setKey("\\\\" + node.getNode() + rs.getString("c_fullname")); - else - child.setKey("\\\\" + rs.getString("tableCd") + rs.getString("c_fullname")); - child.setSynonymCd(rs.getString("c_synonym_cd")); - child.setVisualattributes(rs.getString("c_visualattributes")); - Integer totalNumValue = rs.getInt("c_totalnum"); - boolean nullFlag = rs.wasNull(); - - /* - if (nullFlag) { - ("null in totalnum flag "); - } else { - ("not null in totalnum flag "); - } - - if (rs.getString("c_totalnum") == null) { - ("null in totalnum flag using getString method"); - } else { - ("not null in totalnum flag using getString method [" + rs.getString("c_totalnum") + "]"); - } - */ - if ( ofuscatedUserFlag == false && nullFlag == false) { - child.setTotalnum(totalNumValue); - } - child.setTooltip(rs.getString("c_tooltip")); - child.setValuetypeCd(rs.getString("valuetype_cd")); - if(!(node.getType().equals("limited"))) { - child.setFacttablecolumn(rs.getString("c_facttablecolumn" )); - child.setTablename(rs.getString("c_tablename")); - child.setColumnname(rs.getString("c_columnname")); - child.setColumndatatype(rs.getString("c_columndatatype")); - child.setOperator(rs.getString("c_operator")); - child.setDimcode(rs.getString("c_dimcode")); - } - } - if(node.isBlob() == true){ - try { - if (dbType.equals("POSTGRESQL")) - { - if(rs.getString("c_comment") == null) - child.setComment(null); - else - child.setComment(rs.getString("c_comment")); - } - else { - - if(rs.getClob("c_comment") == null) - child.setComment(null); - else - child.setComment(JDBCUtil.getClobString(rs.getClob("c_comment"))); - } - } catch (IOException e) { - child.setComment(null); - } - - String c_xml = null; - try { - - if (dbType.equals("POSTGRESQL")) - c_xml = rs.getString("c_metadataxml"); - else if (rs.getClob("c_metadataxml") != null) - c_xml = JDBCUtil.getClobString(rs.getClob("c_metadataxml")); - } catch (IOException e) { - child.setMetadataxml(null); - } - - if(c_xml == null){ - child.setMetadataxml(null); - }else { - if ((c_xml!=null)&&(c_xml.trim().length()>0)&&(!c_xml.equals("(null)"))) - { - Element rootElement = null; - try { - Document doc = XMLUtil.loadXMLFrom(new java.io.ByteArrayInputStream(c_xml.getBytes())); - rootElement = doc.getDocumentElement(); - } catch (IOException e) { - child.setMetadataxml(null); - } catch (Exception e1) { - child.setMetadataxml(null); - } - if (rootElement != null) { - XmlValueType xml = new XmlValueType(); - xml.getAny().add(rootElement); - child.setMetadataxml(xml); - } - }else { - child.setMetadataxml(null); - } - } - - } - if((node.getType().equals("all"))){ - DTOFactory factory = new DTOFactory(); - // make sure date isnt null before converting to XMLGregorianCalendar - Date date = rs.getDate("update_date"); - if (date == null) - child.setUpdateDate(null); - else - child.setUpdateDate(factory.getXMLGregorianCalendar(date.getTime())); - - date = rs.getDate("download_date"); - if (date == null) - child.setDownloadDate(null); - else - child.setDownloadDate(factory.getXMLGregorianCalendar(date.getTime())); - - date = rs.getDate("import_date"); - if (date == null) - child.setImportDate(null); - else - child.setImportDate(factory.getXMLGregorianCalendar(date.getTime())); - - child.setSourcesystemCd(rs.getString("sourcesystem_cd")); - - } - return child; - } - -} - - - -class GetConceptNameMapper implements RowMapper { - @Override - public ConceptType mapRow(ResultSet rs, int rowNum) throws SQLException { - ConceptType category = new ConceptType(); - - category.setTablename(rs.getString("c_table_name")); - category.setKey(rs.getString("c_fullname")); - category.setName(rs.getString("c_name")); - category.setTooltip(rs.getString("c_table_cd")); - return category; - } -} - -class GetConceptParentMapper implements RowMapper { - @Override - public ConceptType mapRow(ResultSet rs, int rowNum) throws SQLException { - ConceptType category = new ConceptType(); - - //category.setLevel(rs.getInt("c_hevel")); - category.setName(rs.getString("c_name")); - return category; - } -} - - -class GetConceptFullNameMapper implements RowMapper { - boolean obfuscatedUserFlag; - GetCategoriesType returnType; - public void setReturnType(GetCategoriesType returnType) { - this.returnType = returnType; - } - - - public void setProjectInfo(ProjectType projectInfo) { - this.projectInfo = projectInfo; - } - - - ProjectType projectInfo; - - public void setObfuscatedUserFlag(boolean obfuscatedUserFlag) { - this.obfuscatedUserFlag = obfuscatedUserFlag; - } - - - @Override - public ConceptType mapRow(ResultSet rs, int rowNum) throws SQLException { - ConceptType child = new ConceptType(); - //TODO fix this for all - child.setKey("\\\\" + rs.getString("c_table_cd")+ rs.getString("c_fullname")); - child.setName(rs.getString("c_name")); - if(returnType.getType().equals("limited")) { - child.setBasecode(rs.getString("c_basecode")); - child.setLevel(rs.getInt("c_hlevel")); - child.setSynonymCd(rs.getString("c_synonym_cd")); - child.setVisualattributes(rs.getString("c_visualattributes")); - - child.setTooltip(rs.getString("c_tooltip")); - child.setValuetypeCd(rs.getString("valuetype_cd")); - child.setProtectedAccess(rs.getString("c_protected_access")); - child.setOntologyProtection(rs.getString("c_ontology_protection")); - - } - else if(returnType.getType().equals("core")) { - child.setBasecode(rs.getString("c_basecode")); - child.setLevel(rs.getInt("c_hlevel")); - child.setSynonymCd(rs.getString("c_synonym_cd")); - child.setVisualattributes(rs.getString("c_visualattributes")); - child.setProtectedAccess(rs.getString("c_protected_access")); - child.setOntologyProtection(rs.getString("c_ontology_protection")); - - Integer totalNum = rs.getInt("c_totalnum"); - boolean nullFlag = rs.wasNull(); - - - if (nullFlag) { - } else { - } - - if (rs.getString("c_totalnum") == null) { - } else { - } - - if (obfuscatedUserFlag == false && nullFlag == false) { - child.setTotalnum(totalNum); - } - - - child.setFacttablecolumn(rs.getString("c_facttablecolumn" )); - child.setTablename(rs.getString("c_dimtablename")); - child.setColumnname(rs.getString("c_columnname")); - child.setColumndatatype(rs.getString("c_columndatatype")); - child.setOperator(rs.getString("c_operator")); - child.setDimcode(rs.getString("c_dimcode")); - child.setTooltip(rs.getString("c_tooltip")); - child.setValuetypeCd(rs.getString("valuetype_cd")); - } - if (child.getProtectedAccess().equalsIgnoreCase("Y")) - { - Boolean protectedAccess = false; - String[] dataProt = {"DATA_PROT"}; - List ontologyProtection = Arrays.asList(child.getOntologyProtection() == null || child.getOntologyProtection().equals("")?dataProt:child.getOntologyProtection().split(",")); - for (String s: projectInfo.getRole()) { - if (ontologyProtection.contains(s)) - protectedAccess = true; - - } - if (protectedAccess == false) - child = null; - } - - return child; - } -} - - - - -class GetModNodeMapper implements RowMapper { - - boolean ofuscatedUserFlag; - NodeType node; - String dbType; - - - public void setObfuscatedUserFlag(boolean obfuscatedUserFlag) { - this.ofuscatedUserFlag = obfuscatedUserFlag; - } - - - public void setNodeType(NodeType nodeType) { - this.node = nodeType; - } - - - public void setDbType(String dbType) { - this.dbType = dbType; - } - - - @Override - public ModifierType mapRow(ResultSet rs, int rowNum) throws SQLException { - ModifierType child = new ModifierType(); - if(node.getType().equals("limited")){ - child.setName(rs.getString("c_name")); - child.setAppliedPath(rs.getString("m_applied_path")); - child.setBasecode(rs.getString("c_basecode")); - child.setKey("\\\\" + node.getNode() + rs.getString("c_fullname")); - child.setLevel(rs.getInt("c_hlevel")); - child.setFullname(rs.getString("c_fullname")); - child.setVisualattributes(rs.getString("c_visualattributes")); - child.setSynonymCd(rs.getString("c_synonym_cd")); - child.setTooltip(rs.getString("c_tooltip")); - }else{ - child.setName(rs.getString("c_name")); - child.setAppliedPath(rs.getString("m_applied_path")); - child.setBasecode(rs.getString("c_basecode")); - child.setKey("\\\\" + node.getNode() + rs.getString("c_fullname")); - child.setLevel(rs.getInt("c_hlevel")); - child.setFullname(rs.getString("c_fullname")); - child.setVisualattributes(rs.getString("c_visualattributes")); - child.setSynonymCd(rs.getString("c_synonym_cd")); - child.setFacttablecolumn(rs.getString("c_facttablecolumn" )); - child.setTooltip(rs.getString("c_tooltip")); - child.setTablename(rs.getString("c_tablename")); - child.setColumnname(rs.getString("c_columnname")); - child.setColumndatatype(rs.getString("c_columndatatype")); - child.setOperator(rs.getString("c_operator")); - child.setDimcode(rs.getString("c_dimcode")); - } - - if(node.isBlob() == true){ - try { - if (dbType.equals("POSTGRESQL")) - { - if(rs.getString("c_comment") == null) - child.setComment(null); - else - child.setComment(rs.getString("c_comment")); - - } else { - if(rs.getClob("c_comment") == null) - child.setComment(null); - else - child.setComment(JDBCUtil.getClobString(rs.getClob("c_comment"))); - } - } catch (IOException e) { - child.setComment(null); - } - - - String c_xml = null; - try { - - if (dbType.equals("POSTGRESQL")) - c_xml = rs.getString("c_metadataxml"); - else if (rs.getClob("c_metadataxml") != null) - c_xml = JDBCUtil.getClobString(rs.getClob("c_metadataxml")); - } catch (IOException e) { - child.setMetadataxml(null); - } - - if(c_xml == null){ - child.setMetadataxml(null); - }else { - - if ((c_xml!=null)&&(c_xml.trim().length()>0)&&(!c_xml.equals("(null)"))) - { - Element rootElement = null; - try { - Document doc = XMLUtil.loadXMLFrom(new java.io.ByteArrayInputStream(c_xml.getBytes())); - rootElement = doc.getDocumentElement(); - } catch (IOException e) { - child.setMetadataxml(null); - } catch (Exception e1) { - child.setMetadataxml(null); - } - if (rootElement != null) { - XmlValueType xml = new XmlValueType(); - xml.getAny().add(rootElement); - child.setMetadataxml(xml); - } - }else { - child.setMetadataxml(null); - } - } - - } - if((node.getType().equals("all"))){ - DTOFactory factory = new DTOFactory(); - // make sure date isnt null before converting to XMLGregorianCalendar - Date date = rs.getDate("update_date"); - if (date == null) - child.setUpdateDate(null); - else - child.setUpdateDate(factory.getXMLGregorianCalendar(date.getTime())); - - date = rs.getDate("download_date"); - if (date == null) - child.setDownloadDate(null); - else - child.setDownloadDate(factory.getXMLGregorianCalendar(date.getTime())); - - date = rs.getDate("import_date"); - if (date == null) - child.setImportDate(null); - else - child.setImportDate(factory.getXMLGregorianCalendar(date.getTime())); - - child.setSourcesystemCd(rs.getString("sourcesystem_cd")); - - } - return child; - } - -} - -class GetConceptXMLMapper implements RowMapper { - - DBInfoType dbInfo; - - - - - - public void setdbInfo(DBInfoType dbInfo) { - this.dbInfo = dbInfo; - } - - - @Override - - public ConceptType mapRow(ResultSet rs, int rowNum) throws SQLException { - ConceptType concept = new ConceptType(); - // ResultSetMetaData rsmd = rs.getMetaData(); - // rsmd.get - - String c_xml = null; - try { - - if (dbInfo.getDb_serverType().equals("POSTGRESQL")) - c_xml = rs.getString("c_metadataxml"); - else if (rs.getClob("c_metadataxml") != null) - c_xml = JDBCUtil.getClobString(rs.getClob("c_metadataxml")); - } catch (IOException e) { - concept.setMetadataxml(null); - } - - if(c_xml == null){ - concept.setMetadataxml(null); - }else { - - if ((c_xml!=null)&&(c_xml.trim().length()>0)&&(!c_xml.equals("(null)"))) - { - //SAXBuilder parser = new SAXBuilder(); - java.io.StringReader xmlStringReader = new java.io.StringReader(c_xml); - Element rootElement = null; - try { - Document doc = XMLUtil.loadXMLFrom(new java.io.ByteArrayInputStream(c_xml.getBytes())); - rootElement = doc.getDocumentElement(); - } catch (IOException e) { - concept.setMetadataxml(null); - } catch (Exception e) { - concept.setMetadataxml(null); - } - if(rootElement != null) { - XmlValueType xml = new XmlValueType(); - xml.getAny().add(rootElement); - concept.setMetadataxml(xml); - } - }else { - concept.setMetadataxml(null); - } - } - - try { - if (dbInfo.getDb_serverType().equals("POSTGRESQL")) - { - concept.setComment(rs.getString("c_comment")); - } else if (rs.getClob("c_comment") != null) - { - concept.setComment(JDBCUtil.getClobString(rs.getClob("c_comment"))); - } - } - catch (Exception e) - { - concept.setComment(null); - } - - return concept; - } +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Lori Phillips + */ +package edu.harvard.i2b2.ontology.dao; + +import java.io.IOException; +import java.sql.Date; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import javax.sql.DataSource; + +import org.apache.commons.lang3.StringEscapeUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.dao.DataAccessException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.RowCallbackHandler; +import org.springframework.jdbc.core.RowMapper; +import org.springframework.jdbc.core.support.JdbcDaoSupport; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.db.JDBCUtil; +import edu.harvard.i2b2.common.util.jaxb.DTOFactory; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.common.util.xml.XMLUtil; +import edu.harvard.i2b2.ontology.datavo.pm.ProjectType; +import edu.harvard.i2b2.ontology.datavo.vdo.ConceptType; +import edu.harvard.i2b2.ontology.datavo.vdo.GetCategoriesType; +import edu.harvard.i2b2.ontology.datavo.vdo.GetChildrenType; +import edu.harvard.i2b2.ontology.datavo.vdo.GetModifierChildrenType; +import edu.harvard.i2b2.ontology.datavo.vdo.GetModifierInfoType; + +import edu.harvard.i2b2.ontology.datavo.vdo.GetTermInfoType; +import edu.harvard.i2b2.ontology.datavo.vdo.VocabRequestType; +import edu.harvard.i2b2.ontology.datavo.vdo.ModifierType; +import edu.harvard.i2b2.ontology.datavo.vdo.GetModifiersType; +import edu.harvard.i2b2.ontology.datavo.vdo.XmlValueType; +import edu.harvard.i2b2.ontology.ejb.DBInfoType; +import edu.harvard.i2b2.ontology.ejb.NodeType; +import edu.harvard.i2b2.ontology.util.OntologyUtil; +import edu.harvard.i2b2.ontology.util.Roles; +import edu.harvard.i2b2.ontology.util.StringUtil; +import edu.harvard.i2b2.ontology.ws.GetChildrenDataMessage; + +public class ConceptDao extends JdbcDaoSupport { + + private static Log log = LogFactory.getLog(ConceptDao.class); + final static String CAT_CORE = " c_hlevel, c_fullname, c_name, c_synonym_cd, c_visualattributes, c_totalnum, c_basecode, c_facttablecolumn, c_dimtablename, c_columnname, c_columndatatype, c_operator, c_dimcode, c_tooltip, valuetype_cd, c_protected_access, c_ontology_protection "; + final static String CAT_DEFAULT = " c_fullname, c_name "; + final static String CAT_LIMITED = " c_hlevel, c_fullname, c_name, c_synonym_cd, c_visualattributes, c_totalnum, c_basecode, c_tooltip, valuetype_cd, c_protected_access, c_ontology_protection "; + + final static String MOD_DEFAULT = " c_hlevel, c_fullname, c_name, c_synonym_cd, c_visualattributes, c_totalnum, c_basecode, c_facttablecolumn, c_tablename, c_columnname, c_columndatatype, c_operator, c_dimcode, c_tooltip, m_applied_path "; + final static String MOD_CORE = MOD_DEFAULT; + final static String MOD_LIMITED = " c_hlevel, c_fullname, c_name, c_synonym_cd, c_visualattributes, c_totalnum, c_basecode, c_tooltip, m_applied_path "; + + + final static String DEFAULT = " c_hlevel, c_fullname, c_name, c_synonym_cd, c_visualattributes, c_totalnum, c_basecode, c_facttablecolumn, c_tablename, c_columnname, c_columndatatype, c_operator, c_dimcode, c_tooltip, valuetype_cd "; + final static String CORE = DEFAULT; + final static String LIMITED = " c_hlevel, c_fullname, c_name, c_synonym_cd, c_visualattributes, c_totalnum, c_basecode, c_tooltip, valuetype_cd "; + + final static String ALL = ", update_date, download_date, import_date, sourcesystem_cd "; + final static String BLOB = ", c_metadataxml, c_comment "; + + final static String NAME_DEFAULT = " c_name "; + + private JdbcTemplate jt; + + private void setDataSource(String dataSource) { + DataSource ds = null; + try { + ds = OntologyUtil.getInstance().getDataSource(dataSource); + } catch (I2B2Exception e2) { + log.error(e2.getMessage());; + } + this.jt = new JdbcTemplate(ds); + + } + + private String getMetadataSchema() throws I2B2Exception{ + + return OntologyUtil.getInstance().getMetaDataSchemaName(); + } + + public List findRootCategories(final GetCategoriesType returnType, final ProjectType projectInfo, final DBInfoType dbInfo) throws I2B2Exception, I2B2DAOException{ + + // find return parameters + String parameters = CAT_DEFAULT; + if (returnType.getType().equals("limited")){ + parameters = CAT_LIMITED; + } + else if(returnType.getType().equals("core")){ + parameters = CAT_CORE; + } + + /* else if (returnType.getType().equals("all")){ + parameters = ALL; + } + */ + String metadataSchema = dbInfo.getDb_fullSchema(); + setDataSource(dbInfo.getDb_dataSource()); + + + // First step is to call PM to see what roles user belongs to. + + if (projectInfo.getRole().size() == 0) + { + log.error("no role found for this user in project: " + projectInfo.getName()); + I2B2Exception e = new I2B2Exception("No role found for user"); + throw e; + } + + /* + Boolean protectedAccess = false; + Iterator it = projectInfo.getRole().iterator(); + while (it.hasNext()){ + String role = (String) it.next(); + if(role.toUpperCase().equals("DATA_PROT")) { + protectedAccess = true; + break; + } + } + */ + + final boolean obfuscatedUserFlag = Roles.getInstance().isRoleOfuscated(projectInfo); + + + List queryResult = null; + + + String categoriesSql = "select c_table_cd, " + parameters + " from " + metadataSchema + "table_access "; + + String hidden = ""; + if(returnType.isHiddens() == false) + hidden = " where c_visualattributes not like '_H%'"; + + String synonym = ""; + if(returnType.isSynonyms() == false) + synonym = " c_synonym_cd = 'N'"; + + String whereClause = hidden; + if((whereClause.length() > 2) && (synonym.length() > 2)) + whereClause = whereClause + " and " + synonym; + + else if (synonym.length() > 2) + whereClause = " where " + synonym; + + categoriesSql = categoriesSql + whereClause + " order by upper(c_name)"; + log.debug(categoriesSql); + + try { + queryResult = jt.query(categoriesSql, getConceptFullNameMapper(returnType, projectInfo, obfuscatedUserFlag)); + } catch (DataAccessException e) { + log.error("Get Categories " +e.getMessage()); + throw new I2B2DAOException("Database Error"); + } + //} + log.debug("result size = " + queryResult.size()); + + if (returnType.isBlob() == true && queryResult != null){ + Iterator itr = queryResult.iterator(); + while (itr.hasNext()){ + ConceptType child = (ConceptType) itr.next(); + String clobSql = "select c_metadataxml, c_comment from "+ metadataSchema + "table_access where c_table_cd = ?"; + + List clobResult = null; + try { + clobResult = jt.query(clobSql, getConceptXMLMapper(dbInfo), StringUtil.getTableCd(child.getKey())); + } catch (DataAccessException e) { + log.error(e.getMessage()); + throw new I2B2DAOException("Database Error"); + } + if(clobResult != null) { + child.setMetadataxml(((ConceptType)(clobResult.get(0))).getMetadataxml()); + child.setComment(((ConceptType)(clobResult.get(0))).getComment()); + } + else { + child.setMetadataxml(null); + child.setComment(null); + } + + } + } + return queryResult; + } + + + + public List findChildrenByParent(final GetChildrenDataMessage childrenMsg, ProjectType projectInfo, DBInfoType dbInfo) throws I2B2DAOException, I2B2Exception, JAXBUtilException{ + + final GetChildrenType childrenType = childrenMsg.getChildrenType(); + + // find return parameters + String parameters = DEFAULT; + if (childrenType.getType().equals("limited")){ + parameters = LIMITED; + } + + else if (childrenType.getType().equals("core")){ + parameters = CORE; + } + else if (childrenType.getType().equals("all")){ + parameters = CORE + ALL; + } + if(childrenType.isBlob() == true) + parameters = parameters + BLOB; + + String metadataSchema = dbInfo.getDb_fullSchema(); + setDataSource(dbInfo.getDb_dataSource()); + + if (projectInfo.getRole().size() == 0) + { + log.error("no role found for this user in project: " + projectInfo.getName()); + I2B2Exception e = new I2B2Exception("No role found for user"); + throw e; + } + + /* + Boolean protectedAccess = false; + Iterator it = projectInfo.getRole().iterator(); + while (it.hasNext()){ + String role = (String) it.next(); + if(role.toUpperCase().equals("DATA_PROT")) { + protectedAccess = true; + break; + } + } + */ + + + //extract table code + String tableCd = StringUtil.getTableCd(childrenType.getParent()); + String tableName=null; + String tableSql = "select distinct(c_table_name) from " + metadataSchema + "table_access where c_table_cd = ?"; + try { + tableName = jt.queryForObject(tableSql, String.class, tableCd); + } catch (DataAccessException e) { + log.error("Get Children " + e.getMessage()); + throw new I2B2DAOException("Database Error"); + } + + String path = StringUtil.getPath(childrenType.getParent()); + String searchPath = path + "%"; + + // Lookup to get chlevel + 1 --- dont allow synonyms so we only get one result back + + String levelSql = "select c_hlevel from " + metadataSchema+tableName + " where c_fullname = ? and c_synonym_cd = 'N'"; + + int level = 0; + try { + level = jt.queryForObject(levelSql, Integer.class, path); + } catch (DataAccessException e1) { + // should only get 1 result back (path == c_fullname which should be unique) + log.error("Get Children " + e1.getMessage()); + throw new I2B2DAOException("Database Error"); + } + + String hidden = ""; + if(childrenType.isHiddens() == false) + hidden = " and c_visualattributes not like '_H%'"; + + String synonym = ""; + if(childrenType.isSynonyms() == false) + synonym = " and c_synonym_cd = 'N'"; + + // get all children if the numLevel is less then zero + int numLevel = childrenType.getNumLevel(); + String sql = "select " + parameters + " from " + metadataSchema + tableName + " where c_fullname like ? " + (!dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL") ? "{ESCAPE '?'}" : ""); + sql += (numLevel >= 0) ? " and c_hlevel > ? and c_hlevel <= ? " : " and c_hlevel > ? "; + sql = sql + hidden + synonym + " order by c_hlevel,upper(c_name) "; + + //log.info(sql + " " + path + " " + level); + boolean obfuscatedUserFlag = Roles.getInstance().isRoleOfuscated(projectInfo); + //ParameterizedRowMapper mapper = getMapper(new NodeType(childrenType),obfuscatedUserFlag, dbInfo.getDb_serverType()); + + if(dbInfo.getDb_serverType().toUpperCase().equals("SQLSERVER")){ + searchPath = StringUtil.escapeSQLSERVER(path); + searchPath += "%"; + // log.info("escaped searchPath is " + searchPath); + } + + else if(dbInfo.getDb_serverType().toUpperCase().equals("ORACLE")){ + searchPath = StringUtil.escapeORACLE(path); + searchPath += "%"; + } + else if(dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL")){ + searchPath = StringUtil.escapePOSTGRESQL(path); + searchPath += "%"; + } + + List queryResult = null; + try { + queryResult = (numLevel >= 0) + ? jt.query(sql, getConceptNodeMapper(new NodeType(childrenType), obfuscatedUserFlag, dbInfo.getDb_serverType()), searchPath, level, (level + numLevel)) + : jt.query(sql, getConceptNodeMapper(new NodeType(childrenType), obfuscatedUserFlag, dbInfo.getDb_serverType()), searchPath, level); + } catch (Exception e) { + log.error("Get Children " + e.getMessage()); + throw new I2B2DAOException("Database Error"); + } + + + if ((Float.parseFloat( + childrenMsg.getMessageHeaderType().getSendingApplication().getApplicationVersion()) > 1.5) && + (queryResult.size() > 0)) { + Iterator it2 = queryResult.iterator(); + while (it2.hasNext()){ + ConceptType concept = it2.next(); + // if a leaf has modifiers report it with visAttrib == F + if(concept.getVisualattributes().startsWith("L")){ + String modPath = StringUtil.getPath(concept.getKey()); + // I have to do this the hard way because there are a dynamic number of applied paths to check + // prevent SQL injection + if(modPath.contains("'")){ + modPath = modPath.replaceAll("'", "''"); + } + String sqlCount = "select count(*) from " + metadataSchema+ tableName + " where m_exclusion_cd is null and c_fullname in"; + int queryCount = 0; + // build m_applied_path sub-query + String m_applied_pathSql = "(m_applied_path = '" + modPath +"'"; + while (modPath.length() > 3) { + if(modPath.endsWith("%")){ + modPath = modPath.substring(0, modPath.length()-2); + modPath = modPath.substring(0, modPath.lastIndexOf("\\") + 1) + "%"; + } + else + modPath = modPath + "%"; + m_applied_pathSql = m_applied_pathSql + " or m_applied_path = '" + modPath + "'" ; + } + sqlCount = sqlCount + "(select c_fullname from " + metadataSchema+ tableName + " where c_hlevel = 1 and m_exclusion_cd is null and " + m_applied_pathSql + " )"; + + if(dbInfo.getDb_serverType().toUpperCase().equals("ORACLE")) + sqlCount = sqlCount + " MINUS "; + else + sqlCount = sqlCount + " EXCEPT "; + + sqlCount = sqlCount+ " (select c_fullname from " + metadataSchema+ tableName + " where m_exclusion_cd is not null and " + m_applied_pathSql + " )))"; + + + try { + queryCount = jt.queryForObject(sqlCount, Integer.class); + } catch (DataAccessException e) { + log.error("Get Children " + e.getMessage()); + throw new I2B2DAOException("Database Error"); + } + // log.debug("COUNT " + queryCount + " for " +sqlCount); + + + if(queryCount > 0){ + concept.setVisualattributes(concept.getVisualattributes().replace('L', 'F')); + log.debug("changed " + concept.getName() + " from leaf to folder: modCount > 0"); + } + } + } + } + // log.debug("Find Children By Parent " + sql); + log.debug("get_children result size = " + queryResult.size()); + return queryResult; + // tested statement with aqua data studio verified output from above against this. + // select c_fullname, c_name, c_synonym_cd, c_visualattributes from metadata.testrpdr + // where c_fullname like '\RPDR\Diagnoses\Circulatory system (390-459)\Arterial vascular disease (440-447)\(446) Polyarteritis nodosa and al%' + // and c_hlevel = 5 and c_visualattributes not like '_H%' and c_synonym_cd = 'N' + + // verified both with and without hiddens and synonyms. + + // clob test level = 4 + // \\testrpdr\RPDR\HealthHistory\PHY\Health Maintenance\Mammogram\Mammogram - Deferred + } + + public List findByFullname(final GetTermInfoType termInfoType, ProjectType projectInfo, DBInfoType dbInfo) throws I2B2DAOException, I2B2Exception{ + + // find return parameters + String parameters = DEFAULT; + if (termInfoType.getType().equals("limited")){ + parameters = LIMITED; + } + + else if (termInfoType.getType().equals("core")){ + parameters = CORE; + } + else if (termInfoType.getType().equals("all")){ + parameters = CORE + ALL; + } + if(termInfoType.isBlob() == true) + parameters = parameters + BLOB; + + String metadataSchema = dbInfo.getDb_fullSchema(); + setDataSource(dbInfo.getDb_dataSource()); + + if (projectInfo.getRole().size() == 0) + { + log.error("no role found for this user in project: " + projectInfo.getName()); + I2B2DAOException e = new I2B2DAOException("No role found for user"); + throw e; + } + + + boolean ofuscatedUserFlag = Roles.getInstance().isRoleOfuscated(projectInfo); + + //tableCd to table name conversion + + + String hidden = ""; + if(termInfoType.isHiddens() == false) + hidden = " and c_visualattributes not like '_H%'"; + + //extract table code + String tableCd = StringUtil.getTableCd(termInfoType.getSelf()); + String tableName=null; + String protectedAccess=null; + String ontologyProtection = null; + String tableSql = "select distinct(c_table_name) from " + metadataSchema + "table_access where c_table_cd = ?" + hidden; + try { + tableName = jt.queryForObject(tableSql, String.class, tableCd); + } catch (DataAccessException e) { + log.error("Get Term Info " + e.getMessage()); + throw new I2B2DAOException("Database Error"); + } + tableSql = "select distinct(c_protected_access) from " + metadataSchema + "table_access where c_table_cd = ?" + hidden; + try { + protectedAccess = jt.queryForObject(tableSql, String.class, tableCd); + } catch (DataAccessException e) { + log.error("Get Term Info " + e.getMessage()); + throw new I2B2DAOException("Database Error"); + } + tableSql = "select c_ontology_protection from " + metadataSchema + "table_access where c_table_cd = ?" + hidden; + try { + ontologyProtection = jt.queryForObject(tableSql, String.class, tableCd); + } catch (DataAccessException e) { + log.error("Get Term Info " + e.getMessage()); + throw new I2B2DAOException("Database Error"); + } + + String path = StringUtil.getPath(termInfoType.getSelf()); + /* + if(dbInfo.getDb_serverType().toUpperCase().equals("SQLSERVER")){ + //path = path.replaceAll("\\[", "[[]"); + path = StringUtil.escapeSQLSERVER(path); + } + else if(dbInfo.getDb_serverType().toUpperCase().equals("ORACLE")){ + path = StringUtil.escapeORACLE(path); + } + else if(dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL")){ + path = StringUtil.escapePOSTGRESQL(path); + } + */ + + String searchPath = path; + + String synonym = ""; + if(termInfoType.isSynonyms() == false) + synonym = " and c_synonym_cd = 'N'"; + + // String sql = "select " + parameters +" from " + metadataSchema+tableName + " where c_fullname like ? " + (!dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL") ? "{ESCAPE '?'}" : "" ) + ""; + String sql = "select '" + protectedAccess + "' as c_protected_access, '" + ontologyProtection + "' as c_ontology_protection, " + parameters +" from " + metadataSchema+tableName + " where c_fullname = ? "; + sql = sql + hidden + synonym + " order by upper(c_name) "; + + //log.info(sql + " " + path + " " + level); + + //ParameterizedRowMapper mapper = getMapper(new NodeType(termInfoType), ofuscatedUserFlag, dbInfo.getDb_serverType()); + + List queryResult = null; + try { + queryResult = jt.query(sql, getConceptNodeMapper(new NodeType(termInfoType), ofuscatedUserFlag, dbInfo.getDb_serverType()), searchPath ); + } catch (DataAccessException e) { + log.error("Get Term Info " + e.getMessage()); + throw new I2B2DAOException("Database Error"); + } + + log.debug("Term Info result size = " + queryResult.size()); + + + return queryResult; + + } + + + + public List findNameInfo(final VocabRequestType vocabType, ProjectType projectInfo, DBInfoType dbInfo) throws I2B2DAOException, I2B2Exception{ + + // find return parameters + String parameters = NAME_DEFAULT; + + if (vocabType.getType().equals("limited")){ + parameters = LIMITED; + } + + else if (vocabType.getType().equals("core")){ + parameters = CORE; + } + + else if (vocabType.getType().equals("all")){ + parameters = CORE + ALL; + } + if(vocabType.isBlob() == true) + parameters = parameters + BLOB; + + String metadataSchema = dbInfo.getDb_fullSchema(); + setDataSource(dbInfo.getDb_dataSource()); + + // log.info(metadataSchema); + + if (projectInfo.getRole().size() == 0) + { + log.error("no role found for this user in project: " + projectInfo.getName()); + I2B2Exception e = new I2B2Exception("No role found for user"); + throw e; + } + + + + //tableCd to table name + fullname conversion + + + + //extract table code + String tableCd = vocabType.getCategory(); + List categoryResult; + + List queryResult = null; + if (tableCd.equals("@")) + { + String tableSql = "select distinct(c_table_name), c_fullname, c_name, c_table_cd from " + metadataSchema + "table_access where c_visualattributes not like '_H%'" ; + try { + categoryResult = jt.query(tableSql, new GetConceptNameMapper()); + } catch (DataAccessException e) { + log.error("Search by Name " + e.getMessage()); + throw new I2B2DAOException("Database Error"); + } + + + } else { + String tableSql = "select distinct(c_table_name), c_fullname, c_name, c_table_cd from " + metadataSchema + "table_access where upper(c_table_cd) = ? " ; + try { + categoryResult = jt.query(tableSql, new GetConceptNameMapper(), tableCd.toUpperCase()); + } catch (DataAccessException e) { + log.error("Search by Name " + e.getMessage()); + throw new I2B2DAOException("Database Error"); + } + } + + String nameInfoSql = null; + String compareName = null; + + String value = vocabType.getMatchStr().getValue(); + // using JDBCtemplate so dont need to do apostrophe replace + // if(value.contains("'")){ + // value = value.replaceAll("'", "''"); + // } + + if (categoryResult.size() == 0){ + log.error("Non existent tableCd category passed in getNameInfo request " + tableCd); + return null; + } + + + + for (int i=0; i < categoryResult.size(); i++) { + String category = categoryResult.get(i).getKey(); + if(category.contains("'")){ + category = category.replaceAll("'", "''"); + } + + if(dbInfo.getDb_serverType().toUpperCase().equals("SQLSERVER")){ + category = StringUtil.escapeSQLSERVER(category); + } + else if(dbInfo.getDb_serverType().toUpperCase().equals("ORACLE")){ + category = StringUtil.escapeORACLE(category); + } + else if(dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL")){ + category = StringUtil.escapePOSTGRESQL(category); + } + + + // dont do the sql injection replace; it breaks the service. + if(vocabType.getMatchStr().getStrategy().equals("exact")) { + nameInfoSql = "select " + parameters + " from " + metadataSchema+categoryResult.get(i).getTablename() + " where upper(c_name) = ? and c_fullname like '" + category + "%' " + (!dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL") ? "{ESCAPE '?'}" : "" ) ; //{ESCAPE '?'}"; + compareName = value.toUpperCase(); + } + + else if(vocabType.getMatchStr().getStrategy().equals("left")){ + nameInfoSql = "select " + parameters + " from " + metadataSchema+categoryResult.get(i).getTablename() +" where upper(c_name) like ? " + (!dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL") ? "{ESCAPE '?'}" : "" ) + " and c_fullname like '" + category +"%' " + (!dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL") ? "{ESCAPE '?'}" : "" ) ; //{ESCAPE '?'}"; + if(dbInfo.getDb_serverType().toUpperCase().equals("SQLSERVER")){ + compareName = StringUtil.escapeSQLSERVER(vocabType.getMatchStr().getValue().toUpperCase()); + //compareName = compareName.replaceAll("\\[", "[[]"); + } + else if(dbInfo.getDb_serverType().toUpperCase().equals("ORACLE")){ + compareName = StringUtil.escapeORACLE(vocabType.getMatchStr().getValue().toUpperCase()); + //compareName = compareName.replaceAll("\\[", "[[]"); + } + else if(dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL")){ + compareName = StringUtil.escapePOSTGRESQL(vocabType.getMatchStr().getValue().toUpperCase()); + //compareName = compareName.replaceAll("\\[", "[[]"); + } + compareName = compareName + "%"; + + } + + else if(vocabType.getMatchStr().getStrategy().equals("right")) { + nameInfoSql = "select " + parameters + " from " + metadataSchema+categoryResult.get(i).getTablename() +" where upper(c_name) like ? " + (!dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL") ? "{ESCAPE '?'}" : "" ) + " and c_fullname like '" + category +"%' " + (!dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL") ? "{ESCAPE '?'}" : "" ) ; //{ESCAPE '?'}"; {ESCAPE '?'}"; + if(dbInfo.getDb_serverType().toUpperCase().equals("SQLSERVER")){ + compareName = StringUtil.escapeSQLSERVER(vocabType.getMatchStr().getValue().toUpperCase()); + } + else if(dbInfo.getDb_serverType().toUpperCase().equals("ORACLE")){ + compareName = StringUtil.escapeORACLE(vocabType.getMatchStr().getValue().toUpperCase()); + } + else if(dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL")){ + compareName = StringUtil.escapePOSTGRESQL(vocabType.getMatchStr().getValue().toUpperCase()); + } + + compareName = "%" + compareName; + // if(dbInfo.getDb_serverType().toUpperCase().equals("SQLSERVER")){ + // compareName = compareName.replaceAll("\\[", "[[]"); + // } + } + + else if(vocabType.getMatchStr().getStrategy().equals("contains")) { + if(!(value.contains(" "))){ + nameInfoSql = "select " + parameters + " from " + metadataSchema+categoryResult.get(i).getTablename() +" where upper(c_name) like ? " + (!dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL") ? "{ESCAPE '?'}" : "" ) + " and c_fullname like '" + category +"%' " + (!dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL") ? "{ESCAPE '?'}" : "" ) + ""; + if(dbInfo.getDb_serverType().toUpperCase().equals("SQLSERVER")){ + compareName = StringUtil.escapeSQLSERVER(vocabType.getMatchStr().getValue().toUpperCase()); + } + else if(dbInfo.getDb_serverType().toUpperCase().equals("ORACLE")){ + compareName = StringUtil.escapeORACLE(vocabType.getMatchStr().getValue().toUpperCase()); + } + else if(dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL")){ + compareName = StringUtil.escapePOSTGRESQL(vocabType.getMatchStr().getValue().toUpperCase()); + } + compareName = "%" + compareName + "%"; + //if(dbInfo.getDb_serverType().toUpperCase().equals("SQLSERVER")){ + // compareName = compareName.replaceAll("\\[", "[[]"); + // } + }else{ + nameInfoSql = "select " + parameters + " from " + metadataSchema+categoryResult.get(i).getTablename(); + if(dbInfo.getDb_serverType().toUpperCase().equals("SQLSERVER")){ + compareName = StringUtil.escapeSQLSERVER(vocabType.getMatchStr().getValue().toUpperCase()); + } + else if(dbInfo.getDb_serverType().toUpperCase().equals("ORACLE")){ + compareName = StringUtil.escapeORACLE(vocabType.getMatchStr().getValue().toUpperCase()); + } + else if(dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL")){ + compareName = StringUtil.escapePOSTGRESQL(vocabType.getMatchStr().getValue().toUpperCase()); + } + + // if(dbInfo.getDb_serverType().toUpperCase().equals("SQLSERVER")){ + // value = value.replaceAll("\\[", "[[]"); + // } + // WAS + // nameInfoSql = nameInfoSql + parseMatchString(value)+ " and c_fullname like '" + category +"%'" + (!dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL") ? "{ESCAPE '?'}" : "" ) + "";; + // !dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL") ? compareName.replaceAll("'", "''") : compareName + nameInfoSql = nameInfoSql + parseMatchString((compareName.replaceAll("'", "''")), dbInfo)+ " and c_fullname like '" + category +"%' " + (!dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL") ? "{ESCAPE '?'}" : "" ) + " ";; + + compareName = null; + } + } + + + String hidden = "";// and c_totalnum != 0 "; + if(vocabType.isHiddens() == false) + hidden += " and c_visualattributes not like '_H%'"; + + + String synonym = ""; + if(vocabType.isSynonyms() == false) + synonym = " and c_synonym_cd = 'N'"; + + nameInfoSql = nameInfoSql + hidden + synonym + " order by c_hlevel, c_totalnum, upper(c_name) asc "; + + log.info("nameInfoSql:" + nameInfoSql + " " +compareName); + boolean obfuscatedUserFlag = Roles.getInstance().isRoleOfuscated(projectInfo); + //ParameterizedRowMapper mapper = getMapper(new NodeType(vocabType),obfuscatedUserFlag, dbInfo.getDb_serverType()); + + + try { + List list = null; + if(compareName != null) { + list = jt.query(nameInfoSql, getConceptNodeMapper(new NodeType(vocabType),obfuscatedUserFlag, dbInfo.getDb_serverType()), compareName); + //queryResult.addAll(list); + } else { + vocabType.setCategory(categoryResult.get(i).getTooltip()); + list = jt.query(nameInfoSql, getConceptNodeMapper(new NodeType(vocabType),obfuscatedUserFlag, dbInfo.getDb_serverType())); + //queryResult.addAll(list); + } + + + // Add parent poaths + + String tableName=categoryResult.get(i).getTablename(); + String name = categoryResult.get(i).getName(); + /* + String tableSql = "select distinct(c_table_name) from " + metadataSchema + "table_access where c_table_cd = ?"; + try { + tableName = jt.queryForObject(tableSql, String.class, tableCd); + } catch (DataAccessException e) { + log.error("Get Children " + e.getMessage()); + throw new I2B2DAOException("Database Error"); + } + */ + + //jgk + // This does a linear search through fullnames for each previous fullname, O(n^2) :( + // BUT it assumes its sorted by hlevel so it only has to search through whats already seen - n(n+1)/2 operations + if (list.size()>0 && vocabType.isReducedResults()!=null && vocabType.isReducedResults()) { + ArrayList seen = new ArrayList(); + ArrayList keep = new ArrayList(); + Iterator it = list.iterator(); + while (it.hasNext()) + { + ConceptType node = (ConceptType)it.next(); + String key = node.getKey(); + boolean bAbort = false; + for (String k : seen) { + if(key.startsWith(k) && !key.equals(k) /* <-- don't kill the synonyms */ ) { + bAbort = true; + break; + } + } + if (vocabType.getMax() == 0) { + if (node.getTotalnum() != null && node.getTotalnum() > 0) { + keep.add(node); + } + } + else if (!bAbort) { + // Add nodes that were not subsumed to the keep list + keep.add(node); + } + // Hidden and inactive should not subsume other nodes - exclude them + if (node.getVisualattributes().contains("A")) + seen.add(node.getKey()); + } + log.debug("Reduced find terms from "+list.size()+" to "+keep.size()); + list = keep; + } + + if (vocabType.isKeyname()!=null && vocabType.isKeyname()) { + // Only do keyname lookups if we haven't exceeded the max + HashMap KeynameCache = new HashMap(); + int skipCount = 0; // for debug, number of cache hits + //int skipPathCount = category.split("\\\\").length -2; // preamble elements in path, not to be output in key name (everything but final element in category path) + + // A little code to ignore a path in the category name, if there is more than one element. + // e.g., \\i2b2_MED\Medications\ will ignore i2b2_MED + String[] skipPaths = category.split("\\\\"); + String skipPath = ""; + for (int j=1;jvocabType.getMax()) break; + + if (KeynameCache.containsKey(parentPath)) { + cType.setKeyName(KeynameCache.get(parentPath)); + skipCount++; + } + else { + if(dbInfo.getDb_serverType().toUpperCase().equals("SQLSERVER")){ + sql = "WITH pathnames "; + sql += " AS"; + sql += " ("; + sql += " select c_name, c_fullname,"; + sql += " substring(c_fullname, 1, len(c_fullname) - charindex('\\', reverse(c_fullname), 2) + 1) as c_path,"; + sql += " 1 as c_pathorder"; + sql += " from " + metadataSchema+tableName + " where c_fullname = ? and c_synonym_cd='N'"; + sql += " UNION ALL"; + sql += " select m.c_name, m.c_fullname, substring(m.c_fullname, 1, len(m.c_fullname) - charindex('\\', reverse(m.c_fullname), 2) + 1) as c_path, c_pathorder + 1 as c_pathorder"; + sql += " from " + metadataSchema+tableName + " m"; + sql += " inner join pathnames p on m.c_fullname = p.c_path where c_synonym_cd='N'"; + sql += " )"; + sql += " SELECT distinct c_name, c_fullname, c_pathorder as c_hlevel"; + sql += " FROM pathnames"; + sql += " order by c_pathorder desc "; + + } + + else if(dbInfo.getDb_serverType().toUpperCase().equals("ORACLE")){ + + + sql = "WITH pathnames (c_name, c_fullname, c_path, c_pathorder) "; + sql += " AS "; + sql += " ( "; + sql += " select c_name, c_fullname, "; + sql += " substr(c_fullname, 1, length(c_fullname) - instr(reverse(c_fullname),'\\', 2) + 1) as c_path,"; + sql += " 1 as c_pathorder"; + sql += " from " + metadataSchema+tableName + " where c_fullname = ? and c_synonym_cd='N'"; + sql += " UNION ALL"; + sql += " select m.c_name, m.c_fullname, substr(m.c_fullname, 1, length(m.c_fullname) - instr(reverse(m.c_fullname), '\\', 2) + 1) as c_path, c_pathorder + 1 as c_pathorder"; + sql += " from " + metadataSchema+tableName + " m"; + sql += " inner join pathnames p on m.c_fullname = p.c_path where c_synonym_cd='N'"; + + sql += " )"; + sql += " SELECT distinct c_name, c_fullname, c_pathorder as c_hlevel"; + sql += " FROM pathnames"; + sql += " order by c_pathorder desc "; + } else if(dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL")){ + + sql = "WITH RECURSIVE pathnames "; + sql += " AS"; + sql += " ("; + sql += " select c_name, c_fullname,"; + sql += " substr(c_fullname, 1, length(c_fullname) - strpos(substr(reverse(c_fullname), 2), '\\') ) as c_path,"; + sql += " 1 as c_pathorder"; + sql += " from " + metadataSchema+tableName + " where c_fullname = ? and c_synonym_cd='N'"; + sql += " UNION ALL"; + sql += " select m.c_name, m.c_fullname, "; + sql += " substr(m.c_fullname, 1, length(m.c_fullname) - strpos(substr(reverse(m.c_fullname), 2), '\\') ) as c_path, c_pathorder + 1 as c_pathorder"; + + sql += " from " + metadataSchema+tableName + " m"; + sql += " inner join pathnames p on m.c_fullname = p.c_path where c_synonym_cd='N'"; + + sql += " ) "; + sql += " SELECT distinct c_name, c_fullname, c_pathorder as c_hlevel"; + sql += " FROM pathnames"; + sql += " order by c_pathorder desc"; + } + + + //List rows = jt.queryForList(sql, path); + + /* + * List names = jt.query(sql, new RowMapper() { + public Object mapRow(ResultSet resultSet, int i) throws SQLException { + return resultSet.getString(1); + } + }, path); + */ + List names = jt.query(sql, new RowMapper() { + public ConceptType mapRow(ResultSet rs, int rowNum) throws SQLException { + ConceptType category = new ConceptType(); + + category.setKey(rs.getString("c_fullname")); + category.setLevel(rs.getInt("c_hlevel")); + category.setName(rs.getString("c_name")); + return category; + } + }/*new GetConceptParentMapper()*/, parentPath); + + cType.setKeyName("\\"); + for (int y=0; y< names.size(); y++) { + if(names.get(y).getKey().equals(skipPath)) continue; // only one path component for the category is ever included + if(names.get(y).getKey().equals(category)) + cType.setKeyName(cType.getKeyName() + name); // Use the category name instead of the db row name, for clarity + else cType.setKeyName(cType.getKeyName() + names.get(y).getName()); + if ((y + 1) < names.size()) + cType.setKeyName(cType.getKeyName() + "\\" ); + //+ \\ "); + + } + // In the event that the category does not have a row in the ontology, insert an entry for it manually + // TODO: Is the actual category name anywhere? (Currently using the code) + if (names.size()+skipPaths.length-20) log.debug("Skipped keyname lookups due to caching ="+skipCount); + } + + // Add list to results after adding parent list names + if (queryResult == null) + queryResult = list; + else + queryResult.addAll(list); + + } catch (DataAccessException e) { + log.error("Search by Name " + e.getMessage()); + e.printStackTrace(); + throw new I2B2DAOException("Database Error"); + } + } + log.debug("search by NameInfo result size = " + queryResult.size()); + + + return queryResult; + + } + + public List findCodeInfo(final VocabRequestType vocabType, ProjectType projectInfo, DBInfoType dbInfo) throws I2B2DAOException, I2B2Exception{ + + // find return parameters + String parameters = NAME_DEFAULT; + + if (vocabType.getType().equals("limited")){ + parameters = LIMITED; + } + + else if (vocabType.getType().equals("core")){ + parameters = CORE; + } + + else if (vocabType.getType().equals("all")){ + parameters = CORE + ALL; + } + if(vocabType.isBlob() == true) + parameters = parameters + BLOB; + + String metadataSchema = dbInfo.getDb_fullSchema(); + setDataSource(dbInfo.getDb_dataSource()); + + String dbType = dbInfo.getDb_serverType(); + + // log.info(metadataSchema); + + if (projectInfo.getRole().size() == 0) + { + log.error("no role found for this user in project: " + projectInfo.getName()); + I2B2Exception e = new I2B2Exception("No role found for user"); + throw e; + } + + + + + String hidden = ""; + String whereHidden = ""; + if(vocabType.isHiddens() == false) { + hidden = " and c_visualattributes not like '_H%'"; + whereHidden = " where c_visualattributes not like '_H%'"; + } + //no table code provided so check all tables user has access to + List tableNames=null; + String tableSql = "select distinct(c_table_name) from " + metadataSchema + "table_access " + whereHidden; + try { + tableNames = jt.queryForList(tableSql, String.class); + } catch (DataAccessException e) { + log.error("Search by Code " + e.getMessage()); + throw new I2B2DAOException("Database Error"); + } + + String synonym = ""; + if(vocabType.isSynonyms() == false) + synonym = " and c_synonym_cd = 'N'"; + + // I have to do this the hard way because there are a dynamic number of codes to pass in + // prevent SQL injection + String value = vocabType.getMatchStr().getValue(); + if(value.contains("'")){ + value = vocabType.getMatchStr().getValue().replaceAll("'", "''"); + } + String whereClause = null; + + String compareCode = value.toUpperCase(); + + if(vocabType.getMatchStr().getStrategy().equals("exact")) { + whereClause = " where upper(c_basecode) = '" + compareCode+ "'"; + } + + else { // need escape logic for like operator + + if(dbType.toUpperCase().equals("SQLSERVER")){ + compareCode = StringUtil.escapeSQLSERVER(compareCode); + } + else if(dbType.toUpperCase().equals("ORACLE")){ + compareCode = StringUtil.escapeORACLE(compareCode); + } + else if(dbType.toUpperCase().equals("POSTGRESQL")){ + compareCode = StringUtil.escapePOSTGRESQL(compareCode); + } + + if(vocabType.getMatchStr().getStrategy().equals("left")){ + whereClause = " where upper(c_basecode) like '" + compareCode + "%' " + (!dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL") ? "{ESCAPE '?'}" : "" ) ; //{ESCAPE '?'}"; + } + + else if(vocabType.getMatchStr().getStrategy().equals("right")) { + compareCode = compareCode.replaceFirst(":", ":%"); + whereClause = " where upper(c_basecode) like '" + compareCode + "' " + (!dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL") ? "{ESCAPE '?'}" : "" ) ; //{ESCAPE '?'}"; + } + + else if(vocabType.getMatchStr().getStrategy().equals("contains")) { + compareCode = compareCode.replaceFirst(":", ":%"); + whereClause = " where upper(c_basecode) like '" + compareCode + "%' " + (!dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL") ? "{ESCAPE '?'}" : "" ) ; //{ESCAPE '?'}"; + } + } + // log.debug(vocabType.getMatchStr().getStrategy() + whereClause); + + String codeInfoSql = null; + if(tableNames != null){ + Iterator itTn = tableNames.iterator(); + String table = (String)itTn.next(); + // the following (distinct) doesnt work for a flattened hierarchy but is left for + // dbs other than sqlserver or oracle. [c_table_cd is needed for key] + String tableCdSql = ", (select distinct(c_table_cd) from "+ metadataSchema + "TABLE_ACCESS where c_table_name = '"+ table+ "') as tableCd"; + if(dbType.toUpperCase().equals("SQLSERVER")) + tableCdSql = ", (select top 1(c_table_cd) from "+ metadataSchema + "TABLE_ACCESS where c_table_name = '"+ table+ "') as tableCd"; + else if (dbType.toUpperCase().equals("ORACLE")) + tableCdSql = ", (select c_table_cd from "+ metadataSchema + "TABLE_ACCESS where c_table_name = '"+ table+ "' and rownum <= 1) as tableCd"; + else if(dbType.toUpperCase().equals("POSTGRESQL")) + tableCdSql = ", (select c_table_cd from "+ metadataSchema + "TABLE_ACCESS where c_table_name = '"+ table+ "' limit 1) as tableCd"; + codeInfoSql = "select " + parameters + tableCdSql + " from " + metadataSchema + table + whereClause + hidden + synonym;; + while(itTn.hasNext()){ + table = (String)itTn.next(); + // the following (distinct) doesnt work for a flattened hierarchy but is left for + // dbs other than sqlserver or oracle. [c_table_cd is needed for key] + tableCdSql = ", (select distinct(c_table_cd) from "+ metadataSchema + "TABLE_ACCESS where c_table_name = '"+ table+ "') as tableCd"; + if(dbType.toUpperCase().equals("SQLSERVER")) + tableCdSql = ", (select top 1(c_table_cd) from "+ metadataSchema + "TABLE_ACCESS where c_table_name = '"+ table+ "') as tableCd"; + else if (dbType.toUpperCase().equals("ORACLE")) + tableCdSql = ", (select c_table_cd from "+ metadataSchema + "TABLE_ACCESS where c_table_name = '"+ table+ "' and rownum <= 1) as tableCd"; + else if(dbType.toUpperCase().equals("POSTGRESQL")) + tableCdSql = ", (select c_table_cd from "+ metadataSchema + "TABLE_ACCESS where c_table_name = '"+ table+ "' limit 1) as tableCd"; + + codeInfoSql = codeInfoSql + " union all (select "+ parameters + tableCdSql + " from " + metadataSchema + table + whereClause + + hidden + synonym + ")"; + } + codeInfoSql = codeInfoSql + " order by (c_name) "; + } + else + return null; + + boolean obfuscatedUserFlag = Roles.getInstance().isRoleOfuscated(projectInfo); + // ParameterizedRowMapper mapper = getMapper(new NodeType(vocabType),obfuscatedUserFlag, dbInfo.getDb_serverType()); + + List queryResult = null; + try { + String sqlFinal = codeInfoSql; + queryResult = jt.query(sqlFinal, getConceptNodeMapper(new NodeType(vocabType),obfuscatedUserFlag, dbInfo.getDb_serverType())); + } catch (DataAccessException e) { + log.error("Search by Code " + e.getMessage()); + throw new I2B2DAOException("Database Error"); + } + + log.debug("searchByCodeInfo result size = " + queryResult.size()); + + + return queryResult; + + } + + + /* + private ParameterizedRowMapper getColumnMapper() { + + ParameterizedRowMapper mapper = new ParameterizedRowMapper() { + public String mapRow(ResultSet rs, int rowNum) throws SQLException { + String derivedFactTableColumn; + derivedFactTableColumn=(rs.getString("c_facttablecolumn")); + return derivedFactTableColumn; + } + }; + return mapper; + } + */ + + + + private String parseMatchString(String match, DBInfoType dbInfo){ + String whereClause = null; + + String[] terms = match.split(" "); + ArrayList goodWords = new ArrayList(); + + String word = getStopWords(); + for(int i=0; i< terms.length; i++){ + if(word.contains(terms[i])) + ; + else{ + goodWords.add(terms[i]); + } + } + + if(goodWords.isEmpty()) + return null; + + Iterator it = goodWords.iterator(); + while(it.hasNext()){ + if(whereClause == null) + whereClause = " where upper(c_name) like " + "'%" + ((String)it.next()).toUpperCase() + "%' " + (!dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL") ? "{ESCAPE '?'}" : "" ) ; //{ESCAPE '?'}"; + else + whereClause = whereClause + " AND upper(c_name) like " + "'% " + ((String)it.next()).toUpperCase() + "%' " + (!dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL") ? "{ESCAPE '?'}" : "" ) ; //{ESCAPE '?'}"; + } + return whereClause; + } + + private String getStopWords(){ + + String stopWord = null; + try { + stopWord = OntologyUtil.getInstance().getStopWord(); + } catch (I2B2Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + //"a,able,about,across,after,all,almost,also,am,among,an,and,any,are,as,at,be,because,been,but,by,can,cannot,could,dear,did,do,does,either,else,ever,every,for,from,get,got,had,has,have,he,her,hers,him,his,how,however,i,if,in,into,is,it,its,just,least,let,like,likely,may,me,might,most,must,my,neither,no,nor,not,of,off,often,on,only,or,other,our,own,rather,said,say,says,she,should,since,so,some,than,that,the,their,them,then,there,these,they,this,tis,to,too,twas,us,wants,was,we,were,what,when,where,which,while,who,whom,why,will,with,would,yet,you,your"; + // String[] stopWords = stopWord.split("'"); + return stopWord; + } + + public List findModifiers(final GetModifiersType modifierType, ProjectType projectInfo, DBInfoType dbInfo) throws I2B2DAOException, I2B2Exception{ + + // find return parameters + String parameters = MOD_DEFAULT; + if (modifierType.getType().equals("limited")){ + parameters = MOD_LIMITED; + } + else if (modifierType.getType().equals("core")){ + parameters = MOD_CORE; + } + else if (modifierType.getType().equals("all")){ + parameters = MOD_CORE + ALL; + } + if(modifierType.isBlob() == true) + parameters = parameters + BLOB; + + String metadataSchema = dbInfo.getDb_fullSchema(); + setDataSource(dbInfo.getDb_dataSource()); + + if (projectInfo.getRole().size() == 0) + { + log.error("no role found for this user in project: " + projectInfo.getName()); + I2B2Exception e = new I2B2Exception("No role found for user"); + throw e; + } + + + + + + String hidden = ""; + if(modifierType.isHiddens() == false) + hidden = " and c_visualattributes not like '_H%'"; + + //extract table code + String tableCd = StringUtil.getTableCd(modifierType.getSelf()); + String tableName=null; + String tableSql = "select distinct(c_table_name) from " + metadataSchema + "table_access where c_table_cd = ? " + hidden; + try { + tableName = jt.queryForObject(tableSql, String.class, tableCd); + } catch (DataAccessException e) { + log.error("Find Modifiers " + e.getMessage()); + throw new I2B2DAOException("Database Error"); + } + + + + + // Original sql before exclusions + // String path = StringUtil.getLiteralPath(modifierType.getSelf()); + /* String sql = "select " + parameters +" from " + metadataSchema+ tableName + " where m_applied_path = '" + path + "' and c_hlevel = 1"; + while (path.length() > 2) { + if(path.endsWith("%")){ + path = path.substring(0, path.length()-2); + path = path.substring(0, path.lastIndexOf("\\") + 1) + "%"; + } + else + path = path + "%"; + sql = sql + " union all (select " + parameters +" from " + metadataSchema+ tableName + " where m_applied_path = '" + path + "' and c_hlevel = 1)"; + } + */ + String path = StringUtil.getLiteralPath(modifierType.getSelf()); + // I have to do this the hard way because there are a dynamic number of applied paths to check + // prevent SQL injection + if(path.contains("'")){ + path = path.replaceAll("'", "''"); + } + + String synonym = ""; + if(modifierType.isSynonyms() == false) + synonym = " and c_synonym_cd = 'N'"; + + + // String sql = "select " + parameters + " from "+ metadataSchema+ tableName + " where m_exclusion_cd is null and c_fullname in ("; + String inclusionSql = "select c_fullname from " + metadataSchema+ tableName + " where m_applied_path = '" + path + "' and c_hlevel = 1 and m_exclusion_cd is null " + hidden + synonym; + String modifier_select = " and m_applied_path in ('" + path + "'"; + while (path.length() > 2) { + if(path.endsWith("%")){ + path = path.substring(0, path.length()-2); + path = path.substring(0, path.lastIndexOf("\\") + 1) + "%"; + } + else + path = path + "%"; + inclusionSql = inclusionSql + " union all (select c_fullname from " + metadataSchema+ tableName + " where m_applied_path = '" + path + "' and c_hlevel = 1 and m_exclusion_cd is null " + hidden + synonym +")"; + modifier_select = modifier_select + ", '" + path + "'"; + } + + String sql = "select " + parameters + " from "+ metadataSchema+ tableName + " where m_exclusion_cd is null " + synonym + modifier_select +") and c_fullname in ("; + + if(dbInfo.getDb_serverType().toUpperCase().equals("ORACLE")) + sql = sql + inclusionSql + " MINUS ("; + else + sql = sql + inclusionSql + " EXCEPT ("; + + path = StringUtil.getLiteralPath(modifierType.getSelf()); + // I have to do this the hard way because there are a dynamic number of applied paths to check + // prevent SQL injection + if(path.contains("'")){ + path = path.replaceAll("'", "''"); + } + String exclusionSql = "select c_fullname from " + metadataSchema+ tableName + " where m_applied_path = '" + path + "' and m_exclusion_cd is not null"; + while (path.length() > 2) { + if(path.endsWith("%")){ + path = path.substring(0, path.length()-2); + path = path.substring(0, path.lastIndexOf("\\") + 1) + "%"; + } + else + path = path + "%"; + exclusionSql = exclusionSql + " union all (select c_fullname from " + metadataSchema+ tableName + " where m_applied_path = '" + path + "' and m_exclusion_cd is not null)"; + } + /* // applied paths on exclusions dont end in % + while (path.length() > 2) { + path = path.substring(0, path.length()-2); + path = path.substring(0, path.lastIndexOf("\\") +1) ; + exclusionSql = exclusionSql + " union all (select c_fullname from " + metadataSchema+ tableName + " where m_applied_path = '" + path + "' and m_exclusion_cd = 'X')"; + } + */ + sql = sql + exclusionSql + "))"; + + sql = sql + " order by (c_name) "; + + // ("findMods: " + sql ); + final boolean ofuscatedUserFlag = Roles.getInstance().isRoleOfuscated(projectInfo); + + // ParameterizedRowMapper modMapper = getModMapper(new NodeType (modifierType), ofuscatedUserFlag, dbInfo.getDb_serverType()); + + List queryResult = null; + + try { + // queryResult = jt.query(sql, modMapper, path ); + queryResult = jt.query(sql, getModNodeMapper(new NodeType(modifierType),ofuscatedUserFlag, dbInfo.getDb_serverType())); + } catch (DataAccessException e) { + log.error("Find Modifiers " + e.getMessage()); + throw new I2B2DAOException("Database Error"); + } + log.debug("findModifiers result size " + queryResult.size()); + return queryResult; + } + + + public List findChildrenByParent(final GetModifierChildrenType modifierChildrenType, ProjectType projectInfo, DBInfoType dbInfo) throws I2B2DAOException, I2B2Exception{ + + // ("MOD: " + modifierChildrenType.getParent()); + // log.debug("MOD: " + modifierChildrenType.getAppliedPath()); + + // find return parameters + String parameters = MOD_DEFAULT; + if (modifierChildrenType.getType().equals("limited")){ + parameters = MOD_LIMITED; + } + else if (modifierChildrenType.getType().equals("core")){ + parameters = MOD_CORE; + } + else if (modifierChildrenType.getType().equals("all")){ + parameters = MOD_CORE + ALL; + } + if(modifierChildrenType.isBlob() == true) + parameters = parameters + BLOB; + + String metadataSchema = dbInfo.getDb_fullSchema(); + setDataSource(dbInfo.getDb_dataSource()); + + if (projectInfo.getRole().size() == 0) + { + log.error("no role found for this user in project: " + projectInfo.getName()); + I2B2Exception e = new I2B2Exception("No role found for user"); + throw e; + } + + + + String hidden = ""; + if(modifierChildrenType.isHiddens() == false) + hidden = " and c_visualattributes not like '_H%'"; + + //extract table code + String tableCd = StringUtil.getTableCd(modifierChildrenType.getParent()); + String tableName=null; + String tableSql = "select distinct(c_table_name) from " + metadataSchema + "table_access where c_table_cd = ? " + hidden; + try { + tableName = jt.queryForObject(tableSql, String.class, tableCd); + } catch (DataAccessException e) { + log.error("Get Modifier Children " + e.getMessage()); + throw new I2B2DAOException("Database Error"); + } + + String path = StringUtil.getPath(modifierChildrenType.getParent()); + + String searchPath = path; + if(dbInfo.getDb_serverType().toUpperCase().equals("SQLSERVER")){ + searchPath = StringUtil.escapeSQLSERVER(searchPath); + } + else if(dbInfo.getDb_serverType().toUpperCase().equals("ORACLE")){ + searchPath = StringUtil.escapeORACLE(searchPath); + } + else if(dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL")){ + searchPath = StringUtil.escapePOSTGRESQL(searchPath); + } + + searchPath = searchPath + "%"; + + String levelSql = "select c_hlevel from " + metadataSchema+tableName + " where c_fullname = ? and c_synonym_cd = 'N' and m_applied_path = ? and m_exclusion_cd is null"; + + int level = 0; + try { + level = jt.queryForObject(levelSql, Integer.class, path, modifierChildrenType.getAppliedPath()); + } catch (DataAccessException e1) { + // should only get 1 result back (path == c_fullname which should be unique) + log.error("Get Modifier Children " + e1.getMessage()); + throw new I2B2DAOException("Database Error"); + } + + String synonym = ""; + if(modifierChildrenType.isSynonyms() == false) + synonym = " and c_synonym_cd = 'N'"; + + String appliedConcept = StringUtil.getLiteralPath(modifierChildrenType.getAppliedConcept()); + // I have to do this the hard way because there are a dynamic number of applied paths to check + // prevent SQL injection + if(appliedConcept.contains("'")){ + appliedConcept = appliedConcept.replaceAll("'", "''"); + } + + String inclusionSql = "select c_fullname from " + metadataSchema+ tableName + " where m_applied_path = ? and c_hlevel = " + (level+1) + " and m_exclusion_cd is null"; + String modifier_select = " and m_applied_path in ('" + appliedConcept + "'"; + while (appliedConcept.length() > 2) { + if(appliedConcept.endsWith("%")){ + appliedConcept = appliedConcept.substring(0, appliedConcept.length()-2); + appliedConcept = appliedConcept.substring(0, appliedConcept.lastIndexOf("\\") + 1) + "%"; + } + else + appliedConcept = appliedConcept + "%"; + inclusionSql = inclusionSql + " union all (select c_fullname from " + metadataSchema+ tableName + " where m_applied_path = '" + appliedConcept + "' and c_hlevel = " + (level+1) + " and m_exclusion_cd is null)"; + modifier_select = modifier_select + ", '" + appliedConcept + "'"; + } + + String sql = "select " + parameters + " from "+ metadataSchema+ tableName + " where m_exclusion_cd is null and c_hlevel = ? and c_fullname like ? " + (!dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL") ? "{ESCAPE '?'}" : "" ) + hidden + synonym + + modifier_select +") and c_fullname in ("; + + + if(dbInfo.getDb_serverType().toUpperCase().equals("ORACLE")) + sql = sql + inclusionSql + " MINUS ("; + else + sql = sql + inclusionSql + " EXCEPT ("; + + String exclusionSql = "select c_fullname from " + metadataSchema+ tableName + " where m_applied_path = ? and m_exclusion_cd is not null"; + String appliedExclConcept = StringUtil.getLiteralPath(modifierChildrenType.getAppliedConcept()); + // I have to do this the hard way because there are a dynamic number of applied paths to check + // prevent SQL injection + if(appliedExclConcept.contains("'")){ + appliedExclConcept = appliedExclConcept.replaceAll("'", "''"); + } + while (appliedExclConcept.length() > 2) { + if(appliedExclConcept.endsWith("%")){ + appliedExclConcept = appliedExclConcept.substring(0, appliedExclConcept.length()-2); + appliedExclConcept = appliedExclConcept.substring(0, appliedExclConcept.lastIndexOf("\\") + 1) + "%"; + } + else + appliedExclConcept = appliedExclConcept + "%"; + exclusionSql = exclusionSql + " union all (select c_fullname from " + metadataSchema+ tableName + " where m_applied_path = '" + appliedExclConcept + "' and m_exclusion_cd is not null)"; + } + + sql = sql + exclusionSql + "))"; + + sql = sql + " order by (c_name) "; + + // log.debug("findModChildren: " + sql + (level+1) + searchPath + StringUtil.getLiteralPath(modifierChildrenType.getAppliedConcept())); + + + final boolean ofuscatedUserFlag = Roles.getInstance().isRoleOfuscated(projectInfo); + + //ParameterizedRowMapper modMapper = getModMapper(new NodeType (modifierChildrenType), ofuscatedUserFlag, dbInfo.getDb_serverType()); + + List queryResult = null; + + try { + queryResult = jt.query(sql, getModNodeMapper(new NodeType(modifierChildrenType),ofuscatedUserFlag, dbInfo.getDb_serverType()), (level+1), searchPath, StringUtil.getLiteralPath(modifierChildrenType.getAppliedConcept()), + StringUtil.getLiteralPath(modifierChildrenType.getAppliedConcept())); + } catch (DataAccessException e) { + log.error("Get Modifier Children " + e.getMessage()); + throw new I2B2DAOException("Database Error"); + } + + + log.debug("Get Mod children result size = " + queryResult.size()); + + + return queryResult; + + } + + + + public List findByFullname(final GetModifierInfoType modifierInfoType, ProjectType projectInfo, DBInfoType dbInfo) throws I2B2DAOException, I2B2Exception{ + + // find return parameters + String parameters = MOD_DEFAULT; + if (modifierInfoType.getType().equals("limited")){ + parameters = MOD_LIMITED; + } + else if (modifierInfoType.getType().equals("core")){ + parameters = MOD_CORE; + } + else if (modifierInfoType.getType().equals("all")){ + parameters = MOD_CORE + ALL; + } + if(modifierInfoType.isBlob() == true) + parameters = parameters + BLOB; + + String metadataSchema = dbInfo.getDb_fullSchema(); + setDataSource(dbInfo.getDb_dataSource()); + + if (projectInfo.getRole().size() == 0) + { + log.error("no role found for this user in project: " + projectInfo.getName()); + I2B2DAOException e = new I2B2DAOException("No role found for user"); + throw e; + } + + //tableCd to table name conversion + + + String hidden = ""; + if(modifierInfoType.isHiddens() == false) + hidden = " and c_visualattributes not like '_H%'"; + + + //extract table code + String tableCd = StringUtil.getTableCd(modifierInfoType.getSelf()); + String tableName=null; + String tableSql = "select distinct(c_table_name) from " + metadataSchema + "table_access where c_table_cd = ? " + hidden; + try { + tableName = jt.queryForObject(tableSql, String.class, tableCd); + } catch (DataAccessException e) { + log.error("Get Modifier " + e.getMessage()); + throw new I2B2DAOException("Database Error"); + } + + String path = StringUtil.getPath(modifierInfoType.getSelf()); + String searchPath = path; + + + String synonym = ""; + if(modifierInfoType.isSynonyms() == false) + synonym = " and c_synonym_cd = 'N'"; + + // Removed dependency on m_applied_path 8/4/14 lcp + String sqlWpath = "select " + parameters +" from " + metadataSchema+tableName + " where c_fullname = ? and m_applied_path = ?"; + String sql = "select " + parameters +" from " + metadataSchema+tableName + " where c_fullname = ? "; + + // Putting applied path back.. 1/4/16 CORE-203 + // Was originally omitted for SHRINE (paths would be invalid) but result is that MANY modifiers return and messes up i2b2 + // So first search via applied path; if that returns zero then search w/o applied path + + + sqlWpath = sqlWpath + hidden + synonym + " order by upper(c_name) "; + + //log.info(sql + " " + path + " " + level); + + final boolean ofuscatedUserFlag = Roles.getInstance().isRoleOfuscated(projectInfo); + + // ParameterizedRowMapper modMapper = getModMapper(new NodeType (modifierInfoType), ofuscatedUserFlag, dbInfo.getDb_serverType()); + + List queryResult = null; + try { + queryResult = jt.query(sqlWpath, getModNodeMapper(new NodeType(modifierInfoType),ofuscatedUserFlag, dbInfo.getDb_serverType()), searchPath, modifierInfoType.getAppliedPath()); + + } catch (DataAccessException e) { + log.error("Get Modifier " + e.getMessage()); + throw new I2B2DAOException("Database Error"); + } + + if(queryResult.size() == 0){ + sql = sql + hidden + synonym + " order by upper(c_name) "; + + try { + queryResult = jt.query(sql, getModNodeMapper(new NodeType(modifierInfoType),ofuscatedUserFlag, dbInfo.getDb_serverType()), searchPath); + + } catch (DataAccessException e) { + log.error("Get Modifier " + e.getMessage()); + throw new I2B2DAOException("Database Error"); + } + } + + log.debug("Get ModInfo result size = " + queryResult.size()); + + + return queryResult; + + } + + public List findModifierNameInfo(final VocabRequestType vocabType, ProjectType projectInfo, DBInfoType dbInfo) throws I2B2DAOException, I2B2Exception{ + + // find return parameters + String parameters = NAME_DEFAULT; + + if (vocabType.getType().equals("limited")){ + parameters = MOD_LIMITED; + } + + else if (vocabType.getType().equals("core")){ + parameters = MOD_CORE; + } + + else if (vocabType.getType().equals("all")){ + parameters = MOD_CORE + ALL; + } + if(vocabType.isBlob() == true) + parameters = parameters + BLOB; + + String metadataSchema = dbInfo.getDb_fullSchema(); + setDataSource(dbInfo.getDb_dataSource()); + + // log.info(metadataSchema); + + if (projectInfo.getRole().size() == 0) + { + log.error("no role found for this user in project: " + projectInfo.getName()); + I2B2Exception e = new I2B2Exception("No role found for user"); + throw e; + } + + //tableCd to table name conversion + + + //extract table code + String tableCd = StringUtil.getTableCd(vocabType.getSelf()); + String tableName=null; + String tableSql = "select distinct(c_table_name) from " + metadataSchema + "table_access where c_table_cd = ? " ; + try { + tableName = jt.queryForObject(tableSql, String.class, tableCd); + } catch (DataAccessException e) { + log.error("Get Modifier by name " + e.getMessage()); + throw new I2B2DAOException("Database Error"); + } + + // prevent SQL injection and also catch case where the value contains an (') + String value = vocabType.getMatchStr().getValue(); + if(value.contains("'")){ + value = vocabType.getMatchStr().getValue().replaceAll("'", "''"); + } + String nameInfoSql = null; + String compareName = null; + String modifierPath = StringUtil.getLiteralPath(vocabType.getSelf()); + if(modifierPath.contains("'")){ + modifierPath = modifierPath.replaceAll("'", "''"); + } + + if(vocabType.getMatchStr().getStrategy().equals("exact")) { + compareName = value.toUpperCase(); + nameInfoSql = "select c_fullname from " + metadataSchema + tableName + " where upper(c_name) = '" + compareName + "'" ;//and m_applied_path = '" + path + "'"; + } + + else if(vocabType.getMatchStr().getStrategy().equals("left")){ + compareName = value.toUpperCase(); + if(dbInfo.getDb_serverType().toUpperCase().equals("SQLSERVER")){ + //compareName = compareName.replaceAll("\\[", "[[]"); + compareName = StringUtil.escapeSQLSERVER(compareName); + } + else if(dbInfo.getDb_serverType().toUpperCase().equals("ORACLE")){ + compareName = StringUtil.escapeORACLE(compareName); + } + else if(dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL")){ + compareName = StringUtil.escapePOSTGRESQL(compareName); + } + compareName += "%"; + nameInfoSql = "select c_fullname from " + metadataSchema + tableName +" where upper(c_name) like '" + compareName + "' " + (!dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL") ? "{ESCAPE '?'}" : "" ) ; //{ESCAPE '?'}"; and m_applied_path = '" + path + "'"; + } + + else if(vocabType.getMatchStr().getStrategy().equals("right")) { + compareName = value.toUpperCase(); + if(dbInfo.getDb_serverType().toUpperCase().equals("SQLSERVER")){ + //compareName = compareName.replaceAll("\\[", "[[]"); + compareName = StringUtil.escapeSQLSERVER(compareName); + } + else if(dbInfo.getDb_serverType().toUpperCase().equals("ORACLE")){ + compareName = StringUtil.escapeORACLE(compareName); + } + else if(dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL")){ + compareName = StringUtil.escapePOSTGRESQL(compareName); + } + compareName = "%" + compareName; + nameInfoSql = "select c_fullname from " + metadataSchema + tableName +" where upper(c_name) like '" + compareName + "' " + (!dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL") ? "{ESCAPE '?'}" : "" ) ; //{ESCAPE '?'}"; {ESCAPE '?'}";//and m_applied_path = '" + path + "'"; + } + + else if(vocabType.getMatchStr().getStrategy().equals("contains")) { + if(!(value.contains(" "))){ + // compareName = "%" + value.toUpperCase() + "%"; + compareName = value.toUpperCase(); + if(dbInfo.getDb_serverType().toUpperCase().equals("SQLSERVER")){ + //compareName = compareName.replaceAll("\\[", "[[]"); + compareName = StringUtil.escapeSQLSERVER(compareName); + } + else if(dbInfo.getDb_serverType().toUpperCase().equals("ORACLE")){ + compareName = StringUtil.escapeORACLE(compareName); + } + else if(dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL")){ + compareName = StringUtil.escapePOSTGRESQL(compareName); + } + compareName = "%" + compareName + "%"; + nameInfoSql = "select c_fullname from " + metadataSchema + tableName +" where upper(c_name) like '" + compareName + "' " + (!dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL") ? "{ESCAPE '?'}" : "" ) ; //{ESCAPE '?'}"; {ESCAPE '?'}"; //and m_applied_path = '" + path + "'"; + + }else{ + nameInfoSql = "select c_fullname from " + metadataSchema + tableName ; + // if(dbInfo.getDb_serverType().toUpperCase().equals("SQLSERVER")){ + // value = value.replaceAll("\\[", "[[]"); + // } + if(dbInfo.getDb_serverType().toUpperCase().equals("SQLSERVER")){ + value = StringUtil.escapeSQLSERVER(value); + } + else if(dbInfo.getDb_serverType().toUpperCase().equals("ORACLE")){ + value = StringUtil.escapeORACLE(value); + } + else if(dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL")){ + value = StringUtil.escapePOSTGRESQL(value); + } + nameInfoSql = nameInfoSql + parseMatchString(value, dbInfo);// + "and m_applied_path = '" + path + "'"; + compareName = null; + } + } + + String appliedPath = " and m_applied_path = '" + modifierPath + "' "; + + String hidden = ""; + if(vocabType.isHiddens() == false) + hidden = " and c_visualattributes not like '_H%' "; + + String synonym = ""; + if(vocabType.isSynonyms() == false) + synonym = " and c_synonym_cd = 'N' "; + + String inclusionSql = nameInfoSql + appliedPath + hidden + synonym + " and m_exclusion_cd is null "; + String modifierSelect = "'" + modifierPath + "'"; + while (modifierPath.length() > 3) { + if(modifierPath.endsWith("%")){ + modifierPath = modifierPath.substring(0, modifierPath.length()-2); + modifierPath = modifierPath.substring(0, modifierPath.lastIndexOf("\\") + 1) + "%"; + } + else + modifierPath = modifierPath + "%"; + modifierSelect = modifierSelect + ", '" + modifierPath + "'"; + appliedPath = " and m_applied_path = '" + modifierPath + "' "; + inclusionSql = inclusionSql + " union all " + nameInfoSql + appliedPath + hidden + synonym + " and m_exclusion_cd is null "; + } + + String exclusionSql = nameInfoSql + appliedPath + hidden + synonym + " and m_exclusion_cd is not null"; + modifierPath = StringUtil.getLiteralPath(vocabType.getSelf()); + if(modifierPath.contains("'")){ + modifierPath = modifierPath.replaceAll("'", "''"); + } + while (modifierPath.length() > 3) { + if(modifierPath.endsWith("%")){ + modifierPath = modifierPath.substring(0, modifierPath.length()-2); + modifierPath = modifierPath.substring(0, modifierPath.lastIndexOf("\\") + 1) + "%"; + } + else + modifierPath = modifierPath + "%"; + appliedPath = " and m_applied_path = '" + modifierPath + "' "; + exclusionSql = exclusionSql + " union all " + nameInfoSql + appliedPath + hidden + synonym + " and m_exclusion_cd is not null "; + } + + String exceptSql = " EXCEPT ("; + if(dbInfo.getDb_serverType().toUpperCase().equals("ORACLE")) + exceptSql = " MINUS ("; + + + String modNameInfoSql = " select " + parameters + " from " + metadataSchema + tableName + " where m_exclusion_cd is null and m_applied_path in (" + + modifierSelect +") and c_fullname in (" + inclusionSql + exceptSql + exclusionSql + ")) order by (c_name) "; + + // log.debug("MODnameInfo: " + modNameInfoSql + " " +compareName); + boolean obfuscatedUserFlag = Roles.getInstance().isRoleOfuscated(projectInfo); + + // ParameterizedRowMapper modMapper = getModMapper(new NodeType(vocabType), obfuscatedUserFlag, dbInfo.getDb_serverType()); + + List queryResult = null; + try { + if(compareName != null) + queryResult = jt.query(modNameInfoSql, getModNodeMapper(new NodeType(vocabType),obfuscatedUserFlag, dbInfo.getDb_serverType())); + else + queryResult = jt.query(modNameInfoSql, getModNodeMapper(new NodeType(vocabType),obfuscatedUserFlag, dbInfo.getDb_serverType())); + } catch (DataAccessException e) { + log.error("Get Modifier by name " + e.getMessage()); + throw new I2B2DAOException("Database Error"); + } + + log.debug("Mod search by name result size = " + queryResult.size()); + + + return queryResult; + + } + + public List findModifierCodeInfo(final VocabRequestType vocabType, ProjectType projectInfo, DBInfoType dbInfo) throws I2B2DAOException, I2B2Exception{ + + // find return parameters + String parameters = NAME_DEFAULT; + + if (vocabType.getType().equals("limited")){ + parameters = MOD_LIMITED; + } + + else if (vocabType.getType().equals("core")){ + parameters = MOD_CORE; + } + + else if (vocabType.getType().equals("all")){ + parameters = MOD_CORE + ALL; + } + if(vocabType.isBlob() == true) + parameters = parameters + BLOB; + + String metadataSchema = dbInfo.getDb_fullSchema(); + setDataSource(dbInfo.getDb_dataSource()); + + String dbType = dbInfo.getDb_serverType(); + + // log.info(metadataSchema); + + if (projectInfo.getRole().size() == 0) + { + log.error("no role found for this user in project: " + projectInfo.getName()); + I2B2Exception e = new I2B2Exception("No role found for user"); + throw e; + } + + //tableCd to table name conversion + + + String hidden = ""; + if(vocabType.isHiddens() == false) + hidden = " and c_visualattributes not like '_H%'"; + + //extract table code + String tableCd = StringUtil.getTableCd(vocabType.getSelf()); + String tableName=null; + String tableSql = "select distinct(c_table_name) from " + metadataSchema + "table_access where c_table_cd = ? " + hidden; + try { + tableName = jt.queryForObject(tableSql, String.class, tableCd); + } catch (DataAccessException e) { + log.error("Get Modifier by Code " + e.getMessage()); + throw new I2B2DAOException("Database Error"); + } + + String synonym = ""; + if(vocabType.isSynonyms() == false) + synonym = " and c_synonym_cd = 'N'"; + + // I have to do this the hard way because there are a dynamic number of codes to pass in + // prevent SQL injection + String value = vocabType.getMatchStr().getValue(); + if(value.contains("'")){ + value = vocabType.getMatchStr().getValue().replaceAll("'", "''"); + } + String whereClause = null; + + if(vocabType.getMatchStr().getStrategy().equals("exact")) { + whereClause = " where upper(c_basecode) = '" + value.toUpperCase()+ "'"; + } + + else if(vocabType.getMatchStr().getStrategy().equals("left")){ + if(dbInfo.getDb_serverType().toUpperCase().equals("SQLSERVER")){ + value = StringUtil.escapeSQLSERVER(value); + } + else if(dbInfo.getDb_serverType().toUpperCase().equals("ORACLE")){ + value = StringUtil.escapeORACLE(value); + } + else if(dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL")){ + value = StringUtil.escapePOSTGRESQL(value); + } + whereClause = " where upper(c_basecode) like '" + value.toUpperCase() + "%' " + (!dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL") ? "{ESCAPE '?'}" : "" ) ; //{ESCAPE '?'}"; {ESCAPE '?'}"; + } + + else if(vocabType.getMatchStr().getStrategy().equals("right")) { + if(dbInfo.getDb_serverType().toUpperCase().equals("SQLSERVER")){ + value = StringUtil.escapeSQLSERVER(value); + } + else if(dbInfo.getDb_serverType().toUpperCase().equals("ORACLE")){ + value = StringUtil.escapeORACLE(value); + } + value = value.replaceFirst(":", ":%"); + whereClause = " where upper(c_basecode) like '%" + value.toUpperCase() + "' " + (!dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL") ? "{ESCAPE '?'}" : "" ) ; //{ESCAPE '?'}"; {ESCAPE '?'}"; + + } + + else if(vocabType.getMatchStr().getStrategy().equals("contains")) { + if(dbInfo.getDb_serverType().toUpperCase().equals("SQLSERVER")){ + value = StringUtil.escapeSQLSERVER(value); + } + else if(dbInfo.getDb_serverType().toUpperCase().equals("ORACLE")){ + value = StringUtil.escapeORACLE(value); + } + else if(dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL")){ + value = StringUtil.escapePOSTGRESQL(value); + } + value = value.replaceFirst(":", ":%"); + whereClause = " where upper(c_basecode) like '%" + value.toUpperCase() + "%' " + (!dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL") ? "{ESCAPE '?'}" : "" ) ; //{ESCAPE '?'}"; {ESCAPE '?'}"; + } + + String codeInfoSql = "select c_fullname from " + metadataSchema + tableName + whereClause; + + + String modifierPath = StringUtil.getLiteralPath(vocabType.getSelf()); + if(modifierPath.contains("'")){ + modifierPath = modifierPath.replaceAll("'", "''"); + } + String appliedPath = " and m_applied_path = '" + modifierPath + "' "; + String inclusionSql = codeInfoSql + appliedPath + hidden + synonym + " and m_exclusion_cd is null "; + String modifierSelect = "'" + modifierPath + "'"; + while (modifierPath.length() > 3) { + if(modifierPath.endsWith("%")){ + modifierPath = modifierPath.substring(0, modifierPath.length()-2); + modifierPath = modifierPath.substring(0, modifierPath.lastIndexOf("\\") + 1) + "%"; + } + else + modifierPath = modifierPath + "%"; + modifierSelect = modifierSelect + ", '" + modifierPath + "'"; + appliedPath = " and m_applied_path = '" + modifierPath + "' "; + inclusionSql = inclusionSql + " union all " + codeInfoSql + appliedPath + hidden + synonym + " and m_exclusion_cd is null "; + } + + String exclusionSql = codeInfoSql + appliedPath + hidden + synonym + " and m_exclusion_cd is not null"; + modifierPath = StringUtil.getLiteralPath(vocabType.getSelf()); + if(modifierPath.contains("'")){ + modifierPath = modifierPath.replaceAll("'", "''"); + } + while (modifierPath.length() > 3) { + if(modifierPath.endsWith("%")){ + modifierPath = modifierPath.substring(0, modifierPath.length()-2); + modifierPath = modifierPath.substring(0, modifierPath.lastIndexOf("\\") + 1) + "%"; + } + else + modifierPath = modifierPath + "%"; + appliedPath = " and m_applied_path = '" + modifierPath + "' "; + exclusionSql = exclusionSql + " union all " + codeInfoSql + appliedPath + hidden + synonym + " and m_exclusion_cd is not null "; + } + + String exceptSql = " EXCEPT ("; + if(dbInfo.getDb_serverType().toUpperCase().equals("ORACLE")) + exceptSql = " MINUS ("; + + + String modCodeInfoSql = " select " + parameters + " from " + metadataSchema + tableName + " where m_exclusion_cd is null and m_applied_path in (" + + modifierSelect +") and c_fullname in (" + inclusionSql + exceptSql + exclusionSql + ")) order by (c_name) "; + + + // log.debug("MODCodeInfo " + modCodeInfoSql); + boolean obfuscatedUserFlag = Roles.getInstance().isRoleOfuscated(projectInfo); + //ParameterizedRowMapper modMapper = getModMapper(new NodeType(vocabType),obfuscatedUserFlag, dbInfo.getDb_serverType()); + + List queryResult = null; + try { + queryResult = jt.query(modCodeInfoSql, getModNodeMapper(new NodeType(vocabType),obfuscatedUserFlag, dbInfo.getDb_serverType())); + } catch (DataAccessException e) { + log.error("Get Modifier by Code " + e.getMessage()); + throw new I2B2DAOException("Database Error"); + } + + + log.debug("Mod search by code result size = " + queryResult.size()); + + return queryResult; + + } + + public List findDerivedFactColumns(final GetTermInfoType termInfoType, ProjectType projectInfo, DBInfoType dbInfo) throws I2B2DAOException, I2B2Exception{ + + String metadataSchema = dbInfo.getDb_fullSchema(); + setDataSource(dbInfo.getDb_dataSource()); + + if (projectInfo.getRole().size() == 0) + { + log.error("no role found for this user in project: " + projectInfo.getName()); + I2B2DAOException e = new I2B2DAOException("No role found for user"); + throw e; + } + + Boolean protectedAccess = false; + Iterator it = projectInfo.getRole().iterator(); + while (it.hasNext()){ + String role = (String) it.next(); + if(role.toUpperCase().equals("DATA_PROT")) { + protectedAccess = true; + break; + } + } + boolean ofuscatedUserFlag = Roles.getInstance().isRoleOfuscated(projectInfo); + + //tableCd to table name conversion + + + + String hidden = ""; + if(termInfoType.isHiddens() == false) + hidden = " and c_visualattributes not like '_H%'"; + + //extract table code + String tableCd = StringUtil.getTableCd(termInfoType.getSelf()); + String tableName=null; + if (!protectedAccess){ + String tableSql = "select distinct(c_table_name) from " + metadataSchema + "table_access where c_table_cd = ? and c_protected_access = ? " + hidden; + try { + tableName = jt.queryForObject(tableSql, String.class, tableCd, "N"); + } catch (DataAccessException e) { + log.error("Get Derived Fact Columns " + e.getMessage()); + throw new I2B2DAOException("Database Error"); + } + }else { + String tableSql = "select distinct(c_table_name) from " + metadataSchema + "table_access where c_table_cd = ? " + hidden; + try { + tableName = jt.queryForObject(tableSql, String.class, tableCd); + } catch (DataAccessException e) { + log.error("Get Derived Fact Columns " + e.getMessage()); + throw new I2B2DAOException("Database Error"); + } + } + + String path = StringUtil.getPath(termInfoType.getSelf()); + /* + if(dbInfo.getDb_serverType().toUpperCase().equals("SQLSERVER")){ + //path = path.replaceAll("\\[", "[[]"); + path = StringUtil.escapeSQLSERVER(path); + } + else if(dbInfo.getDb_serverType().toUpperCase().equals("ORACLE")){ + path = StringUtil.escapeORACLE(path); + } + else if(dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL")){ + path = StringUtil.escapePOSTGRESQL(path); + } + */ + + String searchPath = path; + + + String synonym = ""; + if(termInfoType.isSynonyms() == false) + synonym = " and c_synonym_cd = 'N'"; + + String sql = "select distinct(c_facttablecolumn) from " + metadataSchema+tableName + " where c_facttablecolumn is not null and c_fullname like ? "; + if (!dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL")) + sql += "{ESCAPE '?'}" ; + sql = sql + hidden + synonym ; + + if(dbInfo.getDb_serverType().toUpperCase().equals("SQLSERVER")){ + searchPath = StringUtil.escapeSQLSERVER(path); + searchPath += "%"; + } + + else if(dbInfo.getDb_serverType().toUpperCase().equals("ORACLE")){ + searchPath = StringUtil.escapeORACLE(path); + searchPath += "%"; + } + else if(dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL")){ + searchPath = StringUtil.escapePOSTGRESQL(path); + searchPath += "%"; + } + + //ParameterizedRowMapper columnMapper = getColumnMapper(); + + List queryResult = null; + try { + queryResult = jt.queryForList(sql, String.class, searchPath ); + } catch (DataAccessException e) { + log.error("Get Derived Fact Columna " + e.getMessage()); + throw new I2B2DAOException("Database Error"); + } + + log.debug("Derived Fact columns result size = " + queryResult.size()); + + + return queryResult; + + } + + + private GetConceptXMLMapper getConceptXMLMapper(DBInfoType dbInfo) { + GetConceptXMLMapper mapper= new GetConceptXMLMapper(); + mapper.setdbInfo(dbInfo); + return mapper; + } + + + private GetModNodeMapper getModNodeMapper(NodeType nodeType, boolean obfuscatedUserFlag, + String db_serverType) { + // TODO Auto-generated method stub + GetModNodeMapper mapper = new GetModNodeMapper(); + mapper.setDbType(db_serverType); + mapper.setNodeType(nodeType); + mapper.setObfuscatedUserFlag(obfuscatedUserFlag); + return mapper; + } + + + private GetConceptNodeMapper getConceptNodeMapper(NodeType nodeType, boolean obfuscatedUserFlag, + String db_serverType) { + // TODO Auto-generated method stub + GetConceptNodeMapper mapper = new GetConceptNodeMapper(); + mapper.setDbType(db_serverType); + mapper.setNodeType(nodeType); + mapper.setObfuscatedUserFlag(obfuscatedUserFlag); + return mapper; + } + + private GetConceptFullNameMapper getConceptFullNameMapper(GetCategoriesType returnType, ProjectType projectInfo, + boolean obfuscatedUserFlag) { + GetConceptFullNameMapper mapper = new GetConceptFullNameMapper(); + mapper.setObfuscatedUserFlag(obfuscatedUserFlag); + mapper.setProjectInfo(projectInfo); + mapper.setReturnType(returnType); + return mapper; + } + + +} + + +class GetConceptNodeMapper implements RowMapper { + + boolean ofuscatedUserFlag; + NodeType node; + String dbType; + + + public void setObfuscatedUserFlag(boolean obfuscatedUserFlag) { + this.ofuscatedUserFlag = obfuscatedUserFlag; + } + + + public void setNodeType(NodeType nodeType) { + this.node = nodeType; + } + + + public void setDbType(String dbType) { + this.dbType = dbType; + } + + + @Override + public ConceptType mapRow(ResultSet rs, int rowNum) throws SQLException { + ConceptType child = new ConceptType(); + child.setName(rs.getString("c_name")); + if(!(node.getType().equals("default"))){ + child.setBasecode(rs.getString("c_basecode")); + child.setLevel(rs.getInt("c_hlevel")); + if (node.getParent().equals("terminfo")) { + child.setProtectedAccess(rs.getString("c_protected_access")); + child.setOntologyProtection(rs.getString("c_ontology_protection")); + } + // cover get Code Info case where we dont know the vocabType.category apriori + if ((node.getNode() != null) && !node.getNode().equals("@")) + child.setKey("\\\\" + node.getNode() + rs.getString("c_fullname")); + else + child.setKey("\\\\" + rs.getString("tableCd") + rs.getString("c_fullname")); + child.setSynonymCd(rs.getString("c_synonym_cd")); + child.setVisualattributes(rs.getString("c_visualattributes")); + Integer totalNumValue = rs.getInt("c_totalnum"); + boolean nullFlag = rs.wasNull(); + + /* + if (nullFlag) { + ("null in totalnum flag "); + } else { + ("not null in totalnum flag "); + } + + if (rs.getString("c_totalnum") == null) { + ("null in totalnum flag using getString method"); + } else { + ("not null in totalnum flag using getString method [" + rs.getString("c_totalnum") + "]"); + } + */ + if ( ofuscatedUserFlag == false && nullFlag == false) { + child.setTotalnum(totalNumValue); + } + child.setTooltip(rs.getString("c_tooltip")); + child.setValuetypeCd(rs.getString("valuetype_cd")); + if(!(node.getType().equals("limited"))) { + child.setFacttablecolumn(rs.getString("c_facttablecolumn" )); + child.setTablename(rs.getString("c_tablename")); + child.setColumnname(rs.getString("c_columnname")); + child.setColumndatatype(rs.getString("c_columndatatype")); + child.setOperator(rs.getString("c_operator")); + child.setDimcode(rs.getString("c_dimcode")); + } + } + if(node.isBlob() == true){ + try { + if (dbType.equals("POSTGRESQL")) + { + if(rs.getString("c_comment") == null) + child.setComment(null); + else + child.setComment(rs.getString("c_comment")); + } + else { + + if(rs.getClob("c_comment") == null) + child.setComment(null); + else + child.setComment(JDBCUtil.getClobString(rs.getClob("c_comment"))); + } + } catch (IOException e) { + child.setComment(null); + } + + String c_xml = null; + try { + + if (dbType.equals("POSTGRESQL")) + c_xml = rs.getString("c_metadataxml"); + else if (rs.getClob("c_metadataxml") != null) + c_xml = JDBCUtil.getClobString(rs.getClob("c_metadataxml")); + } catch (IOException e) { + child.setMetadataxml(null); + } + + if(c_xml == null){ + child.setMetadataxml(null); + }else { + if ((c_xml!=null)&&(c_xml.trim().length()>0)&&(!c_xml.equals("(null)"))) + { + Element rootElement = null; + try { + Document doc = XMLUtil.loadXMLFrom(new java.io.ByteArrayInputStream(c_xml.getBytes())); + rootElement = doc.getDocumentElement(); + } catch (IOException e) { + child.setMetadataxml(null); + } catch (Exception e1) { + child.setMetadataxml(null); + } + if (rootElement != null) { + XmlValueType xml = new XmlValueType(); + xml.getAny().add(rootElement); + child.setMetadataxml(xml); + } + }else { + child.setMetadataxml(null); + } + } + + } + if((node.getType().equals("all"))){ + DTOFactory factory = new DTOFactory(); + // make sure date isnt null before converting to XMLGregorianCalendar + Date date = rs.getDate("update_date"); + if (date == null) + child.setUpdateDate(null); + else + child.setUpdateDate(factory.getXMLGregorianCalendar(date.getTime())); + + date = rs.getDate("download_date"); + if (date == null) + child.setDownloadDate(null); + else + child.setDownloadDate(factory.getXMLGregorianCalendar(date.getTime())); + + date = rs.getDate("import_date"); + if (date == null) + child.setImportDate(null); + else + child.setImportDate(factory.getXMLGregorianCalendar(date.getTime())); + + child.setSourcesystemCd(rs.getString("sourcesystem_cd")); + + } + return child; + } + +} + + + +class GetConceptNameMapper implements RowMapper { + @Override + public ConceptType mapRow(ResultSet rs, int rowNum) throws SQLException { + ConceptType category = new ConceptType(); + + category.setTablename(rs.getString("c_table_name")); + category.setKey(rs.getString("c_fullname")); + category.setName(rs.getString("c_name")); + category.setTooltip(rs.getString("c_table_cd")); + return category; + } +} + +class GetConceptParentMapper implements RowMapper { + @Override + public ConceptType mapRow(ResultSet rs, int rowNum) throws SQLException { + ConceptType category = new ConceptType(); + + //category.setLevel(rs.getInt("c_hevel")); + category.setName(rs.getString("c_name")); + return category; + } +} + + +class GetConceptFullNameMapper implements RowMapper { + boolean obfuscatedUserFlag; + GetCategoriesType returnType; + public void setReturnType(GetCategoriesType returnType) { + this.returnType = returnType; + } + + + public void setProjectInfo(ProjectType projectInfo) { + this.projectInfo = projectInfo; + } + + + ProjectType projectInfo; + + public void setObfuscatedUserFlag(boolean obfuscatedUserFlag) { + this.obfuscatedUserFlag = obfuscatedUserFlag; + } + + + @Override + public ConceptType mapRow(ResultSet rs, int rowNum) throws SQLException { + ConceptType child = new ConceptType(); + //TODO fix this for all + child.setKey("\\\\" + rs.getString("c_table_cd")+ rs.getString("c_fullname")); + child.setName(rs.getString("c_name")); + if(returnType.getType().equals("limited")) { + child.setBasecode(rs.getString("c_basecode")); + child.setLevel(rs.getInt("c_hlevel")); + child.setSynonymCd(rs.getString("c_synonym_cd")); + child.setVisualattributes(rs.getString("c_visualattributes")); + + child.setTooltip(rs.getString("c_tooltip")); + child.setValuetypeCd(rs.getString("valuetype_cd")); + child.setProtectedAccess(rs.getString("c_protected_access")); + child.setOntologyProtection(rs.getString("c_ontology_protection")); + + } + else if(returnType.getType().equals("core")) { + child.setBasecode(rs.getString("c_basecode")); + child.setLevel(rs.getInt("c_hlevel")); + child.setSynonymCd(rs.getString("c_synonym_cd")); + child.setVisualattributes(rs.getString("c_visualattributes")); + child.setProtectedAccess(rs.getString("c_protected_access")); + child.setOntologyProtection(rs.getString("c_ontology_protection")); + + Integer totalNum = rs.getInt("c_totalnum"); + boolean nullFlag = rs.wasNull(); + + + if (nullFlag) { + } else { + } + + if (rs.getString("c_totalnum") == null) { + } else { + } + + if (obfuscatedUserFlag == false && nullFlag == false) { + child.setTotalnum(totalNum); + } + + + child.setFacttablecolumn(rs.getString("c_facttablecolumn" )); + child.setTablename(rs.getString("c_dimtablename")); + child.setColumnname(rs.getString("c_columnname")); + child.setColumndatatype(rs.getString("c_columndatatype")); + child.setOperator(rs.getString("c_operator")); + child.setDimcode(rs.getString("c_dimcode")); + child.setTooltip(rs.getString("c_tooltip")); + child.setValuetypeCd(rs.getString("valuetype_cd")); + } + if (child.getProtectedAccess().equalsIgnoreCase("Y")) + { + Boolean protectedAccess = false; + String[] dataProt = {"DATA_PROT"}; + List ontologyProtection = Arrays.asList(child.getOntologyProtection() == null || child.getOntologyProtection().equals("")?dataProt:child.getOntologyProtection().split(",")); + for (String s: projectInfo.getRole()) { + if (ontologyProtection.contains(s)) + protectedAccess = true; + + } + if (protectedAccess == false) + child = null; + } + + return child; + } +} + + + + +class GetModNodeMapper implements RowMapper { + + boolean ofuscatedUserFlag; + NodeType node; + String dbType; + + + public void setObfuscatedUserFlag(boolean obfuscatedUserFlag) { + this.ofuscatedUserFlag = obfuscatedUserFlag; + } + + + public void setNodeType(NodeType nodeType) { + this.node = nodeType; + } + + + public void setDbType(String dbType) { + this.dbType = dbType; + } + + + @Override + public ModifierType mapRow(ResultSet rs, int rowNum) throws SQLException { + ModifierType child = new ModifierType(); + if(node.getType().equals("limited")){ + child.setName(rs.getString("c_name")); + child.setAppliedPath(rs.getString("m_applied_path")); + child.setBasecode(rs.getString("c_basecode")); + child.setKey("\\\\" + node.getNode() + rs.getString("c_fullname")); + child.setLevel(rs.getInt("c_hlevel")); + child.setFullname(rs.getString("c_fullname")); + child.setVisualattributes(rs.getString("c_visualattributes")); + child.setSynonymCd(rs.getString("c_synonym_cd")); + child.setTooltip(rs.getString("c_tooltip")); + }else{ + child.setName(rs.getString("c_name")); + child.setAppliedPath(rs.getString("m_applied_path")); + child.setBasecode(rs.getString("c_basecode")); + child.setKey("\\\\" + node.getNode() + rs.getString("c_fullname")); + child.setLevel(rs.getInt("c_hlevel")); + child.setFullname(rs.getString("c_fullname")); + child.setVisualattributes(rs.getString("c_visualattributes")); + child.setSynonymCd(rs.getString("c_synonym_cd")); + child.setFacttablecolumn(rs.getString("c_facttablecolumn" )); + child.setTooltip(rs.getString("c_tooltip")); + child.setTablename(rs.getString("c_tablename")); + child.setColumnname(rs.getString("c_columnname")); + child.setColumndatatype(rs.getString("c_columndatatype")); + child.setOperator(rs.getString("c_operator")); + child.setDimcode(rs.getString("c_dimcode")); + } + + if(node.isBlob() == true){ + try { + if (dbType.equals("POSTGRESQL")) + { + if(rs.getString("c_comment") == null) + child.setComment(null); + else + child.setComment(rs.getString("c_comment")); + + } else { + if(rs.getClob("c_comment") == null) + child.setComment(null); + else + child.setComment(JDBCUtil.getClobString(rs.getClob("c_comment"))); + } + } catch (IOException e) { + child.setComment(null); + } + + + String c_xml = null; + try { + + if (dbType.equals("POSTGRESQL")) + c_xml = rs.getString("c_metadataxml"); + else if (rs.getClob("c_metadataxml") != null) + c_xml = JDBCUtil.getClobString(rs.getClob("c_metadataxml")); + } catch (IOException e) { + child.setMetadataxml(null); + } + + if(c_xml == null){ + child.setMetadataxml(null); + }else { + + if ((c_xml!=null)&&(c_xml.trim().length()>0)&&(!c_xml.equals("(null)"))) + { + Element rootElement = null; + try { + Document doc = XMLUtil.loadXMLFrom(new java.io.ByteArrayInputStream(c_xml.getBytes())); + rootElement = doc.getDocumentElement(); + } catch (IOException e) { + child.setMetadataxml(null); + } catch (Exception e1) { + child.setMetadataxml(null); + } + if (rootElement != null) { + XmlValueType xml = new XmlValueType(); + xml.getAny().add(rootElement); + child.setMetadataxml(xml); + } + }else { + child.setMetadataxml(null); + } + } + + } + if((node.getType().equals("all"))){ + DTOFactory factory = new DTOFactory(); + // make sure date isnt null before converting to XMLGregorianCalendar + Date date = rs.getDate("update_date"); + if (date == null) + child.setUpdateDate(null); + else + child.setUpdateDate(factory.getXMLGregorianCalendar(date.getTime())); + + date = rs.getDate("download_date"); + if (date == null) + child.setDownloadDate(null); + else + child.setDownloadDate(factory.getXMLGregorianCalendar(date.getTime())); + + date = rs.getDate("import_date"); + if (date == null) + child.setImportDate(null); + else + child.setImportDate(factory.getXMLGregorianCalendar(date.getTime())); + + child.setSourcesystemCd(rs.getString("sourcesystem_cd")); + + } + return child; + } + +} + +class GetConceptXMLMapper implements RowMapper { + + DBInfoType dbInfo; + + + + + + public void setdbInfo(DBInfoType dbInfo) { + this.dbInfo = dbInfo; + } + + + @Override + + public ConceptType mapRow(ResultSet rs, int rowNum) throws SQLException { + ConceptType concept = new ConceptType(); + // ResultSetMetaData rsmd = rs.getMetaData(); + // rsmd.get + + String c_xml = null; + try { + + if (dbInfo.getDb_serverType().equals("POSTGRESQL")) + c_xml = rs.getString("c_metadataxml"); + else if (rs.getClob("c_metadataxml") != null) + c_xml = JDBCUtil.getClobString(rs.getClob("c_metadataxml")); + } catch (IOException e) { + concept.setMetadataxml(null); + } + + if(c_xml == null){ + concept.setMetadataxml(null); + }else { + + if ((c_xml!=null)&&(c_xml.trim().length()>0)&&(!c_xml.equals("(null)"))) + { + //SAXBuilder parser = new SAXBuilder(); + java.io.StringReader xmlStringReader = new java.io.StringReader(c_xml); + Element rootElement = null; + try { + Document doc = XMLUtil.loadXMLFrom(new java.io.ByteArrayInputStream(c_xml.getBytes())); + rootElement = doc.getDocumentElement(); + } catch (IOException e) { + concept.setMetadataxml(null); + } catch (Exception e) { + concept.setMetadataxml(null); + } + if(rootElement != null) { + XmlValueType xml = new XmlValueType(); + xml.getAny().add(rootElement); + concept.setMetadataxml(xml); + } + }else { + concept.setMetadataxml(null); + } + } + + try { + if (dbInfo.getDb_serverType().equals("POSTGRESQL")) + { + concept.setComment(rs.getString("c_comment")); + } else if (rs.getClob("c_comment") != null) + { + concept.setComment(JDBCUtil.getClobString(rs.getClob("c_comment"))); + } + } + catch (Exception e) + { + concept.setComment(null); + } + + return concept; + } } \ No newline at end of file diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/dao/ConceptPersistDao.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/dao/ConceptPersistDao.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/dao/ConceptPersistDao.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/dao/ConceptPersistDao.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/dao/CreateConceptXmlDao.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/dao/CreateConceptXmlDao.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/dao/CreateConceptXmlDao.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/dao/CreateConceptXmlDao.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/dao/DataSourceLookupHelper.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/dao/DataSourceLookupHelper.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/dao/DataSourceLookupHelper.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/dao/DataSourceLookupHelper.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/dao/DblookupDao.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/dao/DblookupDao.java similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/dao/DblookupDao.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/dao/DblookupDao.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/dao/GetCategoriesDao.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/dao/GetCategoriesDao.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/dao/GetCategoriesDao.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/dao/GetCategoriesDao.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/dao/GetChildrenDao.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/dao/GetChildrenDao.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/dao/GetChildrenDao.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/dao/GetChildrenDao.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/dao/GetCodeInfoDao.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/dao/GetCodeInfoDao.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/dao/GetCodeInfoDao.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/dao/GetCodeInfoDao.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/dao/GetNameInfoDao.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/dao/GetNameInfoDao.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/dao/GetNameInfoDao.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/dao/GetNameInfoDao.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/dao/GetSchemesDao.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/dao/GetSchemesDao.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/dao/GetSchemesDao.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/dao/GetSchemesDao.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/dao/GetTermInfoDao.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/dao/GetTermInfoDao.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/dao/GetTermInfoDao.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/dao/GetTermInfoDao.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/dao/MetadataDbDao.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/dao/MetadataDbDao.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/dao/MetadataDbDao.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/dao/MetadataDbDao.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/dao/OntProcessStatusDao.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/dao/OntProcessStatusDao.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/dao/OntProcessStatusDao.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/dao/OntProcessStatusDao.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/dao/OntologyProcessType.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/dao/OntologyProcessType.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/dao/OntologyProcessType.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/dao/OntologyProcessType.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/dao/SchemesDao.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/dao/SchemesDao.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/dao/SchemesDao.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/dao/SchemesDao.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/dao/TableAccessDao.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/dao/TableAccessDao.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/dao/TableAccessDao.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/dao/TableAccessDao.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/AddChildHandler.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/AddChildHandler.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/AddChildHandler.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/AddChildHandler.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/AddModifierHandler.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/AddModifierHandler.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/AddModifierHandler.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/AddModifierHandler.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/CRCConceptUpdateHandler.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/CRCConceptUpdateHandler.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/CRCConceptUpdateHandler.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/CRCConceptUpdateHandler.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/CRCConceptUpdateRunnable.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/CRCConceptUpdateRunnable.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/CRCConceptUpdateRunnable.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/CRCConceptUpdateRunnable.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/CheckMetadataTableHandler.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/CheckMetadataTableHandler.java similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/CheckMetadataTableHandler.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/CheckMetadataTableHandler.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/DeleteChildHandler.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/DeleteChildHandler.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/DeleteChildHandler.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/DeleteChildHandler.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/DeleteDblookupHandler.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/DeleteDblookupHandler.java similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/DeleteDblookupHandler.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/DeleteDblookupHandler.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/ExcludeModifierHandler.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/ExcludeModifierHandler.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/ExcludeModifierHandler.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/ExcludeModifierHandler.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/ExecutorRunnable.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/ExecutorRunnable.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/ExecutorRunnable.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/ExecutorRunnable.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/GetAllDblookupsHandler.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/GetAllDblookupsHandler.java similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/GetAllDblookupsHandler.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/GetAllDblookupsHandler.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/GetCategoriesHandler.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/GetCategoriesHandler.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/GetCategoriesHandler.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/GetCategoriesHandler.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/GetChildrenHandler.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/GetChildrenHandler.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/GetChildrenHandler.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/GetChildrenHandler.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/GetCodeInfoHandler.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/GetCodeInfoHandler.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/GetCodeInfoHandler.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/GetCodeInfoHandler.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/GetDblookupHandler.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/GetDblookupHandler.java similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/GetDblookupHandler.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/GetDblookupHandler.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/GetDerivedFactColumnsHandler.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/GetDerivedFactColumnsHandler.java similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/GetDerivedFactColumnsHandler.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/GetDerivedFactColumnsHandler.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/GetDirtyStateHandler.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/GetDirtyStateHandler.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/GetDirtyStateHandler.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/GetDirtyStateHandler.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/GetModifierChildrenHandler.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/GetModifierChildrenHandler.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/GetModifierChildrenHandler.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/GetModifierChildrenHandler.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/GetModifierCodeInfoHandler.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/GetModifierCodeInfoHandler.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/GetModifierCodeInfoHandler.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/GetModifierCodeInfoHandler.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/GetModifierInfoHandler.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/GetModifierInfoHandler.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/GetModifierInfoHandler.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/GetModifierInfoHandler.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/GetModifierNameInfoHandler.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/GetModifierNameInfoHandler.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/GetModifierNameInfoHandler.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/GetModifierNameInfoHandler.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/GetModifiersHandler.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/GetModifiersHandler.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/GetModifiersHandler.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/GetModifiersHandler.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/GetNameInfoHandler.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/GetNameInfoHandler.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/GetNameInfoHandler.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/GetNameInfoHandler.java index 2b031227..3e931a97 --- a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/GetNameInfoHandler.java +++ b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/GetNameInfoHandler.java @@ -1,191 +1,191 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Lori Phillips - */ -package edu.harvard.i2b2.ontology.delegate; - -import java.io.StringWriter; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import javax.xml.datatype.XMLGregorianCalendar; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.XMLGregorianCalendarDeserializer; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.ontology.dao.ConceptDao; -import edu.harvard.i2b2.ontology.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.ontology.datavo.i2b2message.MessageHeaderType; -import edu.harvard.i2b2.ontology.datavo.i2b2message.ResponseHeaderType; -import edu.harvard.i2b2.ontology.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.ontology.datavo.pm.ProjectType; -import edu.harvard.i2b2.ontology.datavo.vdo.ConceptType; -import edu.harvard.i2b2.ontology.datavo.vdo.ConceptsType; -import edu.harvard.i2b2.ontology.datavo.vdo.VocabRequestType; -import edu.harvard.i2b2.ontology.util.OntologyJAXBUtil; -import edu.harvard.i2b2.ontology.ws.GetNameInfoDataMessage; -import edu.harvard.i2b2.ontology.ws.MessageFactory; - -public class GetNameInfoHandler extends RequestHandler { - private static Log log = LogFactory.getLog(GetNameInfoHandler.class); - private GetNameInfoDataMessage nameInfoMsg = null; - private VocabRequestType vocabType = null; - private ProjectType project = null; - - public GetNameInfoHandler(GetNameInfoDataMessage requestMsg) throws I2B2Exception { - try { - nameInfoMsg = requestMsg; - vocabType = requestMsg.getVocabRequestType(); - setDbInfo(requestMsg.getMessageHeaderType()); - // test case for bad user - // nameInfoMsg.getMessageHeaderType().getSecurity().setUsername("aaaaaaa"); - project = getRoleInfo(requestMsg.getMessageHeaderType()); - - } catch (JAXBUtilException e) { - log.error("error setting up getNameInfoHandler"); - throw new I2B2Exception("GetNameInfoHandler not configured"); - } - } - @Override - public String execute() throws I2B2Exception { - // call ejb and pass input object - ConceptDao conceptDao = new ConceptDao(); - ConceptsType concepts = new ConceptsType(); - ResponseMessageType responseMessageType = null; - - // if project == null, user was not validated or PM service problem - - if(project == null) { - String response = null; - responseMessageType = MessageFactory.doBuildErrorResponse(nameInfoMsg.getMessageHeaderType(), "User was not validated"); - response = MessageFactory.convertToXMLString(responseMessageType); - log.debug("USER_INVALID or PM_SERVICE_PROBLEM"); - return response; - } - - List response = null; - try { - response = conceptDao.findNameInfo(vocabType, project, this.getDbInfo()); - } catch (I2B2DAOException e1) { - log.error(e1.getMessage()); - responseMessageType = MessageFactory.doBuildErrorResponse(nameInfoMsg.getMessageHeaderType(), "Database error"); - } catch (I2B2Exception e1) { - log.error(e1.getMessage()); - responseMessageType = MessageFactory.doBuildErrorResponse(nameInfoMsg.getMessageHeaderType(), "Database configuration error"); - } - - //jgk - // This does a linear search through fullnames for each previous fullname, O(n^2) :( - // BUT it assumes its sorted by hlevel so it only has to search through whats already seen - n(n+1)/2 operations - if (response != null && response.size()>0 && vocabType.isReducedResults()!=null && vocabType.isReducedResults()) { - ArrayList seen = new ArrayList(); - ArrayList keep = new ArrayList(); - Iterator it = response.iterator(); - while (it.hasNext()) - { - ConceptType node = (ConceptType)it.next(); - String key = node.getKey(); - boolean bAbort = false; - for (String k : seen) { - if(key.startsWith(k) && !key.equals(k) /* <-- don't kill the synonyms */ ) { - bAbort = true; - break; - } - } - if (!bAbort) { - /*// This section annotates node names with a category prefix, either PREFIX:code from basecode or CATEGORY\etc\ in the key - String nodeType = ""; - if (node.getBasecode().contains(":")) nodeType=node.getBasecode().substring(0,node.getBasecode().indexOf(":")); - else if (node.getKey().contains("\\")) node.getKey().substring(0, node.getKey().indexOf("\\")); - node.setName("("+nodeType+") "+node.getName()); - */ - // Add nodes that were not subsumed to the keep list - keep.add(node); - } - // Hidden and inactive should not subsume other nodes - exclude them - if (node.getVisualattributes().contains("A")) - seen.add(node.getKey()); - } - log.debug("Reduced find terms from "+response.size()+" to "+keep.size()); - response = keep; - } - - // no errors found - String responseVdo = null; - - Gson gson = new GsonBuilder().setPrettyPrinting() - .registerTypeAdapter( - XMLGregorianCalendar.class, - new XMLGregorianCalendarDeserializer() ) - .create(); - - - if(responseMessageType == null) { - // no db error but response is empty - if (response == null) { - log.debug("query results are empty"); - responseMessageType = MessageFactory.doBuildErrorResponse(nameInfoMsg.getMessageHeaderType(), "Query results are empty"); - } - // No errors, non-empty response received - // If max is specified, check that response is not > max - else if(vocabType.getMax() != null && vocabType.getMax() != 0) { - Iterator itr = response.iterator(); - int i=0; - while (itr.hasNext() && i vocabType.getMax()){ - log.debug("Max request size of " + vocabType.getMax() + " exceeded "); - responseMessageType = MessageFactory.doBuildErrorResponse(nameInfoMsg.getMessageHeaderType(), "MAX_EXCEEDED",concepts); - } - // otherwise send results - else { - // create ResponseMessageHeader using information from request message header. - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(nameInfoMsg.getMessageHeaderType()); - responseMessageType = MessageFactory.createBuildResponse(messageHeader,concepts); - } - } - //max not specified so send results - else { - Iterator itr = response.iterator(); - while (itr.hasNext()) - { - ConceptType node = (ConceptType)itr.next(); - concepts.getConcept().add(node); - } - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(nameInfoMsg.getMessageHeaderType()); - responseMessageType = MessageFactory.createBuildResponse(messageHeader,concepts); - - - //responseVdo = gson.toJson(response); - } - } - - if (responseVdo == null) - responseVdo = MessageFactory.convertToXMLString(responseMessageType); - return responseVdo; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Lori Phillips + */ +package edu.harvard.i2b2.ontology.delegate; + +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import javax.xml.datatype.XMLGregorianCalendar; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.XMLGregorianCalendarDeserializer; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.ontology.dao.ConceptDao; +import edu.harvard.i2b2.ontology.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.ontology.datavo.i2b2message.MessageHeaderType; +import edu.harvard.i2b2.ontology.datavo.i2b2message.ResponseHeaderType; +import edu.harvard.i2b2.ontology.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.ontology.datavo.pm.ProjectType; +import edu.harvard.i2b2.ontology.datavo.vdo.ConceptType; +import edu.harvard.i2b2.ontology.datavo.vdo.ConceptsType; +import edu.harvard.i2b2.ontology.datavo.vdo.VocabRequestType; +import edu.harvard.i2b2.ontology.util.OntologyJAXBUtil; +import edu.harvard.i2b2.ontology.ws.GetNameInfoDataMessage; +import edu.harvard.i2b2.ontology.ws.MessageFactory; + +public class GetNameInfoHandler extends RequestHandler { + private static Log log = LogFactory.getLog(GetNameInfoHandler.class); + private GetNameInfoDataMessage nameInfoMsg = null; + private VocabRequestType vocabType = null; + private ProjectType project = null; + + public GetNameInfoHandler(GetNameInfoDataMessage requestMsg) throws I2B2Exception { + try { + nameInfoMsg = requestMsg; + vocabType = requestMsg.getVocabRequestType(); + setDbInfo(requestMsg.getMessageHeaderType()); + // test case for bad user + // nameInfoMsg.getMessageHeaderType().getSecurity().setUsername("aaaaaaa"); + project = getRoleInfo(requestMsg.getMessageHeaderType()); + + } catch (JAXBUtilException e) { + log.error("error setting up getNameInfoHandler"); + throw new I2B2Exception("GetNameInfoHandler not configured"); + } + } + @Override + public String execute() throws I2B2Exception { + // call ejb and pass input object + ConceptDao conceptDao = new ConceptDao(); + ConceptsType concepts = new ConceptsType(); + ResponseMessageType responseMessageType = null; + + // if project == null, user was not validated or PM service problem + + if(project == null) { + String response = null; + responseMessageType = MessageFactory.doBuildErrorResponse(nameInfoMsg.getMessageHeaderType(), "User was not validated"); + response = MessageFactory.convertToXMLString(responseMessageType); + log.debug("USER_INVALID or PM_SERVICE_PROBLEM"); + return response; + } + + List response = null; + try { + response = conceptDao.findNameInfo(vocabType, project, this.getDbInfo()); + } catch (I2B2DAOException e1) { + log.error(e1.getMessage()); + responseMessageType = MessageFactory.doBuildErrorResponse(nameInfoMsg.getMessageHeaderType(), "Database error"); + } catch (I2B2Exception e1) { + log.error(e1.getMessage()); + responseMessageType = MessageFactory.doBuildErrorResponse(nameInfoMsg.getMessageHeaderType(), "Database configuration error"); + } + + //jgk + // This does a linear search through fullnames for each previous fullname, O(n^2) :( + // BUT it assumes its sorted by hlevel so it only has to search through whats already seen - n(n+1)/2 operations + if (response != null && response.size()>0 && vocabType.isReducedResults()!=null && vocabType.isReducedResults()) { + ArrayList seen = new ArrayList(); + ArrayList keep = new ArrayList(); + Iterator it = response.iterator(); + while (it.hasNext()) + { + ConceptType node = (ConceptType)it.next(); + String key = node.getKey(); + boolean bAbort = false; + for (String k : seen) { + if(key.startsWith(k) && !key.equals(k) /* <-- don't kill the synonyms */ ) { + bAbort = true; + break; + } + } + if (!bAbort) { + /*// This section annotates node names with a category prefix, either PREFIX:code from basecode or CATEGORY\etc\ in the key + String nodeType = ""; + if (node.getBasecode().contains(":")) nodeType=node.getBasecode().substring(0,node.getBasecode().indexOf(":")); + else if (node.getKey().contains("\\")) node.getKey().substring(0, node.getKey().indexOf("\\")); + node.setName("("+nodeType+") "+node.getName()); + */ + // Add nodes that were not subsumed to the keep list + keep.add(node); + } + // Hidden and inactive should not subsume other nodes - exclude them + if (node.getVisualattributes().contains("A")) + seen.add(node.getKey()); + } + log.debug("Reduced find terms from "+response.size()+" to "+keep.size()); + response = keep; + } + + // no errors found + String responseVdo = null; + + Gson gson = new GsonBuilder().setPrettyPrinting() + .registerTypeAdapter( + XMLGregorianCalendar.class, + new XMLGregorianCalendarDeserializer() ) + .create(); + + + if(responseMessageType == null) { + // no db error but response is empty + if (response == null) { + log.debug("query results are empty"); + responseMessageType = MessageFactory.doBuildErrorResponse(nameInfoMsg.getMessageHeaderType(), "Query results are empty"); + } + // No errors, non-empty response received + // If max is specified, check that response is not > max + else if(vocabType.getMax() != null && vocabType.getMax() != 0) { + Iterator itr = response.iterator(); + int i=0; + while (itr.hasNext() && i vocabType.getMax()){ + log.debug("Max request size of " + vocabType.getMax() + " exceeded "); + responseMessageType = MessageFactory.doBuildErrorResponse(nameInfoMsg.getMessageHeaderType(), "MAX_EXCEEDED",concepts); + } + // otherwise send results + else { + // create ResponseMessageHeader using information from request message header. + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(nameInfoMsg.getMessageHeaderType()); + responseMessageType = MessageFactory.createBuildResponse(messageHeader,concepts); + } + } + //max not specified so send results + else { + Iterator itr = response.iterator(); + while (itr.hasNext()) + { + ConceptType node = (ConceptType)itr.next(); + concepts.getConcept().add(node); + } + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(nameInfoMsg.getMessageHeaderType()); + responseMessageType = MessageFactory.createBuildResponse(messageHeader,concepts); + + + //responseVdo = gson.toJson(response); + } + } + + if (responseVdo == null) + responseVdo = MessageFactory.convertToXMLString(responseMessageType); + return responseVdo; + } +} diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/GetOntProcessStatusHandler.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/GetOntProcessStatusHandler.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/GetOntProcessStatusHandler.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/GetOntProcessStatusHandler.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/GetSchemesHandler.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/GetSchemesHandler.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/GetSchemesHandler.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/GetSchemesHandler.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/GetTermInfoHandler.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/GetTermInfoHandler.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/GetTermInfoHandler.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/GetTermInfoHandler.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/LoadMetadataHandler.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/LoadMetadataHandler.java similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/LoadMetadataHandler.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/LoadMetadataHandler.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/LoadSchemesHandler.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/LoadSchemesHandler.java similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/LoadSchemesHandler.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/LoadSchemesHandler.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/LoadTableAccessHandler.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/LoadTableAccessHandler.java similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/LoadTableAccessHandler.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/LoadTableAccessHandler.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/ModifyChildHandler.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/ModifyChildHandler.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/ModifyChildHandler.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/ModifyChildHandler.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/RequestHandler.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/RequestHandler.java old mode 100755 new mode 100644 similarity index 95% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/RequestHandler.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/RequestHandler.java index d9b8dfeb..24fbb223 --- a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/RequestHandler.java +++ b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/RequestHandler.java @@ -1,144 +1,144 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Lori Phillips - */ -package edu.harvard.i2b2.ontology.delegate; - -import java.util.Iterator; -import org.apache.axis2.AxisFault; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.ontology.dao.DataSourceLookupHelper; -import edu.harvard.i2b2.ontology.datavo.i2b2message.MessageHeaderType; -import edu.harvard.i2b2.ontology.datavo.i2b2message.StatusType; -import edu.harvard.i2b2.ontology.datavo.pm.ConfigureType; -import edu.harvard.i2b2.ontology.datavo.pm.GetUserConfigurationType; -import edu.harvard.i2b2.ontology.datavo.pm.ProjectType; -import edu.harvard.i2b2.ontology.ejb.DBInfoType; -import edu.harvard.i2b2.ontology.util.OntologyUtil; -import edu.harvard.i2b2.pm.ws.PMResponseMessage; -import edu.harvard.i2b2.pm.ws.PMServiceDriver; - - - -public abstract class RequestHandler { - protected static Log log = LogFactory.getLog(RequestHandler.class); - protected final Log logesapi = LogFactory.getLog(getClass()); - - public abstract String execute() throws I2B2Exception; - - private DBInfoType dbInfo; - - public boolean isAdmin(MessageHeaderType header) { - try { - GetUserConfigurationType userConfigType = new GetUserConfigurationType(); - String response = PMServiceDriver.getRoles(userConfigType, header); - logesapi.debug(response); - PMResponseMessage msg = new PMResponseMessage(); - StatusType procStatus = msg.processResult(response); - if(procStatus.getType().equals("ERROR")) return false; - ConfigureType pmConfigure = msg.readUserInfo(); - if (pmConfigure.getUser().isIsAdmin()) return true; - } catch (AxisFault e) { - log.error("Can't connect to PM service"); - } catch (I2B2Exception e) { - log.error("Problem processing PM service address"); - } catch (Exception e) { - log.error("General PM processing problem: "+ e.getMessage()); - } - return false; - } - - public ProjectType getRoleInfo(MessageHeaderType header) - { - ProjectType projectType = null; - - - try { - GetUserConfigurationType userConfigType = new GetUserConfigurationType(); - - PMResponseMessage msg = new PMResponseMessage(); - StatusType procStatus = null; - String response = PMServiceDriver.getRoles(userConfigType,header); - logesapi.debug(response); - procStatus = msg.processResult(response); - if(procStatus.getType().equals("ERROR")) - return null; - // check that user has access to this project. - // IF THERE IS NO MATCH (header.projectId is null) - // this will return projectType == null. - ConfigureType pmConfigure = msg.readUserInfo(); - Iterator it = pmConfigure.getUser().getProject().iterator(); - while (it.hasNext()) - { - /* BUG projectType = (ProjectType)it.next(); - log.debug("Matching PM response's project name [" + projectType.getName() + "] with the request project name [" + header.getProjectId() + "]"); - if (projectType.getName().equals(header.getProjectId())) { - break; - } - */ - ProjectType project = (ProjectType)it.next(); - log.debug("Matching PM response's project [" + project.getId() + "] with the request project [" + header.getProjectId() + "]"); - if (project.getId().equals(header.getProjectId())) { - projectType = project; - break; - } - - } - - - // projectType = pmConfigure.getUser().getProject().get(0); - } catch (AxisFault e) { - log.error("Cant connect to PM service"); - } catch (I2B2Exception e) { - log.error("Problem processing PM service address"); - } catch (Exception e) { - log.error("General PM processing problem: "+ e.getMessage()); - } - - return projectType; - } - - public void setDbInfo(MessageHeaderType requestMessageHeader) throws I2B2Exception{ - - DataSourceLookupHelper dsHelper = new DataSourceLookupHelper(); - this.dbInfo = - dsHelper.matchDataSource(requestMessageHeader.getSecurity().getDomain(), - requestMessageHeader.getProjectId(), - requestMessageHeader.getSecurity().getUsername()); - } - - - public DBInfoType getDbInfo() { - return this.dbInfo; - } - - public String getMetadata_dataSource() { - return dbInfo.getDb_dataSource(); - } - - - public String getMetadata_fullSchema() { - return dbInfo.getDb_fullSchema(); - } - - public String getMetadata_serverType() { - return dbInfo.getDb_serverType(); - } - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Lori Phillips + */ +package edu.harvard.i2b2.ontology.delegate; + +import java.util.Iterator; +import org.apache.axis2.AxisFault; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.ontology.dao.DataSourceLookupHelper; +import edu.harvard.i2b2.ontology.datavo.i2b2message.MessageHeaderType; +import edu.harvard.i2b2.ontology.datavo.i2b2message.StatusType; +import edu.harvard.i2b2.ontology.datavo.pm.ConfigureType; +import edu.harvard.i2b2.ontology.datavo.pm.GetUserConfigurationType; +import edu.harvard.i2b2.ontology.datavo.pm.ProjectType; +import edu.harvard.i2b2.ontology.ejb.DBInfoType; +import edu.harvard.i2b2.ontology.util.OntologyUtil; +import edu.harvard.i2b2.ontologypm.ws.PMResponseMessage; +import edu.harvard.i2b2.ontologypm.ws.PMServiceDriver; + + + +public abstract class RequestHandler { + protected static Log log = LogFactory.getLog(RequestHandler.class); + protected final Log logesapi = LogFactory.getLog(getClass()); + + public abstract String execute() throws I2B2Exception; + + private DBInfoType dbInfo; + + public boolean isAdmin(MessageHeaderType header) { + try { + GetUserConfigurationType userConfigType = new GetUserConfigurationType(); + String response = PMServiceDriver.getRoles(userConfigType, header); + logesapi.debug(response); + PMResponseMessage msg = new PMResponseMessage(); + StatusType procStatus = msg.processResult(response); + if(procStatus.getType().equals("ERROR")) return false; + ConfigureType pmConfigure = msg.readUserInfo(); + if (pmConfigure.getUser().isIsAdmin()) return true; + } catch (AxisFault e) { + log.error("Can't connect to PM service"); + } catch (I2B2Exception e) { + log.error("Problem processing PM service address"); + } catch (Exception e) { + log.error("General PM processing problem: "+ e.getMessage()); + } + return false; + } + + public ProjectType getRoleInfo(MessageHeaderType header) + { + ProjectType projectType = null; + + + try { + GetUserConfigurationType userConfigType = new GetUserConfigurationType(); + + PMResponseMessage msg = new PMResponseMessage(); + StatusType procStatus = null; + String response = PMServiceDriver.getRoles(userConfigType,header); + logesapi.debug(response); + procStatus = msg.processResult(response); + if(procStatus.getType().equals("ERROR")) + return null; + // check that user has access to this project. + // IF THERE IS NO MATCH (header.projectId is null) + // this will return projectType == null. + ConfigureType pmConfigure = msg.readUserInfo(); + Iterator it = pmConfigure.getUser().getProject().iterator(); + while (it.hasNext()) + { + /* BUG projectType = (ProjectType)it.next(); + log.debug("Matching PM response's project name [" + projectType.getName() + "] with the request project name [" + header.getProjectId() + "]"); + if (projectType.getName().equals(header.getProjectId())) { + break; + } + */ + ProjectType project = (ProjectType)it.next(); + log.debug("Matching PM response's project [" + project.getId() + "] with the request project [" + header.getProjectId() + "]"); + if (project.getId().equals(header.getProjectId())) { + projectType = project; + break; + } + + } + + + // projectType = pmConfigure.getUser().getProject().get(0); + } catch (AxisFault e) { + log.error("Cant connect to PM service"); + } catch (I2B2Exception e) { + log.error("Problem processing PM service address"); + } catch (Exception e) { + log.error("General PM processing problem: "+ e.getMessage()); + } + + return projectType; + } + + public void setDbInfo(MessageHeaderType requestMessageHeader) throws I2B2Exception{ + + DataSourceLookupHelper dsHelper = new DataSourceLookupHelper(); + this.dbInfo = + dsHelper.matchDataSource(requestMessageHeader.getSecurity().getDomain(), + requestMessageHeader.getProjectId(), + requestMessageHeader.getSecurity().getUsername()); + } + + + public DBInfoType getDbInfo() { + return this.dbInfo; + } + + public String getMetadata_dataSource() { + return dbInfo.getDb_dataSource(); + } + + + public String getMetadata_fullSchema() { + return dbInfo.getDb_fullSchema(); + } + + public String getMetadata_serverType() { + return dbInfo.getDb_serverType(); + } + + +} diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/RequestRunnable.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/RequestRunnable.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/RequestRunnable.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/RequestRunnable.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/SetDblookupHandler.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/SetDblookupHandler.java similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/SetDblookupHandler.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/SetDblookupHandler.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/UpdateTotalNumHandler.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/UpdateTotalNumHandler.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/UpdateTotalNumHandler.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/UpdateTotalNumHandler.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/UpdateTotalNumRunnable.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/UpdateTotalNumRunnable.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/UpdateTotalNumRunnable.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/UpdateTotalNumRunnable.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/crc/CallCRCUtil.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/crc/CallCRCUtil.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/crc/CallCRCUtil.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/crc/CallCRCUtil.java index c6496182..83095e0d --- a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/crc/CallCRCUtil.java +++ b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/crc/CallCRCUtil.java @@ -1,550 +1,550 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.ontology.delegate.crc; - -import java.io.StringReader; -import java.io.StringWriter; - -import jakarta.xml.bind.JAXBElement; -import javax.xml.stream.XMLInputFactory; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamReader; - -import org.apache.axiom.om.OMAbstractFactory; -import org.apache.axiom.om.OMElement; -import org.apache.axiom.om.OMFactory; -import org.apache.axiom.om.OMXMLBuilderFactory; -import org.apache.axis2.AxisFault; -import org.apache.axis2.Constants; -import org.apache.axis2.addressing.EndpointReference; -import org.apache.axis2.client.Options; -import edu.harvard.i2b2.common.util.axis2.ServiceClient; -import org.apache.axis2.context.ServiceContext; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.ontology.datavo.crc.setfinder.query.InstanceRequestType; -import edu.harvard.i2b2.ontology.datavo.crc.setfinder.query.ItemType; -import edu.harvard.i2b2.ontology.datavo.crc.setfinder.query.MasterDeleteRequestType; -import edu.harvard.i2b2.ontology.datavo.crc.setfinder.query.MasterInstanceResultResponseType; -import edu.harvard.i2b2.ontology.datavo.crc.setfinder.query.MasterResponseType; -import edu.harvard.i2b2.ontology.datavo.crc.setfinder.query.PanelType; -import edu.harvard.i2b2.ontology.datavo.crc.setfinder.query.PsmQryHeaderType; -import edu.harvard.i2b2.ontology.datavo.crc.setfinder.query.PsmRequestTypeType; -import edu.harvard.i2b2.ontology.datavo.crc.setfinder.query.QueryDefinitionRequestType; -import edu.harvard.i2b2.ontology.datavo.crc.setfinder.query.QueryDefinitionType; -import edu.harvard.i2b2.ontology.datavo.crc.setfinder.query.ResultOutputOptionListType; -import edu.harvard.i2b2.ontology.datavo.crc.setfinder.query.ResultOutputOptionType; -import edu.harvard.i2b2.ontology.datavo.crc.setfinder.query.ResultResponseType; -import edu.harvard.i2b2.ontology.datavo.crcloader.query.DataFormatType; -import edu.harvard.i2b2.ontology.datavo.crcloader.query.DataListType; -import edu.harvard.i2b2.ontology.datavo.crcloader.query.GetUploadInfoRequestType; -import edu.harvard.i2b2.ontology.datavo.crcloader.query.InputOptionListType; -import edu.harvard.i2b2.ontology.datavo.crcloader.query.LoadDataResponseType; -import edu.harvard.i2b2.ontology.datavo.crcloader.query.LoadOptionType; -import edu.harvard.i2b2.ontology.datavo.crcloader.query.LoadType; -import edu.harvard.i2b2.ontology.datavo.crcloader.query.OutputOptionListType; -import edu.harvard.i2b2.ontology.datavo.crcloader.query.PublishDataRequestType; -import edu.harvard.i2b2.ontology.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.ontology.datavo.i2b2message.FacilityType; -import edu.harvard.i2b2.ontology.datavo.i2b2message.MessageHeaderType; -import edu.harvard.i2b2.ontology.datavo.i2b2message.RequestHeaderType; -import edu.harvard.i2b2.ontology.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.ontology.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.ontology.datavo.i2b2message.ResultStatusType; -import edu.harvard.i2b2.ontology.datavo.i2b2message.SecurityType; -import edu.harvard.i2b2.ontology.util.OntologyJAXBUtil; -import edu.harvard.i2b2.ontology.util.OntologyUtil; -import edu.harvard.i2b2.ontology.ws.MessageFactory; - -public class CallCRCUtil { - - //private SecurityType securityType = null; - //private String projectId = null; - private static String crcUrl = null; - static OntologyUtil ontologyUtil = OntologyUtil.getInstance(); - - protected static Log log = LogFactory.getLog(CallCRCUtil.class); - - - public static LoadDataResponseType callCRCUpload(String conceptFileName, - String loadLabel, boolean synchronizeAllFlag, SecurityType securityType, String projectId) throws I2B2Exception { - RequestMessageType requestMessageType = buildUploaderRequestMessage( - conceptFileName, loadLabel, synchronizeAllFlag, securityType, projectId); - LoadDataResponseType loadDataResponseType = null; - try { - OMElement requestElement = buildOMElement(requestMessageType); - log.debug("CRC Ontology call's request xml " - + requestElement); - String response = ServiceClient.sendREST(crcUrl + "/publishDataRequest", requestElement); - log.debug("CRC Ontology call's reponse xml " + response); - loadDataResponseType = getGetPublishDataResponseMessage(response - ); - } catch (JAXBUtilException jaxbEx) { - throw new I2B2Exception("Error in CRC upload ", jaxbEx); - } catch (XMLStreamException e) { - throw new I2B2Exception("Error in CRC upload ", e); - - } catch (Exception e) { - - throw new I2B2Exception("Error in CRC upload ", e); - } - return loadDataResponseType; - } - - public static MasterInstanceResultResponseType callSetfinderQuery(String conceptKey, SecurityType securityType, String projectId) throws I2B2Exception { - RequestMessageType requestMessageType = buildSetfinderQueryRequestMessage(conceptKey, securityType, projectId); - MasterInstanceResultResponseType masterInstanceResultResponseType = null; - try { - OMElement requestElement = buildOMElement(requestMessageType); - log.debug("CRC Ontology call's request xml " - + requestElement); - String response = ServiceClient.sendREST(crcUrl + "/request", requestElement); - log.debug("CRC Ontology call's reponse xml " + response); - masterInstanceResultResponseType = getMasterInstanceResultResponseMessage(response - ); - } catch (JAXBUtilException jaxbEx) { - throw new I2B2Exception("Error in CRC setfinder ", jaxbEx); - } catch (XMLStreamException e) { - throw new I2B2Exception("Error in CRC setfinder ", e); - - } catch (Exception e) { - - throw new I2B2Exception("Error in CRC setfinder ", e); - } - return masterInstanceResultResponseType; - } - - public static MasterResponseType callDeleteMasterQuery(String userId, String queryMasterId, SecurityType securityType, String projectId) - throws I2B2Exception { - RequestMessageType requestMessageType = buildDeleteSetfinderStatusRequestMessage(userId, queryMasterId, securityType, projectId); - MasterResponseType masterResponseType = null; - try { - OMElement requestElement = buildOMElement(requestMessageType); - log.debug("CRC setfinder query delete call's request xml " - + requestElement); - String response = ServiceClient.sendREST(crcUrl + "/request", requestElement); - log.debug("CRC setfinder query delete call's request xml " + response); - masterResponseType = getMasterResponseMessage(response - ); - - } catch (JAXBUtilException jaxbEx) { - throw new I2B2Exception("Error in CRC upload ", jaxbEx); - } catch (XMLStreamException e) { - throw new I2B2Exception("Error in CRC upload ", e); - - } catch (Exception e) { - - throw new I2B2Exception("Error in CRC upload ", e); - } - return masterResponseType; - } - - public static ResultResponseType callCRCQueryStatus(String queryInstanceId, SecurityType securityType, String projectId) - throws I2B2Exception { - RequestMessageType requestMessageType = buildSetfinderStatusRequestMessage(queryInstanceId, securityType, projectId); - ResultResponseType resultResponseType = null; - try { - OMElement requestElement = buildOMElement(requestMessageType); - log.debug("CRC setfinder query status call's request xml " - + requestElement); - String response = ServiceClient.sendREST(crcUrl + "/request", requestElement); - log.debug("CRC setfinder query status call's request xml " + response); - resultResponseType = getResultResponseMessage(response - .toString()); - - } catch (JAXBUtilException jaxbEx) { - throw new I2B2Exception("Error in CRC upload ", jaxbEx); - } catch (XMLStreamException e) { - throw new I2B2Exception("Error in CRC upload ", e); - - } catch (Exception e) { - - throw new I2B2Exception("Error in CRC upload ", e); - } - return resultResponseType; - } - - public static ResultResponseType pollQueryStatus(String instanceId, SecurityType securityType, String projectId) - throws I2B2Exception { - SetfinderQueryStatusRunner setfinderQueryStatusRunner = new SetfinderQueryStatusRunner(); - //setfinderQueryStatusRunner.setCRCUtil(this); - setfinderQueryStatusRunner.setQueryInstanceId(instanceId); - setfinderQueryStatusRunner.setSecurityType(securityType); - setfinderQueryStatusRunner.setProjectId(projectId); - Thread t = new Thread(setfinderQueryStatusRunner); - t.start(); - while (setfinderQueryStatusRunner.isNotDone()) { - try { - Thread.sleep(60000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - String exceptionMsg = setfinderQueryStatusRunner.getExceptionMsg(); - if (exceptionMsg != null) { - throw new I2B2Exception("Error while getting status of upload [" - + exceptionMsg + "]"); - } - ResultResponseType resultResponse = setfinderQueryStatusRunner.getQueryInstanceStatusResponseType(); - - - return resultResponse; - } - - - public static LoadDataResponseType callCRCUploadStatus(String uploadId, SecurityType securityType, String projectId) - throws I2B2Exception { - RequestMessageType requestMessageType = buildUploaderRequestMessage(uploadId, securityType, projectId); - LoadDataResponseType loadDataResponseType = null; - try { - OMElement requestElement = buildOMElement(requestMessageType); - log.debug("CRC Ontology call's request xml " - + requestElement); - String response = ServiceClient.sendREST(crcUrl + "/getLoadDataStatusRequest", requestElement); - log.debug("CRC Ontology call's request xml " + response); - loadDataResponseType = getGetPublishDataResponseMessage(response); - - } catch (JAXBUtilException jaxbEx) { - throw new I2B2Exception("Error in CRC upload ", jaxbEx); - } catch (XMLStreamException e) { - throw new I2B2Exception("Error in CRC upload ", e); - - } catch (Exception e) { - - throw new I2B2Exception("Error in CRC upload ", e); - } - return loadDataResponseType; - } - - public static LoadDataResponseType pollUploadStatus(String uploadId) - throws I2B2Exception { - UploadStatusRunner uploadStatusRunner = new UploadStatusRunner(); - //uploadStatusRunner.setCRCUtil(this); - uploadStatusRunner.setUploadId(uploadId); - Thread t = new Thread(uploadStatusRunner); - t.start(); - while (uploadStatusRunner.isNotDone()) { - try { - Thread.sleep(60000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - String exceptionMsg = uploadStatusRunner.getExceptionMsg(); - if (exceptionMsg != null) { - throw new I2B2Exception("Error while getting status of upload [" - + exceptionMsg + "]"); - } - LoadDataResponseType loadDataResponse = uploadStatusRunner - .getLodDataResponseType(); - - return loadDataResponse; - } - - public static RequestMessageType buildUploaderRequestMessage( - String conceptFileName, String loadLabel, boolean synchronizeAllFlag, SecurityType securityType, String projectId) { - PublishDataRequestType publishDataRequest = new PublishDataRequestType(); - DataListType dataListType = new DataListType(); - DataListType.LocationUri locationUri = new DataListType.LocationUri(); - locationUri.setValue(conceptFileName); - locationUri.setProtocolName("FR"); - dataListType.setLocationUri(locationUri); - - dataListType.setDataFormatType(DataFormatType.PDO); - InputOptionListType inputListType = new InputOptionListType(); - inputListType.setDataFile(dataListType); - dataListType.setLoadLabel(loadLabel); - dataListType.setSourceSystemCd("edu.harvard.i2b2.ontology.sync"); - publishDataRequest.setInputList(inputListType); - - LoadType loadType = new LoadType(); - loadType.setClearTempLoadTables(true); - LoadOptionType loadOption = new LoadOptionType(); - loadOption.setIgnoreBadData(true); - if (synchronizeAllFlag) { - loadOption.setDeleteExistingData(true); - } - loadType.setLoadConceptSet(loadOption); - loadType.setLoadObserverSet(loadOption); - loadType.setLoadModifierSet(loadOption); - publishDataRequest.setLoadList(loadType); - OutputOptionListType outOption = new OutputOptionListType(); - publishDataRequest.setOutputList(outOption); - - MessageHeaderType messageHeaderType = ontologyUtil.getMessageHeader(); - - messageHeaderType.setSecurity(securityType); - messageHeaderType.setProjectId(projectId); - - messageHeaderType.setReceivingApplication(messageHeaderType - .getSendingApplication()); - FacilityType facilityType = new FacilityType(); - facilityType.setFacilityName("sample"); - messageHeaderType.setSendingFacility(facilityType); - messageHeaderType.setReceivingFacility(facilityType); - - RequestMessageType requestMessageType = new RequestMessageType(); - edu.harvard.i2b2.ontology.datavo.crcloader.query.ObjectFactory of = new edu.harvard.i2b2.ontology.datavo.crcloader.query.ObjectFactory(); - BodyType bodyType = new BodyType(); - bodyType.getAny().add(of.createPublishDataRequest(publishDataRequest)); - requestMessageType.setMessageBody(bodyType); - - requestMessageType.setMessageHeader(messageHeaderType); - - RequestHeaderType requestHeader = new RequestHeaderType(); - requestHeader.setResultWaittimeMs(180000); //(3000); - requestMessageType.setRequestHeader(requestHeader); - return requestMessageType; - } - - public static RequestMessageType buildUploaderRequestMessage(String uploadId, SecurityType securityType, String projectId) { - GetUploadInfoRequestType getUploadInfo = new GetUploadInfoRequestType(); - getUploadInfo.setLoadId(uploadId); - getUploadInfo.setUserId(securityType.getUsername()); - - MessageHeaderType messageHeaderType = ontologyUtil.getMessageHeader(); - messageHeaderType.setSecurity(securityType); - messageHeaderType.setProjectId(projectId); - - messageHeaderType.setReceivingApplication(messageHeaderType - .getSendingApplication()); - FacilityType facilityType = new FacilityType(); - facilityType.setFacilityName("sample"); - messageHeaderType.setSendingFacility(facilityType); - messageHeaderType.setReceivingFacility(facilityType); - - RequestMessageType requestMessageType = new RequestMessageType(); - edu.harvard.i2b2.ontology.datavo.crcloader.query.ObjectFactory of = new edu.harvard.i2b2.ontology.datavo.crcloader.query.ObjectFactory(); - BodyType bodyType = new BodyType(); - bodyType.getAny().add(of.createGetUploadInfoRequest(getUploadInfo)); - requestMessageType.setMessageBody(bodyType); - - requestMessageType.setMessageHeader(messageHeaderType); - - RequestHeaderType requestHeader = new RequestHeaderType(); - requestHeader.setResultWaittimeMs(180000); //3000); - requestMessageType.setRequestHeader(requestHeader); - return requestMessageType; - } - - public static RequestMessageType buildSetfinderStatusRequestMessage(String queryInstanceId, SecurityType securityType, String projectId) { - InstanceRequestType instanceRequestType = new InstanceRequestType(); - instanceRequestType.setQueryInstanceId(queryInstanceId); - - MessageHeaderType messageHeaderType = ontologyUtil.getMessageHeader(); - messageHeaderType.setSecurity(securityType); - messageHeaderType.setProjectId(projectId); - - messageHeaderType.setReceivingApplication(messageHeaderType - .getSendingApplication()); - FacilityType facilityType = new FacilityType(); - facilityType.setFacilityName("sample"); - messageHeaderType.setSendingFacility(facilityType); - messageHeaderType.setReceivingFacility(facilityType); - - RequestMessageType requestMessageType = new RequestMessageType(); - - edu.harvard.i2b2.ontology.datavo.crc.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.ontology.datavo.crc.setfinder.query.ObjectFactory(); - BodyType bodyType = new BodyType(); - PsmQryHeaderType psm = new PsmQryHeaderType(); - psm.setRequestType(PsmRequestTypeType.CRC_QRY_GET_QUERY_RESULT_INSTANCE_LIST_FROM_QUERY_INSTANCE_ID); - bodyType.getAny().add(of.createPsmheader(psm)); - - bodyType.getAny().add(of.createRequest(instanceRequestType)); - requestMessageType.setMessageBody(bodyType); - - requestMessageType.setMessageHeader(messageHeaderType); - - RequestHeaderType requestHeader = new RequestHeaderType(); - requestHeader.setResultWaittimeMs(220000); //3000); - requestMessageType.setRequestHeader(requestHeader); - return requestMessageType; - } - - public static RequestMessageType buildDeleteSetfinderStatusRequestMessage(String userId, String queryMasterId, SecurityType securityType, String projectId) { - MasterDeleteRequestType masterDeleteReqType = new MasterDeleteRequestType(); - masterDeleteReqType.setQueryMasterId(queryMasterId); - masterDeleteReqType.setUserId(userId); - - MessageHeaderType messageHeaderType = ontologyUtil.getMessageHeader(); - messageHeaderType.setSecurity(securityType); - messageHeaderType.setProjectId(projectId); - - messageHeaderType.setReceivingApplication(messageHeaderType - .getSendingApplication()); - FacilityType facilityType = new FacilityType(); - facilityType.setFacilityName("sample"); - messageHeaderType.setSendingFacility(facilityType); - messageHeaderType.setReceivingFacility(facilityType); - - RequestMessageType requestMessageType = new RequestMessageType(); - - edu.harvard.i2b2.ontology.datavo.crc.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.ontology.datavo.crc.setfinder.query.ObjectFactory(); - BodyType bodyType = new BodyType(); - PsmQryHeaderType psm = new PsmQryHeaderType(); - psm.setRequestType(PsmRequestTypeType.CRC_QRY_DELETE_QUERY_MASTER); - bodyType.getAny().add(of.createPsmheader(psm)); - - bodyType.getAny().add(of.createRequest(masterDeleteReqType)); - requestMessageType.setMessageBody(bodyType); - - requestMessageType.setMessageHeader(messageHeaderType); - - RequestHeaderType requestHeader = new RequestHeaderType(); - requestHeader.setResultWaittimeMs(180000); //(3000); - requestMessageType.setRequestHeader(requestHeader); - return requestMessageType; - } - - public static RequestMessageType buildSetfinderQueryRequestMessage(String itemKey, SecurityType securityType, String projectId) { - QueryDefinitionType queryDef = new QueryDefinitionType(); - PanelType panelType = new PanelType(); - ItemType itemType = new ItemType(); - itemType.setItemKey(itemKey); - panelType.getItem().add(itemType); - queryDef.getPanel().add(panelType); - - queryDef.setQueryName(itemKey.substring(0,(itemKey.length()>10)?9:itemKey.length()) + System.currentTimeMillis()); - QueryDefinitionRequestType queryDefinitionRequestType = new QueryDefinitionRequestType(); - ResultOutputOptionListType resultOutputOptionListType = new ResultOutputOptionListType(); - ResultOutputOptionType resultOutputOptionType = new ResultOutputOptionType(); - resultOutputOptionType.setName("PATIENT_COUNT_XML"); - resultOutputOptionListType.getResultOutput().add(resultOutputOptionType); - queryDefinitionRequestType.setQueryDefinition(queryDef); - queryDefinitionRequestType.setResultOutputList(resultOutputOptionListType); - - MessageHeaderType messageHeaderType = ontologyUtil.getMessageHeader(); - messageHeaderType.setSecurity(securityType); - messageHeaderType.setProjectId(projectId); - - messageHeaderType.setReceivingApplication(messageHeaderType - .getSendingApplication()); - FacilityType facilityType = new FacilityType(); - facilityType.setFacilityName("sample"); - messageHeaderType.setSendingFacility(facilityType); - messageHeaderType.setReceivingFacility(facilityType); - - RequestMessageType requestMessageType = new RequestMessageType(); - edu.harvard.i2b2.ontology.datavo.crc.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.ontology.datavo.crc.setfinder.query.ObjectFactory(); - BodyType bodyType = new BodyType(); - PsmQryHeaderType psm = new PsmQryHeaderType(); - psm.setRequestType(PsmRequestTypeType.CRC_QRY_RUN_QUERY_INSTANCE_FROM_QUERY_DEFINITION); - bodyType.getAny().add(of.createPsmheader(psm)); - bodyType.getAny().add(of.createRequest(queryDefinitionRequestType)); - requestMessageType.setMessageBody(bodyType); - - requestMessageType.setMessageHeader(messageHeaderType); - - RequestHeaderType requestHeader = new RequestHeaderType(); - requestHeader.setResultWaittimeMs(180000); //3000); - requestMessageType.setRequestHeader(requestHeader); - return requestMessageType; - } - - private static LoadDataResponseType getGetPublishDataResponseMessage( - String responseXml) throws JAXBUtilException, I2B2Exception { - JAXBElement responseJaxb = OntologyJAXBUtil.getJAXBUtil() - .unMashallFromString(responseXml); - ResponseMessageType r = (ResponseMessageType) responseJaxb.getValue(); - log.debug("CRC's ontology call response xml" + responseXml); - - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - ResultStatusType rt = r.getResponseHeader().getResultStatus(); - if (rt.getStatus().getType().equals("ERROR")) { - throw new I2B2Exception(rt.getStatus().getValue()); - } - LoadDataResponseType loadDataResponseType = (LoadDataResponseType) helper - .getObjectByClass(r.getMessageBody().getAny(), - LoadDataResponseType.class); - - return loadDataResponseType; - } - - private static MasterInstanceResultResponseType getMasterInstanceResultResponseMessage( - String responseXml) throws JAXBUtilException, I2B2Exception { - JAXBElement responseJaxb = OntologyJAXBUtil.getJAXBUtil() - .unMashallFromString(responseXml); - ResponseMessageType r = (ResponseMessageType) responseJaxb.getValue(); - log.debug("CRC's ontology call response xml" + responseXml); - - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - ResultStatusType rt = r.getResponseHeader().getResultStatus(); - if (rt.getStatus().getType().equals("ERROR")) { - throw new I2B2Exception(rt.getStatus().getValue()); - } - MasterInstanceResultResponseType masterInstanceResultResponseType = (MasterInstanceResultResponseType) helper - .getObjectByClass(r.getMessageBody().getAny(), - MasterInstanceResultResponseType.class); - - return masterInstanceResultResponseType; - } - - private static MasterResponseType getMasterResponseMessage( - String responseXml) throws JAXBUtilException, I2B2Exception { - JAXBElement responseJaxb = OntologyJAXBUtil.getJAXBUtil() - .unMashallFromString(responseXml); - ResponseMessageType r = (ResponseMessageType) responseJaxb.getValue(); - log.debug("CRC's ontology call response xml" + responseXml); - - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - ResultStatusType rt = r.getResponseHeader().getResultStatus(); - if (rt.getStatus().getType().equals("ERROR")) { - throw new I2B2Exception(rt.getStatus().getValue()); - } - MasterResponseType masterResponseType = (MasterResponseType) helper - .getObjectByClass(r.getMessageBody().getAny(), - MasterResponseType.class); - - return masterResponseType; - } - - private static ResultResponseType getResultResponseMessage( - String responseXml) throws JAXBUtilException, I2B2Exception { - JAXBElement responseJaxb = OntologyJAXBUtil.getJAXBUtil() - .unMashallFromString(responseXml); - ResponseMessageType r = (ResponseMessageType) responseJaxb.getValue(); - log.debug("CRC's ontology call response xml" + responseXml); - - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - ResultStatusType rt = r.getResponseHeader().getResultStatus(); - if (rt.getStatus().getType().equals("ERROR")) { - throw new I2B2Exception(rt.getStatus().getValue()); - } - ResultResponseType instanceResultResponseType = (ResultResponseType) helper - .getObjectByClass(r.getMessageBody().getAny(), - ResultResponseType.class); - - return instanceResultResponseType; - } - - private static OMElement buildOMElement(RequestMessageType requestMessageType) - throws XMLStreamException, JAXBUtilException { - StringWriter strWriter = new StringWriter(); - edu.harvard.i2b2.ontology.datavo.i2b2message.ObjectFactory hiveof = new edu.harvard.i2b2.ontology.datavo.i2b2message.ObjectFactory(); - OntologyJAXBUtil.getJAXBUtil().marshaller( - hiveof.createRequest(requestMessageType), strWriter); - // getOMElement from message - OMFactory fac = OMAbstractFactory.getOMFactory(); - - StringReader strReader = new StringReader(strWriter.toString()); - XMLInputFactory xif = XMLInputFactory.newInstance(); - XMLStreamReader reader = xif.createXMLStreamReader(strReader); - OMElement request =OMXMLBuilderFactory.createStAXOMBuilder(reader).getDocumentElement(); - - return request; - } - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.ontology.delegate.crc; + +import java.io.StringReader; +import java.io.StringWriter; + +import jakarta.xml.bind.JAXBElement; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import org.apache.axiom.om.OMAbstractFactory; +import org.apache.axiom.om.OMElement; +import org.apache.axiom.om.OMFactory; +import org.apache.axiom.om.OMXMLBuilderFactory; +import org.apache.axis2.AxisFault; +import org.apache.axis2.Constants; +import org.apache.axis2.addressing.EndpointReference; +import org.apache.axis2.client.Options; +import edu.harvard.i2b2.common.util.axis2.ServiceClient; +import org.apache.axis2.context.ServiceContext; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.ontology.datavo.crc.setfinder.query.InstanceRequestType; +import edu.harvard.i2b2.ontology.datavo.crc.setfinder.query.ItemType; +import edu.harvard.i2b2.ontology.datavo.crc.setfinder.query.MasterDeleteRequestType; +import edu.harvard.i2b2.ontology.datavo.crc.setfinder.query.MasterInstanceResultResponseType; +import edu.harvard.i2b2.ontology.datavo.crc.setfinder.query.MasterResponseType; +import edu.harvard.i2b2.ontology.datavo.crc.setfinder.query.PanelType; +import edu.harvard.i2b2.ontology.datavo.crc.setfinder.query.PsmQryHeaderType; +import edu.harvard.i2b2.ontology.datavo.crc.setfinder.query.PsmRequestTypeType; +import edu.harvard.i2b2.ontology.datavo.crc.setfinder.query.QueryDefinitionRequestType; +import edu.harvard.i2b2.ontology.datavo.crc.setfinder.query.QueryDefinitionType; +import edu.harvard.i2b2.ontology.datavo.crc.setfinder.query.ResultOutputOptionListType; +import edu.harvard.i2b2.ontology.datavo.crc.setfinder.query.ResultOutputOptionType; +import edu.harvard.i2b2.ontology.datavo.crc.setfinder.query.ResultResponseType; +import edu.harvard.i2b2.ontology.datavo.crcloader.query.DataFormatType; +import edu.harvard.i2b2.ontology.datavo.crcloader.query.DataListType; +import edu.harvard.i2b2.ontology.datavo.crcloader.query.GetUploadInfoRequestType; +import edu.harvard.i2b2.ontology.datavo.crcloader.query.InputOptionListType; +import edu.harvard.i2b2.ontology.datavo.crcloader.query.LoadDataResponseType; +import edu.harvard.i2b2.ontology.datavo.crcloader.query.LoadOptionType; +import edu.harvard.i2b2.ontology.datavo.crcloader.query.LoadType; +import edu.harvard.i2b2.ontology.datavo.crcloader.query.OutputOptionListType; +import edu.harvard.i2b2.ontology.datavo.crcloader.query.PublishDataRequestType; +import edu.harvard.i2b2.ontology.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.ontology.datavo.i2b2message.FacilityType; +import edu.harvard.i2b2.ontology.datavo.i2b2message.MessageHeaderType; +import edu.harvard.i2b2.ontology.datavo.i2b2message.RequestHeaderType; +import edu.harvard.i2b2.ontology.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.ontology.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.ontology.datavo.i2b2message.ResultStatusType; +import edu.harvard.i2b2.ontology.datavo.i2b2message.SecurityType; +import edu.harvard.i2b2.ontology.util.OntologyJAXBUtil; +import edu.harvard.i2b2.ontology.util.OntologyUtil; +import edu.harvard.i2b2.ontology.ws.MessageFactory; + +public class CallCRCUtil { + + //private SecurityType securityType = null; + //private String projectId = null; + private static String crcUrl = null; + static OntologyUtil ontologyUtil = OntologyUtil.getInstance(); + + protected static Log log = LogFactory.getLog(CallCRCUtil.class); + + + public static LoadDataResponseType callCRCUpload(String conceptFileName, + String loadLabel, boolean synchronizeAllFlag, SecurityType securityType, String projectId) throws I2B2Exception { + RequestMessageType requestMessageType = buildUploaderRequestMessage( + conceptFileName, loadLabel, synchronizeAllFlag, securityType, projectId); + LoadDataResponseType loadDataResponseType = null; + try { + OMElement requestElement = buildOMElement(requestMessageType); + log.debug("CRC Ontology call's request xml " + + requestElement); + String response = ServiceClient.sendREST(crcUrl + "/publishDataRequest", requestElement); + log.debug("CRC Ontology call's reponse xml " + response); + loadDataResponseType = getGetPublishDataResponseMessage(response + ); + } catch (JAXBUtilException jaxbEx) { + throw new I2B2Exception("Error in CRC upload ", jaxbEx); + } catch (XMLStreamException e) { + throw new I2B2Exception("Error in CRC upload ", e); + + } catch (Exception e) { + + throw new I2B2Exception("Error in CRC upload ", e); + } + return loadDataResponseType; + } + + public static MasterInstanceResultResponseType callSetfinderQuery(String conceptKey, SecurityType securityType, String projectId) throws I2B2Exception { + RequestMessageType requestMessageType = buildSetfinderQueryRequestMessage(conceptKey, securityType, projectId); + MasterInstanceResultResponseType masterInstanceResultResponseType = null; + try { + OMElement requestElement = buildOMElement(requestMessageType); + log.debug("CRC Ontology call's request xml " + + requestElement); + String response = ServiceClient.sendREST(crcUrl + "/request", requestElement); + log.debug("CRC Ontology call's reponse xml " + response); + masterInstanceResultResponseType = getMasterInstanceResultResponseMessage(response + ); + } catch (JAXBUtilException jaxbEx) { + throw new I2B2Exception("Error in CRC setfinder ", jaxbEx); + } catch (XMLStreamException e) { + throw new I2B2Exception("Error in CRC setfinder ", e); + + } catch (Exception e) { + + throw new I2B2Exception("Error in CRC setfinder ", e); + } + return masterInstanceResultResponseType; + } + + public static MasterResponseType callDeleteMasterQuery(String userId, String queryMasterId, SecurityType securityType, String projectId) + throws I2B2Exception { + RequestMessageType requestMessageType = buildDeleteSetfinderStatusRequestMessage(userId, queryMasterId, securityType, projectId); + MasterResponseType masterResponseType = null; + try { + OMElement requestElement = buildOMElement(requestMessageType); + log.debug("CRC setfinder query delete call's request xml " + + requestElement); + String response = ServiceClient.sendREST(crcUrl + "/request", requestElement); + log.debug("CRC setfinder query delete call's request xml " + response); + masterResponseType = getMasterResponseMessage(response + ); + + } catch (JAXBUtilException jaxbEx) { + throw new I2B2Exception("Error in CRC upload ", jaxbEx); + } catch (XMLStreamException e) { + throw new I2B2Exception("Error in CRC upload ", e); + + } catch (Exception e) { + + throw new I2B2Exception("Error in CRC upload ", e); + } + return masterResponseType; + } + + public static ResultResponseType callCRCQueryStatus(String queryInstanceId, SecurityType securityType, String projectId) + throws I2B2Exception { + RequestMessageType requestMessageType = buildSetfinderStatusRequestMessage(queryInstanceId, securityType, projectId); + ResultResponseType resultResponseType = null; + try { + OMElement requestElement = buildOMElement(requestMessageType); + log.debug("CRC setfinder query status call's request xml " + + requestElement); + String response = ServiceClient.sendREST(crcUrl + "/request", requestElement); + log.debug("CRC setfinder query status call's request xml " + response); + resultResponseType = getResultResponseMessage(response + .toString()); + + } catch (JAXBUtilException jaxbEx) { + throw new I2B2Exception("Error in CRC upload ", jaxbEx); + } catch (XMLStreamException e) { + throw new I2B2Exception("Error in CRC upload ", e); + + } catch (Exception e) { + + throw new I2B2Exception("Error in CRC upload ", e); + } + return resultResponseType; + } + + public static ResultResponseType pollQueryStatus(String instanceId, SecurityType securityType, String projectId) + throws I2B2Exception { + SetfinderQueryStatusRunner setfinderQueryStatusRunner = new SetfinderQueryStatusRunner(); + //setfinderQueryStatusRunner.setCRCUtil(this); + setfinderQueryStatusRunner.setQueryInstanceId(instanceId); + setfinderQueryStatusRunner.setSecurityType(securityType); + setfinderQueryStatusRunner.setProjectId(projectId); + Thread t = new Thread(setfinderQueryStatusRunner); + t.start(); + while (setfinderQueryStatusRunner.isNotDone()) { + try { + Thread.sleep(60000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + String exceptionMsg = setfinderQueryStatusRunner.getExceptionMsg(); + if (exceptionMsg != null) { + throw new I2B2Exception("Error while getting status of upload [" + + exceptionMsg + "]"); + } + ResultResponseType resultResponse = setfinderQueryStatusRunner.getQueryInstanceStatusResponseType(); + + + return resultResponse; + } + + + public static LoadDataResponseType callCRCUploadStatus(String uploadId, SecurityType securityType, String projectId) + throws I2B2Exception { + RequestMessageType requestMessageType = buildUploaderRequestMessage(uploadId, securityType, projectId); + LoadDataResponseType loadDataResponseType = null; + try { + OMElement requestElement = buildOMElement(requestMessageType); + log.debug("CRC Ontology call's request xml " + + requestElement); + String response = ServiceClient.sendREST(crcUrl + "/getLoadDataStatusRequest", requestElement); + log.debug("CRC Ontology call's request xml " + response); + loadDataResponseType = getGetPublishDataResponseMessage(response); + + } catch (JAXBUtilException jaxbEx) { + throw new I2B2Exception("Error in CRC upload ", jaxbEx); + } catch (XMLStreamException e) { + throw new I2B2Exception("Error in CRC upload ", e); + + } catch (Exception e) { + + throw new I2B2Exception("Error in CRC upload ", e); + } + return loadDataResponseType; + } + + public static LoadDataResponseType pollUploadStatus(String uploadId) + throws I2B2Exception { + UploadStatusRunner uploadStatusRunner = new UploadStatusRunner(); + //uploadStatusRunner.setCRCUtil(this); + uploadStatusRunner.setUploadId(uploadId); + Thread t = new Thread(uploadStatusRunner); + t.start(); + while (uploadStatusRunner.isNotDone()) { + try { + Thread.sleep(60000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + String exceptionMsg = uploadStatusRunner.getExceptionMsg(); + if (exceptionMsg != null) { + throw new I2B2Exception("Error while getting status of upload [" + + exceptionMsg + "]"); + } + LoadDataResponseType loadDataResponse = uploadStatusRunner + .getLodDataResponseType(); + + return loadDataResponse; + } + + public static RequestMessageType buildUploaderRequestMessage( + String conceptFileName, String loadLabel, boolean synchronizeAllFlag, SecurityType securityType, String projectId) { + PublishDataRequestType publishDataRequest = new PublishDataRequestType(); + DataListType dataListType = new DataListType(); + DataListType.LocationUri locationUri = new DataListType.LocationUri(); + locationUri.setValue(conceptFileName); + locationUri.setProtocolName("FR"); + dataListType.setLocationUri(locationUri); + + dataListType.setDataFormatType(DataFormatType.PDO); + InputOptionListType inputListType = new InputOptionListType(); + inputListType.setDataFile(dataListType); + dataListType.setLoadLabel(loadLabel); + dataListType.setSourceSystemCd("edu.harvard.i2b2.ontology.sync"); + publishDataRequest.setInputList(inputListType); + + LoadType loadType = new LoadType(); + loadType.setClearTempLoadTables(true); + LoadOptionType loadOption = new LoadOptionType(); + loadOption.setIgnoreBadData(true); + if (synchronizeAllFlag) { + loadOption.setDeleteExistingData(true); + } + loadType.setLoadConceptSet(loadOption); + loadType.setLoadObserverSet(loadOption); + loadType.setLoadModifierSet(loadOption); + publishDataRequest.setLoadList(loadType); + OutputOptionListType outOption = new OutputOptionListType(); + publishDataRequest.setOutputList(outOption); + + MessageHeaderType messageHeaderType = ontologyUtil.getMessageHeader(); + + messageHeaderType.setSecurity(securityType); + messageHeaderType.setProjectId(projectId); + + messageHeaderType.setReceivingApplication(messageHeaderType + .getSendingApplication()); + FacilityType facilityType = new FacilityType(); + facilityType.setFacilityName("sample"); + messageHeaderType.setSendingFacility(facilityType); + messageHeaderType.setReceivingFacility(facilityType); + + RequestMessageType requestMessageType = new RequestMessageType(); + edu.harvard.i2b2.ontology.datavo.crcloader.query.ObjectFactory of = new edu.harvard.i2b2.ontology.datavo.crcloader.query.ObjectFactory(); + BodyType bodyType = new BodyType(); + bodyType.getAny().add(of.createPublishDataRequest(publishDataRequest)); + requestMessageType.setMessageBody(bodyType); + + requestMessageType.setMessageHeader(messageHeaderType); + + RequestHeaderType requestHeader = new RequestHeaderType(); + requestHeader.setResultWaittimeMs(180000); //(3000); + requestMessageType.setRequestHeader(requestHeader); + return requestMessageType; + } + + public static RequestMessageType buildUploaderRequestMessage(String uploadId, SecurityType securityType, String projectId) { + GetUploadInfoRequestType getUploadInfo = new GetUploadInfoRequestType(); + getUploadInfo.setLoadId(uploadId); + getUploadInfo.setUserId(securityType.getUsername()); + + MessageHeaderType messageHeaderType = ontologyUtil.getMessageHeader(); + messageHeaderType.setSecurity(securityType); + messageHeaderType.setProjectId(projectId); + + messageHeaderType.setReceivingApplication(messageHeaderType + .getSendingApplication()); + FacilityType facilityType = new FacilityType(); + facilityType.setFacilityName("sample"); + messageHeaderType.setSendingFacility(facilityType); + messageHeaderType.setReceivingFacility(facilityType); + + RequestMessageType requestMessageType = new RequestMessageType(); + edu.harvard.i2b2.ontology.datavo.crcloader.query.ObjectFactory of = new edu.harvard.i2b2.ontology.datavo.crcloader.query.ObjectFactory(); + BodyType bodyType = new BodyType(); + bodyType.getAny().add(of.createGetUploadInfoRequest(getUploadInfo)); + requestMessageType.setMessageBody(bodyType); + + requestMessageType.setMessageHeader(messageHeaderType); + + RequestHeaderType requestHeader = new RequestHeaderType(); + requestHeader.setResultWaittimeMs(180000); //3000); + requestMessageType.setRequestHeader(requestHeader); + return requestMessageType; + } + + public static RequestMessageType buildSetfinderStatusRequestMessage(String queryInstanceId, SecurityType securityType, String projectId) { + InstanceRequestType instanceRequestType = new InstanceRequestType(); + instanceRequestType.setQueryInstanceId(queryInstanceId); + + MessageHeaderType messageHeaderType = ontologyUtil.getMessageHeader(); + messageHeaderType.setSecurity(securityType); + messageHeaderType.setProjectId(projectId); + + messageHeaderType.setReceivingApplication(messageHeaderType + .getSendingApplication()); + FacilityType facilityType = new FacilityType(); + facilityType.setFacilityName("sample"); + messageHeaderType.setSendingFacility(facilityType); + messageHeaderType.setReceivingFacility(facilityType); + + RequestMessageType requestMessageType = new RequestMessageType(); + + edu.harvard.i2b2.ontology.datavo.crc.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.ontology.datavo.crc.setfinder.query.ObjectFactory(); + BodyType bodyType = new BodyType(); + PsmQryHeaderType psm = new PsmQryHeaderType(); + psm.setRequestType(PsmRequestTypeType.CRC_QRY_GET_QUERY_RESULT_INSTANCE_LIST_FROM_QUERY_INSTANCE_ID); + bodyType.getAny().add(of.createPsmheader(psm)); + + bodyType.getAny().add(of.createRequest(instanceRequestType)); + requestMessageType.setMessageBody(bodyType); + + requestMessageType.setMessageHeader(messageHeaderType); + + RequestHeaderType requestHeader = new RequestHeaderType(); + requestHeader.setResultWaittimeMs(220000); //3000); + requestMessageType.setRequestHeader(requestHeader); + return requestMessageType; + } + + public static RequestMessageType buildDeleteSetfinderStatusRequestMessage(String userId, String queryMasterId, SecurityType securityType, String projectId) { + MasterDeleteRequestType masterDeleteReqType = new MasterDeleteRequestType(); + masterDeleteReqType.setQueryMasterId(queryMasterId); + masterDeleteReqType.setUserId(userId); + + MessageHeaderType messageHeaderType = ontologyUtil.getMessageHeader(); + messageHeaderType.setSecurity(securityType); + messageHeaderType.setProjectId(projectId); + + messageHeaderType.setReceivingApplication(messageHeaderType + .getSendingApplication()); + FacilityType facilityType = new FacilityType(); + facilityType.setFacilityName("sample"); + messageHeaderType.setSendingFacility(facilityType); + messageHeaderType.setReceivingFacility(facilityType); + + RequestMessageType requestMessageType = new RequestMessageType(); + + edu.harvard.i2b2.ontology.datavo.crc.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.ontology.datavo.crc.setfinder.query.ObjectFactory(); + BodyType bodyType = new BodyType(); + PsmQryHeaderType psm = new PsmQryHeaderType(); + psm.setRequestType(PsmRequestTypeType.CRC_QRY_DELETE_QUERY_MASTER); + bodyType.getAny().add(of.createPsmheader(psm)); + + bodyType.getAny().add(of.createRequest(masterDeleteReqType)); + requestMessageType.setMessageBody(bodyType); + + requestMessageType.setMessageHeader(messageHeaderType); + + RequestHeaderType requestHeader = new RequestHeaderType(); + requestHeader.setResultWaittimeMs(180000); //(3000); + requestMessageType.setRequestHeader(requestHeader); + return requestMessageType; + } + + public static RequestMessageType buildSetfinderQueryRequestMessage(String itemKey, SecurityType securityType, String projectId) { + QueryDefinitionType queryDef = new QueryDefinitionType(); + PanelType panelType = new PanelType(); + ItemType itemType = new ItemType(); + itemType.setItemKey(itemKey); + panelType.getItem().add(itemType); + queryDef.getPanel().add(panelType); + + queryDef.setQueryName(itemKey.substring(0,(itemKey.length()>10)?9:itemKey.length()) + System.currentTimeMillis()); + QueryDefinitionRequestType queryDefinitionRequestType = new QueryDefinitionRequestType(); + ResultOutputOptionListType resultOutputOptionListType = new ResultOutputOptionListType(); + ResultOutputOptionType resultOutputOptionType = new ResultOutputOptionType(); + resultOutputOptionType.setName("PATIENT_COUNT_XML"); + resultOutputOptionListType.getResultOutput().add(resultOutputOptionType); + queryDefinitionRequestType.setQueryDefinition(queryDef); + queryDefinitionRequestType.setResultOutputList(resultOutputOptionListType); + + MessageHeaderType messageHeaderType = ontologyUtil.getMessageHeader(); + messageHeaderType.setSecurity(securityType); + messageHeaderType.setProjectId(projectId); + + messageHeaderType.setReceivingApplication(messageHeaderType + .getSendingApplication()); + FacilityType facilityType = new FacilityType(); + facilityType.setFacilityName("sample"); + messageHeaderType.setSendingFacility(facilityType); + messageHeaderType.setReceivingFacility(facilityType); + + RequestMessageType requestMessageType = new RequestMessageType(); + edu.harvard.i2b2.ontology.datavo.crc.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.ontology.datavo.crc.setfinder.query.ObjectFactory(); + BodyType bodyType = new BodyType(); + PsmQryHeaderType psm = new PsmQryHeaderType(); + psm.setRequestType(PsmRequestTypeType.CRC_QRY_RUN_QUERY_INSTANCE_FROM_QUERY_DEFINITION); + bodyType.getAny().add(of.createPsmheader(psm)); + bodyType.getAny().add(of.createRequest(queryDefinitionRequestType)); + requestMessageType.setMessageBody(bodyType); + + requestMessageType.setMessageHeader(messageHeaderType); + + RequestHeaderType requestHeader = new RequestHeaderType(); + requestHeader.setResultWaittimeMs(180000); //3000); + requestMessageType.setRequestHeader(requestHeader); + return requestMessageType; + } + + private static LoadDataResponseType getGetPublishDataResponseMessage( + String responseXml) throws JAXBUtilException, I2B2Exception { + JAXBElement responseJaxb = OntologyJAXBUtil.getJAXBUtil() + .unMashallFromString(responseXml); + ResponseMessageType r = (ResponseMessageType) responseJaxb.getValue(); + log.debug("CRC's ontology call response xml" + responseXml); + + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + ResultStatusType rt = r.getResponseHeader().getResultStatus(); + if (rt.getStatus().getType().equals("ERROR")) { + throw new I2B2Exception(rt.getStatus().getValue()); + } + LoadDataResponseType loadDataResponseType = (LoadDataResponseType) helper + .getObjectByClass(r.getMessageBody().getAny(), + LoadDataResponseType.class); + + return loadDataResponseType; + } + + private static MasterInstanceResultResponseType getMasterInstanceResultResponseMessage( + String responseXml) throws JAXBUtilException, I2B2Exception { + JAXBElement responseJaxb = OntologyJAXBUtil.getJAXBUtil() + .unMashallFromString(responseXml); + ResponseMessageType r = (ResponseMessageType) responseJaxb.getValue(); + log.debug("CRC's ontology call response xml" + responseXml); + + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + ResultStatusType rt = r.getResponseHeader().getResultStatus(); + if (rt.getStatus().getType().equals("ERROR")) { + throw new I2B2Exception(rt.getStatus().getValue()); + } + MasterInstanceResultResponseType masterInstanceResultResponseType = (MasterInstanceResultResponseType) helper + .getObjectByClass(r.getMessageBody().getAny(), + MasterInstanceResultResponseType.class); + + return masterInstanceResultResponseType; + } + + private static MasterResponseType getMasterResponseMessage( + String responseXml) throws JAXBUtilException, I2B2Exception { + JAXBElement responseJaxb = OntologyJAXBUtil.getJAXBUtil() + .unMashallFromString(responseXml); + ResponseMessageType r = (ResponseMessageType) responseJaxb.getValue(); + log.debug("CRC's ontology call response xml" + responseXml); + + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + ResultStatusType rt = r.getResponseHeader().getResultStatus(); + if (rt.getStatus().getType().equals("ERROR")) { + throw new I2B2Exception(rt.getStatus().getValue()); + } + MasterResponseType masterResponseType = (MasterResponseType) helper + .getObjectByClass(r.getMessageBody().getAny(), + MasterResponseType.class); + + return masterResponseType; + } + + private static ResultResponseType getResultResponseMessage( + String responseXml) throws JAXBUtilException, I2B2Exception { + JAXBElement responseJaxb = OntologyJAXBUtil.getJAXBUtil() + .unMashallFromString(responseXml); + ResponseMessageType r = (ResponseMessageType) responseJaxb.getValue(); + log.debug("CRC's ontology call response xml" + responseXml); + + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + ResultStatusType rt = r.getResponseHeader().getResultStatus(); + if (rt.getStatus().getType().equals("ERROR")) { + throw new I2B2Exception(rt.getStatus().getValue()); + } + ResultResponseType instanceResultResponseType = (ResultResponseType) helper + .getObjectByClass(r.getMessageBody().getAny(), + ResultResponseType.class); + + return instanceResultResponseType; + } + + private static OMElement buildOMElement(RequestMessageType requestMessageType) + throws XMLStreamException, JAXBUtilException { + StringWriter strWriter = new StringWriter(); + edu.harvard.i2b2.ontology.datavo.i2b2message.ObjectFactory hiveof = new edu.harvard.i2b2.ontology.datavo.i2b2message.ObjectFactory(); + OntologyJAXBUtil.getJAXBUtil().marshaller( + hiveof.createRequest(requestMessageType), strWriter); + // getOMElement from message + OMFactory fac = OMAbstractFactory.getOMFactory(); + + StringReader strReader = new StringReader(strWriter.toString()); + XMLInputFactory xif = XMLInputFactory.newInstance(); + XMLStreamReader reader = xif.createXMLStreamReader(strReader); + OMElement request =OMXMLBuilderFactory.createStAXOMBuilder(reader).getDocumentElement(); + + return request; + } + + +} diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/crc/SetfinderQueryStatusRunner.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/crc/SetfinderQueryStatusRunner.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/crc/SetfinderQueryStatusRunner.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/crc/SetfinderQueryStatusRunner.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/crc/UploadStatusRunner.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/crc/UploadStatusRunner.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/crc/UploadStatusRunner.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/crc/UploadStatusRunner.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/fr/CallFileRepositoryUtil.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/fr/CallFileRepositoryUtil.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/fr/CallFileRepositoryUtil.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/fr/CallFileRepositoryUtil.java index aeeac352..88daaaf1 --- a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/delegate/fr/CallFileRepositoryUtil.java +++ b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/delegate/fr/CallFileRepositoryUtil.java @@ -1,252 +1,252 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.ontology.delegate.fr; - -import java.io.StringReader; -import java.io.StringWriter; - -import jakarta.xml.bind.JAXBElement; -import javax.xml.stream.XMLInputFactory; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamReader; - -import org.apache.axiom.om.OMAbstractFactory; -import org.apache.axiom.om.OMElement; -import org.apache.axiom.om.OMXMLBuilderFactory; -import org.apache.axiom.soap.SOAP11Constants; -import org.apache.axiom.soap.SOAPBody; -import org.apache.axiom.soap.SOAPEnvelope; -import org.apache.axiom.soap.SOAPFactory; -import org.apache.axis2.AxisFault; -import org.apache.axis2.Constants; -import org.apache.axis2.addressing.EndpointReference; -import org.apache.axis2.client.OperationClient; -import org.apache.axis2.client.Options; -import edu.harvard.i2b2.common.util.axis2.ServiceClient; -import org.apache.axis2.context.MessageContext; -import org.apache.axis2.context.OperationContext; -import org.apache.axis2.wsdl.WSDLConstants; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.ontology.datavo.fr.ObjectFactory; -import edu.harvard.i2b2.ontology.datavo.fr.SendfileRequestType; -import edu.harvard.i2b2.ontology.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.ontology.datavo.i2b2message.FacilityType; -import edu.harvard.i2b2.ontology.datavo.i2b2message.MessageHeaderType; -import edu.harvard.i2b2.ontology.datavo.i2b2message.RequestHeaderType; -import edu.harvard.i2b2.ontology.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.ontology.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.ontology.datavo.i2b2message.ResultStatusType; -import edu.harvard.i2b2.ontology.datavo.i2b2message.SecurityType; -import edu.harvard.i2b2.ontology.util.OntologyJAXBUtil; -import edu.harvard.i2b2.ontology.util.OntologyUtil; - -/** - * - * @author rk903 - * - */ -public class CallFileRepositoryUtil { - - /** log **/ - protected static Log log = LogFactory.getLog(CallFileRepositoryUtil.class); - protected static Log logesapi = LogFactory.getLog(CallFileRepositoryUtil.class); - - //private SecurityType securityType = null; - //private String projectId = null; - private static String frUrl = null; - private static OntologyUtil ontologyUtil = OntologyUtil.getInstance(); - - - public static String callFileRepository(String fileRepositoryFileName, SecurityType securityType, String projectId) - throws I2B2Exception { - String localFileName = null; - RequestMessageType requestMessageType = getI2B2RequestMessage(fileRepositoryFileName, securityType, projectId); - OMElement requestElement = buildOMElement(requestMessageType); - log.debug("FileRespository request message [" - + requestElement.toString() + "]"); - // MessageContext response = getResponseSOAPBody(requestElement); - uploadConceptFile(fileRepositoryFileName, securityType, projectId); - return fileRepositoryFileName; - } - - private static ResultStatusType getI2B2ResponseStatus(OMElement response) - throws JAXBUtilException { - JAXBElement responseJaxb = OntologyJAXBUtil.getJAXBUtil() - .unMashallFromString(response.toString()); - ResponseMessageType r = (ResponseMessageType) responseJaxb.getValue(); - return r.getResponseHeader().getResultStatus(); - } - - private static OMElement buildOMElement(RequestMessageType requestMessageType) - throws I2B2Exception { - StringWriter strWriter = new StringWriter(); - edu.harvard.i2b2.ontology.datavo.i2b2message.ObjectFactory hiveof = new edu.harvard.i2b2.ontology.datavo.i2b2message.ObjectFactory(); - OMElement request = null; - try { - OntologyJAXBUtil.getJAXBUtil().marshaller( - hiveof.createRequest(requestMessageType), strWriter); - StringReader strReader = new StringReader(strWriter.toString()); - XMLInputFactory xif = XMLInputFactory.newInstance(); - XMLStreamReader reader = xif.createXMLStreamReader(strReader); - request = OMXMLBuilderFactory.createStAXOMBuilder(reader).getDocumentElement(); - - } catch (XMLStreamException xmlEx) { - throw new I2B2Exception("FileRepository request omelement failed [" - + xmlEx.getMessage() + "]"); - } catch (JAXBUtilException jaxbEx) { - throw new I2B2Exception("FileRepository request omelement failed [" - + jaxbEx.getMessage() + "]"); - } - return request; - } - - private static RequestMessageType getI2B2RequestMessage(String sendFileName, SecurityType securityType, String projectId) { - - MessageHeaderType messageHeaderType = ontologyUtil.getMessageHeader(); -// .getSpringBeanFactory().getBean("message_header"); - messageHeaderType.setSecurity(securityType); - messageHeaderType.setProjectId(projectId); - - messageHeaderType.setReceivingApplication(messageHeaderType - .getSendingApplication()); - FacilityType facilityType = new FacilityType(); - facilityType.setFacilityName("sample"); - messageHeaderType.setSendingFacility(facilityType); - messageHeaderType.setReceivingFacility(facilityType); - // build message body - SendfileRequestType sendfileRequestType = new SendfileRequestType(); - edu.harvard.i2b2.ontology.datavo.fr.File sendFile = new edu.harvard.i2b2.ontology.datavo.fr.File(); - sendFile.setName(sendFileName); - sendfileRequestType.setUploadFile(sendFile); - - RequestMessageType requestMessageType = new RequestMessageType(); - ObjectFactory of = new ObjectFactory(); - BodyType bodyType = new BodyType(); - bodyType.getAny().add(of.createSendfileRequest(sendfileRequestType)); - requestMessageType.setMessageBody(bodyType); - - requestMessageType.setMessageHeader(messageHeaderType); - - RequestHeaderType requestHeader = new RequestHeaderType(); - requestHeader.setResultWaittimeMs(180000); - requestMessageType.setRequestHeader(requestHeader); - - return requestMessageType; - - } - - private static void uploadConceptFile(String conceptFile, SecurityType securityType, String projectId) throws I2B2Exception { - org.apache.axis2.client.ServiceClient sender = null; - try { - - Options options = new Options(); - options.setTo(new EndpointReference(frUrl)); - options.setAction("urn:sendfileRequest"); - options - .setSoapVersionURI(SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI); - - // Increase the time out to receive large attachments - options.setTimeOutInMilliSeconds(10000); - - options.setProperty(Constants.Configuration.ENABLE_SWA, - Constants.VALUE_TRUE); - options.setProperty(Constants.Configuration.CACHE_ATTACHMENTS, - Constants.VALUE_TRUE); - options.setProperty(Constants.Configuration.ATTACHMENT_TEMP_DIR, - "temp"); - options.setProperty(Constants.Configuration.FILE_SIZE_THRESHOLD, - "4000"); - - sender = ServiceClient - .getServiceClient(); - sender.setOptions(options); - OperationClient mepClient = sender - .createClient(org.apache.axis2.client.ServiceClient.ANON_OUT_IN_OP); - - //MM TODO - /*MessageContext mc = new MessageContext(); - DataHandler dataHandler = new DataHandler( - new FileDataSource(conceptFile)); - - mc.addAttachment("cid", dataHandler); - mc.setDoingSwA(true); - - SOAPFactory sfac = OMAbstractFactory.getSOAP11Factory(); - SOAPEnvelope env = sfac.getDefaultEnvelope(); - - RequestMessageType requestMessageType = getI2B2RequestMessage(conceptFile, securityType, projectId); - OMElement requestElement = buildOMElement(requestMessageType); - log.debug("File repository request message from ontology [" - + requestElement + "]"); - env.getBody().addChild(requestElement); - - // SOAPEnvelope env = createEnvelope("fileattachment"); - mc.setEnvelope(env); - mepClient.addMessageContext(mc); - mepClient.execute(true); - */ - MessageContext response = mepClient - .getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE); - SOAPBody body = response.getEnvelope().getBody(); - - response = mepClient - .getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE); - logesapi.debug("File Repository response envelope: " - + response.toString() + "]"); - OMElement frResponse = (OMElement) response.getEnvelope().getBody() - .getFirstOMChild(); - log.debug("File Repository response body [: " + frResponse + "]"); - - - - - // read header status - ResultStatusType resultStatusType = getI2B2ResponseStatus(frResponse); - - // if the status type is error, then throw i2b2exception - if (resultStatusType.getStatus() != null - && resultStatusType.getStatus().getType() != null - && resultStatusType.getStatus().getType().equalsIgnoreCase( - "error")) { - String errorMsg = resultStatusType.getStatus().getValue(); - - throw new I2B2Exception( - "Unable to send file to file repository [" + errorMsg - + "]"); - } - - } catch (AxisFault axisFault) { - throw new I2B2Exception( - "Unable to send file to file repository :Axisfault [" - + axisFault.getCause().getMessage() + "]"); - } catch (Throwable t) { - t.printStackTrace(); - throw new I2B2Exception( - "Unable to send file to file repository :Axisfault [" - + t.getMessage() + "]"); - } finally { - if (sender != null) { - try{ - sender.cleanupTransport(); - sender.cleanup(); - } catch (AxisFault e) { - log.debug("Error .", e); - } - } - } - } - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.ontology.delegate.fr; + +import java.io.StringReader; +import java.io.StringWriter; + +import jakarta.xml.bind.JAXBElement; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import org.apache.axiom.om.OMAbstractFactory; +import org.apache.axiom.om.OMElement; +import org.apache.axiom.om.OMXMLBuilderFactory; +import org.apache.axiom.soap.SOAP11Constants; +import org.apache.axiom.soap.SOAPBody; +import org.apache.axiom.soap.SOAPEnvelope; +import org.apache.axiom.soap.SOAPFactory; +import org.apache.axis2.AxisFault; +import org.apache.axis2.Constants; +import org.apache.axis2.addressing.EndpointReference; +import org.apache.axis2.client.OperationClient; +import org.apache.axis2.client.Options; +import edu.harvard.i2b2.common.util.axis2.ServiceClient; +import org.apache.axis2.context.MessageContext; +import org.apache.axis2.context.OperationContext; +import org.apache.axis2.wsdl.WSDLConstants; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.ontology.datavo.fr.ObjectFactory; +import edu.harvard.i2b2.ontology.datavo.fr.SendfileRequestType; +import edu.harvard.i2b2.ontology.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.ontology.datavo.i2b2message.FacilityType; +import edu.harvard.i2b2.ontology.datavo.i2b2message.MessageHeaderType; +import edu.harvard.i2b2.ontology.datavo.i2b2message.RequestHeaderType; +import edu.harvard.i2b2.ontology.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.ontology.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.ontology.datavo.i2b2message.ResultStatusType; +import edu.harvard.i2b2.ontology.datavo.i2b2message.SecurityType; +import edu.harvard.i2b2.ontology.util.OntologyJAXBUtil; +import edu.harvard.i2b2.ontology.util.OntologyUtil; + +/** + * + * @author rk903 + * + */ +public class CallFileRepositoryUtil { + + /** log **/ + protected static Log log = LogFactory.getLog(CallFileRepositoryUtil.class); + protected static Log logesapi = LogFactory.getLog(CallFileRepositoryUtil.class); + + //private SecurityType securityType = null; + //private String projectId = null; + private static String frUrl = null; + private static OntologyUtil ontologyUtil = OntologyUtil.getInstance(); + + + public static String callFileRepository(String fileRepositoryFileName, SecurityType securityType, String projectId) + throws I2B2Exception { + String localFileName = null; + RequestMessageType requestMessageType = getI2B2RequestMessage(fileRepositoryFileName, securityType, projectId); + OMElement requestElement = buildOMElement(requestMessageType); + log.debug("FileRespository request message [" + + requestElement.toString() + "]"); + // MessageContext response = getResponseSOAPBody(requestElement); + uploadConceptFile(fileRepositoryFileName, securityType, projectId); + return fileRepositoryFileName; + } + + private static ResultStatusType getI2B2ResponseStatus(OMElement response) + throws JAXBUtilException { + JAXBElement responseJaxb = OntologyJAXBUtil.getJAXBUtil() + .unMashallFromString(response.toString()); + ResponseMessageType r = (ResponseMessageType) responseJaxb.getValue(); + return r.getResponseHeader().getResultStatus(); + } + + private static OMElement buildOMElement(RequestMessageType requestMessageType) + throws I2B2Exception { + StringWriter strWriter = new StringWriter(); + edu.harvard.i2b2.ontology.datavo.i2b2message.ObjectFactory hiveof = new edu.harvard.i2b2.ontology.datavo.i2b2message.ObjectFactory(); + OMElement request = null; + try { + OntologyJAXBUtil.getJAXBUtil().marshaller( + hiveof.createRequest(requestMessageType), strWriter); + StringReader strReader = new StringReader(strWriter.toString()); + XMLInputFactory xif = XMLInputFactory.newInstance(); + XMLStreamReader reader = xif.createXMLStreamReader(strReader); + request = OMXMLBuilderFactory.createStAXOMBuilder(reader).getDocumentElement(); + + } catch (XMLStreamException xmlEx) { + throw new I2B2Exception("FileRepository request omelement failed [" + + xmlEx.getMessage() + "]"); + } catch (JAXBUtilException jaxbEx) { + throw new I2B2Exception("FileRepository request omelement failed [" + + jaxbEx.getMessage() + "]"); + } + return request; + } + + private static RequestMessageType getI2B2RequestMessage(String sendFileName, SecurityType securityType, String projectId) { + + MessageHeaderType messageHeaderType = ontologyUtil.getMessageHeader(); +// .getSpringBeanFactory().getBean("message_header"); + messageHeaderType.setSecurity(securityType); + messageHeaderType.setProjectId(projectId); + + messageHeaderType.setReceivingApplication(messageHeaderType + .getSendingApplication()); + FacilityType facilityType = new FacilityType(); + facilityType.setFacilityName("sample"); + messageHeaderType.setSendingFacility(facilityType); + messageHeaderType.setReceivingFacility(facilityType); + // build message body + SendfileRequestType sendfileRequestType = new SendfileRequestType(); + edu.harvard.i2b2.ontology.datavo.fr.File sendFile = new edu.harvard.i2b2.ontology.datavo.fr.File(); + sendFile.setName(sendFileName); + sendfileRequestType.setUploadFile(sendFile); + + RequestMessageType requestMessageType = new RequestMessageType(); + ObjectFactory of = new ObjectFactory(); + BodyType bodyType = new BodyType(); + bodyType.getAny().add(of.createSendfileRequest(sendfileRequestType)); + requestMessageType.setMessageBody(bodyType); + + requestMessageType.setMessageHeader(messageHeaderType); + + RequestHeaderType requestHeader = new RequestHeaderType(); + requestHeader.setResultWaittimeMs(180000); + requestMessageType.setRequestHeader(requestHeader); + + return requestMessageType; + + } + + private static void uploadConceptFile(String conceptFile, SecurityType securityType, String projectId) throws I2B2Exception { + org.apache.axis2.client.ServiceClient sender = null; + try { + + Options options = new Options(); + options.setTo(new EndpointReference(frUrl)); + options.setAction("urn:sendfileRequest"); + options + .setSoapVersionURI(SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI); + + // Increase the time out to receive large attachments + options.setTimeOutInMilliSeconds(10000); + + options.setProperty(Constants.Configuration.ENABLE_SWA, + Constants.VALUE_TRUE); + options.setProperty(Constants.Configuration.CACHE_ATTACHMENTS, + Constants.VALUE_TRUE); + options.setProperty(Constants.Configuration.ATTACHMENT_TEMP_DIR, + "temp"); + options.setProperty(Constants.Configuration.FILE_SIZE_THRESHOLD, + "4000"); + + sender = ServiceClient + .getServiceClient(); + sender.setOptions(options); + OperationClient mepClient = sender + .createClient(org.apache.axis2.client.ServiceClient.ANON_OUT_IN_OP); + + //MM TODO + /*MessageContext mc = new MessageContext(); + DataHandler dataHandler = new DataHandler( + new FileDataSource(conceptFile)); + + mc.addAttachment("cid", dataHandler); + mc.setDoingSwA(true); + + SOAPFactory sfac = OMAbstractFactory.getSOAP11Factory(); + SOAPEnvelope env = sfac.getDefaultEnvelope(); + + RequestMessageType requestMessageType = getI2B2RequestMessage(conceptFile, securityType, projectId); + OMElement requestElement = buildOMElement(requestMessageType); + log.debug("File repository request message from ontology [" + + requestElement + "]"); + env.getBody().addChild(requestElement); + + // SOAPEnvelope env = createEnvelope("fileattachment"); + mc.setEnvelope(env); + mepClient.addMessageContext(mc); + mepClient.execute(true); + */ + MessageContext response = mepClient + .getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE); + SOAPBody body = response.getEnvelope().getBody(); + + response = mepClient + .getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE); + logesapi.debug("File Repository response envelope: " + + response.toString() + "]"); + OMElement frResponse = (OMElement) response.getEnvelope().getBody() + .getFirstOMChild(); + log.debug("File Repository response body [: " + frResponse + "]"); + + + + + // read header status + ResultStatusType resultStatusType = getI2B2ResponseStatus(frResponse); + + // if the status type is error, then throw i2b2exception + if (resultStatusType.getStatus() != null + && resultStatusType.getStatus().getType() != null + && resultStatusType.getStatus().getType().equalsIgnoreCase( + "error")) { + String errorMsg = resultStatusType.getStatus().getValue(); + + throw new I2B2Exception( + "Unable to send file to file repository [" + errorMsg + + "]"); + } + + } catch (AxisFault axisFault) { + throw new I2B2Exception( + "Unable to send file to file repository :Axisfault [" + + axisFault.getCause().getMessage() + "]"); + } catch (Throwable t) { + t.printStackTrace(); + throw new I2B2Exception( + "Unable to send file to file repository :Axisfault [" + + t.getMessage() + "]"); + } finally { + if (sender != null) { + try{ + sender.cleanupTransport(); + sender.cleanup(); + } catch (AxisFault e) { + log.debug("Error .", e); + } + } + } + } + + +} diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ejb/DBInfoType.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ejb/DBInfoType.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ejb/DBInfoType.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ejb/DBInfoType.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ejb/DataSourceLookup.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ejb/DataSourceLookup.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ejb/DataSourceLookup.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ejb/DataSourceLookup.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ejb/ExpandedConceptType.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ejb/ExpandedConceptType.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ejb/ExpandedConceptType.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ejb/ExpandedConceptType.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ejb/NodeType.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ejb/NodeType.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ejb/NodeType.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ejb/NodeType.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ejb/SchemeType.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ejb/SchemeType.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ejb/SchemeType.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ejb/SchemeType.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ejb/TableAccessType.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ejb/TableAccessType.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ejb/TableAccessType.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ejb/TableAccessType.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/util/ConceptXMLWriterUtil.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/util/ConceptXMLWriterUtil.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/util/ConceptXMLWriterUtil.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/util/ConceptXMLWriterUtil.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/util/JAXBConstant.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/util/JAXBConstant.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/util/JAXBConstant.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/util/JAXBConstant.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/util/ModifierXMLWriterUtil.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/util/ModifierXMLWriterUtil.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/util/ModifierXMLWriterUtil.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/util/ModifierXMLWriterUtil.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/util/ObserverXMLWriterUtil.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/util/ObserverXMLWriterUtil.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/util/ObserverXMLWriterUtil.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/util/ObserverXMLWriterUtil.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/util/OntologyJAXBUtil.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/util/OntologyJAXBUtil.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/util/OntologyJAXBUtil.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/util/OntologyJAXBUtil.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/util/OntologyUtil.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/util/OntologyUtil.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/util/OntologyUtil.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/util/OntologyUtil.java index aa7638b3..311d25ff --- a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/util/OntologyUtil.java +++ b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/util/OntologyUtil.java @@ -1,337 +1,337 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Raj Kuttan - * Lori Phillips - */ -package edu.harvard.i2b2.ontology.util; - -import java.io.IOException; -import java.lang.management.ManagementFactory; -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.HashMap; -import java.util.List; -import java.util.Properties; - -import javax.management.ObjectName; -import javax.sql.DataSource; - -import org.apache.axis2.AxisFault; -import org.apache.axis2.context.ConfigurationContext; -import org.apache.axis2.context.MessageContext; -import org.apache.axis2.description.Parameter; -import org.apache.axis2.description.TransportInDescription; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.beans.factory.BeanFactory; -import org.springframework.beans.factory.config.PropertiesFactoryBean; -import org.springframework.context.support.FileSystemXmlApplicationContext; -import org.springframework.core.io.FileSystemResource; -import org.springframework.dao.DataAccessException; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.RowMapper; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.ServiceLocator; -import edu.harvard.i2b2.common.util.axis2.ServiceClient; -import edu.harvard.i2b2.common.util.jaxb.DTOFactory; -import edu.harvard.i2b2.ontology.datavo.i2b2message.ApplicationType; -import edu.harvard.i2b2.ontology.datavo.i2b2message.MessageHeaderType; -import edu.harvard.i2b2.ontology.datavo.pm.ParamType; - -/** - * This is the Ontology service's main utility class This utility class provides - * support for fetching resources like datasouce, to read application - * properties, to get ejb home,etc. $Id: OntologyUtil.java,v 1.15 2009/01/08 - * 19:27:01 lcp5 Exp $ - * - * @author rkuttan - */ -public class OntologyUtil { - - - private static List appProperties = null; - - - /** property name for PM endpoint reference **/ - private static final String PM_WS_EPR = "ontology.ws.pm.url"; - - /** property name for ONT_TERM_DELIMITER **/ - private static final String ONT_TERM_DELIMITER = "ontology.terminal.delimiter"; - - private static final String FRCELL_WS_TEMPSPACE_PROPERTIES = "edu.harvard.i2b2.ontology.ws.fr.tempspace"; - - private static final String FRCELL_WS_TIMEOUT_PROPERTIES = "edu.harvard.i2b2.ontology.ws.fr.timeout"; - - private static final String FRCELL_WS_FILETHRESHOLD_PROPERTIES = "edu.harvard.i2b2.ontology.ws.fr.filethreshold"; - - private static final String FRCELL_WS_ATTACHMENTNAME_PROPERTIES = "edu.harvard.i2b2.ontology.ws.fr.attachmentname"; - - private static final String FRCELL_WS_OPERATIONNAME_PROPERTIES = "edu.harvard.i2b2.ontology.ws.fr.operation"; - - /** property name for metadata schema name* */ - private static final String FRCELL_WS_URL_PROPERTIES = "edu.harvard.i2b2.ontology.ws.fr.url"; - private static final String STOPWORD_PROPERTIES = "edu.harvard.i2b2.ontology.stopword"; - - - private static final String CRCCELL_WS_URL_PROPERTIES = "edu.harvard.i2b2.ontology.ws.crc.url"; - - private static final String SERVICE_ACCOUNT_USER = "edu.harvard.i2b2.ontology.pm.serviceaccount.user"; - private static final String SERVICE_ACCOUNT_PASSWORD = "edu.harvard.i2b2.ontology.pm.serviceaccount.password"; - - /** class instance field **/ - private static OntologyUtil thisInstance = null; - - /** service locator field **/ - private static ServiceLocator serviceLocator = null; - - /** log **/ - protected final Log log = LogFactory.getLog(getClass()); - - /** field to store app datasource **/ - private DataSource dataSource = null; - - /** single instance of spring bean factory **/ - private BeanFactory beanFactory = null; - - /** - * Private constructor to make the class singleton - */ - private OntologyUtil() { - } - - /** - * Return this class instance - * - * @return OntologyUtil - */ - public static OntologyUtil getInstance() { - if (thisInstance == null) { - thisInstance = new OntologyUtil(); - } - - serviceLocator = ServiceLocator.getInstance(); - - return thisInstance; - } - - /** - * Return the ontology spring config - * - * @return - */ - - /** - * Return metadata schema name - * - * @return - * @throws I2B2Exception - */ - public String getMetaDataSchemaName() throws I2B2Exception { - try { - Connection conn = dataSource.getConnection(); - - String metadataSchema = conn.getSchema() + "."; - conn.close(); - - return metadataSchema ; - } catch (SQLException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } //getPropertyValue(METADATA_SCHEMA_NAME_PROPERTIES).trim() + "."; - return null; - } - - /** - * Return PM cell endpoint reference URL - * - * @return - * @throws I2B2Exception - */ - public String getPmEndpointReference() throws I2B2Exception { - return getPropertyValue(PM_WS_EPR).trim(); - } - - - - /** - * Return Ontology terminal delimiter - * - * @return - * @throws I2B2Exception - */ - public Boolean getOntTerminalDelimiter() throws I2B2Exception { - return Boolean.valueOf(getPropertyValue(ONT_TERM_DELIMITER).trim()); - } - - public String getFileRepositoryTempSpace() throws I2B2Exception { - return getPropertyValue(FRCELL_WS_TEMPSPACE_PROPERTIES); - } - - public String getStopWord() throws I2B2Exception { - return getPropertyValue(STOPWORD_PROPERTIES); - } - - public String getFileRepositoryTimeout() throws I2B2Exception { - return getPropertyValue(FRCELL_WS_TIMEOUT_PROPERTIES); - } - - public String getFileRepositoryThreshold() throws I2B2Exception { - return getPropertyValue(FRCELL_WS_FILETHRESHOLD_PROPERTIES); - } - - public String getFileRepositoryAttachmentName() throws I2B2Exception { - return getPropertyValue(FRCELL_WS_ATTACHMENTNAME_PROPERTIES); - } - - public String getFileRepositoryOperationName() throws I2B2Exception { - return getPropertyValue(FRCELL_WS_OPERATIONNAME_PROPERTIES); - } - - public String getFileManagentCellUrl() throws I2B2Exception { - return getPropertyValue(FRCELL_WS_URL_PROPERTIES); - } - - public String getCRCUrl() throws I2B2Exception { - return getPropertyValue(CRCCELL_WS_URL_PROPERTIES); - } - - public String getServiceAccountUser() throws I2B2Exception { - return getPropertyValue(SERVICE_ACCOUNT_USER); - } - - public String getServiceAccountPassword() throws I2B2Exception { - return getPropertyValue(SERVICE_ACCOUNT_PASSWORD); - } - - - /** - * Return app server datasource - * - * @return datasource - * @throws I2B2Exception - * @throws SQLException - */ - public DataSource getDataSource(String dataSourceName) throws I2B2Exception { - // DataSource dataSource = (DataSource) getSpringBeanFactory() - // .getBean(DATASOURCE_BEAN_NAME); - - dataSource = (DataSource) serviceLocator - .getAppServerDataSource(dataSourceName); - return dataSource; - - } - - // --------------------- - // private methods here - // --------------------- - - - - /** - * Load application property file into memory - */ - private String getPropertyValue(String propertyName) throws I2B2Exception { - - if (appProperties == null) { - - - - // log.info(sql + domainId + projectId + ownerId); - // List queryResult = null; - try { - DataSource ds = this.getDataSource("java:/OntologyBootStrapDS"); - - JdbcTemplate jt = new JdbcTemplate(ds); - Connection conn = ds.getConnection(); - - String metadataSchema = conn.getSchema(); - conn.close(); - String sql = "select * from " + metadataSchema + ".hive_cell_params where status_cd <> 'D' and cell_id = 'ONT'"; - - log.debug("Start query"); - appProperties = jt.query(sql, new getHiveCellParam()); - log.debug("End query"); - - - } catch (DataAccessException e) { - log.error(e.getMessage()); - e.printStackTrace(); - throw new I2B2DAOException("Database error"); - } - //return queryResult; - catch (SQLException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - } - - String propertyValue = null;//appProperties.getProperty(propertyName); - for (int i=0; i < appProperties.size(); i++) - { - if (appProperties.get(i).getName() != null) - { - if (appProperties.get(i).getName().equalsIgnoreCase(propertyName)) - if (appProperties.get(i).getDatatype().equalsIgnoreCase("U")) - try { - propertyValue = ServiceClient.getContextRoot() + appProperties.get(i).getValue(); - - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - else - propertyValue = appProperties.get(i).getValue(); - } - } - - if ((propertyValue == null) || (propertyValue.trim().length() == 0)) { - throw new I2B2Exception("Application property file(" - // + APPLICATION_PROPERTIES_FILENAME + ") missing " - + propertyName + " entry"); - } - - return propertyValue; - } - - public MessageHeaderType getMessageHeader() { - MessageHeaderType messageHeader = new MessageHeaderType(); - ApplicationType appType = new ApplicationType(); - try { - appType.setApplicationName(getPropertyValue("applicationName")); - appType.setApplicationVersion(getPropertyValue("applicationVersion")); - } catch (I2B2Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - messageHeader.setSendingApplication(appType); - return messageHeader; - } -} - -class getHiveCellParam implements RowMapper { - @Override - public ParamType mapRow(ResultSet rs, int rowNum) throws SQLException { - - ParamType param = new ParamType(); - param.setId(rs.getInt("id")); - param.setName(rs.getString("param_name_cd")); - param.setValue(rs.getString("value")); - param.setDatatype(rs.getString("datatype_cd")); - return param; - } -} - +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Raj Kuttan + * Lori Phillips + */ +package edu.harvard.i2b2.ontology.util; + +import java.io.IOException; +import java.lang.management.ManagementFactory; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.HashMap; +import java.util.List; +import java.util.Properties; + +import javax.management.ObjectName; +import javax.sql.DataSource; + +import org.apache.axis2.AxisFault; +import org.apache.axis2.context.ConfigurationContext; +import org.apache.axis2.context.MessageContext; +import org.apache.axis2.description.Parameter; +import org.apache.axis2.description.TransportInDescription; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.config.PropertiesFactoryBean; +import org.springframework.context.support.FileSystemXmlApplicationContext; +import org.springframework.core.io.FileSystemResource; +import org.springframework.dao.DataAccessException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.RowMapper; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.ServiceLocator; +import edu.harvard.i2b2.common.util.axis2.ServiceClient; +import edu.harvard.i2b2.common.util.jaxb.DTOFactory; +import edu.harvard.i2b2.ontology.datavo.i2b2message.ApplicationType; +import edu.harvard.i2b2.ontology.datavo.i2b2message.MessageHeaderType; +import edu.harvard.i2b2.ontology.datavo.pm.ParamType; + +/** + * This is the Ontology service's main utility class This utility class provides + * support for fetching resources like datasouce, to read application + * properties, to get ejb home,etc. $Id: OntologyUtil.java,v 1.15 2009/01/08 + * 19:27:01 lcp5 Exp $ + * + * @author rkuttan + */ +public class OntologyUtil { + + + private static List appProperties = null; + + + /** property name for PM endpoint reference **/ + private static final String PM_WS_EPR = "ontology.ws.pm.url"; + + /** property name for ONT_TERM_DELIMITER **/ + private static final String ONT_TERM_DELIMITER = "ontology.terminal.delimiter"; + + private static final String FRCELL_WS_TEMPSPACE_PROPERTIES = "edu.harvard.i2b2.ontology.ws.fr.tempspace"; + + private static final String FRCELL_WS_TIMEOUT_PROPERTIES = "edu.harvard.i2b2.ontology.ws.fr.timeout"; + + private static final String FRCELL_WS_FILETHRESHOLD_PROPERTIES = "edu.harvard.i2b2.ontology.ws.fr.filethreshold"; + + private static final String FRCELL_WS_ATTACHMENTNAME_PROPERTIES = "edu.harvard.i2b2.ontology.ws.fr.attachmentname"; + + private static final String FRCELL_WS_OPERATIONNAME_PROPERTIES = "edu.harvard.i2b2.ontology.ws.fr.operation"; + + /** property name for metadata schema name* */ + private static final String FRCELL_WS_URL_PROPERTIES = "edu.harvard.i2b2.ontology.ws.fr.url"; + private static final String STOPWORD_PROPERTIES = "edu.harvard.i2b2.ontology.stopword"; + + + private static final String CRCCELL_WS_URL_PROPERTIES = "edu.harvard.i2b2.ontology.ws.crc.url"; + + private static final String SERVICE_ACCOUNT_USER = "edu.harvard.i2b2.ontology.pm.serviceaccount.user"; + private static final String SERVICE_ACCOUNT_PASSWORD = "edu.harvard.i2b2.ontology.pm.serviceaccount.password"; + + /** class instance field **/ + private static OntologyUtil thisInstance = null; + + /** service locator field **/ + private static ServiceLocator serviceLocator = null; + + /** log **/ + protected final Log log = LogFactory.getLog(getClass()); + + /** field to store app datasource **/ + private DataSource dataSource = null; + + /** single instance of spring bean factory **/ + private BeanFactory beanFactory = null; + + /** + * Private constructor to make the class singleton + */ + private OntologyUtil() { + } + + /** + * Return this class instance + * + * @return OntologyUtil + */ + public static OntologyUtil getInstance() { + if (thisInstance == null) { + thisInstance = new OntologyUtil(); + } + + serviceLocator = ServiceLocator.getInstance(); + + return thisInstance; + } + + /** + * Return the ontology spring config + * + * @return + */ + + /** + * Return metadata schema name + * + * @return + * @throws I2B2Exception + */ + public String getMetaDataSchemaName() throws I2B2Exception { + try { + Connection conn = dataSource.getConnection(); + + String metadataSchema = conn.getSchema() + "."; + conn.close(); + + return metadataSchema ; + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } //getPropertyValue(METADATA_SCHEMA_NAME_PROPERTIES).trim() + "."; + return null; + } + + /** + * Return PM cell endpoint reference URL + * + * @return + * @throws I2B2Exception + */ + public String getPmEndpointReference() throws I2B2Exception { + return getPropertyValue(PM_WS_EPR).trim(); + } + + + + /** + * Return Ontology terminal delimiter + * + * @return + * @throws I2B2Exception + */ + public Boolean getOntTerminalDelimiter() throws I2B2Exception { + return Boolean.valueOf(getPropertyValue(ONT_TERM_DELIMITER).trim()); + } + + public String getFileRepositoryTempSpace() throws I2B2Exception { + return getPropertyValue(FRCELL_WS_TEMPSPACE_PROPERTIES); + } + + public String getStopWord() throws I2B2Exception { + return getPropertyValue(STOPWORD_PROPERTIES); + } + + public String getFileRepositoryTimeout() throws I2B2Exception { + return getPropertyValue(FRCELL_WS_TIMEOUT_PROPERTIES); + } + + public String getFileRepositoryThreshold() throws I2B2Exception { + return getPropertyValue(FRCELL_WS_FILETHRESHOLD_PROPERTIES); + } + + public String getFileRepositoryAttachmentName() throws I2B2Exception { + return getPropertyValue(FRCELL_WS_ATTACHMENTNAME_PROPERTIES); + } + + public String getFileRepositoryOperationName() throws I2B2Exception { + return getPropertyValue(FRCELL_WS_OPERATIONNAME_PROPERTIES); + } + + public String getFileManagentCellUrl() throws I2B2Exception { + return getPropertyValue(FRCELL_WS_URL_PROPERTIES); + } + + public String getCRCUrl() throws I2B2Exception { + return getPropertyValue(CRCCELL_WS_URL_PROPERTIES); + } + + public String getServiceAccountUser() throws I2B2Exception { + return getPropertyValue(SERVICE_ACCOUNT_USER); + } + + public String getServiceAccountPassword() throws I2B2Exception { + return getPropertyValue(SERVICE_ACCOUNT_PASSWORD); + } + + + /** + * Return app server datasource + * + * @return datasource + * @throws I2B2Exception + * @throws SQLException + */ + public DataSource getDataSource(String dataSourceName) throws I2B2Exception { + // DataSource dataSource = (DataSource) getSpringBeanFactory() + // .getBean(DATASOURCE_BEAN_NAME); + + dataSource = (DataSource) serviceLocator + .getAppServerDataSource(dataSourceName); + return dataSource; + + } + + // --------------------- + // private methods here + // --------------------- + + + + /** + * Load application property file into memory + */ + private String getPropertyValue(String propertyName) throws I2B2Exception { + + if (appProperties == null) { + + + + // log.info(sql + domainId + projectId + ownerId); + // List queryResult = null; + try { + DataSource ds = this.getDataSource("java:/OntologyBootStrapDS"); + + JdbcTemplate jt = new JdbcTemplate(ds); + Connection conn = ds.getConnection(); + + String metadataSchema = conn.getSchema(); + conn.close(); + String sql = "select * from " + metadataSchema + ".hive_cell_params where status_cd <> 'D' and cell_id = 'ONT'"; + + log.debug("Start query"); + appProperties = jt.query(sql, new getHiveCellParam()); + log.debug("End query"); + + + } catch (DataAccessException e) { + log.error(e.getMessage()); + e.printStackTrace(); + throw new I2B2DAOException("Database error"); + } + //return queryResult; + catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + + String propertyValue = null;//appProperties.getProperty(propertyName); + for (int i=0; i < appProperties.size(); i++) + { + if (appProperties.get(i).getName() != null) + { + if (appProperties.get(i).getName().equalsIgnoreCase(propertyName)) + if (appProperties.get(i).getDatatype().equalsIgnoreCase("U")) + try { + propertyValue = ServiceClient.getContextRoot() + appProperties.get(i).getValue(); + + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + else + propertyValue = appProperties.get(i).getValue(); + } + } + + if ((propertyValue == null) || (propertyValue.trim().length() == 0)) { + throw new I2B2Exception("Application property file(" + // + APPLICATION_PROPERTIES_FILENAME + ") missing " + + propertyName + " entry"); + } + + return propertyValue; + } + + public MessageHeaderType getMessageHeader() { + MessageHeaderType messageHeader = new MessageHeaderType(); + ApplicationType appType = new ApplicationType(); + try { + appType.setApplicationName(getPropertyValue("applicationName")); + appType.setApplicationVersion(getPropertyValue("applicationVersion")); + } catch (I2B2Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + messageHeader.setSendingApplication(appType); + return messageHeader; + } +} + +class getHiveCellParam implements RowMapper { + @Override + public ParamType mapRow(ResultSet rs, int rowNum) throws SQLException { + + ParamType param = new ParamType(); + param.setId(rs.getInt("id")); + param.setName(rs.getString("param_name_cd")); + param.setValue(rs.getString("value")); + param.setDatatype(rs.getString("datatype_cd")); + return param; + } +} + diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/util/PatientDataXMLWriterUtil.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/util/PatientDataXMLWriterUtil.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/util/PatientDataXMLWriterUtil.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/util/PatientDataXMLWriterUtil.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/util/Roles.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/util/Roles.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/util/Roles.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/util/Roles.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/util/StringUtil.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/util/StringUtil.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/util/StringUtil.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/util/StringUtil.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ws/AddChildDataMessage.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ws/AddChildDataMessage.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ws/AddChildDataMessage.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ws/AddChildDataMessage.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ws/CRCUpdateConceptMessage.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ws/CRCUpdateConceptMessage.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ws/CRCUpdateConceptMessage.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ws/CRCUpdateConceptMessage.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ws/DeleteChildDataMessage.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ws/DeleteChildDataMessage.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ws/DeleteChildDataMessage.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ws/DeleteChildDataMessage.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ws/DeleteDblookupDataMessage.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ws/DeleteDblookupDataMessage.java similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ws/DeleteDblookupDataMessage.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ws/DeleteDblookupDataMessage.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ws/ExecutorRunnable.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ws/ExecutorRunnable.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ws/ExecutorRunnable.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ws/ExecutorRunnable.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ws/GetAllDblookupsDataMessage.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ws/GetAllDblookupsDataMessage.java similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ws/GetAllDblookupsDataMessage.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ws/GetAllDblookupsDataMessage.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ws/GetCategoriesDataMessage.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ws/GetCategoriesDataMessage.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ws/GetCategoriesDataMessage.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ws/GetCategoriesDataMessage.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ws/GetChildrenDataMessage.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ws/GetChildrenDataMessage.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ws/GetChildrenDataMessage.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ws/GetChildrenDataMessage.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ws/GetCodeInfoDataMessage.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ws/GetCodeInfoDataMessage.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ws/GetCodeInfoDataMessage.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ws/GetCodeInfoDataMessage.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ws/GetDblookupDataMessage.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ws/GetDblookupDataMessage.java similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ws/GetDblookupDataMessage.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ws/GetDblookupDataMessage.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ws/GetDirtyStateDataMessage.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ws/GetDirtyStateDataMessage.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ws/GetDirtyStateDataMessage.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ws/GetDirtyStateDataMessage.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ws/GetModifierChildrenDataMessage.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ws/GetModifierChildrenDataMessage.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ws/GetModifierChildrenDataMessage.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ws/GetModifierChildrenDataMessage.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ws/GetModifierCodeInfoDataMessage.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ws/GetModifierCodeInfoDataMessage.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ws/GetModifierCodeInfoDataMessage.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ws/GetModifierCodeInfoDataMessage.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ws/GetModifierInfoDataMessage.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ws/GetModifierInfoDataMessage.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ws/GetModifierInfoDataMessage.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ws/GetModifierInfoDataMessage.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ws/GetModifierNameInfoDataMessage.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ws/GetModifierNameInfoDataMessage.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ws/GetModifierNameInfoDataMessage.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ws/GetModifierNameInfoDataMessage.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ws/GetModifiersDataMessage.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ws/GetModifiersDataMessage.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ws/GetModifiersDataMessage.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ws/GetModifiersDataMessage.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ws/GetNameInfoDataMessage.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ws/GetNameInfoDataMessage.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ws/GetNameInfoDataMessage.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ws/GetNameInfoDataMessage.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ws/GetOntProcessStatusMessage.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ws/GetOntProcessStatusMessage.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ws/GetOntProcessStatusMessage.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ws/GetOntProcessStatusMessage.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ws/GetSchemesDataMessage.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ws/GetSchemesDataMessage.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ws/GetSchemesDataMessage.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ws/GetSchemesDataMessage.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ws/GetTermInfoDataMessage.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ws/GetTermInfoDataMessage.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ws/GetTermInfoDataMessage.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ws/GetTermInfoDataMessage.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ws/LoadDataMessage.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ws/LoadDataMessage.java similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ws/LoadDataMessage.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ws/LoadDataMessage.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ws/MessageFactory.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ws/MessageFactory.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ws/MessageFactory.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ws/MessageFactory.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ws/ModifyChildDataMessage.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ws/ModifyChildDataMessage.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ws/ModifyChildDataMessage.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ws/ModifyChildDataMessage.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ws/OntologyService.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ws/OntologyService.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ws/OntologyService.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ws/OntologyService.java index a65ebdc8..334b9fe1 --- a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ws/OntologyService.java +++ b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ws/OntologyService.java @@ -1,1292 +1,1289 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Raj Kuttan - * Lori Phillips - */ -package edu.harvard.i2b2.ontology.ws; - -import java.io.IOException; -import java.nio.charset.StandardCharsets; - -import javax.xml.stream.XMLStreamWriter; - -import org.apache.axiom.om.OMDataSource; -import org.apache.axiom.om.OMElement; -import org.apache.axiom.om.util.StAXUtils; -import org.apache.axis2.json.JSONDataSource; -import org.apache.axis2.util.StreamWrapper; -import org.apache.commons.io.output.ByteArrayOutputStream; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.ontology.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.ontology.delegate.AddChildHandler; -import edu.harvard.i2b2.ontology.delegate.AddModifierHandler; -import edu.harvard.i2b2.ontology.delegate.CRCConceptUpdateHandler; -import edu.harvard.i2b2.ontology.delegate.DeleteChildHandler; -import edu.harvard.i2b2.ontology.delegate.DeleteDblookupHandler; -import edu.harvard.i2b2.ontology.delegate.ExcludeModifierHandler; -import edu.harvard.i2b2.ontology.delegate.GetAllDblookupsHandler; -import edu.harvard.i2b2.ontology.delegate.GetCategoriesHandler; -import edu.harvard.i2b2.ontology.delegate.GetChildrenHandler; -import edu.harvard.i2b2.ontology.delegate.GetCodeInfoHandler; -import edu.harvard.i2b2.ontology.delegate.GetDblookupHandler; -import edu.harvard.i2b2.ontology.delegate.GetDerivedFactColumnsHandler; -import edu.harvard.i2b2.ontology.delegate.GetDirtyStateHandler; -import edu.harvard.i2b2.ontology.delegate.GetModifierChildrenHandler; -import edu.harvard.i2b2.ontology.delegate.GetModifierCodeInfoHandler; -import edu.harvard.i2b2.ontology.delegate.GetModifierInfoHandler; -import edu.harvard.i2b2.ontology.delegate.GetModifierNameInfoHandler; -import edu.harvard.i2b2.ontology.delegate.GetModifiersHandler; -import edu.harvard.i2b2.ontology.delegate.GetNameInfoHandler; -import edu.harvard.i2b2.ontology.delegate.GetOntProcessStatusHandler; -import edu.harvard.i2b2.ontology.delegate.GetSchemesHandler; -import edu.harvard.i2b2.ontology.delegate.GetTermInfoHandler; -import edu.harvard.i2b2.ontology.delegate.ModifyChildHandler; -import edu.harvard.i2b2.ontology.delegate.CheckMetadataTableHandler; -import edu.harvard.i2b2.ontology.delegate.LoadMetadataHandler; -import edu.harvard.i2b2.ontology.delegate.LoadSchemesHandler; -import edu.harvard.i2b2.ontology.delegate.LoadTableAccessHandler; -import edu.harvard.i2b2.ontology.delegate.RequestHandler; -import edu.harvard.i2b2.ontology.delegate.SetDblookupHandler; -import edu.harvard.i2b2.ontology.delegate.UpdateTotalNumHandler; - -/** - * This is webservice skeleton class. It parses incoming Ontology service - * requests and generates responses in the Vocab Data Object XML format. - * - */ -public class OntologyService { - private static Log log = LogFactory.getLog(OntologyService.class); - protected static Log logesapi = LogFactory.getLog(OntologyService.class); - - /** - * This function is main webservice interface to get vocab data for a query. - * It uses AXIOM elements(OMElement) to conveniently parse xml messages. - * - * It excepts incoming request in i2b2 message format, which wraps an - * Ontology query inside a vocab query request object. The response is also - * will be in i2b2 message format, which will wrap vocab data object. Vocab - * data object will have all the results returned by the query. - * - * - * @param getChildren - * @return OMElement in i2b2message format - * @throws Exception - */ - public OMElement getChildren(OMElement getChildrenElement) - throws I2B2Exception { - - OMElement returnElement = null; - String ontologyDataResponse = null; - String unknownErrorMessage = "Error message delivered from the remote server \n" - + "You may wish to retry your last action"; - - if (getChildrenElement == null) { - log.error("Incoming Ontology request is null"); - ResponseMessageType responseMsgType = MessageFactory - .doBuildErrorResponse(null, unknownErrorMessage); - ontologyDataResponse = MessageFactory - .convertToXMLString(responseMsgType); - return MessageFactory - .createResponseOMElementFromString(ontologyDataResponse); - } - - String requestElementString = getChildrenElement.toString(); - - - GetChildrenDataMessage childrenDataMsg = new GetChildrenDataMessage( - requestElementString); - long waitTime = 0; - if ((childrenDataMsg.getRequestMessageType() != null) && (childrenDataMsg.getRequestMessageType().getRequestHeader() != null)) { - waitTime = childrenDataMsg.getRequestMessageType() - .getRequestHeader().getResultWaittimeMs(); - } - - // do Ontology query processing inside thread, so that - // service could sends back message with timeout error. - // ExecutorRunnable er = new ExecutorRunnable(); - return execute(new GetChildrenHandler(childrenDataMsg), waitTime); - - } - - /** - * This function is main webservice interface to get vocab data for a query. - * It uses AXIOM elements(OMElement) to conveniently parse xml messages. - * - * It excepts incoming request in i2b2 message format, which wraps an - * Ontology query inside a vocab query request object. The response is also - * will be in i2b2 message format, which will wrap vocab data object. Vocab - * data object will have all the results returned by the query. - * - * - * @param OMElement - * getCategoriesElement - * @return OMElement in i2b2message format - * @throws Exception - */ - public OMElement getCategories(OMElement getCategoriesElement) - throws I2B2Exception { - - OMElement returnElement = null; - String ontologyDataResponse = null; - String unknownErrorMessage = "Error message delivered from the remote server \n" - + "You may wish to retry your last action"; - - if (getCategoriesElement == null) { - log.error("Incoming Ontology request is null"); - ResponseMessageType responseMsgType = MessageFactory - .doBuildErrorResponse(null, unknownErrorMessage); - ontologyDataResponse = MessageFactory - .convertToXMLString(responseMsgType); - return MessageFactory - .createResponseOMElementFromString(ontologyDataResponse); - } - - String requestElementString = getCategoriesElement.toString(); - - - GetCategoriesDataMessage categoriesDataMsg = new GetCategoriesDataMessage( - requestElementString); - long waitTime = 0; - if ((categoriesDataMsg.getRequestMessageType() != null) && (categoriesDataMsg.getRequestMessageType().getRequestHeader() != null)) { - waitTime = categoriesDataMsg.getRequestMessageType() - .getRequestHeader().getResultWaittimeMs(); - } - - // do Ontology query processing inside thread, so that - // service could sends back message with timeout error. - // ExecutorRunnable er = new ExecutorRunnable(); - return execute(new GetCategoriesHandler(categoriesDataMsg), waitTime); - } - - /** - * This function is main webservice interface to get vocab data for a query. - * It uses AXIOM elements(OMElement) to conveniently parse xml messages. - * - * It excepts incoming request in i2b2 message format, which wraps an - * Ontology query inside a vocab query request object. The response is also - * will be in i2b2 message format, which will wrap vocab data object. Vocab - * data object will have all the results returned by the query. - * - * - * @param OMElement - * geSchemesElement - * @return OMElement in i2b2message format - * @throws Exception - */ - public OMElement getSchemes(OMElement getSchemesElement) - throws I2B2Exception { - OMElement returnElement = null; - String ontologyDataResponse = null; - String unknownErrorMessage = "Error message delivered from the remote server \n" - + "You may wish to retry your last action"; - - if (getSchemesElement == null) { - log.error("Incoming Ontology request is null"); - ResponseMessageType responseMsgType = MessageFactory - .doBuildErrorResponse(null, unknownErrorMessage); - ontologyDataResponse = MessageFactory - .convertToXMLString(responseMsgType); - return MessageFactory - .createResponseOMElementFromString(ontologyDataResponse); - } - - // (OMSourcedElement) getSchemesElement - // OMSourcedElement aa = ((OMSourcedElement) getSchemesElement).getDataSource(); - // JSONBadgerfishDataSource jsonDataSource = (JSONBadgerfishDataSource) ((OMSourcedElement) getSchemesElement).getDataSource(); - // String jsonString = jsonDataSource.toString(); //.getCompleteJOSNString(); // this will return json string - - // if (element instanceof OMSourcedElementImpl && getStringToWrite(((OMSourcedElementImpl) - // element).getDataSource()) != null) { - - - - - String requestElementString = getSchemesElement.toString(); - GetSchemesDataMessage schemesDataMsg = new GetSchemesDataMessage( - requestElementString); - - long waitTime = 0; - if ((schemesDataMsg.getRequestMessageType() != null) && (schemesDataMsg.getRequestMessageType().getRequestHeader() != null)) { - waitTime = schemesDataMsg.getRequestMessageType() - .getRequestHeader().getResultWaittimeMs(); - } - - // do Ontology query processing inside thread, so that - // service could sends back message with timeout error. - // ExecutorRunnable er = new ExecutorRunnable(); - return execute(new GetSchemesHandler(schemesDataMsg), waitTime); - } - - /** - * This function is main webservice interface to get vocab data for a query. - * It uses AXIOM elements(OMElement) to conveniently parse xml messages. - * - * It excepts incoming request in i2b2 message format, which wraps an - * Ontology query inside a vocab query request object. The response is also - * will be in i2b2 message format, which will wrap vocab data object. Vocab - * data object will have all the results returned by the query. - * - * - * @param OMElement - * getCodeInfoElement - * @return OMElement in i2b2message format - * @throws Exception - */ - public OMElement getCodeInfo(OMElement getCodeInfoElement) - throws I2B2Exception { - OMElement returnElement = null; - String ontologyDataResponse = null; - String unknownErrorMessage = "Error message delivered from the remote server \n" - + "You may wish to retry your last action"; - - if (getCodeInfoElement == null) { - log.error("Incoming Ontology request is null"); - ResponseMessageType responseMsgType = MessageFactory - .doBuildErrorResponse(null, unknownErrorMessage); - ontologyDataResponse = MessageFactory - .convertToXMLString(responseMsgType); - return MessageFactory - .createResponseOMElementFromString(ontologyDataResponse); - } - - String requestElementString = getCodeInfoElement.toString(); - GetCodeInfoDataMessage codeInfoDataMsg = new GetCodeInfoDataMessage( - requestElementString); - - long waitTime = 0; - if ((codeInfoDataMsg.getRequestMessageType() != null) && (codeInfoDataMsg.getRequestMessageType().getRequestHeader() != null)) { - waitTime = codeInfoDataMsg.getRequestMessageType() - .getRequestHeader().getResultWaittimeMs(); - } - - // do Ontology query processing inside thread, so that - // service could sends back message with timeout error. - - // ExecutorRunnable er = new ExecutorRunnable(); - return execute(new GetCodeInfoHandler(codeInfoDataMsg), waitTime); - } - - /** - * This function is main webservice interface to get vocab data for a query. - * It uses AXIOM elements(OMElement) to conveniently parse xml messages. - * - * It excepts incoming request in i2b2 message format, which wraps an - * Ontology query inside a vocab query request object. The response is also - * will be in i2b2 message format, which will wrap vocab data object. Vocab - * data object will have all the results returned by the query. - * - * - * @param OMElement - * getCodeInfoElement - * @return OMElement in i2b2message format - * @throws Exception - */ - public OMElement getNameInfo(OMElement getNameInfoElement) - throws I2B2Exception { - OMElement returnElement = null; - String ontologyDataResponse = null; - String unknownErrorMessage = "Error message delivered from the remote server \n" - + "You may wish to retry your last action"; - - if (getNameInfoElement == null) { - log.error("Incoming Ontology request is null"); - ResponseMessageType responseMsgType = MessageFactory - .doBuildErrorResponse(null, unknownErrorMessage); - ontologyDataResponse = MessageFactory - .convertToXMLString(responseMsgType); - return MessageFactory - .createResponseOMElementFromString(ontologyDataResponse); - } - - String requestElementString = getNameInfoElement.toString(); - - - GetNameInfoDataMessage nameInfoDataMsg = new GetNameInfoDataMessage( - requestElementString); - - long waitTime = 0; - if ((nameInfoDataMsg.getRequestMessageType() != null) && (nameInfoDataMsg.getRequestMessageType().getRequestHeader() != null)) { - waitTime = nameInfoDataMsg.getRequestMessageType() - .getRequestHeader().getResultWaittimeMs(); - } - - // do Ontology query processing inside thread, so that - // service could sends back message with timeout error. - - // ExecutorRunnable er = new ExecutorRunnable(); - return execute(new GetNameInfoHandler(nameInfoDataMsg), waitTime); - } - - /** - * This function is main webservice interface to get vocab data for a query. - * It uses AXIOM elements(OMElement) to conveniently parse xml messages. - * - * It excepts incoming request in i2b2 message format, which wraps an - * Ontology query inside a vocab query request object. The response is also - * will be in i2b2 message format, which will wrap vocab data object. Vocab - * data object will have all the results returned by the query. - * - * - * @param getTermInfo - * @return OMElement in i2b2message format - * @throws Exception - */ - public OMElement getTermInfo(OMElement getTermInfoElement) - throws I2B2Exception { - - OMElement returnElement = null; - String ontologyDataResponse = null; - String unknownErrorMessage = "Error message delivered from the remote server \n" - + "You may wish to retry your last action"; - - if (getTermInfoElement == null) { - log.error("Incoming Ontology request is null"); - ResponseMessageType responseMsgType = MessageFactory - .doBuildErrorResponse(null, unknownErrorMessage); - ontologyDataResponse = MessageFactory - .convertToXMLString(responseMsgType); - return MessageFactory - .createResponseOMElementFromString(ontologyDataResponse); - - } - - String requestElementString = getTermInfoElement.toString(); - GetTermInfoDataMessage termInfoDataMsg = new GetTermInfoDataMessage( - requestElementString); - - long waitTime = 0; - if ((termInfoDataMsg.getRequestMessageType() != null) && (termInfoDataMsg.getRequestMessageType().getRequestHeader() != null)) { - waitTime = termInfoDataMsg.getRequestMessageType() - .getRequestHeader().getResultWaittimeMs(); - } - - // do Ontology query processing inside thread, so that - // service could sends back message with timeout error. - - // ExecutorRunnable er = new ExecutorRunnable(); - return execute(new GetTermInfoHandler(termInfoDataMsg), waitTime); - } - - /** - * This function is main webservice interface to get vocab data for a query. - * It uses AXIOM elements(OMElement) to conveniently parse xml messages. - * - * It excepts incoming request in i2b2 message format, which wraps an - * Ontology query inside a vocab query request object. The response is also - * will be in i2b2 message format, which will wrap vocab data object. Vocab - * data object will have all the results returned by the query. - * - * - * @param getDerivedFactColumns - * @return OMElement in i2b2message format - * @throws Exception - */ - public OMElement getDerivedFactColumns(OMElement getDerivedFactColumnsElement) - throws I2B2Exception { - - OMElement returnElement = null; - String ontologyDataResponse = null; - String unknownErrorMessage = "Error message delivered from the remote server \n" - + "You may wish to retry your last action"; - - if (getDerivedFactColumnsElement == null) { - log.error("Incoming Ontology request is null"); - ResponseMessageType responseMsgType = MessageFactory - .doBuildErrorResponse(null, unknownErrorMessage); - ontologyDataResponse = MessageFactory - .convertToXMLString(responseMsgType); - return MessageFactory - .createResponseOMElementFromString(ontologyDataResponse); - - } - - String requestElementString = getDerivedFactColumnsElement.toString(); - logesapi.debug("ONT derivedFactCol request " + requestElementString); - GetTermInfoDataMessage dataMsg = new GetTermInfoDataMessage( - requestElementString); - - long waitTime = 0; - if ((dataMsg.getRequestMessageType() != null) && (dataMsg.getRequestMessageType().getRequestHeader() != null)) { - waitTime = dataMsg.getRequestMessageType() - .getRequestHeader().getResultWaittimeMs(); - } - - // do Ontology query processing inside thread, so that - // service could sends back message with timeout error. - - // ExecutorRunnable er = new ExecutorRunnable(); - return execute(new GetDerivedFactColumnsHandler(dataMsg), waitTime); - } - - - - private OMElement execute(RequestHandler handler, long waitTime) - throws I2B2Exception { - // do Ontology query processing inside thread, so that - // service could sends back message with timeout error. - OMElement returnElement = null; - - String unknownErrorMessage = "Error message delivered from the remote server \n" - + "You may wish to retry your last action"; - - ExecutorRunnable er = new ExecutorRunnable(); - - er.setRequestHandler(handler); - - Thread t = new Thread(er); - String ontologyDataResponse = null; - - synchronized (t) { - t.start(); - - // try { - // if (waitTime > 0) { - // t.wait(waitTime); - // } else { - // t.wait(); - // } - - try { - long startTime = System.currentTimeMillis(); - long deltaTime = -1; - while ((er.isJobCompleteFlag() == false) - && (deltaTime < waitTime)) { - if (waitTime > 0) { - t.wait(waitTime - deltaTime); - deltaTime = System.currentTimeMillis() - startTime; - } else { - t.wait(); - } - } - - ontologyDataResponse = er.getOutputString(); - - if (ontologyDataResponse == null) { - if (er.getJobException() != null) { - log.error("er.jobException is " - + er.getJobException().getMessage()); - - log.info("waitTime is " + waitTime); - - ResponseMessageType responseMsgType = MessageFactory - .doBuildErrorResponse(null, unknownErrorMessage); - ontologyDataResponse = MessageFactory - .convertToXMLString(responseMsgType); - - } else if (er.isJobCompleteFlag() == false) { - // 5000 - String timeOuterror = "Remote server timed out \n" - + "Result waittime = " + waitTime - + " ms elapsed,\nPlease try again"; - log.error(timeOuterror); - - log.debug("ontology waited " + deltaTime + "ms for " - + er.getRequestHandler().getClass().getName()); - - ResponseMessageType responseMsgType = MessageFactory - .doBuildErrorResponse(null, timeOuterror); - ontologyDataResponse = MessageFactory - .convertToXMLString(responseMsgType); - - } else { - log.error("ontology data response is null"); - log.info("waitTime is " + waitTime); - log.debug("ontology waited " + deltaTime + "ms for " - + er.getRequestHandler().getClass().getName()); - ResponseMessageType responseMsgType = MessageFactory - .doBuildErrorResponse(null, unknownErrorMessage); - ontologyDataResponse = MessageFactory - .convertToXMLString(responseMsgType); - } - } - } catch (InterruptedException e) { - log.error(e.getMessage()); - throw new I2B2Exception( - "Thread error while running Ontology job "); - } finally { - t.interrupt(); - er = null; - t = null; - } - } - returnElement = MessageFactory - .createResponseOMElementFromString(ontologyDataResponse); - - return returnElement; - } - - public OMElement addChild(OMElement addChildElement) throws I2B2Exception { - - OMElement returnElement = null; - String ontologyDataResponse = null; - String unknownErrorMessage = "Error message delivered from the remote server \n" - + "You may wish to retry your last action"; - - if (addChildElement == null) { - log.error("Incoming Ontology request is null"); - ResponseMessageType responseMsgType = MessageFactory - .doBuildErrorResponse(null, unknownErrorMessage); - ontologyDataResponse = MessageFactory - .convertToXMLString(responseMsgType); - return MessageFactory - .createResponseOMElementFromString(ontologyDataResponse); - } - String requestElementString = addChildElement.toString(); - AddChildDataMessage childDataMsg = new AddChildDataMessage( - requestElementString); - long waitTime = 0; - if ((childDataMsg.getRequestMessageType() != null) && (childDataMsg.getRequestMessageType().getRequestHeader() != null)) { - waitTime = childDataMsg.getRequestMessageType() - .getRequestHeader().getResultWaittimeMs(); - } - - // do Ontology query processing inside thread, so that - // service could sends back message with timeout error. - // ExecutorRunnable er = new ExecutorRunnable(); - return execute(new AddChildHandler(childDataMsg), waitTime); - - } - - public OMElement modifyChild(OMElement modifyChildElement) throws I2B2Exception { - - OMElement returnElement = null; - String ontologyDataResponse = null; - String unknownErrorMessage = "Error message delivered from the remote server \n" - + "You may wish to retry your last action"; - - if (modifyChildElement == null) { - log.error("Incoming Ontology request is null"); - ResponseMessageType responseMsgType = MessageFactory - .doBuildErrorResponse(null, unknownErrorMessage); - ontologyDataResponse = MessageFactory - .convertToXMLString(responseMsgType); - return MessageFactory - .createResponseOMElementFromString(ontologyDataResponse); - } - String requestElementString = modifyChildElement.toString(); - logesapi.debug(requestElementString); - ModifyChildDataMessage childDataMsg = new ModifyChildDataMessage( - requestElementString); - long waitTime = 0; - if ((childDataMsg.getRequestMessageType() != null) && (childDataMsg.getRequestMessageType().getRequestHeader() != null)) { - waitTime = childDataMsg.getRequestMessageType() - .getRequestHeader().getResultWaittimeMs(); - } - - // do Ontology query processing inside thread, so that - // service could sends back message with timeout error. - // ExecutorRunnable er = new ExecutorRunnable(); - return execute(new ModifyChildHandler(childDataMsg), waitTime); - - } - - public OMElement deleteChild(OMElement deleteNodeElement) throws Exception { - OMElement returnElement = null; - String ontologyDataResponse = null; - String unknownErrorMessage = "Error message delivered from the remote server \n" - + "You may wish to retry your last action"; - - if (deleteNodeElement == null) { - log.error("Incoming Ontology request is null"); - - ResponseMessageType responseMsgType = MessageFactory - .doBuildErrorResponse(null, unknownErrorMessage); - ontologyDataResponse = MessageFactory - .convertToXMLString(responseMsgType); - return MessageFactory - .createResponseOMElementFromString(ontologyDataResponse); - } - - String requestElementString = deleteNodeElement.toString(); - DeleteChildDataMessage deleteDataMsg = new DeleteChildDataMessage( - requestElementString); - // log.info(requestElementString); - // deleteDataMsg.setRequestMessageType(requestElementString); - - long waitTime = 0; - if ((deleteDataMsg.getRequestMessageType() != null) && (deleteDataMsg.getRequestMessageType().getRequestHeader() != null)) { - waitTime = deleteDataMsg.getRequestMessageType() - .getRequestHeader().getResultWaittimeMs(); - } - - // do Workplace query processing inside thread, so that - // service could send back message with timeout error. - // ExecutorRunnable er = new ExecutorRunnable(); - return execute(new DeleteChildHandler(deleteDataMsg), waitTime); - - } - - public OMElement updateCRCConcept(OMElement updateCRCConceptElement) - throws I2B2Exception { - - OMElement returnElement = null; - String ontologyDataResponse = null; - String unknownErrorMessage = "Error message delivered from the remote server \n" - + "You may wish to retry your last action"; - - if (updateCRCConceptElement == null) { - log.error("Incoming Ontology request is null"); - ResponseMessageType responseMsgType = MessageFactory - .doBuildErrorResponse(null, unknownErrorMessage); - ontologyDataResponse = MessageFactory - .convertToXMLString(responseMsgType); - return MessageFactory - .createResponseOMElementFromString(ontologyDataResponse); - } - String requestElementString = updateCRCConceptElement.toString(); - CRCUpdateConceptMessage childDataMsg = new CRCUpdateConceptMessage( - requestElementString); - long waitTime = 0; - if ((childDataMsg.getRequestMessageType() != null) && (childDataMsg.getRequestMessageType().getRequestHeader() != null)) { - waitTime = childDataMsg.getRequestMessageType() - .getRequestHeader().getResultWaittimeMs(); - } - - // do Ontology query processing inside thread, so that - // service could sends back message with timeout error. - // ExecutorRunnable er = new ExecutorRunnable(); - return execute(new CRCConceptUpdateHandler(childDataMsg), waitTime); - - } - - public OMElement updateConceptTotalNum(OMElement updateConceptTotalNumElement) - throws I2B2Exception { - - OMElement returnElement = null; - String ontologyDataResponse = null; - String unknownErrorMessage = "Error message delivered from the remote server \n" - + "You may wish to retry your last action"; - - if (updateConceptTotalNumElement == null) { - log.error("Incoming Ontology request is null"); - ResponseMessageType responseMsgType = MessageFactory - .doBuildErrorResponse(null, unknownErrorMessage); - ontologyDataResponse = MessageFactory - .convertToXMLString(responseMsgType); - return MessageFactory - .createResponseOMElementFromString(ontologyDataResponse); - } - String requestElementString = updateConceptTotalNumElement.toString(); - UpdateTotalNumMessage childDataMsg = new UpdateTotalNumMessage( - requestElementString); - long waitTime = 0; - if ((childDataMsg.getRequestMessageType() != null) && (childDataMsg.getRequestMessageType().getRequestHeader() != null)) { - waitTime = childDataMsg.getRequestMessageType() - .getRequestHeader().getResultWaittimeMs(); - } - - // do Ontology query processing inside thread, so that - // service could sends back message with timeout error. - // ExecutorRunnable er = new ExecutorRunnable(); - return execute(new UpdateTotalNumHandler(childDataMsg), waitTime); - - } - - public OMElement getProcessStatus(OMElement getOntProcessStatus) - throws I2B2Exception { - - OMElement returnElement = null; - String ontologyDataResponse = null; - String unknownErrorMessage = "Error message delivered from the remote server \n" - + "You may wish to retry your last action"; - - if (getOntProcessStatus == null) { - log.error("Incoming Ontology request is null"); - ResponseMessageType responseMsgType = MessageFactory - .doBuildErrorResponse(null, unknownErrorMessage); - ontologyDataResponse = MessageFactory - .convertToXMLString(responseMsgType); - return MessageFactory - .createResponseOMElementFromString(ontologyDataResponse); - } - String requestElementString = getOntProcessStatus.toString(); - GetOntProcessStatusMessage childDataMsg = new GetOntProcessStatusMessage( - requestElementString); - long waitTime = 0; - if ((childDataMsg.getRequestMessageType() != null) && (childDataMsg.getRequestMessageType().getRequestHeader() != null)) { - waitTime = childDataMsg.getRequestMessageType() - .getRequestHeader().getResultWaittimeMs(); - } - - // do Ontology query processing inside thread, so that - // service could sends back message with timeout error. - // ExecutorRunnable er = new ExecutorRunnable(); - return execute(new GetOntProcessStatusHandler(childDataMsg), waitTime); - - } - - /** - * This function is main webservice interface to get vocab data for a query. - * It uses AXIOM elements(OMElement) to conveniently parse xml messages. - * - * It excepts incoming request in i2b2 message format, which wraps an - * Ontology query inside a vocab query request object. The response is also - * will be in i2b2 message format, which will wrap vocab data object. Vocab - * data object will have all the results returned by the query. - * - * - * @param OMElement - * getDirtyStateElement - * @return OMElement in i2b2message format - * @throws Exception - */ - public OMElement getDirtyState(OMElement getDirtyStateElement) - throws I2B2Exception { - OMElement returnElement = null; - String ontologyDataResponse = null; - String unknownErrorMessage = "Error message delivered from the remote server \n" - + "You may wish to retry your last action"; - - if (getDirtyStateElement == null) { - log.error("Incoming Ontology request is null"); - ResponseMessageType responseMsgType = MessageFactory - .doBuildErrorResponse(null, unknownErrorMessage); - ontologyDataResponse = MessageFactory - .convertToXMLString(responseMsgType); - return MessageFactory - .createResponseOMElementFromString(ontologyDataResponse); - } - - String requestElementString = getDirtyStateElement.toString(); - GetDirtyStateDataMessage dirtyStateDataMsg = new GetDirtyStateDataMessage( - requestElementString); - - long waitTime = 0; - if ((dirtyStateDataMsg.getRequestMessageType() != null) && (dirtyStateDataMsg.getRequestMessageType().getRequestHeader() != null)) { - waitTime = dirtyStateDataMsg.getRequestMessageType() - .getRequestHeader().getResultWaittimeMs(); - } - - // do Ontology query processing inside thread, so that - // service could sends back message with timeout error. - // ExecutorRunnable er = new ExecutorRunnable(); - return execute(new GetDirtyStateHandler(dirtyStateDataMsg), waitTime); - } - - /** - * This function is main webservice interface to get modifier data for a query. - * It uses AXIOM elements(OMElement) to conveniently parse xml messages. - * - * It excepts incoming request in i2b2 message format, which wraps an - * Ontology query inside a modifier query request object. The response is also - * will be in i2b2 message format, which will wrap modifier data object. Modifier - * data object will have all the results returned by the query. - * - * - * @param getModifiers - * @return OMElement in i2b2message format - * @throws Exception - */ - public OMElement getModifiers(OMElement getModifiersElement) - throws I2B2Exception { - - OMElement returnElement = null; - String ontologyDataResponse = null; - String unknownErrorMessage = "Error message delivered from the remote server \n" - + "You may wish to retry your last action"; - - if (getModifiersElement == null) { - log.error("Incoming Ontology request is null"); - ResponseMessageType responseMsgType = MessageFactory - .doBuildErrorResponse(null, unknownErrorMessage); - ontologyDataResponse = MessageFactory - .convertToXMLString(responseMsgType); - return MessageFactory - .createResponseOMElementFromString(ontologyDataResponse); - } - String requestElementString = getModifiersElement.toString(); - GetModifiersDataMessage modifiersDataMsg = new GetModifiersDataMessage( - requestElementString); - long waitTime = 0; - if ((modifiersDataMsg.getRequestMessageType() != null) && (modifiersDataMsg.getRequestMessageType().getRequestHeader() != null)) { - waitTime = modifiersDataMsg.getRequestMessageType() - .getRequestHeader().getResultWaittimeMs(); - } - - // do Ontology query processing inside thread, so that - // service could sends back message with timeout error. - // ExecutorRunnable er = new ExecutorRunnable(); - return execute(new GetModifiersHandler(modifiersDataMsg), waitTime); - - } - /** - * This function is main webservice interface to get modifier data for a query. - * It uses AXIOM elements(OMElement) to conveniently parse xml messages. - * - * It excepts incoming request in i2b2 message format, which wraps an - * Ontology query inside a modifier query request object. The response is also - * will be in i2b2 message format, which will wrap modifier data object. Modifier - * data object will have all the results returned by the query. - * - * - * @param getModifierInfo - * @return OMElement in i2b2message format - * @throws Exception - */ - public OMElement getModifierInfo(OMElement getModifierInfoElement) - throws I2B2Exception { - - OMElement returnElement = null; - String ontologyDataResponse = null; - String unknownErrorMessage = "Error message delivered from the remote server \n" - + "You may wish to retry your last action"; - - if (getModifierInfoElement == null) { - log.error("Incoming Ontology request is null"); - ResponseMessageType responseMsgType = MessageFactory - .doBuildErrorResponse(null, unknownErrorMessage); - ontologyDataResponse = MessageFactory - .convertToXMLString(responseMsgType); - return MessageFactory - .createResponseOMElementFromString(ontologyDataResponse); - } - String requestElementString = getModifierInfoElement.toString(); - GetModifierInfoDataMessage modifierInfoDataMsg = new GetModifierInfoDataMessage( - requestElementString); - long waitTime = 0; - if ((modifierInfoDataMsg.getRequestMessageType() != null) && (modifierInfoDataMsg.getRequestMessageType().getRequestHeader() != null)) { - waitTime = modifierInfoDataMsg.getRequestMessageType() - .getRequestHeader().getResultWaittimeMs(); - } - - // do Ontology query processing inside thread, so that - // service could sends back message with timeout error. - // ExecutorRunnable er = new ExecutorRunnable(); - return execute(new GetModifierInfoHandler(modifierInfoDataMsg), waitTime); - - } - - /** - * This function is main webservice interface to get modifier data for a query. - * It uses AXIOM elements(OMElement) to conveniently parse xml messages. - * - * It excepts incoming request in i2b2 message format, which wraps an - * Ontology query inside a modifier query request object. The response is also - * will be in i2b2 message format, which will wrap modifier data object. Modifier - * data object will have all the results returned by the query. - * - * - * @param getModifierInfo - * @return OMElement in i2b2message format - * @throws Exception - */ - public OMElement getModifierChildren(OMElement getModifierChildrenElement) - throws I2B2Exception { - - OMElement returnElement = null; - String ontologyDataResponse = null; - String unknownErrorMessage = "Error message delivered from the remote server \n" - + "You may wish to retry your last action"; - - if (getModifierChildrenElement == null) { - log.error("Incoming Ontology request is null"); - ResponseMessageType responseMsgType = MessageFactory - .doBuildErrorResponse(null, unknownErrorMessage); - ontologyDataResponse = MessageFactory - .convertToXMLString(responseMsgType); - return MessageFactory - .createResponseOMElementFromString(ontologyDataResponse); - } - String requestElementString = getModifierChildrenElement.toString(); - GetModifierChildrenDataMessage modifierChildrenDataMsg = new GetModifierChildrenDataMessage( - requestElementString); - long waitTime = 0; - if ((modifierChildrenDataMsg.getRequestMessageType() != null) && (modifierChildrenDataMsg.getRequestMessageType().getRequestHeader() != null)) { - waitTime = modifierChildrenDataMsg.getRequestMessageType() - .getRequestHeader().getResultWaittimeMs(); - } - - // do Ontology query processing inside thread, so that - // service could sends back message with timeout error. - // ExecutorRunnable er = new ExecutorRunnable(); - return execute(new GetModifierChildrenHandler(modifierChildrenDataMsg), waitTime); - - } - - public OMElement addModifier(OMElement addChildElement) throws I2B2Exception { - - OMElement returnElement = null; - String ontologyDataResponse = null; - String unknownErrorMessage = "Error message delivered from the remote server \n" - + "You may wish to retry your last action"; - - if (addChildElement == null) { - log.error("Incoming Ontology request is null"); - ResponseMessageType responseMsgType = MessageFactory - .doBuildErrorResponse(null, unknownErrorMessage); - ontologyDataResponse = MessageFactory - .convertToXMLString(responseMsgType); - return MessageFactory - .createResponseOMElementFromString(ontologyDataResponse); - } - String requestElementString = addChildElement.toString(); - AddChildDataMessage childDataMsg = new AddChildDataMessage( - requestElementString); - long waitTime = 0; - if ((childDataMsg.getRequestMessageType() != null) && (childDataMsg.getRequestMessageType().getRequestHeader() != null)) { - waitTime = childDataMsg.getRequestMessageType() - .getRequestHeader().getResultWaittimeMs(); - } - - // do Ontology query processing inside thread, so that - // service could sends back message with timeout error. - // ExecutorRunnable er = new ExecutorRunnable(); - return execute(new AddModifierHandler(childDataMsg), waitTime); - - } - - public OMElement excludeModifier(OMElement addChildElement) throws I2B2Exception { - - OMElement returnElement = null; - String ontologyDataResponse = null; - String unknownErrorMessage = "Error message delivered from the remote server \n" - + "You may wish to retry your last action"; - - if (addChildElement == null) { - log.error("Incoming Ontology request is null"); - ResponseMessageType responseMsgType = MessageFactory - .doBuildErrorResponse(null, unknownErrorMessage); - ontologyDataResponse = MessageFactory - .convertToXMLString(responseMsgType); - return MessageFactory - .createResponseOMElementFromString(ontologyDataResponse); - } - String requestElementString = addChildElement.toString(); - AddChildDataMessage childDataMsg = new AddChildDataMessage( - requestElementString); - long waitTime = 0; - if ((childDataMsg.getRequestMessageType() != null) && (childDataMsg.getRequestMessageType().getRequestHeader() != null)) { - waitTime = childDataMsg.getRequestMessageType() - .getRequestHeader().getResultWaittimeMs(); - } - - // do Ontology query processing inside thread, so that - // service could sends back message with timeout error. - // ExecutorRunnable er = new ExecutorRunnable(); - return execute(new ExcludeModifierHandler(childDataMsg), waitTime); - - } - - /** - * This function is main webservice interface to get vocab data for a query. - * It uses AXIOM elements(OMElement) to conveniently parse xml messages. - * - * It excepts incoming request in i2b2 message format, which wraps an - * Ontology query inside a vocab query request object. The response is also - * will be in i2b2 message format, which will wrap vocab data object. Vocab - * data object will have all the results returned by the query. - * - * - * @param OMElement - * getModifierNameInfoElement - * @return OMElement in i2b2message format - * @throws Exception - */ - public OMElement getModifierNameInfo(OMElement getNameInfoElement) - throws I2B2Exception { - OMElement returnElement = null; - String ontologyDataResponse = null; - String unknownErrorMessage = "Error message delivered from the remote server \n" - + "You may wish to retry your last action"; - - if (getNameInfoElement == null) { - log.error("Incoming Ontology request is null"); - ResponseMessageType responseMsgType = MessageFactory - .doBuildErrorResponse(null, unknownErrorMessage); - ontologyDataResponse = MessageFactory - .convertToXMLString(responseMsgType); - return MessageFactory - .createResponseOMElementFromString(ontologyDataResponse); - } - - String requestElementString = getNameInfoElement.toString(); - GetNameInfoDataMessage nameInfoDataMsg = new GetNameInfoDataMessage( - requestElementString); - - long waitTime = 0; - if ((nameInfoDataMsg.getRequestMessageType() != null) && (nameInfoDataMsg.getRequestMessageType().getRequestHeader() != null)) { - waitTime = nameInfoDataMsg.getRequestMessageType() - .getRequestHeader().getResultWaittimeMs(); - } - - // do Ontology query processing inside thread, so that - // service could sends back message with timeout error. - - // ExecutorRunnable er = new ExecutorRunnable(); - return execute(new GetModifierNameInfoHandler(nameInfoDataMsg), waitTime); - } - - /** - * This function is main webservice interface to get vocab data for a query. - * It uses AXIOM elements(OMElement) to conveniently parse xml messages. - * - * It excepts incoming request in i2b2 message format, which wraps an - * Ontology query inside a vocab query request object. The response is also - * will be in i2b2 message format, which will wrap vocab data object. Vocab - * data object will have all the results returned by the query. - * - * - * @param OMElement - * getModifierCodeInfoElement - * @return OMElement in i2b2message format - * @throws Exception - */ - public OMElement getModifierCodeInfo(OMElement getCodeInfoElement) - throws I2B2Exception { - OMElement returnElement = null; - String ontologyDataResponse = null; - String unknownErrorMessage = "Error message delivered from the remote server \n" - + "You may wish to retry your last action"; - - if (getCodeInfoElement == null) { - log.error("Incoming Ontology request is null"); - ResponseMessageType responseMsgType = MessageFactory - .doBuildErrorResponse(null, unknownErrorMessage); - ontologyDataResponse = MessageFactory - .convertToXMLString(responseMsgType); - return MessageFactory - .createResponseOMElementFromString(ontologyDataResponse); - } - - String requestElementString = getCodeInfoElement.toString(); - GetCodeInfoDataMessage codeInfoDataMsg = new GetCodeInfoDataMessage( - requestElementString); - - long waitTime = 0; - if ((codeInfoDataMsg.getRequestMessageType() != null) && (codeInfoDataMsg.getRequestMessageType().getRequestHeader() != null)) { - waitTime = codeInfoDataMsg.getRequestMessageType() - .getRequestHeader().getResultWaittimeMs(); - } - - // do Ontology query processing inside thread, so that - // service could sends back message with timeout error. - - // ExecutorRunnable er = new ExecutorRunnable(); - return execute(new GetModifierCodeInfoHandler(codeInfoDataMsg), waitTime); - } - - - - public OMElement loadMetadata(OMElement loadElement) throws I2B2Exception { - - OMElement returnElement = null; - String ontologyDataResponse = null; - String unknownErrorMessage = "Error message delivered from the remote server \n" - + "You may wish to retry your last action"; - - if (loadElement == null) { - log.error("Incoming Ontology request is null"); - ResponseMessageType responseMsgType = MessageFactory - .doBuildErrorResponse(null, unknownErrorMessage); - ontologyDataResponse = MessageFactory - .convertToXMLString(responseMsgType); - return MessageFactory - .createResponseOMElementFromString(ontologyDataResponse); - } - String requestElementString = loadElement.toString(); - - LoadDataMessage loadDataMsg = new LoadDataMessage( - requestElementString); - - log.info(loadDataMsg.getMetadataLoad().getTableName()); - long waitTime = 0; - if ((loadDataMsg.getRequestMessageType() != null) && (loadDataMsg.getRequestMessageType().getRequestHeader() != null)) { - waitTime = loadDataMsg.getRequestMessageType() - .getRequestHeader().getResultWaittimeMs(); - } - - // do Ontology query processing inside thread, so that - // service could sends back message with timeout error. - // ExecutorRunnable er = new ExecutorRunnable(); - if(loadDataMsg.getMetadataLoad().getTableName().equalsIgnoreCase("SCHEMES")) { - logesapi.info(requestElementString); - return execute(new LoadSchemesHandler(loadDataMsg), waitTime); - } - else if(loadDataMsg.getMetadataLoad().getTableName().equalsIgnoreCase("TABLE_ACCESS")) { - logesapi.info(requestElementString); - return execute(new LoadTableAccessHandler(loadDataMsg), waitTime); - } - else - return execute(new LoadMetadataHandler(loadDataMsg), waitTime); - - } - - - public OMElement checkForTableExistence(OMElement loadElement) throws I2B2Exception { - - OMElement returnElement = null; - String ontologyDataResponse = null; - String unknownErrorMessage = "Error message delivered from the remote server \n" - + "You may wish to retry your last action"; - - if (loadElement == null) { - log.error("Incoming Ontology request is null"); - ResponseMessageType responseMsgType = MessageFactory - .doBuildErrorResponse(null, unknownErrorMessage); - ontologyDataResponse = MessageFactory - .convertToXMLString(responseMsgType); - return MessageFactory - .createResponseOMElementFromString(ontologyDataResponse); - } - String requestElementString = loadElement.toString(); - - LoadDataMessage loadDataMsg = new LoadDataMessage( - requestElementString); - - log.info(loadDataMsg.getMetadataLoad().getTableName()); - long waitTime = 0; - if ((loadDataMsg.getRequestMessageType() != null) && (loadDataMsg.getRequestMessageType().getRequestHeader() != null)) { - waitTime = loadDataMsg.getRequestMessageType() - .getRequestHeader().getResultWaittimeMs(); - } - - // do Ontology query processing inside thread, so that - // service could sends back message with timeout error. - // ExecutorRunnable er = new ExecutorRunnable(); - - - return execute(new CheckMetadataTableHandler(loadDataMsg), waitTime); - - } - - /** swc20160515 - * This function is main webservice interface to get the I2B2HIVE.ONT_DB_LOOKUP data. - * It uses AXIOM elements(OMElement) to conveniently parse xml messages. - * - * It accepts incoming request, and returns a response, both in i2b2 message format. - * - * @param OMElement - * getAllDblookupsElement - * @return OMElement in i2b2message format - * @throws Exception - */ - public OMElement getAllDblookups(OMElement getAllDblookupsElement) throws I2B2Exception { - String ontologyDataResponse = null; - String unknownErrMsg = null; - if (null == getAllDblookupsElement) { - log.error("Incoming Ontology request is null"); - unknownErrMsg = "Error message delivered from the remote server.\nYou may wish to retry your last action"; - ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, unknownErrMsg); - ontologyDataResponse = MessageFactory.convertToXMLString(responseMsgType); - return MessageFactory.createResponseOMElementFromString(ontologyDataResponse); - } - String requestElementString = getAllDblookupsElement.toString(); - GetAllDblookupsDataMessage dblookupsDataMsg = new GetAllDblookupsDataMessage(requestElementString); - long waitTime = 0; - if ((null != dblookupsDataMsg.getRequestMessageType()) && (null != dblookupsDataMsg.getRequestMessageType().getRequestHeader())) { - waitTime = dblookupsDataMsg.getRequestMessageType().getRequestHeader().getResultWaittimeMs(); - } - // do processing inside thread, so that service could send back message with timeout error. - return execute(new GetAllDblookupsHandler(dblookupsDataMsg), waitTime); - } - - /** swc20160517 - * This function is main webservice interface to get specific I2B2HIVE.ONT_DB_LOOKUP data. - * It uses AXIOM elements(OMElement) to conveniently parse xml messages. - * - * It accepts incoming request, and returns a response, both in i2b2 message format. - * - * @param OMElement - * getDblookupElement - * @return OMElement in i2b2message format - * @throws Exception - */ - public OMElement getDblookup(OMElement getDblookupElement) throws I2B2Exception { - String ontologyDataResponse = null; - String unknownErrMsg = null; - if (null == getDblookupElement) { - log.error("Incoming Ontology request is null"); - unknownErrMsg = "Error message delivered from the remote server.\nYou may wish to retry your last action"; - ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, unknownErrMsg); - ontologyDataResponse = MessageFactory.convertToXMLString(responseMsgType); - return MessageFactory.createResponseOMElementFromString(ontologyDataResponse); - } - String requestElementString = getDblookupElement.toString(); - GetDblookupDataMessage dblookupDataMsg = new GetDblookupDataMessage(requestElementString); - long waitTime = 0; - if ((null != dblookupDataMsg.getRequestMessageType()) && (null != dblookupDataMsg.getRequestMessageType().getRequestHeader())) { - waitTime = dblookupDataMsg.getRequestMessageType().getRequestHeader().getResultWaittimeMs(); - } - // do processing inside thread, so that service could send back message with timeout error. - return execute(new GetDblookupHandler(dblookupDataMsg), waitTime); - } - - /** swc20160516 - * This function is main webservice interface to add a new entry to the I2B2HIVE.ONT_DB_LOOKUP data. - * It uses AXIOM elements(OMElement) to conveniently parse xml messages. - * - * It accepts incoming request, and returns a response, both in i2b2 message format. - * - * @param OMElement - * getAllDblookupsElement - * @return OMElement in i2b2message format - * @throws Exception - */ - public OMElement setDblookup(OMElement setDblookupElement) throws I2B2Exception { - // OMElement returnElement = null; - String ontologyDataResponse = null; - String unknownErrMsg = null; - if (null == setDblookupElement) { - log.error("Incoming Ontology request is null"); - unknownErrMsg = "Error message delivered from the remote server.\nYou may wish to retry your last action"; - ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, unknownErrMsg); - ontologyDataResponse = MessageFactory.convertToXMLString(responseMsgType); - return MessageFactory.createResponseOMElementFromString(ontologyDataResponse); - } - String requestElementString = setDblookupElement.toString(); - SetDblookupDataMessage dblookupDataMsg = new SetDblookupDataMessage(requestElementString); - long waitTime = 0; - if ((null != dblookupDataMsg.getRequestMessageType()) && (null != dblookupDataMsg.getRequestMessageType().getRequestHeader())) { - waitTime = dblookupDataMsg.getRequestMessageType().getRequestHeader().getResultWaittimeMs(); - } - // do processing inside thread, so that service could send back message with timeout error. - return execute(new SetDblookupHandler(dblookupDataMsg), waitTime); - } - - /** swc20160518 - * This function is main webservice interface to delete specific I2B2HIVE.ONT_DB_LOOKUP data. - * It uses AXIOM elements(OMElement) to conveniently parse xml messages. - * - * It accepts incoming request, and returns a response, both in i2b2 message format. - * - * @param OMElement - * deleteDblookupElement - * @return OMElement in i2b2message format - * @throws Exception - */ - public OMElement deleteDblookup(OMElement deleteDblookupElement) throws I2B2Exception { - String ontologyDataResponse = null; - String unknownErrMsg = null; - if (null == deleteDblookupElement) { - log.error("Incoming Ontology request is null"); - unknownErrMsg = "Error message delivered from the remote server.\nYou may wish to retry your last action"; - ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, unknownErrMsg); - ontologyDataResponse = MessageFactory.convertToXMLString(responseMsgType); - return MessageFactory.createResponseOMElementFromString(ontologyDataResponse); - } - String requestElementString = deleteDblookupElement.toString(); - DeleteDblookupDataMessage dblookupDataMsg = new DeleteDblookupDataMessage(requestElementString); - long waitTime = 0; - if ((null != dblookupDataMsg.getRequestMessageType()) && (null != dblookupDataMsg.getRequestMessageType().getRequestHeader())) { - waitTime = dblookupDataMsg.getRequestMessageType().getRequestHeader().getResultWaittimeMs(); - } - // do processing inside thread, so that service could send back message with timeout error. - return execute(new DeleteDblookupHandler(dblookupDataMsg), waitTime); - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Raj Kuttan + * Lori Phillips + */ +package edu.harvard.i2b2.ontology.ws; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; + +import javax.xml.stream.XMLStreamWriter; + +import org.apache.axiom.om.OMDataSource; +import org.apache.axiom.om.OMElement; +import org.apache.axiom.om.util.StAXUtils; +import org.apache.axis2.util.StreamWrapper; +import org.apache.commons.io.output.ByteArrayOutputStream; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.ontology.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.ontology.delegate.AddChildHandler; +import edu.harvard.i2b2.ontology.delegate.AddModifierHandler; +import edu.harvard.i2b2.ontology.delegate.CRCConceptUpdateHandler; +import edu.harvard.i2b2.ontology.delegate.DeleteChildHandler; +import edu.harvard.i2b2.ontology.delegate.DeleteDblookupHandler; +import edu.harvard.i2b2.ontology.delegate.ExcludeModifierHandler; +import edu.harvard.i2b2.ontology.delegate.GetAllDblookupsHandler; +import edu.harvard.i2b2.ontology.delegate.GetCategoriesHandler; +import edu.harvard.i2b2.ontology.delegate.GetChildrenHandler; +import edu.harvard.i2b2.ontology.delegate.GetCodeInfoHandler; +import edu.harvard.i2b2.ontology.delegate.GetDblookupHandler; +import edu.harvard.i2b2.ontology.delegate.GetDerivedFactColumnsHandler; +import edu.harvard.i2b2.ontology.delegate.GetDirtyStateHandler; +import edu.harvard.i2b2.ontology.delegate.GetModifierChildrenHandler; +import edu.harvard.i2b2.ontology.delegate.GetModifierCodeInfoHandler; +import edu.harvard.i2b2.ontology.delegate.GetModifierInfoHandler; +import edu.harvard.i2b2.ontology.delegate.GetModifierNameInfoHandler; +import edu.harvard.i2b2.ontology.delegate.GetModifiersHandler; +import edu.harvard.i2b2.ontology.delegate.GetNameInfoHandler; +import edu.harvard.i2b2.ontology.delegate.GetOntProcessStatusHandler; +import edu.harvard.i2b2.ontology.delegate.GetSchemesHandler; +import edu.harvard.i2b2.ontology.delegate.GetTermInfoHandler; +import edu.harvard.i2b2.ontology.delegate.ModifyChildHandler; +import edu.harvard.i2b2.ontology.delegate.CheckMetadataTableHandler; +import edu.harvard.i2b2.ontology.delegate.LoadMetadataHandler; +import edu.harvard.i2b2.ontology.delegate.LoadSchemesHandler; +import edu.harvard.i2b2.ontology.delegate.LoadTableAccessHandler; +import edu.harvard.i2b2.ontology.delegate.RequestHandler; +import edu.harvard.i2b2.ontology.delegate.SetDblookupHandler; +import edu.harvard.i2b2.ontology.delegate.UpdateTotalNumHandler; + +/** + * This is webservice skeleton class. It parses incoming Ontology service + * requests and generates responses in the Vocab Data Object XML format. + * + */ +public class OntologyService { + private static Log log = LogFactory.getLog(OntologyService.class); + protected static Log logesapi = LogFactory.getLog(OntologyService.class); + + /** + * This function is main webservice interface to get vocab data for a query. + * It uses AXIOM elements(OMElement) to conveniently parse xml messages. + * + * It excepts incoming request in i2b2 message format, which wraps an + * Ontology query inside a vocab query request object. The response is also + * will be in i2b2 message format, which will wrap vocab data object. Vocab + * data object will have all the results returned by the query. + * + * + * @param getChildren + * @return OMElement in i2b2message format + * @throws Exception + */ + public OMElement getChildren(OMElement getChildrenElement) + throws I2B2Exception { + + OMElement returnElement = null; + String ontologyDataResponse = null; + String unknownErrorMessage = "Error message delivered from the remote server \n" + + "You may wish to retry your last action"; + + if (getChildrenElement == null) { + log.error("Incoming Ontology request is null"); + ResponseMessageType responseMsgType = MessageFactory + .doBuildErrorResponse(null, unknownErrorMessage); + ontologyDataResponse = MessageFactory + .convertToXMLString(responseMsgType); + return MessageFactory + .createResponseOMElementFromString(ontologyDataResponse); + } + + String requestElementString = getChildrenElement.toString(); + + + GetChildrenDataMessage childrenDataMsg = new GetChildrenDataMessage( + requestElementString); + long waitTime = 0; + if ((childrenDataMsg.getRequestMessageType() != null) && (childrenDataMsg.getRequestMessageType().getRequestHeader() != null)) { + waitTime = childrenDataMsg.getRequestMessageType() + .getRequestHeader().getResultWaittimeMs(); + } + + // do Ontology query processing inside thread, so that + // service could sends back message with timeout error. + // ExecutorRunnable er = new ExecutorRunnable(); + return execute(new GetChildrenHandler(childrenDataMsg), waitTime); + + } + + /** + * This function is main webservice interface to get vocab data for a query. + * It uses AXIOM elements(OMElement) to conveniently parse xml messages. + * + * It excepts incoming request in i2b2 message format, which wraps an + * Ontology query inside a vocab query request object. The response is also + * will be in i2b2 message format, which will wrap vocab data object. Vocab + * data object will have all the results returned by the query. + * + * + * @param OMElement + * getCategoriesElement + * @return OMElement in i2b2message format + * @throws Exception + */ + public OMElement getCategories(OMElement getCategoriesElement) + throws I2B2Exception { + + OMElement returnElement = null; + String ontologyDataResponse = null; + String unknownErrorMessage = "Error message delivered from the remote server \n" + + "You may wish to retry your last action"; + + if (getCategoriesElement == null) { + log.error("Incoming Ontology request is null"); + ResponseMessageType responseMsgType = MessageFactory + .doBuildErrorResponse(null, unknownErrorMessage); + ontologyDataResponse = MessageFactory + .convertToXMLString(responseMsgType); + return MessageFactory + .createResponseOMElementFromString(ontologyDataResponse); + } + + String requestElementString = getCategoriesElement.toString(); + + + GetCategoriesDataMessage categoriesDataMsg = new GetCategoriesDataMessage( + requestElementString); + long waitTime = 0; + if ((categoriesDataMsg.getRequestMessageType() != null) && (categoriesDataMsg.getRequestMessageType().getRequestHeader() != null)) { + waitTime = categoriesDataMsg.getRequestMessageType() + .getRequestHeader().getResultWaittimeMs(); + } + + // do Ontology query processing inside thread, so that + // service could sends back message with timeout error. + // ExecutorRunnable er = new ExecutorRunnable(); + return execute(new GetCategoriesHandler(categoriesDataMsg), waitTime); + } + + /** + * This function is main webservice interface to get vocab data for a query. + * It uses AXIOM elements(OMElement) to conveniently parse xml messages. + * + * It excepts incoming request in i2b2 message format, which wraps an + * Ontology query inside a vocab query request object. The response is also + * will be in i2b2 message format, which will wrap vocab data object. Vocab + * data object will have all the results returned by the query. + * + * + * @param OMElement + * geSchemesElement + * @return OMElement in i2b2message format + * @throws Exception + */ + public OMElement getSchemes(OMElement getSchemesElement) + throws I2B2Exception { + OMElement returnElement = null; + String ontologyDataResponse = null; + String unknownErrorMessage = "Error message delivered from the remote server \n" + + "You may wish to retry your last action"; + + if (getSchemesElement == null) { + log.error("Incoming Ontology request is null"); + ResponseMessageType responseMsgType = MessageFactory + .doBuildErrorResponse(null, unknownErrorMessage); + ontologyDataResponse = MessageFactory + .convertToXMLString(responseMsgType); + return MessageFactory + .createResponseOMElementFromString(ontologyDataResponse); + } + + // (OMSourcedElement) getSchemesElement + // OMSourcedElement aa = ((OMSourcedElement) getSchemesElement).getDataSource(); + // JSONBadgerfishDataSource jsonDataSource = (JSONBadgerfishDataSource) ((OMSourcedElement) getSchemesElement).getDataSource(); + // String jsonString = jsonDataSource.toString(); //.getCompleteJOSNString(); // this will return json string + + // if (element instanceof OMSourcedElementImpl && getStringToWrite(((OMSourcedElementImpl) + // element).getDataSource()) != null) { + + + + + String requestElementString = getSchemesElement.toString(); + GetSchemesDataMessage schemesDataMsg = new GetSchemesDataMessage( + requestElementString); + + long waitTime = 0; + if ((schemesDataMsg.getRequestMessageType() != null) && (schemesDataMsg.getRequestMessageType().getRequestHeader() != null)) { + waitTime = schemesDataMsg.getRequestMessageType() + .getRequestHeader().getResultWaittimeMs(); + } + + // do Ontology query processing inside thread, so that + // service could sends back message with timeout error. + // ExecutorRunnable er = new ExecutorRunnable(); + return execute(new GetSchemesHandler(schemesDataMsg), waitTime); + } + + /** + * This function is main webservice interface to get vocab data for a query. + * It uses AXIOM elements(OMElement) to conveniently parse xml messages. + * + * It excepts incoming request in i2b2 message format, which wraps an + * Ontology query inside a vocab query request object. The response is also + * will be in i2b2 message format, which will wrap vocab data object. Vocab + * data object will have all the results returned by the query. + * + * + * @param OMElement + * getCodeInfoElement + * @return OMElement in i2b2message format + * @throws Exception + */ + public OMElement getCodeInfo(OMElement getCodeInfoElement) + throws I2B2Exception { + OMElement returnElement = null; + String ontologyDataResponse = null; + String unknownErrorMessage = "Error message delivered from the remote server \n" + + "You may wish to retry your last action"; + + if (getCodeInfoElement == null) { + log.error("Incoming Ontology request is null"); + ResponseMessageType responseMsgType = MessageFactory + .doBuildErrorResponse(null, unknownErrorMessage); + ontologyDataResponse = MessageFactory + .convertToXMLString(responseMsgType); + return MessageFactory + .createResponseOMElementFromString(ontologyDataResponse); + } + + String requestElementString = getCodeInfoElement.toString(); + GetCodeInfoDataMessage codeInfoDataMsg = new GetCodeInfoDataMessage( + requestElementString); + + long waitTime = 0; + if ((codeInfoDataMsg.getRequestMessageType() != null) && (codeInfoDataMsg.getRequestMessageType().getRequestHeader() != null)) { + waitTime = codeInfoDataMsg.getRequestMessageType() + .getRequestHeader().getResultWaittimeMs(); + } + + // do Ontology query processing inside thread, so that + // service could sends back message with timeout error. + + // ExecutorRunnable er = new ExecutorRunnable(); + return execute(new GetCodeInfoHandler(codeInfoDataMsg), waitTime); + } + + /** + * This function is main webservice interface to get vocab data for a query. + * It uses AXIOM elements(OMElement) to conveniently parse xml messages. + * + * It excepts incoming request in i2b2 message format, which wraps an + * Ontology query inside a vocab query request object. The response is also + * will be in i2b2 message format, which will wrap vocab data object. Vocab + * data object will have all the results returned by the query. + * + * + * @param OMElement + * getCodeInfoElement + * @return OMElement in i2b2message format + * @throws Exception + */ + public OMElement getNameInfo(OMElement getNameInfoElement) + throws I2B2Exception { + OMElement returnElement = null; + String ontologyDataResponse = null; + String unknownErrorMessage = "Error message delivered from the remote server \n" + + "You may wish to retry your last action"; + + if (getNameInfoElement == null) { + log.error("Incoming Ontology request is null"); + ResponseMessageType responseMsgType = MessageFactory + .doBuildErrorResponse(null, unknownErrorMessage); + ontologyDataResponse = MessageFactory + .convertToXMLString(responseMsgType); + return MessageFactory + .createResponseOMElementFromString(ontologyDataResponse); + } + + String requestElementString = getNameInfoElement.toString(); + + + GetNameInfoDataMessage nameInfoDataMsg = new GetNameInfoDataMessage( + requestElementString); + + long waitTime = 0; + if ((nameInfoDataMsg.getRequestMessageType() != null) && (nameInfoDataMsg.getRequestMessageType().getRequestHeader() != null)) { + waitTime = nameInfoDataMsg.getRequestMessageType() + .getRequestHeader().getResultWaittimeMs(); + } + + // do Ontology query processing inside thread, so that + // service could sends back message with timeout error. + + // ExecutorRunnable er = new ExecutorRunnable(); + return execute(new GetNameInfoHandler(nameInfoDataMsg), waitTime); + } + + /** + * This function is main webservice interface to get vocab data for a query. + * It uses AXIOM elements(OMElement) to conveniently parse xml messages. + * + * It excepts incoming request in i2b2 message format, which wraps an + * Ontology query inside a vocab query request object. The response is also + * will be in i2b2 message format, which will wrap vocab data object. Vocab + * data object will have all the results returned by the query. + * + * + * @param getTermInfo + * @return OMElement in i2b2message format + * @throws Exception + */ + public OMElement getTermInfo(OMElement getTermInfoElement) + throws I2B2Exception { + + OMElement returnElement = null; + String ontologyDataResponse = null; + String unknownErrorMessage = "Error message delivered from the remote server \n" + + "You may wish to retry your last action"; + + if (getTermInfoElement == null) { + log.error("Incoming Ontology request is null"); + ResponseMessageType responseMsgType = MessageFactory + .doBuildErrorResponse(null, unknownErrorMessage); + ontologyDataResponse = MessageFactory + .convertToXMLString(responseMsgType); + return MessageFactory + .createResponseOMElementFromString(ontologyDataResponse); + + } + + String requestElementString = getTermInfoElement.toString(); + GetTermInfoDataMessage termInfoDataMsg = new GetTermInfoDataMessage( + requestElementString); + + long waitTime = 0; + if ((termInfoDataMsg.getRequestMessageType() != null) && (termInfoDataMsg.getRequestMessageType().getRequestHeader() != null)) { + waitTime = termInfoDataMsg.getRequestMessageType() + .getRequestHeader().getResultWaittimeMs(); + } + + // do Ontology query processing inside thread, so that + // service could sends back message with timeout error. + + // ExecutorRunnable er = new ExecutorRunnable(); + return execute(new GetTermInfoHandler(termInfoDataMsg), waitTime); + } + + /** + * This function is main webservice interface to get vocab data for a query. + * It uses AXIOM elements(OMElement) to conveniently parse xml messages. + * + * It excepts incoming request in i2b2 message format, which wraps an + * Ontology query inside a vocab query request object. The response is also + * will be in i2b2 message format, which will wrap vocab data object. Vocab + * data object will have all the results returned by the query. + * + * + * @param getDerivedFactColumns + * @return OMElement in i2b2message format + * @throws Exception + */ + public OMElement getDerivedFactColumns(OMElement getDerivedFactColumnsElement) + throws I2B2Exception { + + OMElement returnElement = null; + String ontologyDataResponse = null; + String unknownErrorMessage = "Error message delivered from the remote server \n" + + "You may wish to retry your last action"; + + if (getDerivedFactColumnsElement == null) { + log.error("Incoming Ontology request is null"); + ResponseMessageType responseMsgType = MessageFactory + .doBuildErrorResponse(null, unknownErrorMessage); + ontologyDataResponse = MessageFactory + .convertToXMLString(responseMsgType); + return MessageFactory + .createResponseOMElementFromString(ontologyDataResponse); + + } + + String requestElementString = getDerivedFactColumnsElement.toString(); + logesapi.debug("ONT derivedFactCol request " + requestElementString); + GetTermInfoDataMessage dataMsg = new GetTermInfoDataMessage( + requestElementString); + + long waitTime = 0; + if ((dataMsg.getRequestMessageType() != null) && (dataMsg.getRequestMessageType().getRequestHeader() != null)) { + waitTime = dataMsg.getRequestMessageType() + .getRequestHeader().getResultWaittimeMs(); + } + + // do Ontology query processing inside thread, so that + // service could sends back message with timeout error. + + // ExecutorRunnable er = new ExecutorRunnable(); + return execute(new GetDerivedFactColumnsHandler(dataMsg), waitTime); + } + + + + private OMElement execute(RequestHandler handler, long waitTime) + throws I2B2Exception { + // do Ontology query processing inside thread, so that + // service could sends back message with timeout error. + OMElement returnElement = null; + + String unknownErrorMessage = "Error message delivered from the remote server \n" + + "You may wish to retry your last action"; + + ExecutorRunnable er = new ExecutorRunnable(); + + er.setRequestHandler(handler); + + Thread t = new Thread(er); + String ontologyDataResponse = null; + + synchronized (t) { + t.start(); + + // try { + // if (waitTime > 0) { + // t.wait(waitTime); + // } else { + // t.wait(); + // } + + try { + long startTime = System.currentTimeMillis(); + long deltaTime = -1; + while ((er.isJobCompleteFlag() == false) + && (deltaTime < waitTime)) { + if (waitTime > 0) { + t.wait(waitTime - deltaTime); + deltaTime = System.currentTimeMillis() - startTime; + } else { + t.wait(); + } + } + + ontologyDataResponse = er.getOutputString(); + + if (ontologyDataResponse == null) { + if (er.getJobException() != null) { + log.error("er.jobException is " + + er.getJobException().getMessage()); + + log.info("waitTime is " + waitTime); + + ResponseMessageType responseMsgType = MessageFactory + .doBuildErrorResponse(null, unknownErrorMessage); + ontologyDataResponse = MessageFactory + .convertToXMLString(responseMsgType); + + } else if (er.isJobCompleteFlag() == false) { + // 5000 + String timeOuterror = "Remote server timed out \n" + + "Result waittime = " + waitTime + + " ms elapsed,\nPlease try again"; + log.error(timeOuterror); + + log.debug("ontology waited " + deltaTime + "ms for " + + er.getRequestHandler().getClass().getName()); + + ResponseMessageType responseMsgType = MessageFactory + .doBuildErrorResponse(null, timeOuterror); + ontologyDataResponse = MessageFactory + .convertToXMLString(responseMsgType); + + } else { + log.error("ontology data response is null"); + log.info("waitTime is " + waitTime); + log.debug("ontology waited " + deltaTime + "ms for " + + er.getRequestHandler().getClass().getName()); + ResponseMessageType responseMsgType = MessageFactory + .doBuildErrorResponse(null, unknownErrorMessage); + ontologyDataResponse = MessageFactory + .convertToXMLString(responseMsgType); + } + } + } catch (InterruptedException e) { + log.error(e.getMessage()); + throw new I2B2Exception( + "Thread error while running Ontology job "); + } finally { + t.interrupt(); + er = null; + t = null; + } + } + returnElement = MessageFactory + .createResponseOMElementFromString(ontologyDataResponse); + + return returnElement; + } + + public OMElement addChild(OMElement addChildElement) throws I2B2Exception { + + OMElement returnElement = null; + String ontologyDataResponse = null; + String unknownErrorMessage = "Error message delivered from the remote server \n" + + "You may wish to retry your last action"; + + if (addChildElement == null) { + log.error("Incoming Ontology request is null"); + ResponseMessageType responseMsgType = MessageFactory + .doBuildErrorResponse(null, unknownErrorMessage); + ontologyDataResponse = MessageFactory + .convertToXMLString(responseMsgType); + return MessageFactory + .createResponseOMElementFromString(ontologyDataResponse); + } + String requestElementString = addChildElement.toString(); + AddChildDataMessage childDataMsg = new AddChildDataMessage( + requestElementString); + long waitTime = 0; + if ((childDataMsg.getRequestMessageType() != null) && (childDataMsg.getRequestMessageType().getRequestHeader() != null)) { + waitTime = childDataMsg.getRequestMessageType() + .getRequestHeader().getResultWaittimeMs(); + } + + // do Ontology query processing inside thread, so that + // service could sends back message with timeout error. + // ExecutorRunnable er = new ExecutorRunnable(); + return execute(new AddChildHandler(childDataMsg), waitTime); + + } + + public OMElement modifyChild(OMElement modifyChildElement) throws I2B2Exception { + + OMElement returnElement = null; + String ontologyDataResponse = null; + String unknownErrorMessage = "Error message delivered from the remote server \n" + + "You may wish to retry your last action"; + + if (modifyChildElement == null) { + log.error("Incoming Ontology request is null"); + ResponseMessageType responseMsgType = MessageFactory + .doBuildErrorResponse(null, unknownErrorMessage); + ontologyDataResponse = MessageFactory + .convertToXMLString(responseMsgType); + return MessageFactory + .createResponseOMElementFromString(ontologyDataResponse); + } + String requestElementString = modifyChildElement.toString(); + logesapi.debug(requestElementString); + ModifyChildDataMessage childDataMsg = new ModifyChildDataMessage( + requestElementString); + long waitTime = 0; + if ((childDataMsg.getRequestMessageType() != null) && (childDataMsg.getRequestMessageType().getRequestHeader() != null)) { + waitTime = childDataMsg.getRequestMessageType() + .getRequestHeader().getResultWaittimeMs(); + } + + // do Ontology query processing inside thread, so that + // service could sends back message with timeout error. + // ExecutorRunnable er = new ExecutorRunnable(); + return execute(new ModifyChildHandler(childDataMsg), waitTime); + + } + + public OMElement deleteChild(OMElement deleteNodeElement) throws Exception { + OMElement returnElement = null; + String ontologyDataResponse = null; + String unknownErrorMessage = "Error message delivered from the remote server \n" + + "You may wish to retry your last action"; + + if (deleteNodeElement == null) { + log.error("Incoming Ontology request is null"); + + ResponseMessageType responseMsgType = MessageFactory + .doBuildErrorResponse(null, unknownErrorMessage); + ontologyDataResponse = MessageFactory + .convertToXMLString(responseMsgType); + return MessageFactory + .createResponseOMElementFromString(ontologyDataResponse); + } + + String requestElementString = deleteNodeElement.toString(); + DeleteChildDataMessage deleteDataMsg = new DeleteChildDataMessage( + requestElementString); + // log.info(requestElementString); + // deleteDataMsg.setRequestMessageType(requestElementString); + + long waitTime = 0; + if ((deleteDataMsg.getRequestMessageType() != null) && (deleteDataMsg.getRequestMessageType().getRequestHeader() != null)) { + waitTime = deleteDataMsg.getRequestMessageType() + .getRequestHeader().getResultWaittimeMs(); + } + + // do Workplace query processing inside thread, so that + // service could send back message with timeout error. + // ExecutorRunnable er = new ExecutorRunnable(); + return execute(new DeleteChildHandler(deleteDataMsg), waitTime); + + } + + public OMElement updateCRCConcept(OMElement updateCRCConceptElement) + throws I2B2Exception { + + OMElement returnElement = null; + String ontologyDataResponse = null; + String unknownErrorMessage = "Error message delivered from the remote server \n" + + "You may wish to retry your last action"; + + if (updateCRCConceptElement == null) { + log.error("Incoming Ontology request is null"); + ResponseMessageType responseMsgType = MessageFactory + .doBuildErrorResponse(null, unknownErrorMessage); + ontologyDataResponse = MessageFactory + .convertToXMLString(responseMsgType); + return MessageFactory + .createResponseOMElementFromString(ontologyDataResponse); + } + String requestElementString = updateCRCConceptElement.toString(); + CRCUpdateConceptMessage childDataMsg = new CRCUpdateConceptMessage( + requestElementString); + long waitTime = 0; + if ((childDataMsg.getRequestMessageType() != null) && (childDataMsg.getRequestMessageType().getRequestHeader() != null)) { + waitTime = childDataMsg.getRequestMessageType() + .getRequestHeader().getResultWaittimeMs(); + } + + // do Ontology query processing inside thread, so that + // service could sends back message with timeout error. + // ExecutorRunnable er = new ExecutorRunnable(); + return execute(new CRCConceptUpdateHandler(childDataMsg), waitTime); + + } + + public OMElement updateConceptTotalNum(OMElement updateConceptTotalNumElement) + throws I2B2Exception { + + OMElement returnElement = null; + String ontologyDataResponse = null; + String unknownErrorMessage = "Error message delivered from the remote server \n" + + "You may wish to retry your last action"; + + if (updateConceptTotalNumElement == null) { + log.error("Incoming Ontology request is null"); + ResponseMessageType responseMsgType = MessageFactory + .doBuildErrorResponse(null, unknownErrorMessage); + ontologyDataResponse = MessageFactory + .convertToXMLString(responseMsgType); + return MessageFactory + .createResponseOMElementFromString(ontologyDataResponse); + } + String requestElementString = updateConceptTotalNumElement.toString(); + UpdateTotalNumMessage childDataMsg = new UpdateTotalNumMessage( + requestElementString); + long waitTime = 0; + if ((childDataMsg.getRequestMessageType() != null) && (childDataMsg.getRequestMessageType().getRequestHeader() != null)) { + waitTime = childDataMsg.getRequestMessageType() + .getRequestHeader().getResultWaittimeMs(); + } + + // do Ontology query processing inside thread, so that + // service could sends back message with timeout error. + // ExecutorRunnable er = new ExecutorRunnable(); + return execute(new UpdateTotalNumHandler(childDataMsg), waitTime); + + } + + public OMElement getProcessStatus(OMElement getOntProcessStatus) + throws I2B2Exception { + + OMElement returnElement = null; + String ontologyDataResponse = null; + String unknownErrorMessage = "Error message delivered from the remote server \n" + + "You may wish to retry your last action"; + + if (getOntProcessStatus == null) { + log.error("Incoming Ontology request is null"); + ResponseMessageType responseMsgType = MessageFactory + .doBuildErrorResponse(null, unknownErrorMessage); + ontologyDataResponse = MessageFactory + .convertToXMLString(responseMsgType); + return MessageFactory + .createResponseOMElementFromString(ontologyDataResponse); + } + String requestElementString = getOntProcessStatus.toString(); + GetOntProcessStatusMessage childDataMsg = new GetOntProcessStatusMessage( + requestElementString); + long waitTime = 0; + if ((childDataMsg.getRequestMessageType() != null) && (childDataMsg.getRequestMessageType().getRequestHeader() != null)) { + waitTime = childDataMsg.getRequestMessageType() + .getRequestHeader().getResultWaittimeMs(); + } + + // do Ontology query processing inside thread, so that + // service could sends back message with timeout error. + // ExecutorRunnable er = new ExecutorRunnable(); + return execute(new GetOntProcessStatusHandler(childDataMsg), waitTime); + + } + + /** + * This function is main webservice interface to get vocab data for a query. + * It uses AXIOM elements(OMElement) to conveniently parse xml messages. + * + * It excepts incoming request in i2b2 message format, which wraps an + * Ontology query inside a vocab query request object. The response is also + * will be in i2b2 message format, which will wrap vocab data object. Vocab + * data object will have all the results returned by the query. + * + * + * @param OMElement + * getDirtyStateElement + * @return OMElement in i2b2message format + * @throws Exception + */ + public OMElement getDirtyState(OMElement getDirtyStateElement) + throws I2B2Exception { + OMElement returnElement = null; + String ontologyDataResponse = null; + String unknownErrorMessage = "Error message delivered from the remote server \n" + + "You may wish to retry your last action"; + + if (getDirtyStateElement == null) { + log.error("Incoming Ontology request is null"); + ResponseMessageType responseMsgType = MessageFactory + .doBuildErrorResponse(null, unknownErrorMessage); + ontologyDataResponse = MessageFactory + .convertToXMLString(responseMsgType); + return MessageFactory + .createResponseOMElementFromString(ontologyDataResponse); + } + + String requestElementString = getDirtyStateElement.toString(); + GetDirtyStateDataMessage dirtyStateDataMsg = new GetDirtyStateDataMessage( + requestElementString); + + long waitTime = 0; + if ((dirtyStateDataMsg.getRequestMessageType() != null) && (dirtyStateDataMsg.getRequestMessageType().getRequestHeader() != null)) { + waitTime = dirtyStateDataMsg.getRequestMessageType() + .getRequestHeader().getResultWaittimeMs(); + } + + // do Ontology query processing inside thread, so that + // service could sends back message with timeout error. + // ExecutorRunnable er = new ExecutorRunnable(); + return execute(new GetDirtyStateHandler(dirtyStateDataMsg), waitTime); + } + + /** + * This function is main webservice interface to get modifier data for a query. + * It uses AXIOM elements(OMElement) to conveniently parse xml messages. + * + * It excepts incoming request in i2b2 message format, which wraps an + * Ontology query inside a modifier query request object. The response is also + * will be in i2b2 message format, which will wrap modifier data object. Modifier + * data object will have all the results returned by the query. + * + * + * @param getModifiers + * @return OMElement in i2b2message format + * @throws Exception + */ + public OMElement getModifiers(OMElement getModifiersElement) + throws I2B2Exception { + + OMElement returnElement = null; + String ontologyDataResponse = null; + String unknownErrorMessage = "Error message delivered from the remote server \n" + + "You may wish to retry your last action"; + + if (getModifiersElement == null) { + log.error("Incoming Ontology request is null"); + ResponseMessageType responseMsgType = MessageFactory + .doBuildErrorResponse(null, unknownErrorMessage); + ontologyDataResponse = MessageFactory + .convertToXMLString(responseMsgType); + return MessageFactory + .createResponseOMElementFromString(ontologyDataResponse); + } + String requestElementString = getModifiersElement.toString(); + GetModifiersDataMessage modifiersDataMsg = new GetModifiersDataMessage( + requestElementString); + long waitTime = 0; + if ((modifiersDataMsg.getRequestMessageType() != null) && (modifiersDataMsg.getRequestMessageType().getRequestHeader() != null)) { + waitTime = modifiersDataMsg.getRequestMessageType() + .getRequestHeader().getResultWaittimeMs(); + } + + // do Ontology query processing inside thread, so that + // service could sends back message with timeout error. + // ExecutorRunnable er = new ExecutorRunnable(); + return execute(new GetModifiersHandler(modifiersDataMsg), waitTime); + + } + /** + * This function is main webservice interface to get modifier data for a query. + * It uses AXIOM elements(OMElement) to conveniently parse xml messages. + * + * It excepts incoming request in i2b2 message format, which wraps an + * Ontology query inside a modifier query request object. The response is also + * will be in i2b2 message format, which will wrap modifier data object. Modifier + * data object will have all the results returned by the query. + * + * + * @param getModifierInfo + * @return OMElement in i2b2message format + * @throws Exception + */ + public OMElement getModifierInfo(OMElement getModifierInfoElement) + throws I2B2Exception { + + OMElement returnElement = null; + String ontologyDataResponse = null; + String unknownErrorMessage = "Error message delivered from the remote server \n" + + "You may wish to retry your last action"; + + if (getModifierInfoElement == null) { + log.error("Incoming Ontology request is null"); + ResponseMessageType responseMsgType = MessageFactory + .doBuildErrorResponse(null, unknownErrorMessage); + ontologyDataResponse = MessageFactory + .convertToXMLString(responseMsgType); + return MessageFactory + .createResponseOMElementFromString(ontologyDataResponse); + } + String requestElementString = getModifierInfoElement.toString(); + GetModifierInfoDataMessage modifierInfoDataMsg = new GetModifierInfoDataMessage( + requestElementString); + long waitTime = 0; + if ((modifierInfoDataMsg.getRequestMessageType() != null) && (modifierInfoDataMsg.getRequestMessageType().getRequestHeader() != null)) { + waitTime = modifierInfoDataMsg.getRequestMessageType() + .getRequestHeader().getResultWaittimeMs(); + } + + // do Ontology query processing inside thread, so that + // service could sends back message with timeout error. + // ExecutorRunnable er = new ExecutorRunnable(); + return execute(new GetModifierInfoHandler(modifierInfoDataMsg), waitTime); + + } + + /** + * This function is main webservice interface to get modifier data for a query. + * It uses AXIOM elements(OMElement) to conveniently parse xml messages. + * + * It excepts incoming request in i2b2 message format, which wraps an + * Ontology query inside a modifier query request object. The response is also + * will be in i2b2 message format, which will wrap modifier data object. Modifier + * data object will have all the results returned by the query. + * + * + * @param getModifierInfo + * @return OMElement in i2b2message format + * @throws Exception + */ + public OMElement getModifierChildren(OMElement getModifierChildrenElement) + throws I2B2Exception { + + OMElement returnElement = null; + String ontologyDataResponse = null; + String unknownErrorMessage = "Error message delivered from the remote server \n" + + "You may wish to retry your last action"; + + if (getModifierChildrenElement == null) { + log.error("Incoming Ontology request is null"); + ResponseMessageType responseMsgType = MessageFactory + .doBuildErrorResponse(null, unknownErrorMessage); + ontologyDataResponse = MessageFactory + .convertToXMLString(responseMsgType); + return MessageFactory + .createResponseOMElementFromString(ontologyDataResponse); + } + String requestElementString = getModifierChildrenElement.toString(); + GetModifierChildrenDataMessage modifierChildrenDataMsg = new GetModifierChildrenDataMessage( + requestElementString); + long waitTime = 0; + if ((modifierChildrenDataMsg.getRequestMessageType() != null) && (modifierChildrenDataMsg.getRequestMessageType().getRequestHeader() != null)) { + waitTime = modifierChildrenDataMsg.getRequestMessageType() + .getRequestHeader().getResultWaittimeMs(); + } + + // do Ontology query processing inside thread, so that + // service could sends back message with timeout error. + // ExecutorRunnable er = new ExecutorRunnable(); + return execute(new GetModifierChildrenHandler(modifierChildrenDataMsg), waitTime); + + } + + public OMElement addModifier(OMElement addChildElement) throws I2B2Exception { + + OMElement returnElement = null; + String ontologyDataResponse = null; + String unknownErrorMessage = "Error message delivered from the remote server \n" + + "You may wish to retry your last action"; + + if (addChildElement == null) { + log.error("Incoming Ontology request is null"); + ResponseMessageType responseMsgType = MessageFactory + .doBuildErrorResponse(null, unknownErrorMessage); + ontologyDataResponse = MessageFactory + .convertToXMLString(responseMsgType); + return MessageFactory + .createResponseOMElementFromString(ontologyDataResponse); + } + String requestElementString = addChildElement.toString(); + AddChildDataMessage childDataMsg = new AddChildDataMessage( + requestElementString); + long waitTime = 0; + if ((childDataMsg.getRequestMessageType() != null) && (childDataMsg.getRequestMessageType().getRequestHeader() != null)) { + waitTime = childDataMsg.getRequestMessageType() + .getRequestHeader().getResultWaittimeMs(); + } + + // do Ontology query processing inside thread, so that + // service could sends back message with timeout error. + // ExecutorRunnable er = new ExecutorRunnable(); + return execute(new AddModifierHandler(childDataMsg), waitTime); + + } + + public OMElement excludeModifier(OMElement addChildElement) throws I2B2Exception { + + OMElement returnElement = null; + String ontologyDataResponse = null; + String unknownErrorMessage = "Error message delivered from the remote server \n" + + "You may wish to retry your last action"; + + if (addChildElement == null) { + log.error("Incoming Ontology request is null"); + ResponseMessageType responseMsgType = MessageFactory + .doBuildErrorResponse(null, unknownErrorMessage); + ontologyDataResponse = MessageFactory + .convertToXMLString(responseMsgType); + return MessageFactory + .createResponseOMElementFromString(ontologyDataResponse); + } + String requestElementString = addChildElement.toString(); + AddChildDataMessage childDataMsg = new AddChildDataMessage( + requestElementString); + long waitTime = 0; + if ((childDataMsg.getRequestMessageType() != null) && (childDataMsg.getRequestMessageType().getRequestHeader() != null)) { + waitTime = childDataMsg.getRequestMessageType() + .getRequestHeader().getResultWaittimeMs(); + } + + // do Ontology query processing inside thread, so that + // service could sends back message with timeout error. + // ExecutorRunnable er = new ExecutorRunnable(); + return execute(new ExcludeModifierHandler(childDataMsg), waitTime); + + } + + /** + * This function is main webservice interface to get vocab data for a query. + * It uses AXIOM elements(OMElement) to conveniently parse xml messages. + * + * It excepts incoming request in i2b2 message format, which wraps an + * Ontology query inside a vocab query request object. The response is also + * will be in i2b2 message format, which will wrap vocab data object. Vocab + * data object will have all the results returned by the query. + * + * + * @param OMElement + * getModifierNameInfoElement + * @return OMElement in i2b2message format + * @throws Exception + */ + public OMElement getModifierNameInfo(OMElement getNameInfoElement) + throws I2B2Exception { + OMElement returnElement = null; + String ontologyDataResponse = null; + String unknownErrorMessage = "Error message delivered from the remote server \n" + + "You may wish to retry your last action"; + + if (getNameInfoElement == null) { + log.error("Incoming Ontology request is null"); + ResponseMessageType responseMsgType = MessageFactory + .doBuildErrorResponse(null, unknownErrorMessage); + ontologyDataResponse = MessageFactory + .convertToXMLString(responseMsgType); + return MessageFactory + .createResponseOMElementFromString(ontologyDataResponse); + } + + String requestElementString = getNameInfoElement.toString(); + GetNameInfoDataMessage nameInfoDataMsg = new GetNameInfoDataMessage( + requestElementString); + + long waitTime = 0; + if ((nameInfoDataMsg.getRequestMessageType() != null) && (nameInfoDataMsg.getRequestMessageType().getRequestHeader() != null)) { + waitTime = nameInfoDataMsg.getRequestMessageType() + .getRequestHeader().getResultWaittimeMs(); + } + + // do Ontology query processing inside thread, so that + // service could sends back message with timeout error. + + // ExecutorRunnable er = new ExecutorRunnable(); + return execute(new GetModifierNameInfoHandler(nameInfoDataMsg), waitTime); + } + + /** + * This function is main webservice interface to get vocab data for a query. + * It uses AXIOM elements(OMElement) to conveniently parse xml messages. + * + * It excepts incoming request in i2b2 message format, which wraps an + * Ontology query inside a vocab query request object. The response is also + * will be in i2b2 message format, which will wrap vocab data object. Vocab + * data object will have all the results returned by the query. + * + * + * @param OMElement + * getModifierCodeInfoElement + * @return OMElement in i2b2message format + * @throws Exception + */ + public OMElement getModifierCodeInfo(OMElement getCodeInfoElement) + throws I2B2Exception { + OMElement returnElement = null; + String ontologyDataResponse = null; + String unknownErrorMessage = "Error message delivered from the remote server \n" + + "You may wish to retry your last action"; + + if (getCodeInfoElement == null) { + log.error("Incoming Ontology request is null"); + ResponseMessageType responseMsgType = MessageFactory + .doBuildErrorResponse(null, unknownErrorMessage); + ontologyDataResponse = MessageFactory + .convertToXMLString(responseMsgType); + return MessageFactory + .createResponseOMElementFromString(ontologyDataResponse); + } + + String requestElementString = getCodeInfoElement.toString(); + GetCodeInfoDataMessage codeInfoDataMsg = new GetCodeInfoDataMessage( + requestElementString); + + long waitTime = 0; + if ((codeInfoDataMsg.getRequestMessageType() != null) && (codeInfoDataMsg.getRequestMessageType().getRequestHeader() != null)) { + waitTime = codeInfoDataMsg.getRequestMessageType() + .getRequestHeader().getResultWaittimeMs(); + } + + // do Ontology query processing inside thread, so that + // service could sends back message with timeout error. + + // ExecutorRunnable er = new ExecutorRunnable(); + return execute(new GetModifierCodeInfoHandler(codeInfoDataMsg), waitTime); + } + + + + public OMElement loadMetadata(OMElement loadElement) throws I2B2Exception { + + OMElement returnElement = null; + String ontologyDataResponse = null; + String unknownErrorMessage = "Error message delivered from the remote server \n" + + "You may wish to retry your last action"; + + if (loadElement == null) { + log.error("Incoming Ontology request is null"); + ResponseMessageType responseMsgType = MessageFactory + .doBuildErrorResponse(null, unknownErrorMessage); + ontologyDataResponse = MessageFactory + .convertToXMLString(responseMsgType); + return MessageFactory + .createResponseOMElementFromString(ontologyDataResponse); + } + String requestElementString = loadElement.toString(); + + LoadDataMessage loadDataMsg = new LoadDataMessage( + requestElementString); + + log.info(loadDataMsg.getMetadataLoad().getTableName()); + long waitTime = 0; + if ((loadDataMsg.getRequestMessageType() != null) && (loadDataMsg.getRequestMessageType().getRequestHeader() != null)) { + waitTime = loadDataMsg.getRequestMessageType() + .getRequestHeader().getResultWaittimeMs(); + } + + // do Ontology query processing inside thread, so that + // service could sends back message with timeout error. + // ExecutorRunnable er = new ExecutorRunnable(); + if(loadDataMsg.getMetadataLoad().getTableName().equalsIgnoreCase("SCHEMES")) { + logesapi.info(requestElementString); + return execute(new LoadSchemesHandler(loadDataMsg), waitTime); + } + else if(loadDataMsg.getMetadataLoad().getTableName().equalsIgnoreCase("TABLE_ACCESS")) { + logesapi.info(requestElementString); + return execute(new LoadTableAccessHandler(loadDataMsg), waitTime); + } + else + return execute(new LoadMetadataHandler(loadDataMsg), waitTime); + + } + + + public OMElement checkForTableExistence(OMElement loadElement) throws I2B2Exception { + + OMElement returnElement = null; + String ontologyDataResponse = null; + String unknownErrorMessage = "Error message delivered from the remote server \n" + + "You may wish to retry your last action"; + + if (loadElement == null) { + log.error("Incoming Ontology request is null"); + ResponseMessageType responseMsgType = MessageFactory + .doBuildErrorResponse(null, unknownErrorMessage); + ontologyDataResponse = MessageFactory + .convertToXMLString(responseMsgType); + return MessageFactory + .createResponseOMElementFromString(ontologyDataResponse); + } + String requestElementString = loadElement.toString(); + + LoadDataMessage loadDataMsg = new LoadDataMessage( + requestElementString); + + log.info(loadDataMsg.getMetadataLoad().getTableName()); + long waitTime = 0; + if ((loadDataMsg.getRequestMessageType() != null) && (loadDataMsg.getRequestMessageType().getRequestHeader() != null)) { + waitTime = loadDataMsg.getRequestMessageType() + .getRequestHeader().getResultWaittimeMs(); + } + + // do Ontology query processing inside thread, so that + // service could sends back message with timeout error. + // ExecutorRunnable er = new ExecutorRunnable(); + + + return execute(new CheckMetadataTableHandler(loadDataMsg), waitTime); + + } + + /** swc20160515 + * This function is main webservice interface to get the I2B2HIVE.ONT_DB_LOOKUP data. + * It uses AXIOM elements(OMElement) to conveniently parse xml messages. + * + * It accepts incoming request, and returns a response, both in i2b2 message format. + * + * @param OMElement + * getAllDblookupsElement + * @return OMElement in i2b2message format + * @throws Exception + */ + public OMElement getAllDblookups(OMElement getAllDblookupsElement) throws I2B2Exception { + String ontologyDataResponse = null; + String unknownErrMsg = null; + if (null == getAllDblookupsElement) { + log.error("Incoming Ontology request is null"); + unknownErrMsg = "Error message delivered from the remote server.\nYou may wish to retry your last action"; + ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, unknownErrMsg); + ontologyDataResponse = MessageFactory.convertToXMLString(responseMsgType); + return MessageFactory.createResponseOMElementFromString(ontologyDataResponse); + } + String requestElementString = getAllDblookupsElement.toString(); + GetAllDblookupsDataMessage dblookupsDataMsg = new GetAllDblookupsDataMessage(requestElementString); + long waitTime = 0; + if ((null != dblookupsDataMsg.getRequestMessageType()) && (null != dblookupsDataMsg.getRequestMessageType().getRequestHeader())) { + waitTime = dblookupsDataMsg.getRequestMessageType().getRequestHeader().getResultWaittimeMs(); + } + // do processing inside thread, so that service could send back message with timeout error. + return execute(new GetAllDblookupsHandler(dblookupsDataMsg), waitTime); + } + + /** swc20160517 + * This function is main webservice interface to get specific I2B2HIVE.ONT_DB_LOOKUP data. + * It uses AXIOM elements(OMElement) to conveniently parse xml messages. + * + * It accepts incoming request, and returns a response, both in i2b2 message format. + * + * @param OMElement + * getDblookupElement + * @return OMElement in i2b2message format + * @throws Exception + */ + public OMElement getDblookup(OMElement getDblookupElement) throws I2B2Exception { + String ontologyDataResponse = null; + String unknownErrMsg = null; + if (null == getDblookupElement) { + log.error("Incoming Ontology request is null"); + unknownErrMsg = "Error message delivered from the remote server.\nYou may wish to retry your last action"; + ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, unknownErrMsg); + ontologyDataResponse = MessageFactory.convertToXMLString(responseMsgType); + return MessageFactory.createResponseOMElementFromString(ontologyDataResponse); + } + String requestElementString = getDblookupElement.toString(); + GetDblookupDataMessage dblookupDataMsg = new GetDblookupDataMessage(requestElementString); + long waitTime = 0; + if ((null != dblookupDataMsg.getRequestMessageType()) && (null != dblookupDataMsg.getRequestMessageType().getRequestHeader())) { + waitTime = dblookupDataMsg.getRequestMessageType().getRequestHeader().getResultWaittimeMs(); + } + // do processing inside thread, so that service could send back message with timeout error. + return execute(new GetDblookupHandler(dblookupDataMsg), waitTime); + } + + /** swc20160516 + * This function is main webservice interface to add a new entry to the I2B2HIVE.ONT_DB_LOOKUP data. + * It uses AXIOM elements(OMElement) to conveniently parse xml messages. + * + * It accepts incoming request, and returns a response, both in i2b2 message format. + * + * @param OMElement + * getAllDblookupsElement + * @return OMElement in i2b2message format + * @throws Exception + */ + public OMElement setDblookup(OMElement setDblookupElement) throws I2B2Exception { + // OMElement returnElement = null; + String ontologyDataResponse = null; + String unknownErrMsg = null; + if (null == setDblookupElement) { + log.error("Incoming Ontology request is null"); + unknownErrMsg = "Error message delivered from the remote server.\nYou may wish to retry your last action"; + ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, unknownErrMsg); + ontologyDataResponse = MessageFactory.convertToXMLString(responseMsgType); + return MessageFactory.createResponseOMElementFromString(ontologyDataResponse); + } + String requestElementString = setDblookupElement.toString(); + SetDblookupDataMessage dblookupDataMsg = new SetDblookupDataMessage(requestElementString); + long waitTime = 0; + if ((null != dblookupDataMsg.getRequestMessageType()) && (null != dblookupDataMsg.getRequestMessageType().getRequestHeader())) { + waitTime = dblookupDataMsg.getRequestMessageType().getRequestHeader().getResultWaittimeMs(); + } + // do processing inside thread, so that service could send back message with timeout error. + return execute(new SetDblookupHandler(dblookupDataMsg), waitTime); + } + + /** swc20160518 + * This function is main webservice interface to delete specific I2B2HIVE.ONT_DB_LOOKUP data. + * It uses AXIOM elements(OMElement) to conveniently parse xml messages. + * + * It accepts incoming request, and returns a response, both in i2b2 message format. + * + * @param OMElement + * deleteDblookupElement + * @return OMElement in i2b2message format + * @throws Exception + */ + public OMElement deleteDblookup(OMElement deleteDblookupElement) throws I2B2Exception { + String ontologyDataResponse = null; + String unknownErrMsg = null; + if (null == deleteDblookupElement) { + log.error("Incoming Ontology request is null"); + unknownErrMsg = "Error message delivered from the remote server.\nYou may wish to retry your last action"; + ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, unknownErrMsg); + ontologyDataResponse = MessageFactory.convertToXMLString(responseMsgType); + return MessageFactory.createResponseOMElementFromString(ontologyDataResponse); + } + String requestElementString = deleteDblookupElement.toString(); + DeleteDblookupDataMessage dblookupDataMsg = new DeleteDblookupDataMessage(requestElementString); + long waitTime = 0; + if ((null != dblookupDataMsg.getRequestMessageType()) && (null != dblookupDataMsg.getRequestMessageType().getRequestHeader())) { + waitTime = dblookupDataMsg.getRequestMessageType().getRequestHeader().getResultWaittimeMs(); + } + // do processing inside thread, so that service could send back message with timeout error. + return execute(new DeleteDblookupHandler(dblookupDataMsg), waitTime); + } + +} diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ws/RequestDataMessage.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ws/RequestDataMessage.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ws/RequestDataMessage.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ws/RequestDataMessage.java index f9b94537..3323316b --- a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ws/RequestDataMessage.java +++ b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ws/RequestDataMessage.java @@ -1,68 +1,68 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Raj Kuttan - * Lori Phillips - */ -package edu.harvard.i2b2.ontology.ws; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.ontology.datavo.i2b2message.MessageHeaderType; -import edu.harvard.i2b2.ontology.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.ontology.util.OntologyJAXBUtil; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import jakarta.xml.bind.JAXBElement; - - -/** - * The RequestDataMessage class is a helper class to build Ontology messages in the - * i2b2 format - */ -public abstract class RequestDataMessage{ - private static Log log = LogFactory.getLog(RequestDataMessage.class); - - RequestMessageType reqMessageType = null; - - /** - * The constructor - */ - public RequestDataMessage(String requestVdo) throws I2B2Exception { - try { - JAXBElement jaxbElement = OntologyJAXBUtil.getJAXBUtil().unMashallFromString(requestVdo); - - if (jaxbElement == null) { - throw new I2B2Exception( - "Null value from unmarshall for VDO xml : " + requestVdo); - } - - this.reqMessageType = (RequestMessageType) jaxbElement.getValue(); - } catch (JAXBUtilException e) { - log.error(e.getMessage(), e); - throw new I2B2Exception("Umarshaller error: " + e.getMessage() + - requestVdo, e); - } - } - - - - public RequestMessageType getRequestMessageType() { - return reqMessageType; - } - - public MessageHeaderType getMessageHeaderType() { - return reqMessageType.getMessageHeader(); - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Raj Kuttan + * Lori Phillips + */ +package edu.harvard.i2b2.ontology.ws; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.ontology.datavo.i2b2message.MessageHeaderType; +import edu.harvard.i2b2.ontology.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.ontology.util.OntologyJAXBUtil; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import jakarta.xml.bind.JAXBElement; + + +/** + * The RequestDataMessage class is a helper class to build Ontology messages in the + * i2b2 format + */ +public abstract class RequestDataMessage{ + private static Log log = LogFactory.getLog(RequestDataMessage.class); + + RequestMessageType reqMessageType = null; + + /** + * The constructor + */ + public RequestDataMessage(String requestVdo) throws I2B2Exception { + try { + JAXBElement jaxbElement = OntologyJAXBUtil.getJAXBUtil().unMashallFromString(requestVdo); + + if (jaxbElement == null) { + throw new I2B2Exception( + "Null value from unmarshall for VDO xml : " + requestVdo); + } + + this.reqMessageType = (RequestMessageType) jaxbElement.getValue(); + } catch (JAXBUtilException e) { + log.error(e.getMessage(), e); + throw new I2B2Exception("Umarshaller error: " + e.getMessage() + + requestVdo, e); + } + } + + + + public RequestMessageType getRequestMessageType() { + return reqMessageType; + } + + public MessageHeaderType getMessageHeaderType() { + return reqMessageType.getMessageHeader(); + } + +} diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ws/SetDblookupDataMessage.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ws/SetDblookupDataMessage.java similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ws/SetDblookupDataMessage.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ws/SetDblookupDataMessage.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ws/UpdateTotalNumMessage.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ws/UpdateTotalNumMessage.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/ontology/ws/UpdateTotalNumMessage.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontology/ws/UpdateTotalNumMessage.java diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/pm/ws/GetUserConfigurationRequestMessage.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontologypm/ws/GetUserConfigurationRequestMessage.java old mode 100755 new mode 100644 similarity index 98% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/pm/ws/GetUserConfigurationRequestMessage.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontologypm/ws/GetUserConfigurationRequestMessage.java index c5b6d445..9a80f3ff --- a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/pm/ws/GetUserConfigurationRequestMessage.java +++ b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontologypm/ws/GetUserConfigurationRequestMessage.java @@ -13,7 +13,7 @@ * Mike Mendis * Raj Kuttan */ -package edu.harvard.i2b2.pm.ws; +package edu.harvard.i2b2.ontologypm.ws; import java.io.StringWriter; diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/pm/ws/PMResponseMessage.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontologypm/ws/PMResponseMessage.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/pm/ws/PMResponseMessage.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontologypm/ws/PMResponseMessage.java index 388a62b9..d0ae9ec5 --- a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/pm/ws/PMResponseMessage.java +++ b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontologypm/ws/PMResponseMessage.java @@ -1,77 +1,77 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Mike Mendis - * Raj Kuttan - */ -package edu.harvard.i2b2.pm.ws; - -import jakarta.xml.bind.JAXBElement; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.ontology.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.ontology.datavo.i2b2message.ResponseHeaderType; -import edu.harvard.i2b2.ontology.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.ontology.datavo.i2b2message.StatusType; -import edu.harvard.i2b2.ontology.datavo.pm.ConfigureType; -import edu.harvard.i2b2.ontology.util.OntologyJAXBUtil; - - -public class PMResponseMessage { - - public static final String THIS_CLASS_NAME = PMResponseMessage.class.getName(); - private Log log = LogFactory.getLog(THIS_CLASS_NAME); - private ResponseMessageType pmRespMessageType = null; - - public PMResponseMessage() {} - - public StatusType processResult(String response){ - StatusType status = null; - try { - JAXBElement jaxbElement = OntologyJAXBUtil.getJAXBUtil().unMashallFromString(response); - pmRespMessageType = (ResponseMessageType) jaxbElement.getValue(); - - // Get response message status - ResponseHeaderType responseHeader = pmRespMessageType.getResponseHeader(); - status = responseHeader.getResultStatus().getStatus(); - String procStatus = status.getType(); - String procMessage = status.getValue(); - - if(procStatus.equals("ERROR")){ - log.error("Error reported by Ont web Service " + procMessage); - } - else if(procStatus.equals("WARNING")){ - log.debug("Warning reported by Ont web Service" + procMessage); - } - - } catch (JAXBUtilException e) { - log.error(e.getMessage()); - } - return status; - } - - - public ConfigureType readUserInfo() throws Exception { - ConfigureType pmResponse = null; - - BodyType bodyType = pmRespMessageType.getMessageBody(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - pmResponse = (ConfigureType)helper.getObjectByClass(bodyType.getAny(), ConfigureType.class); - - return pmResponse; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Mike Mendis + * Raj Kuttan + */ +package edu.harvard.i2b2.ontologypm.ws; + +import jakarta.xml.bind.JAXBElement; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.ontology.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.ontology.datavo.i2b2message.ResponseHeaderType; +import edu.harvard.i2b2.ontology.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.ontology.datavo.i2b2message.StatusType; +import edu.harvard.i2b2.ontology.datavo.pm.ConfigureType; +import edu.harvard.i2b2.ontology.util.OntologyJAXBUtil; + + +public class PMResponseMessage { + + public static final String THIS_CLASS_NAME = PMResponseMessage.class.getName(); + private Log log = LogFactory.getLog(THIS_CLASS_NAME); + private ResponseMessageType pmRespMessageType = null; + + public PMResponseMessage() {} + + public StatusType processResult(String response){ + StatusType status = null; + try { + JAXBElement jaxbElement = OntologyJAXBUtil.getJAXBUtil().unMashallFromString(response); + pmRespMessageType = (ResponseMessageType) jaxbElement.getValue(); + + // Get response message status + ResponseHeaderType responseHeader = pmRespMessageType.getResponseHeader(); + status = responseHeader.getResultStatus().getStatus(); + String procStatus = status.getType(); + String procMessage = status.getValue(); + + if(procStatus.equals("ERROR")){ + log.error("Error reported by Ont web Service " + procMessage); + } + else if(procStatus.equals("WARNING")){ + log.debug("Warning reported by Ont web Service" + procMessage); + } + + } catch (JAXBUtilException e) { + log.error(e.getMessage()); + } + return status; + } + + + public ConfigureType readUserInfo() throws Exception { + ConfigureType pmResponse = null; + + BodyType bodyType = pmRespMessageType.getMessageBody(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + pmResponse = (ConfigureType)helper.getObjectByClass(bodyType.getAny(), ConfigureType.class); + + return pmResponse; + } + +} diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/pm/ws/PMServiceDriver.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontologypm/ws/PMServiceDriver.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/pm/ws/PMServiceDriver.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontologypm/ws/PMServiceDriver.java index 7ec6503c..8267694c --- a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/pm/ws/PMServiceDriver.java +++ b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontologypm/ws/PMServiceDriver.java @@ -1,96 +1,96 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Mike Mendis - * Raj Kuttan - * Lori Phillips - */ -package edu.harvard.i2b2.pm.ws; - -import java.io.StringReader; - -import javax.xml.stream.FactoryConfigurationError; -import javax.xml.stream.XMLInputFactory; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamReader; - -import org.apache.axiom.om.OMAbstractFactory; -import org.apache.axiom.om.OMElement; -import org.apache.axiom.om.OMNamespace; -import org.apache.axiom.soap.SOAPEnvelope; -import org.apache.axiom.soap.SOAPFactory; -import org.apache.axis2.AxisFault; -import org.apache.axis2.Constants; -import org.apache.axis2.addressing.EndpointReference; -import org.apache.axis2.client.OperationClient; -import org.apache.axis2.client.Options; -import edu.harvard.i2b2.common.util.axis2.ServiceClient; -import org.apache.axis2.context.MessageContext; -import org.apache.axis2.context.ServiceContext; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.exception.StackTraceUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.ontology.datavo.i2b2message.MessageHeaderType; -import edu.harvard.i2b2.ontology.datavo.pm.GetUserConfigurationType; -import edu.harvard.i2b2.ontology.util.OntologyUtil; - -public class PMServiceDriver { - private static Log log = LogFactory.getLog(PMServiceDriver.class.getName()); - - protected static Log logesapi = LogFactory.getLog(PMServiceDriver.class); - - - /** - * Function to send getRoles request to PM web service - * - * @param GetUserConfigurationType userConfig we wish to get data for - * @return A String containing the PM web service response - */ - - public static String getRoles(GetUserConfigurationType userConfig, MessageHeaderType header) throws I2B2Exception, AxisFault, Exception{ - String response = null; - try { - GetUserConfigurationRequestMessage reqMsg = new GetUserConfigurationRequestMessage(); - String getRolesRequestString = reqMsg.doBuildXML(userConfig, header); - // OMElement getPm = getPmPayLoad(getRolesRequestString); - - - // First step is to get PM endpoint reference from properties file. - String pmEPR = ""; - // String pmMethod = ""; - try { - pmEPR = OntologyUtil.getInstance().getPmEndpointReference(); - // pmMethod = OntologyUtil.getInstance().getPmWebServiceMethod(); - } catch (I2B2Exception e1) { - log.error(e1.getMessage()); - throw e1; - } - - - response = ServiceClient.sendREST(pmEPR, getRolesRequestString); - - - logesapi.debug("PM response = " + response); - } catch (Exception e) { - log.error(e.getMessage()); - throw new Exception(e); - } - return response; - } - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Mike Mendis + * Raj Kuttan + * Lori Phillips + */ +package edu.harvard.i2b2.ontologypm.ws; + +import java.io.StringReader; + +import javax.xml.stream.FactoryConfigurationError; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import org.apache.axiom.om.OMAbstractFactory; +import org.apache.axiom.om.OMElement; +import org.apache.axiom.om.OMNamespace; +import org.apache.axiom.soap.SOAPEnvelope; +import org.apache.axiom.soap.SOAPFactory; +import org.apache.axis2.AxisFault; +import org.apache.axis2.Constants; +import org.apache.axis2.addressing.EndpointReference; +import org.apache.axis2.client.OperationClient; +import org.apache.axis2.client.Options; +import edu.harvard.i2b2.common.util.axis2.ServiceClient; +import org.apache.axis2.context.MessageContext; +import org.apache.axis2.context.ServiceContext; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.exception.StackTraceUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.ontology.datavo.i2b2message.MessageHeaderType; +import edu.harvard.i2b2.ontology.datavo.pm.GetUserConfigurationType; +import edu.harvard.i2b2.ontology.util.OntologyUtil; + +public class PMServiceDriver { + private static Log log = LogFactory.getLog(PMServiceDriver.class.getName()); + + protected static Log logesapi = LogFactory.getLog(PMServiceDriver.class); + + + /** + * Function to send getRoles request to PM web service + * + * @param GetUserConfigurationType userConfig we wish to get data for + * @return A String containing the PM web service response + */ + + public static String getRoles(GetUserConfigurationType userConfig, MessageHeaderType header) throws I2B2Exception, AxisFault, Exception{ + String response = null; + try { + GetUserConfigurationRequestMessage reqMsg = new GetUserConfigurationRequestMessage(); + String getRolesRequestString = reqMsg.doBuildXML(userConfig, header); + // OMElement getPm = getPmPayLoad(getRolesRequestString); + + + // First step is to get PM endpoint reference from properties file. + String pmEPR = ""; + // String pmMethod = ""; + try { + pmEPR = OntologyUtil.getInstance().getPmEndpointReference(); + // pmMethod = OntologyUtil.getInstance().getPmWebServiceMethod(); + } catch (I2B2Exception e1) { + log.error(e1.getMessage()); + throw e1; + } + + + response = ServiceClient.sendREST(pmEPR, getRolesRequestString); + + + logesapi.debug("PM response = " + response); + } catch (Exception e) { + log.error(e.getMessage()); + throw new Exception(e); + } + return response; + } + + +} diff --git a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/pm/ws/ProjectManagementRequestData.java b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontologypm/ws/ProjectManagementRequestData.java old mode 100755 new mode 100644 similarity index 99% rename from edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/pm/ws/ProjectManagementRequestData.java rename to edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontologypm/ws/ProjectManagementRequestData.java index b1926892..b4512335 --- a/edu.harvard.i2b2.ontology/src/core/edu/harvard/i2b2/pm/ws/ProjectManagementRequestData.java +++ b/edu.harvard.i2b2.ontology/src/main/java/edu/harvard/i2b2/ontologypm/ws/ProjectManagementRequestData.java @@ -13,7 +13,7 @@ * Mike Mendis * Raj Kuttan */ -package edu.harvard.i2b2.pm.ws; +package edu.harvard.i2b2.ontologypm.ws; import java.io.StringWriter; import java.math.BigDecimal; diff --git a/edu.harvard.i2b2.pm/.classpath b/edu.harvard.i2b2.pm/.classpath index 62a0d0bc..b9f6029d 100755 --- a/edu.harvard.i2b2.pm/.classpath +++ b/edu.harvard.i2b2.pm/.classpath @@ -1,158 +1,46 @@ - - - - - - - - - - + - + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/edu.harvard.i2b2.pm/.cvsignore b/edu.harvard.i2b2.pm/.cvsignore deleted file mode 100755 index 009b250a..00000000 --- a/edu.harvard.i2b2.pm/.cvsignore +++ /dev/null @@ -1,3 +0,0 @@ -gensrc -classes -genlib diff --git a/edu.harvard.i2b2.pm/.gitignore b/edu.harvard.i2b2.pm/.gitignore deleted file mode 100644 index ae3c1726..00000000 --- a/edu.harvard.i2b2.pm/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/bin/ diff --git a/edu.harvard.i2b2.pm/.project b/edu.harvard.i2b2.pm/.project index 79e42550..13bae3a0 100755 --- a/edu.harvard.i2b2.pm/.project +++ b/edu.harvard.i2b2.pm/.project @@ -10,8 +10,14 @@ + + org.eclipse.m2e.core.maven2Builder + + + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature diff --git a/edu.harvard.i2b2.pm/.settings/org.hibernate.eclipse.console.prefs b/edu.harvard.i2b2.pm/.settings/org.hibernate.eclipse.console.prefs deleted file mode 100755 index 21fefffa..00000000 --- a/edu.harvard.i2b2.pm/.settings/org.hibernate.eclipse.console.prefs +++ /dev/null @@ -1,3 +0,0 @@ -default.configuration= -eclipse.preferences.version=1 -hibernate3.enabled=false diff --git a/edu.harvard.i2b2.pm/LICENSE.txt b/edu.harvard.i2b2.pm/LICENSE.txt deleted file mode 100644 index e5a5569a..00000000 --- a/edu.harvard.i2b2.pm/LICENSE.txt +++ /dev/null @@ -1,406 +0,0 @@ -#------------------------------------------------------------------------------- -# Copyright (c) 2006-2018 Massachusetts General Hospital -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Mozilla Public License, -# v. 2.0. If a copy of the MPL was not distributed with this file, You can -# obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under -# the terms of the Healthcare Disclaimer. -#------------------------------------------------------------------------------- -Mozilla Public License, version 2.0 - -1. Definitions - -1.1. "Contributor" - - means each individual or legal entity that creates, contributes to the - creation of, or owns Covered Software. - -1.2. "Contributor Version" - - means the combination of the Contributions of others (if any) used by a - Contributor and that particular Contributor's Contribution. - -1.3. "Contribution" - - means Covered Software of a particular Contributor. - -1.4. "Covered Software" - - means Source Code Form to which the initial Contributor has attached the - notice in Exhibit A, the Executable Form of such Source Code Form, and - Modifications of such Source Code Form, in each case including portions - thereof. - -1.5. "Incompatible With Secondary Licenses" - means - - a. that the initial Contributor has attached the notice described in - Exhibit B to the Covered Software; or - - b. that the Covered Software was made available under the terms of - version 1.1 or earlier of the License, but not also under the terms of - a Secondary License. - -1.6. "Executable Form" - - means any form of the work other than Source Code Form. - -1.7. "Larger Work" - - means a work that combines Covered Software with other material, in a - separate file or files, that is not Covered Software. - -1.8. "License" - - means this document. - -1.9. "Licensable" - - means having the right to grant, to the maximum extent possible, whether - at the time of the initial grant or subsequently, any and all of the - rights conveyed by this License. - -1.10. "Modifications" - - means any of the following: - - a. any file in Source Code Form that results from an addition to, - deletion from, or modification of the contents of Covered Software; or - - b. any new file in Source Code Form that contains any Covered Software. - -1.11. "Patent Claims" of a Contributor - - means any patent claim(s), including without limitation, method, - process, and apparatus claims, in any patent Licensable by such - Contributor that would be infringed, but for the grant of the License, - by the making, using, selling, offering for sale, having made, import, - or transfer of either its Contributions or its Contributor Version. - -1.12. "Secondary License" - - means either the GNU General Public License, Version 2.0, the GNU Lesser - General Public License, Version 2.1, the GNU Affero General Public - License, Version 3.0, or any later versions of those licenses. - -1.13. "Source Code Form" - - means the form of the work preferred for making modifications. - -1.14. "You" (or "Your") - - means an individual or a legal entity exercising rights under this - License. For legal entities, "You" includes any entity that controls, is - controlled by, or is under common control with You. For purposes of this - definition, "control" means (a) the power, direct or indirect, to cause - the direction or management of such entity, whether by contract or - otherwise, or (b) ownership of more than fifty percent (50%) of the - outstanding shares or beneficial ownership of such entity. - - -2. License Grants and Conditions - -2.1. Grants - - Each Contributor hereby grants You a world-wide, royalty-free, - non-exclusive license: - - a. under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or - as part of a Larger Work; and - - b. under Patent Claims of such Contributor to make, use, sell, offer for - sale, have made, import, and otherwise transfer either its - Contributions or its Contributor Version. - -2.2. Effective Date - - The licenses granted in Section 2.1 with respect to any Contribution - become effective for each Contribution on the date the Contributor first - distributes such Contribution. - -2.3. Limitations on Grant Scope - - The licenses granted in this Section 2 are the only rights granted under - this License. No additional rights or licenses will be implied from the - distribution or licensing of Covered Software under this License. - Notwithstanding Section 2.1(b) above, no patent license is granted by a - Contributor: - - a. for any code that a Contributor has removed from Covered Software; or - - b. for infringements caused by: (i) Your and any other third party's - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - - c. under Patent Claims infringed by Covered Software in the absence of - its Contributions. - - This License does not grant any rights in the trademarks, service marks, - or logos of any Contributor (except as may be necessary to comply with - the notice requirements in Section 3.4). - -2.4. Subsequent Licenses - - No Contributor makes additional grants as a result of Your choice to - distribute the Covered Software under a subsequent version of this - License (see Section 10.2) or under the terms of a Secondary License (if - permitted under the terms of Section 3.3). - -2.5. Representation - - Each Contributor represents that the Contributor believes its - Contributions are its original creation(s) or it has sufficient rights to - grant the rights to its Contributions conveyed by this License. - -2.6. Fair Use - - This License is not intended to limit any rights You have under - applicable copyright doctrines of fair use, fair dealing, or other - equivalents. - -2.7. Conditions - - Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in - Section 2.1. - - -3. Responsibilities - -3.1. Distribution of Source Form - - All distribution of Covered Software in Source Code Form, including any - Modifications that You create or to which You contribute, must be under - the terms of this License. You must inform recipients that the Source - Code Form of the Covered Software is governed by the terms of this - License, and how they can obtain a copy of this License. You may not - attempt to alter or restrict the recipients' rights in the Source Code - Form. - -3.2. Distribution of Executable Form - - If You distribute Covered Software in Executable Form then: - - a. such Covered Software must also be made available in Source Code Form, - as described in Section 3.1, and You must inform recipients of the - Executable Form how they can obtain a copy of such Source Code Form by - reasonable means in a timely manner, at a charge no more than the cost - of distribution to the recipient; and - - b. You may distribute such Executable Form under the terms of this - License, or sublicense it under different terms, provided that the - license for the Executable Form does not attempt to limit or alter the - recipients' rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - - You may create and distribute a Larger Work under terms of Your choice, - provided that You also comply with the requirements of this License for - the Covered Software. If the Larger Work is a combination of Covered - Software with a work governed by one or more Secondary Licenses, and the - Covered Software is not Incompatible With Secondary Licenses, this - License permits You to additionally distribute such Covered Software - under the terms of such Secondary License(s), so that the recipient of - the Larger Work may, at their option, further distribute the Covered - Software under the terms of either this License or such Secondary - License(s). - -3.4. Notices - - You may not remove or alter the substance of any license notices - (including copyright notices, patent notices, disclaimers of warranty, or - limitations of liability) contained within the Source Code Form of the - Covered Software, except that You may alter any license notices to the - extent required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - - You may choose to offer, and to charge a fee for, warranty, support, - indemnity or liability obligations to one or more recipients of Covered - Software. However, You may do so only on Your own behalf, and not on - behalf of any Contributor. You must make it absolutely clear that any - such warranty, support, indemnity, or liability obligation is offered by - You alone, and You hereby agree to indemnify every Contributor for any - liability incurred by such Contributor as a result of warranty, support, - indemnity or liability terms You offer. You may include additional - disclaimers of warranty and limitations of liability specific to any - jurisdiction. - -4. Inability to Comply Due to Statute or Regulation - - If it is impossible for You to comply with any of the terms of this License - with respect to some or all of the Covered Software due to statute, - judicial order, or regulation then You must: (a) comply with the terms of - this License to the maximum extent possible; and (b) describe the - limitations and the code they affect. Such description must be placed in a - text file included with all distributions of the Covered Software under - this License. Except to the extent prohibited by statute or regulation, - such description must be sufficiently detailed for a recipient of ordinary - skill to be able to understand it. - -5. Termination - -5.1. The rights granted under this License will terminate automatically if You - fail to comply with any of its terms. However, if You become compliant, - then the rights granted under this License from a particular Contributor - are reinstated (a) provisionally, unless and until such Contributor - explicitly and finally terminates Your grants, and (b) on an ongoing - basis, if such Contributor fails to notify You of the non-compliance by - some reasonable means prior to 60 days after You have come back into - compliance. Moreover, Your grants from a particular Contributor are - reinstated on an ongoing basis if such Contributor notifies You of the - non-compliance by some reasonable means, this is the first time You have - received notice of non-compliance with this License from such - Contributor, and You become compliant prior to 30 days after Your receipt - of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent - infringement claim (excluding declaratory judgment actions, - counter-claims, and cross-claims) alleging that a Contributor Version - directly or indirectly infringes any patent, then the rights granted to - You by any and all Contributors for the Covered Software under Section - 2.1 of this License shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user - license agreements (excluding distributors and resellers) which have been - validly granted by You or Your distributors under this License prior to - termination shall survive termination. - -6. Disclaimer of Warranty - - Covered Software is provided under this License on an "as is" basis, - without warranty of any kind, either expressed, implied, or statutory, - including, without limitation, warranties that the Covered Software is free - of defects, merchantable, fit for a particular purpose or non-infringing. - The entire risk as to the quality and performance of the Covered Software - is with You. Should any Covered Software prove defective in any respect, - You (not any Contributor) assume the cost of any necessary servicing, - repair, or correction. This disclaimer of warranty constitutes an essential - part of this License. No use of any Covered Software is authorized under - this License except under this disclaimer. - -7. Limitation of Liability - - Under no circumstances and under no legal theory, whether tort (including - negligence), contract, or otherwise, shall any Contributor, or anyone who - distributes Covered Software as permitted above, be liable to You for any - direct, indirect, special, incidental, or consequential damages of any - character including, without limitation, damages for lost profits, loss of - goodwill, work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses, even if such party shall have been - informed of the possibility of such damages. This limitation of liability - shall not apply to liability for death or personal injury resulting from - such party's negligence to the extent applicable law prohibits such - limitation. Some jurisdictions do not allow the exclusion or limitation of - incidental or consequential damages, so this exclusion and limitation may - not apply to You. - -8. Litigation - - Any litigation relating to this License may be brought only in the courts - of a jurisdiction where the defendant maintains its principal place of - business and such litigation shall be governed by laws of that - jurisdiction, without reference to its conflict-of-law provisions. Nothing - in this Section shall prevent a party's ability to bring cross-claims or - counter-claims. - -9. Miscellaneous - - This License represents the complete agreement concerning the subject - matter hereof. If any provision of this License is held to be - unenforceable, such provision shall be reformed only to the extent - necessary to make it enforceable. Any law or regulation which provides that - the language of a contract shall be construed against the drafter shall not - be used to construe this License against a Contributor. - - -10. Versions of the License - -10.1. New Versions - - Mozilla Foundation is the license steward. Except as provided in Section - 10.3, no one other than the license steward has the right to modify or - publish new versions of this License. Each version will be given a - distinguishing version number. - -10.2. Effect of New Versions - - You may distribute the Covered Software under the terms of the version - of the License under which You originally received the Covered Software, - or under the terms of any subsequent version published by the license - steward. - -10.3. Modified Versions - - If you create software not governed by this License, and you want to - create a new license for such software, you may create and use a - modified version of this License if you rename the license and remove - any references to the name of the license steward (except to note that - such modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary - Licenses If You choose to distribute Source Code Form that is - Incompatible With Secondary Licenses under the terms of this version of - the License, the notice described in Exhibit B of this License must be - attached. - -Exhibit A - Source Code Form License Notice - - This Source Code Form is subject to the - terms of the Mozilla Public License, v. - 2.0. If a copy of the MPL was not - distributed with this file, You can - obtain one at - http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular file, -then You may include the notice in a location (such as a LICENSE file in a -relevant directory) where a recipient would be likely to look for such a -notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - "Incompatible With Secondary Licenses" Notice - - This Source Code Form is "Incompatible - With Secondary Licenses", as defined by - the Mozilla Public License, v. 2.0. - ---------------------- - -Healthcare Disclaimer - -In the United States, or any other jurisdictions where they may apply, the -following additional disclaimer of warranty and limitation of liability are -hereby incorporated into the terms and conditions of MPL 2.0: - -1. No warranties of any kind whatsoever are made as to the results that - You will obtain from relying upon the covered code (or any information - or content obtained by way of the covered code), including but not - limited to compliance with privacy laws or regulations or clinical - care industry standards and protocols. Use of the covered code is not - a substitute for a health care provider’s standard practice or - professional judgment. Any decision with regard to the appropriateness - of treatment, or the validity or reliability of information or content - made available by the covered code, is the sole responsibility of the - health care provider. Consequently, it is incumbent upon each health - care provider to verify all medical history and treatment plans with - each patient. - -2. Under no circumstances and under no legal theory, whether tort - (including negligence), contract, or otherwise, shall any Contributor, - or anyone who distributes Covered Software as permitted by the - license, be liable to You for any indirect, special, incidental, - consequential damages of any character including, without limitation, - damages for loss of goodwill, work stoppage, computer failure or - malfunction, or any and all other damages or losses, of any nature - whatsoever (direct or otherwise) on account of or associated with the - use or inability to use the covered content (including, without - limitation, the use of information or content made available by the - covered code, all documentation associated therewith, and the failure - of the covered code to comply with privacy laws and regulations or - clinical care industry standards and protocols), even if such party - shall have been informed of the possibility of such damages. diff --git a/edu.harvard.i2b2.pm/build.properties b/edu.harvard.i2b2.pm/build.properties deleted file mode 100755 index a66ae5e9..00000000 --- a/edu.harvard.i2b2.pm/build.properties +++ /dev/null @@ -1,9 +0,0 @@ -#Ant build property file - -## JBOSS HOME -jboss.home=/opt/wildfly-17.0.1.Final -axis2.war.name=i2b2.war - -report=test-reports -testfiledir=testfiles -testhost=http://127.0.0.1:9090/i2b2/services diff --git a/edu.harvard.i2b2.pm/build.xml b/edu.harvard.i2b2.pm/build.xml deleted file mode 100755 index 8ada0e0e..00000000 --- a/edu.harvard.i2b2.pm/build.xml +++ /dev/null @@ -1,193 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/edu.harvard.i2b2.pm/master_build.xml b/edu.harvard.i2b2.pm/master_build.xml deleted file mode 100755 index d2d81578..00000000 --- a/edu.harvard.i2b2.pm/master_build.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/edu.harvard.i2b2.pm/pom.xml b/edu.harvard.i2b2.pm/pom.xml new file mode 100644 index 00000000..f107a574 --- /dev/null +++ b/edu.harvard.i2b2.pm/pom.xml @@ -0,0 +1,70 @@ + + 4.0.0 + + edu.harvard.i2b2 + i2b2-parent + 2.0.0-SNAPSHOT + + edu.harvard.i2b2.pm + jar + PM Cell + + + + + org.codehaus.mojo + build-helper-maven-plugin + 3.0.0 + + + generate-sources + + add-source + + + + gensrc + + + + + + + + + + + edu.harvard.i2b2 + edu.harvard.i2b2.server-common + + + + org.wildfly.core + wildfly-controller-client + 28.0.1.Final + + + + jakarta.servlet + jakarta.servlet-api + 6.1.0 + provided + + + + com.hierynomus + smbj + 0.14.0 + + + + com.okta.authn.sdk + okta-authn-sdk-api + + 3.0.0 + + + + + \ No newline at end of file diff --git a/edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/dao/PMDbDao.java b/edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/dao/PMDbDao.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/dao/PMDbDao.java rename to edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/dao/PMDbDao.java diff --git a/edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/delegate/RequestHandler.java b/edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/delegate/RequestHandler.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/delegate/RequestHandler.java rename to edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/delegate/RequestHandler.java diff --git a/edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/delegate/ServicesHandler.java b/edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/delegate/ServicesHandler.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/delegate/ServicesHandler.java rename to edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/delegate/ServicesHandler.java index fc860075..2fff5b8d --- a/edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/delegate/ServicesHandler.java +++ b/edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/delegate/ServicesHandler.java @@ -1,2450 +1,2452 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Lori Phillips - */ -package edu.harvard.i2b2.pm.delegate; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.net.InetAddress; -import java.sql.Connection; -import java.sql.DriverManager; -import java.util.ArrayList; -import java.util.Date; -import java.util.Hashtable; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import javax.management.AttributeNotFoundException; -import javax.management.InstanceNotFoundException; -import javax.management.MBeanException; -import javax.management.MBeanServer; -import javax.management.MalformedObjectNameException; -import javax.management.ObjectInstance; -import javax.management.ObjectName; -import javax.management.ReflectionException; -import javax.naming.Binding; -import javax.naming.Context; -import javax.naming.InitialContext; -import javax.naming.NameClassPair; -import javax.naming.NamingEnumeration; -import javax.naming.NamingException; -import javax.sql.DataSource; - -import jakarta.servlet.http.HttpServletRequest; -import jakarta.xml.bind.JAXBElement; - -import org.jboss.as.connector.subsystems.datasources.WildFlyDataSource; -import org.jboss.as.controller.client.ModelControllerClient; -import org.jboss.as.controller.client.OperationBuilder; -import org.jboss.as.controller.client.helpers.ClientConstants; -import org.jboss.dmr.ModelNode; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; -import edu.harvard.i2b2.pm.dao.PMDbDao; -import edu.harvard.i2b2.pm.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.pm.datavo.i2b2message.MessageHeaderType; -import edu.harvard.i2b2.pm.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.pm.datavo.i2b2message.ResultStatusType; -import edu.harvard.i2b2.pm.datavo.i2b2message.SecurityType; -import edu.harvard.i2b2.pm.datavo.i2b2message.StatusType; -import edu.harvard.i2b2.pm.datavo.pm.ApprovalType; -import edu.harvard.i2b2.pm.datavo.pm.ApprovalsType; -import edu.harvard.i2b2.pm.datavo.pm.CellDataType; -import edu.harvard.i2b2.pm.datavo.pm.CellDatasType; -import edu.harvard.i2b2.pm.datavo.pm.ConfigureType; -import edu.harvard.i2b2.pm.datavo.pm.ConfiguresType; -import edu.harvard.i2b2.pm.datavo.pm.DatasourceType; -import edu.harvard.i2b2.pm.datavo.pm.DatasourcesType; -import edu.harvard.i2b2.pm.datavo.pm.GetUserConfigurationType; -import edu.harvard.i2b2.pm.datavo.pm.GlobalDataType; -import edu.harvard.i2b2.pm.datavo.pm.ParamType; -import edu.harvard.i2b2.pm.datavo.pm.ParamsType; -import edu.harvard.i2b2.pm.datavo.pm.PasswordType; -import edu.harvard.i2b2.pm.datavo.pm.ProjectRequestType; -import edu.harvard.i2b2.pm.datavo.pm.ProjectRequestsType; -import edu.harvard.i2b2.pm.datavo.pm.ProjectType; -import edu.harvard.i2b2.pm.datavo.pm.ProjectsType; -import edu.harvard.i2b2.pm.datavo.pm.RoleType; -import edu.harvard.i2b2.pm.datavo.pm.RolesType; -import edu.harvard.i2b2.pm.datavo.pm.UserLoginType; -import edu.harvard.i2b2.pm.datavo.pm.UserLoginsType; -import edu.harvard.i2b2.pm.datavo.pm.UserType; -import edu.harvard.i2b2.pm.datavo.pm.UsersType; -import edu.harvard.i2b2.pm.services.HiveParamData; -import edu.harvard.i2b2.pm.services.SessionData; -import edu.harvard.i2b2.pm.services.UserParamData; -import edu.harvard.i2b2.pm.util.PMUtil; -import edu.harvard.i2b2.pm.util.SecurityAuthentication; -//import edu.harvard.i2b2.pm.util.SessionKey; -import edu.harvard.i2b2.pm.ws.MessageFactory; -import edu.harvard.i2b2.pm.ws.ServicesMessage; -import java.util.Enumeration; -//import javax.servlet.http.HttpServletRequest; - - -public class ServicesHandler extends RequestHandler { - private ProjectType projectInfo = null; - private ServicesMessage getServicesMsg = null; - private final HttpServletRequest req; - protected final Log logesapi = LogFactory.getLog(getClass()); - - public ServicesHandler(ServicesMessage servicesMsg, HttpServletRequest req) throws I2B2Exception{ - this.req = req; - log.debug("Setting the servicesMsg"); - - getServicesMsg = servicesMsg; - //setDbInfo(servicesMsg.getRequestMessageType().getMessageHeader()); - } - - private void addParamsFromHeaders(Hashtable params) { - Enumeration enuStr = req.getHeaderNames(); - while (enuStr.hasMoreElements()) { - String key = enuStr.nextElement(); - Object obj = req.getHeader(key); - params.put(key, obj); - } - } - - private void saveLoginAttempt(PMDbDao pmDb, String username, String attempt) - { - // Add new timeout to it - pmDb.setLoginAttempt(username, attempt ); - - } - - - private UserType validateSuppliedPassword (String username, String password, Hashtable param, boolean skipValidation) throws Exception - { - PMDbDao pmDb = new PMDbDao(); - - if (pmDb.verifyNotLockedOut(username)) - { - saveLoginAttempt(pmDb, username, "LOCKED_OUT"); - throw new Exception ("Too many invalid attempts, user locked out"); - } - if (pmDb.verifyExpiredPassword(username) && (skipValidation == false)) - { - saveLoginAttempt(pmDb, username, "PASSWORD_EXPIRED"); - throw new Exception ("Password Expired."); - } - - if ((param.get("authentication_method") == null) || (param.get("authentication_method").equals(""))) - { - param.put("authentication_method", "BASIC"); - } - - //String SQL_QUERY ="from UserData where oid='" + username + "'"; - List response = null; - try { - response = pmDb.getUser(username, null); - } catch (I2B2DAOException e1) { - throw new Exception ( "Database error in getting user data for " + param.get("authentication_method")); - } catch (I2B2Exception e1) { - throw new Exception ("Database error in getting user data for " + param.get("authentication_method")); - } - - Iterator it = response.iterator(); - UserType user = null; - while (it.hasNext()) - { - user = (UserType)it.next(); - } - - if (user == null) - { - log.debug("Did not find user: " + username); - saveLoginAttempt(pmDb, username, "NONEXIST"); - - throw new Exception ("Unable to sign in"); - } - - // Handle all internal classnames. Also for backward compatibility need to call it NTLM. - //String classname = sanitizeClassName("edu.harvard.i2b2.pm.util.SecurityAuthentication" + param.get("authentication_method"), param); - - ClassLoader classLoader = ServicesHandler.class.getClassLoader(); - - try { - - Class securityClass = classLoader.loadClass(sanitizeClassName("edu.harvard.i2b2.pm.util.SecurityAuthentication" + param.get("authentication_method"))); - - SecurityAuthentication security = (SecurityAuthentication) securityClass.newInstance(); - - if (skipValidation == false) - security.validateUser(username, password, param); - - } catch (ClassNotFoundException e) { - log.equals("Did not find class: " + e.getMessage()); - throw new Exception ("Error loading class: " + e.getMessage()); - } - - return user; - } - - - public static String sanitizeClassName(final String AssemblyName ) throws Exception { - - - if (AssemblyName.equals("edu.harvard.i2b2.pm.util.SecurityAuthenticationBASIC")) { - - return "edu.harvard.i2b2.pm.util.SecurityAuthenticationBASIC"; // <-- hardcoded, not coming from outside of application - - } - - else if (AssemblyName.equals("edu.harvard.i2b2.pm.util.SecurityAuthenticationLDAP")) { - - return "edu.harvard.i2b2.pm.util.SecurityAuthenticationLDAP"; // <-- hardcoded, not coming from outside of application - - } - else if (AssemblyName.equals("edu.harvard.i2b2.pm.util.SecurityAuthenticationNTLM2") || - AssemblyName.equals("edu.harvard.i2b2.pm.util.SecurityAuthenticationNTLM")) { - - return "edu.harvard.i2b2.pm.util.SecurityAuthenticationNTLM2"; // <-- hardcoded, not coming from outside of application - - } - else if (AssemblyName.equals("edu.harvard.i2b2.pm.util.SecurityAuthenticationOKTA")) { - - return "edu.harvard.i2b2.pm.util.SecurityAuthenticationOKTA"; // <-- hardcoded, not coming from outside of application - - } - else if (AssemblyName.equals("edu.harvard.i2b2.pm.util.SecurityAuthenticationSAML")) { - - return "edu.harvard.i2b2.pm.util.SecurityAuthenticationSAML"; // <-- hardcoded, not coming from outside of application - - } - else - - throw new Exception("Unknown class provided"+ AssemblyName); - - } - - private boolean verifySession(PMDbDao pmDb, int timeout, String sessionId, String userId) throws Exception - { - - List response = pmDb.getSession(userId, sessionId); - - - //SessionKey k=SessionKey.Decrypt(sessionKey); - Date now=new Date(); - - Iterator it = response.iterator(); - SessionData session = null; - while (it.hasNext()) - { - log.debug("Found: " + response.size()); - session = (SessionData)it.next(); - } - - if (session == null) - return false; - - //check if the session is still valid - log.debug("checking date"); - log.debug("Now Time: "+ now.toString()); - log.debug("Current session: "+ session.getExpiredDate().toString()); - if(now.after(session.getExpiredDate())) - { - log.debug("Session Expired"); - return false; - } - log.debug("date ok"); - - // Add new timeout to it - pmDb.updateSession(userId, sessionId, timeout); - return true; - } - - public String execute() throws I2B2Exception{ - - PMDbDao pmDb = new PMDbDao(); - - log.debug("I am in the RequestHandler"); - - ConfigureType cType = new ConfigureType(); - UserType uType = new UserType(); - CellDatasType aType = new CellDatasType(); - - ResponseMessageType responseMessageType = null; - - try { - String domainId = null; - SecurityType rmt = getServicesMsg.getRequestMessageType().getMessageHeader().getSecurity(); - String project = getServicesMsg.getRequestMessageType().getMessageHeader().getProjectId(); - log.debug("My username: " + rmt.getUsername()); - - - String SQL_QUERY = null; - - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - - - //Get Enviornment Data - List response = null; - try { - response = pmDb.getEnvironment(null); - } catch (I2B2DAOException e1) { - e1.printStackTrace(); - throw new Exception ( "Database error in getting environment data"); - } catch (I2B2Exception e1) { - e1.printStackTrace(); - throw new Exception ("Database error in getting environment data"); - } - logesapi.debug("Start parsing environment results of: " + response); - - Iterator it = response.iterator(); - while (it.hasNext()) - { - cType =(ConfigureType)it.next(); - //Make sure domain is set correctly - if (!cType.getDomainName().equalsIgnoreCase(rmt.getDomain().toUpperCase())) - throw new Exception (rmt.getDomain() + " is not associated with this domain " + cType.getDomainName() + ". Please check the i2b2workbench.properties file."); - - //Get wiki and environment data - log.debug("Helpurl: " + cType.getHelpURL()); - log.debug("Environment: " + cType.getEnvironment()); - domainId = cType.getDomainName();; - } - if (cType.getEnvironment() == null) - { - throw new Exception ("Environment group has not been setup"); - } - - //Determine authentication method - log.debug("Get authentication method by using domain: " + domainId); - //String method = "", domainController= "", domain= ""; - String method = null; - for( it=pmDb.getEnvironmentData(domainId).iterator();it.hasNext();){ - HiveParamData hivedata =(HiveParamData)it.next(); - - if (hivedata.getName().equalsIgnoreCase("authentication_method")) - method = hivedata.getValue(); - } - - Hashtable params = new Hashtable(); - addParamsFromHeaders(params); // For SAML auth - - //Get params from the environment first - for( it=pmDb.getEnvironmentData(domainId).iterator();it.hasNext();){ - HiveParamData hivedata =(HiveParamData)it.next(); - params.put(hivedata.getName(), hivedata.getValue()); - } - - //Next, update the params from the user params - UserType userType = new UserType(); - userType.setUserName(rmt.getUsername()); - - for( it=pmDb.getAllParam(userType,null,null).iterator();it.hasNext();){ - UserParamData userdata =(UserParamData)it.next(); - params.put(userdata.getName(), userdata.getValue()); - - if (userdata.getName().equalsIgnoreCase("authentication_method")) - method = userdata.getValue(); - } - - String password = rmt.getPassword().getValue(); - - BodyType bodyType = getServicesMsg.getRequestType(); - Object obj = bodyType.getAny().get(0); - - - //If password begins with "SessionKey:" its a session key and decrypt it and validate it - if (password.startsWith("SessionKey:")) - { - String sessionKey=password.replace("SessionKey:", ""); - log.debug("Encrypted Session key: "+sessionKey+" passed in for validation."); - if (rmt.getPassword().getTokenMsTimeout() == null) - rmt.getPassword().setTokenMsTimeout(1800000); - if (verifySession(pmDb, rmt.getPassword().getTokenMsTimeout(), sessionKey, rmt.getUsername()) == false) - throw new Exception ("Session invalid"); - - //get the user from the service - - UserType user = null; - for( it=pmDb.getUser(rmt.getUsername(), null).iterator();it.hasNext();){ - user=(UserType)it.next(); - } - - //user = userManagerService.getUserByUserName(k.getUsername()); - if (user == null) - { - log.debug("Did not find user: " + rmt.getUsername()); - throw new Exception ("Unable to sign in"); - } - //check the password - - - //everything is good so just return the same session key and the other info - uType.setFullName(user.getFullName()); - uType.setUserName(rmt.getUsername()); - uType.setDomain(rmt.getDomain()); - uType.setEmail(user.getEmail()); - uType.setIsAdmin(user.isIsAdmin()); - PasswordType passType = new PasswordType(); - passType.setIsToken(true); - passType.setValue(password); - passType.setTokenMsTimeout(rmt.getPassword().getTokenMsTimeout()); - uType.setPassword(passType); //"SessionKey:"+sessionKey); //return the key instead of password - //uType.setKey(rmt.getPassword()); //return password so client can reaunthenticate later - } - //otherwise check username and password and generate a sessionkey for the password - else - { - - //get the user from the service - try { - log.debug("Validating user: " + rmt.getUsername()); - - boolean skipValidation = false; - if (obj instanceof JAXBElement) { - String value = null; - String name = null; - name = ((JAXBElement) obj).getName().getLocalPart(); - if (name.equalsIgnoreCase("set_password")) - skipValidation = true; - - if (rmt.getUsername().equalsIgnoreCase("AGG_SERVICE_ACCOUNT") && - (name.equalsIgnoreCase("get_user") || name.equalsIgnoreCase("set_user") || name.equalsIgnoreCase("set_user_param")) ) - skipValidation = true; - } - - UserType user = validateSuppliedPassword( rmt.getUsername(), rmt.getPassword().getValue(), params, skipValidation); - uType.setFullName(user.getFullName()); - uType.setIsAdmin(user.isIsAdmin()); - uType.setEmail(user.getEmail()); - //Dont log AGG_SERVICE_ACOUNT - if (!rmt.getUsername().equals("AGG_SERVICE_ACCOUNT")) - saveLoginAttempt(pmDb, rmt.getUsername(), "SUCCESS"); - - } catch (Exception e) - { - throw new Exception (e.getMessage()); - } - - //if password was good then set info and generate a new session key - uType.setUserName(rmt.getUsername()); - uType.setDomain(rmt.getDomain()); - - //SessionKey newKey; - - //build the date for the expiration of the key - //Calendar cal=Calendar.getInstance(); - //cal.add(Calendar.MILLISECOND, rmt.getPassword().getTokenMsTimeout()); //timeout in minutes from now - //cal.getTime(); - - //create the key in unecrypted form - //newKey=new SessionKey(rmt.getUsername(),PMUtil.getInstance().getHashedPassword(rmt.getPassword().getValue()), rmt.getDomain(), cal.getTime()); - //log.debug("Made new key for: "+rmt.getUsername()+" expires on: "+cal.getTime().toString()); - //encrypt the key - // String encryptedKey=SessionKey.Encrypt(newKey); - - log.debug("Creating new session key"); - String encryptedKey = PMUtil.getInstance().generateMessageId(); - log.debug("Saving new session key: " + encryptedKey); - int timeout = 1800000; - if (rmt.getPassword().getTokenMsTimeout() != null) - timeout = rmt.getPassword().getTokenMsTimeout(); - int result = pmDb.setSession(rmt.getUsername(), encryptedKey, timeout); - - if (result < 1) - throw new Exception("Failed to save session"); - //return the key in the password slot - PasswordType ptype = new PasswordType(); - ptype.setValue("SessionKey:" + encryptedKey); - ptype.setIsToken(true); - ptype.setTokenMsTimeout(timeout); - //ptype.sett - uType.setPassword(ptype); //password slot contains password or key - //uType.setKey(rmt.getPassword().getValue()); //"key" slot contains original password passed back so client can re-authenticate later - //for testing to undo all the previous security stuff - - } - - log.debug("Working on GetUserConfigure"); - GetUserConfigurationType userConfigurationType = (GetUserConfigurationType) helper.getObjectByClass(getServicesMsg.getRequestType().getAny(), - GetUserConfigurationType.class); - - if (userConfigurationType != null) - { - PMUtil.getInstance().convertToUppercaseStrings(userConfigurationType.getDataNeeded()); - PMUtil.getInstance().convertToUppercaseStrings(userConfigurationType.getProject()); - return runGetUserConfiguration(pmDb, userConfigurationType, rmt.getUsername(), rmt.getDomain(), cType, uType); - } - - - log.debug("Working on Rest of services: 1"); - log.debug("Working on Rest of services: " + obj); - if (obj instanceof JAXBElement) { - String value = null; - String name = null; - name = ((JAXBElement) obj).getName().getLocalPart(); - - // If admin than log entry - if (uType.isIsAdmin()) - saveLoginAttempt(pmDb, rmt.getUsername(), name); - - - log.debug("Element name is: " + name ); - if (name.equals("set_user")) - return runSetUser(pmDb, project, rmt.getUsername(), (UserType) ((JAXBElement) obj).getValue() ); - else if (name.equals("get_all_user")) - return runGetAllUser(pmDb, project, rmt.getUsername() ); - else if (name.equals("set_project")) - return runSetProject(pmDb, project, rmt.getUsername(), (ProjectType) ((JAXBElement) obj).getValue() ); - else if (name.equals("get_all_project")) - return runGetAllProject(pmDb, project, rmt.getUsername() ); - else if (name.equals("set_project_request")) - return runSetProjectRequest(pmDb, project, rmt.getUsername(), (ProjectRequestType) ((JAXBElement) obj).getValue() ); - - else if (name.equals("set_approval")) - return runSetApproval(pmDb, project, rmt.getUsername(), (ApprovalType) ((JAXBElement) obj).getValue() ); - else if (name.equals("delete_approval")) - return runDeleteApproval(pmDb, project, rmt.getUsername(), (ApprovalType) ((JAXBElement) obj).getValue() ); - else if (name.equals("get_approval")) - return runGetApproval(pmDb, project, rmt.getUsername(), (ApprovalType) ((JAXBElement) obj).getValue() ); - else if (name.equals("get_all_approval")) - return runGetAllApproval(pmDb, project, rmt.getUsername() ); - - else if (name.equals("set_cell")) - return runSetCell(pmDb, project, rmt.getUsername(), (CellDataType) ((JAXBElement) obj).getValue() ); - else if (name.equals("delete_cell")) - return runDeleteCell(pmDb, project, rmt.getUsername(), (CellDataType) ((JAXBElement) obj).getValue() ); - else if (name.equals("get_cell")) - return runGetCell(pmDb, project, rmt.getUsername(), (CellDataType) ((JAXBElement) obj).getValue() ); - else if (name.equals("get_all_cell")) - return runGetAllCell(pmDb, project, rmt.getUsername() ); - else if (name.equals("set_global")) - return runSetParam(pmDb, project, name, rmt.getUsername(), (GlobalDataType) ((JAXBElement) obj).getValue() ); - else if (name.equals("set_project_param")) - return runSetParam(pmDb, project, name, rmt.getUsername(), (ProjectType) ((JAXBElement) obj).getValue() ); - else if (name.equals("set_project_user_param")) - return runSetParam(pmDb, ((ProjectType) ((JAXBElement) obj).getValue()).getId(), name, rmt.getUsername(), (ProjectType) ((JAXBElement) obj).getValue() ); - else if (name.equals("get_all_project_user_param")) - return runGetAllParam(pmDb, project, rmt.getUsername(), (ProjectType) ((JAXBElement) obj).getValue() ); - else if (name.equals("set_user_param")) - return runSetParam(pmDb, project, name, rmt.getUsername(), (UserType) ((JAXBElement) obj).getValue() ); - else if (name.equals("set_cell_param")) - return runSetParam(pmDb, project, name, rmt.getUsername(), (CellDataType) ((JAXBElement) obj).getValue() ); - else if (name.equals("get_all_cell_param")) - return runGetAllParam(pmDb, project, rmt.getUsername(), (CellDataType) ((JAXBElement) obj).getValue() ); - else if (name.equals("get_all_user_param")) - return runGetAllParam(pmDb, project, rmt.getUsername(), (UserType) ((JAXBElement) obj).getValue() ); - else if (name.equals("set_hive_param")) - return runSetParam(pmDb, project, name, rmt.getUsername(), (ConfigureType) ((JAXBElement) obj).getValue() ); - else if (name.equals("set_role")) - return runSetParam(pmDb, project, name, rmt.getUsername(), (RoleType) ((JAXBElement) obj).getValue() ); - else if (name.equals("get_all_role")) - return runGetAllParam(pmDb, project, rmt.getUsername(), (RoleType) ((JAXBElement) obj).getValue() ); - else if (name.equals("delete_role")) - return runDeleteParam(pmDb, project, rmt.getUsername(), (RoleType) ((JAXBElement) obj).getValue() ); - else if (name.equals("get_role")) - return runGetParam(pmDb, project, rmt.getUsername(), (RoleType) ((JAXBElement) obj).getValue() ); - else if (name.equals("set_hive")) - return runSetParam(pmDb, project, name, rmt.getUsername(), (ConfigureType) ((JAXBElement) obj).getValue() ); - else if (name.equals("get_all_hive")) - return runGetAllParam(pmDb, project, rmt.getUsername(), new ConfigureType() ); - else if (name.equals("delete_hive")) - return runDeleteParam(pmDb, project, rmt.getUsername(), (ConfigureType) ((JAXBElement) obj).getValue() ); - else if (name.equals("get_hive")) - return runGetParam(pmDb, project, rmt.getUsername(), (ConfigureType) ((JAXBElement) obj).getValue() ); - else if (name.equals("delete_project")) - return runDeleteProject(pmDb, rmt.getUsername(), (ProjectType) ((JAXBElement) obj).getValue() ); - else if (name.equals("get_project")) - return runGetProject(pmDb, rmt.getUsername(), (ProjectType) ((JAXBElement) obj).getValue() ); - else if (name.equals("set_datasource")) - return runSetDatasource(pmDb, rmt.getUsername(), (DatasourceType) ((JAXBElement) obj).getValue() ); - else if (name.equals("get_all_datasource")) - return runGetAllDatasource(pmDb, project, rmt.getUsername() ); - else if (name.equals("get_user_login")) - return runUserLogin(pmDb, rmt.getUsername(), (UserLoginType) ((JAXBElement) obj).getValue() ); - - - log.debug("working on value"); - value = ((String) ((JAXBElement) obj).getValue()).trim(); - log.debug("Element is single and is: " + value); - if (name.equals("delete_user")) - return runDeleteUser(pmDb, project, rmt.getUsername(), value ); - else if (name.equals("set_password") && method != null) - throw new Exception(method + " authencation method is used, use that provider to change the password."); - else if (name.equals("set_password")) - return runSetPassword(pmDb, rmt.getUsername(), value ); - else if (name.equals("get_user")) - return runGetUser(pmDb, project, rmt.getUsername(), value ); - else if (name.equals("get_global")) - { - ParamType param = new ParamType(); - param.setId(Integer.valueOf(value)); - GlobalDataType global = new GlobalDataType(); - global.getParam().add(param); - return runGetParam(pmDb, project, rmt.getUsername(), global ); - } - else if (name.equals("get_all_global")) - { - GlobalDataType global = new GlobalDataType (); - global.setProjectPath(value); - return runGetAllParam(pmDb, project, rmt.getUsername(), global ); - } - else if (name.equals("delete_global")) - { - ParamType param = new ParamType(); - param.setId(Integer.valueOf(value)); - GlobalDataType global = new GlobalDataType(); - global.getParam().add(param); - return runDeleteParam(pmDb, project, rmt.getUsername(), global); - } - else if (name.equals("delete_project_param")) - { - ParamType param = new ParamType(); - param.setId(Integer.valueOf(value)); - ProjectType global = new ProjectType(); - global.getParam().add(param); - return runDeleteParam(pmDb, project, rmt.getUsername(), global); - } - else if (name.equals("delete_project_user_param")) - { - ParamType param = new ParamType(); - param.setId(Integer.valueOf(value)); - ProjectType global = new ProjectType(); - global.setUserName(rmt.getUsername()); - global.getParam().add(param); - return runDeleteParam(pmDb, project, rmt.getUsername(), global); - } - else if (name.equals("delete_cell_param")) - { - ParamType param = new ParamType(); - param.setId(Integer.valueOf(value)); - CellDataType global = new CellDataType(); - global.getParam().add(param); - return runDeleteParam(pmDb, project, rmt.getUsername(), global); - } - else if (name.equals("delete_hive_param")) - { - ParamType param = new ParamType(); - param.setId(Integer.valueOf(value)); - ConfigureType global = new ConfigureType(); - global.getParam().add(param); - return runDeleteParam(pmDb, project, rmt.getUsername(), global); - } - else if (name.equals("delete_user_param")) - { - ParamType param = new ParamType(); - param.setId(Integer.valueOf(value)); - UserType global = new UserType(); - global.setUserName(rmt.getUsername()); - global.getParam().add(param); - return runDeleteParam(pmDb, project, rmt.getUsername(), global); - } - - else if (name.equals("get_all_hive_param")) - { - ConfigureType lcType = new ConfigureType(); - lcType.setDomainId(value); - return runGetAllParam(pmDb, project, rmt.getUsername(),lcType);//(CellDataType) ((JAXBElement) obj).getValue() ); - } - else if (name.equals("get_all_project_param")) - { - ProjectType pType = new ProjectType(); - pType.setId(value); - return runGetAllParam(pmDb, project, rmt.getUsername(), pType ); - } - /* else if (name.equals("get_all_user_param")) - { - UserType pType = new UserType(); - pType.setUserName(value); - return runGetAllParam(pmDb, project, rmt.getUsername(), pType ); - } - */ - else if (name.equals("get_project_user_param")) - { - ParamType param = new ParamType(); - param.setId(Integer.valueOf(value)); - ProjectType global = new ProjectType(); - global.setUserName("USER"); - global.getParam().add(param); - - return runGetParam(pmDb, project, rmt.getUsername(), global ); - - // return runGetParam(pmDb, project, rmt.getUsername(), (ProjectType) ((JAXBElement) obj).getValue() ); - } - else if (name.equals("get_project_param")) - { - ParamType param = new ParamType(); - param.setId(Integer.valueOf(value)); - ProjectType global = new ProjectType(); - global.getParam().add(param); - - return runGetParam(pmDb, project, rmt.getUsername(), global ); - } - else if (name.equals("get_cell_param")) - { - ParamType param = new ParamType(); - param.setId(Integer.valueOf(value)); - CellDataType global = new CellDataType(); - global.getParam().add(param); - - return runGetParam(pmDb, project, rmt.getUsername(), global ); - } - else if (name.equals("get_user_param")) - { - ParamType param = new ParamType(); - param.setId(Integer.valueOf(value)); - UserType global = new UserType(); - global.getParam().add(param); - - return runGetParam(pmDb, project, rmt.getUsername(), global ); - } - else if (name.equals("get_hive_param")) - { - ParamType param = new ParamType(); - param.setId(Integer.valueOf(value)); - ConfigureType global = new ConfigureType(); - global.getParam().add(param); - - return runGetParam(pmDb, project, rmt.getUsername(), global ); - } - else if (name.equals("get_all_project_request")) - { - return runGetAllProjectRequest(pmDb, project, rmt.getUsername() ); - } - else if (name.equals("get_project_request")) - { - log.debug("Got this:" + value); - return null; - } - } - } - catch (Exception ee) - { - log.error(ee.getMessage()); - // throw new Exception (ee.getMessage()); - ee.printStackTrace(); - - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); - responseMessageType = MessageFactory.doBuildErrorResponse(messageHeader, - ee.getMessage()); - } - - String responseVdo = "DONE"; - try { - responseVdo = MessageFactory.convertToXMLString(responseMessageType); - } catch (I2B2Exception e) { - log.error(e.getMessage()); - } - return responseVdo; - } - - private String runUserLogin(PMDbDao pmDb, String caller, UserLoginType value) { - ResponseMessageType responseMessageType = null; - - try { - - - List response = null; - try { - response = pmDb.getUserLogin(value, caller); - } catch (I2B2DAOException e1) { - throw new Exception ( "Database error in getting user data for NTLM"); - } catch (I2B2Exception e1) { - throw new Exception ("Database error in getting user data for NTLM"); - } - - Iterator it = response.iterator(); - UserLoginsType users = new UserLoginsType(); - log.debug("Records returned: " + response.size()); - while (it.hasNext()) - { - UserLoginType user = (UserLoginType)it.next(); - users.getUserLogin().add(user); - } - //everything is good so just return the same session key and the other info - - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); - responseMessageType = MessageFactory.createBuildResponse(messageHeader,users); - - } - catch (Exception ee) - { - log.error(ee.getMessage()); - // throw new Exception (ee.getMessage()); - ee.printStackTrace(); - - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); - responseMessageType = MessageFactory.doBuildErrorResponse(messageHeader, - ee.getMessage()); - } - - String responseVdo = "DONE"; - try { - responseVdo = MessageFactory.convertToXMLString(responseMessageType); - } catch (I2B2Exception e) { - log.error(e.getMessage()); - } - return responseVdo; - } - - private String runGetAllDatasource(PMDbDao pmDb, String project, String caller) { - ResponseMessageType responseMessageType = null; - - try { - - - List response = new ArrayList(); - - //List availableDatasources = new ArrayList(); - try { - - // retrieve the mbean server - MBeanServer server = java.lang.management.ManagementFactory.getPlatformMBeanServer(); - - // key for retrieving mbeans representing LOCAL Datasource - // configuration from JMX namespace: jboss.as:subsystem=datasources (1) - - //add datasources of given type to the list - addDatasourcesForKeyName(response, server, "data-source"); - - // key for retrieving mbeans representing XA Datasource - // configuration from JMX namespace: jboss.as:subsystem=datasources (2) - addDatasourcesForKeyName(response, server, "xa-data-source"); - - } catch (Exception e) { - - throw new Exception ("Database error in getting datasources"); - } - - Iterator it = response.iterator(); - DatasourcesType users = new DatasourcesType(); - log.debug("Records returned: " + response.size()); - /* - while (it.hasNext()) - { - DataSource user = (DataSource)it.next(); - DatasourceType datasource = new DatasourceType(); - datasource.setConnectionUrl(user.getConnection().getMetaData().getURL()); - datasource.setDriverName(user.getConnection().getMetaData().getDriverName()); - datasource.setUserName(user.getConnection().getMetaData().getUserName()); - users.getDatasource().add(datasource); - //users.getProjectRequest().add(user); - } - */ - //everything is good so just return the same session key and the other info - // get list of hot deployed datasources - Context initCtx = new InitialContext(); - // NamingEnumeration namedEnum = initCtx.list("java:/"); - NamingEnumeration namedEnum = initCtx.listBindings(""); - while (namedEnum.hasMore()) - { - try { - //NameClassPair nameClassPair = (NameClassPair)namedEnum.nextElement(); - Binding nameClassPair = (Binding)namedEnum.next(); - - if (nameClassPair.getObject() instanceof DataSource) { - - DataSource user = (DataSource)nameClassPair.getObject(); - DatasourceType datasource = new DatasourceType(); - - - for(Field f : nameClassPair.getObject().getClass().getDeclaredFields()) { - try { - f.setAccessible(true); - if (f.getName().equals("jndiName")) - { - datasource.setJndiName(f.get(nameClassPair.getObject()).toString()); - datasource.setPoolName(datasource.getJndiName().substring(datasource.getJndiName().lastIndexOf("/")+1)); - try { - - Connection conn = user.getConnection(); - datasource.setActive(true); - } catch (Exception ee) - { - datasource.setActive(false); - } - } - if (f.getName().equals("delegate")) - { - Object obj = f.get(nameClassPair.getObject()); - //System.out.println(f.getName()); - - for(Field f2 : obj.getClass().getDeclaredFields()) { - f2.setAccessible(true); - - if (f2.getName().equals("defaultCRI")) - { - Object obj2 = f2.get(obj); - for(Field f3 : obj2.getClass().getDeclaredFields()) { - f3.setAccessible(true); - if (f3.getName().equals("user")) - datasource.setUserName(f3.get(obj2).toString()); - // else if (f3.getName().equals("password")) - // datasource.setPassword(f3.get(obj2).toString()); - } - } - if (f2.getName().equals("mcf")) - { - Object obj2 = f2.get(obj); - for(Field f3 : obj2.getClass().getDeclaredFields()) { - f3.setAccessible(true); - if (f3.getName().equals("connectionURL")) - datasource.setConnectionUrl(f3.get(obj2).toString()); - else if (f3.getName().equals("driverClass")) - datasource.setDriverName(f3.get(obj2).toString()); - else if (f3.getName().equals("jta")) - datasource.setJta(Boolean.valueOf(f3.get(obj2).toString())); - log.debug(f3.getName()); - } - } - } - - } - - - //System.out.println(f.get(nameClassPair.getObject())); - } catch(IllegalAccessException e) { - e.printStackTrace(); - } - } - users.getDatasource().add(datasource); - } - } catch (Exception e) - { - //e.printStackTrace(); - //throw new Exception ("Database error in getting datasources, " + e.getMessage()); - - } - } - - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); - responseMessageType = MessageFactory.createBuildResponse(messageHeader,users); - - } - catch (Exception ee) - { - log.error(ee.getMessage()); - // throw new Exception (ee.getMessage()); - ee.printStackTrace(); - - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); - responseMessageType = MessageFactory.doBuildErrorResponse(messageHeader, - ee.getMessage()); - } - - String responseVdo = "DONE"; - try { - responseVdo = MessageFactory.convertToXMLString(responseMessageType); - } catch (I2B2Exception e) { - log.error(e.getMessage()); - } - return responseVdo; - } - - private void addDatasourcesForKeyName(List availableDatasources, MBeanServer server, String dataSourceKeyName) throws MalformedObjectNameException, NamingException, AttributeNotFoundException, InstanceNotFoundException, MBeanException, ReflectionException { - - // Get the starting point of the namespace - Context ctx = new InitialContext(); - - // create jmx filter name eg. (3) - // "jboss.as:subsystem=datasources,xa-data-source=*" - final ObjectName filterName = new ObjectName("jboss.as:subsystem=datasources," + dataSourceKeyName + "=*"); - - // get the results matching given filter. (4) - final Set mBeans = server.queryMBeans(filterName, null); - - // iterate over mbeans and retrieve information about jndi-name of datasource - for (final ObjectInstance mBean : mBeans) { - - // get name for mbean describing current datasource mbean - ObjectName mbeanName = mBean.getObjectName(); - - // one of the attributes of mbean is - // "jndiName" , we will read that attribute now:(5) - String bindName = (String) server.getAttribute(mbeanName, "jndiName"); - - // having the jndi-name, we can look up the datasource instance - DataSource ds = (DataSource) ctx.lookup(bindName); - availableDatasources.add(ds); - } - } - - private String runSetDatasource(PMDbDao pmDb, String username, DatasourceType value) { - ResponseMessageType responseMessageType = null; - - try { - - ModelControllerClient client = ModelControllerClient.Factory.create(InetAddress.getByName("localhost"), 9990); - - ModelNode request = new ModelNode(); - request.get(ClientConstants.OP).set(ClientConstants.ADD); - request.get(ClientConstants.OP_ADDR).add("subsystem","datasources"); - request.get(ClientConstants.OP_ADDR).add("data-source",value.getDataSource()); - request.get("jta").set(false); - request.get("jndi-name").set("java:/" + value.getDataSource()); - request.get("pool-name").set(value.getPoolName()); - request.get("use-java-context").set(true); - request.get("use-ccm").set(false); - - request.get("connection-url").set(value.getConnectionUrl()); - request.get("driver-name").set(value.getDriverName()); - request.get("transaction-isolation").set("TRANSACTION_READ_COMMITTED"); - - request.get("min-pool-size").set(5); - request.get("max-pool-size").set(20); - request.get("pool-prefill").set(true); - request.get("pool-use-strict-min").set(false); - request.get("flush-strategy").set("FailingConnectionOnly"); - - request.get("user-name").set(value.getUserName()); - request.get("password").set(value.getPassword()); - - request.get("prepared-statements-cache-size").set(32); - request.get("share-prepared-statements").set(false); - - client.execute(new OperationBuilder(request).build()); - client.close(); - - ResultStatusType results = new ResultStatusType(); - StatusType status = new StatusType(); - status.setValue("1 records"); - results.setStatus(status); - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); - responseMessageType = MessageFactory.createBuildResponse(messageHeader,results); - } - catch (Exception ee) - { - log.error(ee.getMessage()); - // throw new Exception (ee.getMessage()); - ee.printStackTrace(); - - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); - responseMessageType = MessageFactory.doBuildErrorResponse(messageHeader, - ee.getMessage()); - } - - String responseVdo = "DONE"; - try { - responseVdo = MessageFactory.convertToXMLString(responseMessageType); - } catch (I2B2Exception e) { - log.error(e.getMessage()); - } - return responseVdo; - } - - //All Param process - private String runDeleteParam(PMDbDao pmDb, String project, String caller, - Object utype) { - ResponseMessageType responseMessageType = null; - - try { - int result = -1; - result = pmDb.deleteParam(utype, project, caller); - - ResultStatusType results = new ResultStatusType(); - StatusType status = new StatusType(); - status.setValue(result + " records"); - results.setStatus(status); - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); - responseMessageType = MessageFactory.createBuildResponse(messageHeader,results); - - } - catch (Exception ee) - { - log.error(ee.getMessage()); - // throw new Exception (ee.getMessage()); - ee.printStackTrace(); - - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); - responseMessageType = MessageFactory.doBuildErrorResponse(messageHeader, - ee.getMessage()); - } - - String responseVdo = "DONE"; - try { - responseVdo = MessageFactory.convertToXMLString(responseMessageType); - } catch (I2B2Exception e) { - log.error(e.getMessage()); - } - return responseVdo; - } - - private String runSetParam(PMDbDao pmDb, String project, String name, String caller, - Object utype) { - ResponseMessageType responseMessageType = null; - - try { - - //String SQL_QUERY ="from UserData where oid='" + username + "'"; - - log.debug("Start of setParam"); - int result = -1; - result = pmDb.setParam(utype,project, name, caller); - - ResultStatusType results = new ResultStatusType(); - StatusType status = new StatusType(); - status.setValue(result + " records"); - results.setStatus(status); - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); - responseMessageType = MessageFactory.createBuildResponse(messageHeader,results); - - } - catch (Exception ee) - { - log.error(ee.getMessage()); - // throw new Exception (ee.getMessage()); - ee.printStackTrace(); - - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); - responseMessageType = MessageFactory.doBuildErrorResponse(messageHeader, - ee.getMessage()); - } - - String responseVdo = "DONE"; - try { - responseVdo = MessageFactory.convertToXMLString(responseMessageType); - } catch (I2B2Exception e) { - log.error(e.getMessage()); - } - return responseVdo; - } - - - - - private String runGetAllProjectRequest(PMDbDao pmDb, String project, String caller) { - ResponseMessageType responseMessageType = null; - - try { - - - List response = null; - try { - response = pmDb.getAllProjectRequest(project, caller); - } catch (I2B2DAOException e1) { - throw new Exception ( "Database error in getting user data for NTLM"); - } catch (I2B2Exception e1) { - throw new Exception ("Database error in getting user data for NTLM"); - } - - Iterator it = response.iterator(); - ProjectRequestsType users = new ProjectRequestsType(); - log.debug("Records returned: " + response.size()); - while (it.hasNext()) - { - ProjectRequestType user = (ProjectRequestType)it.next(); - users.getProjectRequest().add(user); - } - //everything is good so just return the same session key and the other info - - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); - responseMessageType = MessageFactory.createBuildResponse(messageHeader,users); - - } - catch (Exception ee) - { - log.error(ee.getMessage()); - // throw new Exception (ee.getMessage()); - ee.printStackTrace(); - - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); - responseMessageType = MessageFactory.doBuildErrorResponse(messageHeader, - ee.getMessage()); - } - - String responseVdo = "DONE"; - try { - responseVdo = MessageFactory.convertToXMLString(responseMessageType); - } catch (I2B2Exception e) { - log.error(e.getMessage()); - } - return responseVdo; - } - - private String runSetProjectRequest(PMDbDao pmDb, String project, String caller, - ProjectRequestType value) { - ResponseMessageType responseMessageType = null; - - try { - - //String SQL_QUERY ="from UserData where oid='" + username + "'"; - - log.debug("Start of setProjectRequest"); - - String result = ""; - - - List response = null; - try { - response = pmDb.setProjectRequest(value,project, caller); - } catch (I2B2DAOException e1) { - e1.printStackTrace(); - throw new Exception ( "Database error in setting Projet Request: " + e1.getMessage()); - } catch (I2B2Exception e1) { - e1.printStackTrace(); - throw new Exception ("Database error in setting Projet Request: " + e1.getMessage()); - } - - Iterator it = response.iterator(); - log.debug("Records returned: " + response.size()); - while (it.hasNext()) - { - ProjectRequestType user = (ProjectRequestType)it.next(); - result = user.getId(); - log.debug("added ID: " + user.getId()); - } - - ResultStatusType results = new ResultStatusType(); - StatusType status = new StatusType(); - status.setValue(result); - results.setStatus(status); - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); - responseMessageType = MessageFactory.createBuildResponse(messageHeader,results); - - } - catch (Exception ee) - { - log.error(ee.getMessage()); - // throw new Exception (ee.getMessage()); - ee.printStackTrace(); - - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); - responseMessageType = MessageFactory.doBuildErrorResponse(messageHeader, - ee.getMessage()); - } - - String responseVdo = "DONE"; - try { - responseVdo = MessageFactory.convertToXMLString(responseMessageType); - } catch (I2B2Exception e) { - log.error(e.getMessage()); - } - return responseVdo; - } - - private String runGetAllParam(PMDbDao pmDb, String project, String caller, Object utype) { - ResponseMessageType responseMessageType = null; - - //ParamsType users = new ParamsType();; - Object users = null; - try { - - - List response = null; - try { - int result = -1; - //response = pmDb.getAllParam(utype,project, caller); - - //Iterator it = response.iterator(); - // users = new Para(); - - - if (utype instanceof RoleType) - { - response = pmDb.getAllParam(utype,project, caller); - - log.debug("Records returned: " + response.size()); - Iterator it = response.iterator(); - users = new RolesType(); - //ParamsType user = null; - - - while (it.hasNext()) - { - RoleType user = (RoleType)it.next(); - ((RolesType) users).getRole().add(user); - } - - } else if ((utype instanceof ConfigureType) && - ((((ConfigureType) utype).getDomainId() == null))) - { - response = pmDb.getAllParam(utype,project, caller); - - log.debug("Records returned: " + response.size()); - Iterator it = response.iterator(); - users = new ConfiguresType(); - //ParamsType user = null; - while (it.hasNext()) - { - ConfigureType user = (ConfigureType)it.next(); - ((ConfiguresType) users).getHive().add(user); - } - } else if (utype instanceof UserType) - { - response = pmDb.getAllParam(utype,project, caller); - - log.debug("Records returned: " + response.size()); - Iterator it = response.iterator(); - - users = new UsersType(); - - UserType userType = new UserType(); - - while (it.hasNext()) - { - UserParamData user = (UserParamData)it.next(); - - if (((UserType)userType).getUserName() != null && !user.getUser().equals(((UserType)userType).getUserName())) - { - log.debug("adding user: " + ((UserType)userType).getUserName()); - ((UsersType)users).getUser().add(userType); - userType = new UserType(); - } - - ParamType param = new ParamType(); - param.setName(user.getName()); - param.setId(user.getId()); - param.setDatatype(user.getDatatype()); - param.setValue(user.getValue()); - ((UserType)userType).setUserName(user.getUser()); - ((UserType)userType).getParam().add(param); - log.debug("adding param: " + param.getName()); - } - ((UsersType)users).getUser().add(userType); - // } - } else - { - response = pmDb.getAllParam(utype,project, caller); - - log.debug("Records returned: " + response.size()); - Iterator it = response.iterator(); - users = new ParamsType(); - //ParamsType user = null; - - - while (it.hasNext()) - { - ParamType user = (ParamType)it.next(); - ((ParamsType) users).getParam().add(user); - //((ParamType) users)..getRole().add(user); - } - } - - } catch (I2B2DAOException e1) { - throw new Exception ( "Database error in getting user data for NTLM"); - } catch (I2B2Exception e1) { - throw new Exception ("Database error in getting user data for NTLM"); - } - - - //everything is good so just return the same session key and the other info - - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); - responseMessageType = MessageFactory.createBuildResponse(messageHeader,users); - - } - catch (Exception ee) - { - log.error(ee.getMessage()); - // throw new Exception (ee.getMessage()); - ee.printStackTrace(); - - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); - responseMessageType = MessageFactory.doBuildErrorResponse(messageHeader, - ee.getMessage()); - } - - String responseVdo = "DONE"; - try { - responseVdo = MessageFactory.convertToXMLString(responseMessageType); - } catch (I2B2Exception e) { - log.error(e.getMessage()); - } - return responseVdo; - } - - private String runGetParam(PMDbDao pmDb, String project, String caller, - Object utype) { - ResponseMessageType responseMessageType = null; - - Object users = null; - - try { - - log.debug("In GetGlobal"); - List response = null; - try { - int result = -1; - if (utype instanceof RoleType) - { - response = pmDb.getParam(utype, true); - - Iterator it = response.iterator(); - //ParamsType user = null; - users = new RolesType(); - while (it.hasNext()) - { - RoleType user = (RoleType)it.next(); - ((RolesType) users).getRole().add(user); - } - } else if (utype instanceof ConfigureType) - { - response = pmDb.getParam(utype, true); - - Iterator it = response.iterator(); - //ParamsType user = null; - while (it.hasNext()) - users = (ConfigureType)it.next(); - } else if (utype instanceof GlobalDataType) - { - response = pmDb.getParam(utype, true); - - Iterator it = response.iterator(); - //ParamsType user = null; - while (it.hasNext()) - users = (GlobalDataType)it.next(); - } else { - response = pmDb.getParam(utype, true); - - Iterator it = response.iterator(); - //ParamsType user = null; - while (it.hasNext()) - users = (ParamType)it.next(); - - } - } catch (I2B2DAOException e1) { - throw new Exception ( "Database error in getting user data for NTLM"); - } catch (I2B2Exception e1) { - throw new Exception ("Database error in getting user data for NTLM"); - } - - - - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); - responseMessageType = MessageFactory.createBuildResponse(messageHeader,users); - - } - catch (Exception ee) - { - log.error(ee.getMessage()); - // throw new Exception (ee.getMessage()); - ee.printStackTrace(); - - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); - responseMessageType = MessageFactory.doBuildErrorResponse(messageHeader, - ee.getMessage()); - } - - String responseVdo = "DONE"; - try { - responseVdo = MessageFactory.convertToXMLString(responseMessageType); - } catch (I2B2Exception e) { - log.error(e.getMessage()); - } - return responseVdo; - } - - - //All Users process - private String runDeleteUser(PMDbDao pmDb, String project, String caller, - String user) { - ResponseMessageType responseMessageType = null; - - try { - int result = pmDb.deleteUser(user, caller); - - ResultStatusType results = new ResultStatusType(); - StatusType status = new StatusType(); - status.setValue(result + " records"); - results.setStatus(status); - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); - responseMessageType = MessageFactory.createBuildResponse(messageHeader,results); - - } - catch (Exception ee) - { - log.error(ee.getMessage()); - // throw new Exception (ee.getMessage()); - ee.printStackTrace(); - - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); - responseMessageType = MessageFactory.doBuildErrorResponse(messageHeader, - ee.getMessage()); - } - - String responseVdo = "DONE"; - try { - responseVdo = MessageFactory.convertToXMLString(responseMessageType); - } catch (I2B2Exception e) { - log.error(e.getMessage()); - } - return responseVdo; - } - - - private String runSetPassword(PMDbDao pmDb, String caller, String password) { - ResponseMessageType responseMessageType = null; - - try { - - int result = pmDb.setPassword(password, caller); - - ResultStatusType results = new ResultStatusType(); - StatusType status = new StatusType(); - status.setValue(result + " records"); - results.setStatus(status); - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); - responseMessageType = MessageFactory.createBuildResponse(messageHeader,results); - - } - catch (Exception ee) - { - log.error(ee.getMessage()); - // throw new Exception (ee.getMessage()); - ee.printStackTrace(); - - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); - responseMessageType = MessageFactory.doBuildErrorResponse(messageHeader, - ee.getMessage()); - } - - String responseVdo = "DONE"; - try { - responseVdo = MessageFactory.convertToXMLString(responseMessageType); - } catch (I2B2Exception e) { - log.error(e.getMessage()); - } - return responseVdo; - } - - private String runSetUser(PMDbDao pmDb, String project, String caller, - UserType utype) { - ResponseMessageType responseMessageType = null; - - try { - int result = pmDb.setUser(utype, caller); - - ResultStatusType results = new ResultStatusType(); - StatusType status = new StatusType(); - status.setValue(result + " records"); - results.setStatus(status); - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); - responseMessageType = MessageFactory.createBuildResponse(messageHeader,results); - - } - catch (Exception ee) - { - log.error(ee.getMessage()); - // throw new Exception (ee.getMessage()); - ee.printStackTrace(); - - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); - responseMessageType = MessageFactory.doBuildErrorResponse(messageHeader, - ee.getMessage()); - } - - String responseVdo = "DONE"; - try { - responseVdo = MessageFactory.convertToXMLString(responseMessageType); - } catch (I2B2Exception e) { - log.error(e.getMessage()); - } - return responseVdo; - } - - - private String runGetAllUser(PMDbDao pmDb, String project, String caller) { - ResponseMessageType responseMessageType = null; - - try { - - - List response = null; - try { - response = pmDb.getAllUser(project, caller); - } catch (I2B2DAOException e1) { - throw new Exception ( "Database error in getting user data for NTLM"); - } catch (I2B2Exception e1) { - throw new Exception ("Database error in getting user data for NTLM"); - } - - Iterator it = response.iterator(); - UsersType users = new UsersType(); - log.debug("Records returned: " + response.size()); - while (it.hasNext()) - { - UserType user = (UserType)it.next(); - users.getUser().add(user); - log.debug("added: " + user.getUserName()); - } - //everything is good so just return the same session key and the other info - - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); - responseMessageType = MessageFactory.createBuildResponse(messageHeader,users); - - } - catch (Exception ee) - { - log.error(ee.getMessage()); - // throw new Exception (ee.getMessage()); - ee.printStackTrace(); - - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); - responseMessageType = MessageFactory.doBuildErrorResponse(messageHeader, - ee.getMessage()); - } - - String responseVdo = "DONE"; - try { - responseVdo = MessageFactory.convertToXMLString(responseMessageType); - } catch (I2B2Exception e) { - log.error(e.getMessage()); - } - return responseVdo; - } - - private String runGetUser(PMDbDao pmDb, String project, String caller, - String username) { - ResponseMessageType responseMessageType = null; - - try { - - - List response = null; - try { - response = pmDb.getUser(username, caller); - } catch (I2B2DAOException e1) { - throw new Exception ( "Database error in getting user data for NTLM"); - } catch (I2B2Exception e1) { - throw new Exception ("Database error in getting user data for NTLM"); - } - - Iterator it = response.iterator(); - UserType user = null; - while (it.hasNext()) - user = (UserType)it.next(); - - //user = userManagerService.getUserByUserName(k.getUsername()); - if (user == null) - throw new Exception ("Unable to sign in"); - - - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); - responseMessageType = MessageFactory.createBuildResponse(messageHeader,user); - - } - catch (Exception ee) - { - log.error(ee.getMessage()); - // throw new Exception (ee.getMessage()); - ee.printStackTrace(); - - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); - responseMessageType = MessageFactory.doBuildErrorResponse(messageHeader, - ee.getMessage()); - } - - String responseVdo = "DONE"; - try { - responseVdo = MessageFactory.convertToXMLString(responseMessageType); - } catch (I2B2Exception e) { - log.error(e.getMessage()); - } - return responseVdo; - } - - //All Cell process - private String runDeleteCell(PMDbDao pmDb, String project, String caller, CellDataType utype) { - ResponseMessageType responseMessageType = null; - - try { - int result = pmDb.deleteCell(utype.getId(), utype.getProjectPath(), caller); - - ResultStatusType results = new ResultStatusType(); - StatusType status = new StatusType(); - status.setValue(result + " records"); - results.setStatus(status); - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); - responseMessageType = MessageFactory.createBuildResponse(messageHeader,results); - - } - catch (Exception ee) - { - log.error(ee.getMessage()); - // throw new Exception (ee.getMessage()); - ee.printStackTrace(); - - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); - responseMessageType = MessageFactory.doBuildErrorResponse(messageHeader, - ee.getMessage()); - } - - String responseVdo = "DONE"; - try { - responseVdo = MessageFactory.convertToXMLString(responseMessageType); - } catch (I2B2Exception e) { - log.error(e.getMessage()); - } - return responseVdo; - } - - private String runSetCell(PMDbDao pmDb, String project, String caller, - CellDataType utype) { - ResponseMessageType responseMessageType = null; - - try { - - //String SQL_QUERY ="from UserData where oid='" + username + "'"; - - int result = pmDb.setCell(utype, project, caller); - - ResultStatusType results = new ResultStatusType(); - StatusType status = new StatusType(); - status.setValue(result + " records"); - results.setStatus(status); - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); - responseMessageType = MessageFactory.createBuildResponse(messageHeader,results); - - } - catch (Exception ee) - { - log.error(ee.getMessage()); - // throw new Exception (ee.getMessage()); - ee.printStackTrace(); - - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); - responseMessageType = MessageFactory.doBuildErrorResponse(messageHeader, - ee.getMessage()); - } - - String responseVdo = "DONE"; - try { - responseVdo = MessageFactory.convertToXMLString(responseMessageType); - } catch (I2B2Exception e) { - log.error(e.getMessage()); - } - return responseVdo; - } - - - private String runGetAllCell(PMDbDao pmDb, String project, String caller) { - ResponseMessageType responseMessageType = null; - - try { - - - List response = null; - try { - response = pmDb.getAllCell(project, caller); - } catch (I2B2DAOException e1) { - throw new Exception ( "Database error in getting user data for NTLM"); - } catch (I2B2Exception e1) { - throw new Exception ("Database error in getting user data for NTLM"); - } - - Iterator it = response.iterator(); - CellDatasType users = new CellDatasType(); - log.debug("Records returned: " + response.size()); - while (it.hasNext()) - { - CellDataType user = (CellDataType)it.next(); - users.getCellData().add(user); - log.debug("added: " + user.getName()); - } - //everything is good so just return the same session key and the other info - - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); - responseMessageType = MessageFactory.createBuildResponse(messageHeader,users); - - } - catch (Exception ee) - { - log.error(ee.getMessage()); - // throw new Exception (ee.getMessage()); - ee.printStackTrace(); - - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); - responseMessageType = MessageFactory.doBuildErrorResponse(messageHeader, - ee.getMessage()); - } - - String responseVdo = "DONE"; - try { - responseVdo = MessageFactory.convertToXMLString(responseMessageType); - } catch (I2B2Exception e) { - log.error(e.getMessage()); - } - return responseVdo; - } - - private String runGetCell(PMDbDao pmDb, String project, - String owner, CellDataType utype) { - ResponseMessageType responseMessageType = null; - - try { - - log.debug("In runGetCell, with cell of: " + utype.getId() + " | " +utype.getProjectPath()); - - List response = null; - try { - response = pmDb.getCell(utype.getId(), utype.getProjectPath(), true); - } catch (I2B2DAOException e1) { - throw new Exception ( "Database error in getting user data for NTLM"); - } catch (I2B2Exception e1) { - throw new Exception ("Database error in getting user data for NTLM"); - } - - Iterator it = response.iterator(); - CellDataType user = null; - while (it.hasNext()) - user = (CellDataType)it.next(); - - //user = userManagerService.getUserByUserName(k.getUsername()); - if (user == null) - throw new Exception ("Cell does not exist"); - - - - - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); - responseMessageType = MessageFactory.createBuildResponse(messageHeader,user); - - } - catch (Exception ee) - { - log.error(ee.getMessage()); - // throw new Exception (ee.getMessage()); - ee.printStackTrace(); - - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); - responseMessageType = MessageFactory.doBuildErrorResponse(messageHeader, - ee.getMessage()); - } - - String responseVdo = "DONE"; - try { - responseVdo = MessageFactory.convertToXMLString(responseMessageType); - } catch (I2B2Exception e) { - log.error(e.getMessage()); - } - return responseVdo; - } - - - - //All Approval process - private String runDeleteApproval(PMDbDao pmDb, String project, String caller, ApprovalType utype) { - ResponseMessageType responseMessageType = null; - - try { - int result = pmDb.deleteApproval(utype.getId(), project, caller); - - ResultStatusType results = new ResultStatusType(); - StatusType status = new StatusType(); - status.setValue(result + " records"); - results.setStatus(status); - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); - responseMessageType = MessageFactory.createBuildResponse(messageHeader,results); - - } - catch (Exception ee) - { - log.error(ee.getMessage()); - // throw new Exception (ee.getMessage()); - ee.printStackTrace(); - - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); - responseMessageType = MessageFactory.doBuildErrorResponse(messageHeader, - ee.getMessage()); - } - - String responseVdo = "DONE"; - try { - responseVdo = MessageFactory.convertToXMLString(responseMessageType); - } catch (I2B2Exception e) { - log.error(e.getMessage()); - } - return responseVdo; - } - - private String runSetApproval(PMDbDao pmDb, String project, String caller, - ApprovalType utype) { - ResponseMessageType responseMessageType = null; - - try { - - //String SQL_QUERY ="from UserData where oid='" + username + "'"; - - int result = pmDb.setApproval(utype, project, caller); - - ResultStatusType results = new ResultStatusType(); - StatusType status = new StatusType(); - status.setValue(result + ""); - results.setStatus(status); - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); - responseMessageType = MessageFactory.createBuildResponse(messageHeader,results); - - } - catch (Exception ee) - { - log.error(ee.getMessage()); - // throw new Exception (ee.getMessage()); - ee.printStackTrace(); - - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); - responseMessageType = MessageFactory.doBuildErrorResponse(messageHeader, - ee.getMessage()); - } - - String responseVdo = "DONE"; - try { - responseVdo = MessageFactory.convertToXMLString(responseMessageType); - } catch (I2B2Exception e) { - log.error(e.getMessage()); - } - return responseVdo; - } - - - private String runGetAllApproval(PMDbDao pmDb, String project, String caller) { - ResponseMessageType responseMessageType = null; - - try { - - - List response = null; - try { - response = pmDb.getAllApproval(project, caller); - } catch (I2B2DAOException e1) { - throw new Exception ( "Database error in getting user data for NTLM"); - } catch (I2B2Exception e1) { - throw new Exception ("Database error in getting user data for NTLM"); - } - - Iterator it = response.iterator(); - ApprovalsType users = new ApprovalsType(); - log.debug("Records returned: " + response.size()); - while (it.hasNext()) - { - ApprovalType user = (ApprovalType)it.next(); - users.getApproval().add(user); - log.debug("added: " + user.getName()); - } - //everything is good so just return the same session key and the other info - - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); - responseMessageType = MessageFactory.createBuildResponse(messageHeader,users); - - } - catch (Exception ee) - { - log.error(ee.getMessage()); - // throw new Exception (ee.getMessage()); - ee.printStackTrace(); - - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); - responseMessageType = MessageFactory.doBuildErrorResponse(messageHeader, - ee.getMessage()); - } - - String responseVdo = "DONE"; - try { - responseVdo = MessageFactory.convertToXMLString(responseMessageType); - } catch (I2B2Exception e) { - log.error(e.getMessage()); - } - return responseVdo; - } - - private String runGetApproval(PMDbDao pmDb, String project, - String owner, ApprovalType utype) { - ResponseMessageType responseMessageType = null; - - try { - - List response = null; - try { - response = pmDb.getApproval(utype, true); - } catch (I2B2DAOException e1) { - throw new Exception ( "Database error in getting user data for NTLM"); - } catch (I2B2Exception e1) { - throw new Exception ("Database error in getting user data for NTLM"); - } - - - Iterator it = response.iterator(); - ApprovalsType users = new ApprovalsType(); - log.debug("Records returned: " + response.size()); - while (it.hasNext()) - { - ApprovalType user = (ApprovalType)it.next(); - users.getApproval().add(user); - log.debug("added: " + user.getName()); - } - - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); - responseMessageType = MessageFactory.createBuildResponse(messageHeader,users); - - } - catch (Exception ee) - { - log.error(ee.getMessage()); - // throw new Exception (ee.getMessage()); - ee.printStackTrace(); - - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); - responseMessageType = MessageFactory.doBuildErrorResponse(messageHeader, - ee.getMessage()); - } - - String responseVdo = "DONE"; - try { - responseVdo = MessageFactory.convertToXMLString(responseMessageType); - } catch (I2B2Exception e) { - log.error(e.getMessage()); - } - return responseVdo; - } - - - - //All Project process - private String runDeleteProject(PMDbDao pmDb, String caller, Object project) { - ResponseMessageType responseMessageType = null; - - try { - int result = pmDb.deleteProject(project, caller); - - ResultStatusType results = new ResultStatusType(); - StatusType status = new StatusType(); - status.setValue(result + " records"); - results.setStatus(status); - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); - responseMessageType = MessageFactory.createBuildResponse(messageHeader,results); - - } - catch (Exception ee) - { - log.error(ee.getMessage()); - // throw new Exception (ee.getMessage()); - ee.printStackTrace(); - - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); - responseMessageType = MessageFactory.doBuildErrorResponse(messageHeader, - ee.getMessage()); - } - - String responseVdo = "DONE"; - try { - responseVdo = MessageFactory.convertToXMLString(responseMessageType); - } catch (I2B2Exception e) { - log.error(e.getMessage()); - } - return responseVdo; - } - - private String runSetProject(PMDbDao pmDb, String project, String caller, - ProjectType utype) { - ResponseMessageType responseMessageType = null; - - try { - - //String SQL_QUERY ="from UserData where oid='" + username + "'"; - - int result = pmDb.setProject(utype, caller); - - ResultStatusType results = new ResultStatusType(); - StatusType status = new StatusType(); - status.setValue(result + " records"); - results.setStatus(status); - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); - responseMessageType = MessageFactory.createBuildResponse(messageHeader,results); - - } - catch (Exception ee) - { - log.error(ee.getMessage()); - // throw new Exception (ee.getMessage()); - ee.printStackTrace(); - - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); - responseMessageType = MessageFactory.doBuildErrorResponse(messageHeader, - ee.getMessage()); - } - - String responseVdo = "DONE"; - try { - responseVdo = MessageFactory.convertToXMLString(responseMessageType); - } catch (I2B2Exception e) { - log.error(e.getMessage()); - } - return responseVdo; - } - - - private String runGetAllProject(PMDbDao pmDb, String project, String caller) { - ResponseMessageType responseMessageType = null; - - try { - - - List response = null; - try { - response = pmDb.getAllProject(project, caller); - } catch (I2B2DAOException e1) { - throw new Exception ( "Database error in getting user data for NTLM"); - } catch (I2B2Exception e1) { - throw new Exception ("Database error in getting user data for NTLM"); - } - - Iterator it = response.iterator(); - ProjectsType users = new ProjectsType(); - log.debug("Records returned: " + response.size()); - while (it.hasNext()) - { - ProjectType user = (ProjectType)it.next(); - - users.getProject().add(user); - log.debug("added: " + user.getName()); - } - //everything is good so just return the same session key and the other info - - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); - responseMessageType = MessageFactory.createBuildResponse(messageHeader,users); - - } - catch (Exception ee) - { - log.error(ee.getMessage()); - // throw new Exception (ee.getMessage()); - ee.printStackTrace(); - - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); - responseMessageType = MessageFactory.doBuildErrorResponse(messageHeader, - ee.getMessage()); - } - - String responseVdo = "DONE"; - try { - responseVdo = MessageFactory.convertToXMLString(responseMessageType); - } catch (I2B2Exception e) { - log.error(e.getMessage()); - } - return responseVdo; - } - - private String runGetProject(PMDbDao pmDb, String caller, Object utype) { - ResponseMessageType responseMessageType = null; - - try { - - List response = null; - try { - response = pmDb.getProject(utype, true); - } catch (I2B2DAOException e1) { - throw new Exception ( "Database error in getting user data for NTLM"); - } catch (I2B2Exception e1) { - throw new Exception ("Database error in getting user data for NTLM"); - } - - Iterator it = response.iterator(); - ProjectType user = null; - while (it.hasNext()) - user = (ProjectType)it.next(); - - //user = userManagerService.getUserByUserName(k.getUsername()); - if (user == null) - throw new Exception ("Project does not exist"); - - - //everything is good so just return the same session key and the other info - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); - responseMessageType = MessageFactory.createBuildResponse(messageHeader,user); - - } - catch (Exception ee) - { - log.error(ee.getMessage()); - // throw new Exception (ee.getMessage()); - ee.printStackTrace(); - - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); - responseMessageType = MessageFactory.doBuildErrorResponse(messageHeader, - ee.getMessage()); - } - - String responseVdo = "DONE"; - try { - responseVdo = MessageFactory.convertToXMLString(responseMessageType); - } catch (I2B2Exception e) { - log.error(e.getMessage()); - } - return responseVdo; - } - - - - private String runGetUserConfiguration(PMDbDao pmDb, GetUserConfigurationType userType, - String username, String domain, ConfigureType cType, UserType uType) { - - //ConfigureType cType = new ConfigureType(); - //UserType uType = new UserType(); - CellDatasType aType = new CellDatasType(); - - ResponseMessageType responseMessageType = null; - - try { - //Get user Data - cType.setUser(uType); - - if ((userType.getDataNeeded() == null) || (userType.getDataNeeded().size() == 0) || (userType.getDataNeeded().contains("USER"))) - { - - - Iterator itsg = pmDb.getUserProject(username).iterator(); - if (itsg == null) - throw new Exception (username + " is not associated with any groups"); - while (itsg.hasNext()) { - ProjectType pType = (ProjectType)itsg.next(); - - - //Get Variables for the project - for(Iterator it2=pmDb.getProjectParams(pType.getId()).iterator();it2.hasNext();){ - ParamType vardata =(ParamType)it2.next(); - log.debug("Added Project Param: " + vardata.getName()); - pType.getParam().add(vardata); - } - //Get user project params for the project - ProjectType tempptype = new ProjectType(); - tempptype.setId(pType.getId()); - tempptype.setUserName(uType.getUserName()); - for(Iterator it2=pmDb.getAllParam(tempptype, null, username).iterator();it2.hasNext();){ - ParamType vardata =(ParamType)it2.next(); - log.debug("Added Project Param: " + vardata.getName()); - pType.getParam().add(vardata); - } - - //Get Roles for the project - for(Iterator it2=pmDb.getRole(username, pType.getId()).iterator();it2.hasNext();){ - RoleType g = (RoleType) it2.next(); - - log.debug("got Role: " + g.getRole()); - pType.getRole().add(g.getRole()); - - } - //Get ADMIN @ role - for (Iterator it2=pmDb.getRole(username, "@").iterator();it2.hasNext();){ - RoleType g = (RoleType) it2.next(); - - log.debug("got Role: " + g.getRole()); - if (g.getRole().equals("ADMIN")) - uType.setIsAdmin(true); - - } - - - uType.getProject().add(pType); - - } - - - //OLD CODE - /* - - Iterator itsg = pmDb.getRole(username).iterator(); - if (itsg == null) - throw new Exception (username + " is not associated with any groups"); - boolean found = false; - String origProject = ""; - while (itsg.hasNext()) { - found = true; - ProjectType pType = new ProjectType(); - - RoleData g = (RoleData) itsg.next(); - - pType.getRole().add(g.getRole()); - - log.debug("got Role: " + g.getRole()); - if (g.getProject().equals(origProject)) - { - // Project is the same, just a new role. So add it and continue - continue; - } - - - origProject = g.getProject(); - - log.debug("pdata: " + g.getProject()); - - //Only get valid projects, - - //GroupData pData = globaldataservice.getGroupDataByOid(g.getName()); - - for(Iterator it=pmDb.getProject(g.getProject()).iterator();it.hasNext();){ - ProjectType pData =(ProjectType)it.next(); - - //Get Variables for the group - for(Iterator it2=pmDb.getProjectParams(g.getProject()).iterator();it2.hasNext();){ - ParamType vardata =(ParamType)it2.next(); - log.debug("Added Project Param: " + vardata.getName()); - pType.getParam().add(vardata); - } - - pType.setChangeDate(pData.getChangeDate()); - pType.setEntryDate(pData.getEntryDate()); - pType.setKey(pData.getKey()); - pType.setId(pData.getId()); - pType.setName(pData.getName()); - pType.setStatus(pData.getStatus()); - pType.setWiki(pData.getWiki()); - log.debug("Added Project: " + pData.getId()); - //uType.getProject().add(pData); - } - - - - //Get user variables for the group - for(Iterator it=pmDb.getProjectUserParams(g.getProject(), username).iterator();it.hasNext();){ - - ParamType vardata =(ParamType)it.next(); - log.debug("Added Project User Param: " + vardata.getName()); - pType.getParam().add(vardata); - } - uType.getProject().add(pType); - - - // Set project only if null or requested - // log.debug("Adding Project: " + userType.getProject()); - // if ((userType.getProject() == null) || (userType.getProject().size() == 0) || (userType.getProject().contains(pType.getId().toUpperCase()))) - // uType.getProject().add(pType); - - log.debug("Adding usertype"); - cType.setUser(uType); - } - */ - if (cType.getUser() == null) - throw new Exception ("Group Data has not been filled out"); - //if (found == false) - // throw new Exception (username + " is not part of project " + domain); - } - - - - - - //Get Cell Data - if ((userType.getDataNeeded() == null) || (userType.getDataNeeded().size() == 0) || (userType.getDataNeeded().contains("CELL_DATA"))) - { - - // Get all cells - for(Iterator it=pmDb.getCell("@", "/", true).iterator();it.hasNext();){ - CellDataType cell =(CellDataType)it.next(); - - - if (cell == null) - { - throw new Exception ("No cells are be registered yet"); - } - - log.debug("my url is " + cell.getUrl()); - - - for(Iterator it2=pmDb.getCellParam(cell.getId(),"/").iterator();it2.hasNext();){ - ParamType cellParam =(ParamType)it2.next(); - cell.getParam().add(cellParam); - } - aType.getCellData().add(cell); - } - - // Get project specific cells - for (ProjectType p : uType.getProject()) { - log.debug("Searching cells for: " + p.getId() + ":" + p.getPath()); - if (p.getPath() != null) - for(Iterator it=pmDb.getCell("@", p.getPath(), true).iterator();it.hasNext();){ - CellDataType cell =(CellDataType)it.next(); - - - if (cell == null) - { - throw new Exception ("No cells are be registered yet"); - } - - log.debug("my url is " + cell.getUrl()); - - - for(Iterator it2=pmDb.getCellParam(cell.getId(),"/").iterator();it2.hasNext();){ - ParamType cellParam =(ParamType)it2.next(); - cell.getParam().add(cellParam); - } - - aType.getCellData().add(cell); - } - } - - cType.setCellDatas(aType); - } - - //Get User Params - - for(Iterator it2=pmDb.getAllParam(uType,null,null).iterator();it2.hasNext();){ - UserParamData p = (UserParamData)it2.next(); - ParamType param = new ParamType(); - param.setName(p.getName()); - param.setValue(p.getValue()); - uType.getParam().add(param); - } - // - - // Get Global Data - GlobalDataType globaldata = new GlobalDataType(); - - for(Iterator it=pmDb.getAllParam(new GlobalDataType(), null, null).iterator();it.hasNext();){ - - //GlobalDataType globaldata =(GlobalDataType)it.next(); - - // List gData = globaldataservice.getGlobalData(); - // GlobalDataType gValue = new GlobalDataType(); - - // if (gData!=null) { - // for (int i=0;i enuStr = req.getHeaderNames(); + while (enuStr.hasMoreElements()) { + String key = enuStr.nextElement(); + Object obj = req.getHeader(key); + params.put(key, obj); + } + } + + private void saveLoginAttempt(PMDbDao pmDb, String username, String attempt) + { + // Add new timeout to it + pmDb.setLoginAttempt(username, attempt ); + + } + + + private UserType validateSuppliedPassword (String username, String password, Hashtable param, boolean skipValidation) throws Exception + { + PMDbDao pmDb = new PMDbDao(); + + if (pmDb.verifyNotLockedOut(username)) + { + saveLoginAttempt(pmDb, username, "LOCKED_OUT"); + throw new Exception ("Too many invalid attempts, user locked out"); + } + if (pmDb.verifyExpiredPassword(username) && (skipValidation == false)) + { + saveLoginAttempt(pmDb, username, "PASSWORD_EXPIRED"); + throw new Exception ("Password Expired."); + } + + if ((param.get("authentication_method") == null) || (param.get("authentication_method").equals(""))) + { + param.put("authentication_method", "BASIC"); + } + + //String SQL_QUERY ="from UserData where oid='" + username + "'"; + List response = null; + try { + response = pmDb.getUser(username, null); + } catch (I2B2DAOException e1) { + throw new Exception ( "Database error in getting user data for " + param.get("authentication_method")); + } catch (I2B2Exception e1) { + throw new Exception ("Database error in getting user data for " + param.get("authentication_method")); + } + + Iterator it = response.iterator(); + UserType user = null; + while (it.hasNext()) + { + user = (UserType)it.next(); + } + + if (user == null) + { + log.debug("Did not find user: " + username); + saveLoginAttempt(pmDb, username, "NONEXIST"); + + throw new Exception ("Unable to sign in"); + } + + // Handle all internal classnames. Also for backward compatibility need to call it NTLM. + //String classname = sanitizeClassName("edu.harvard.i2b2.pm.util.SecurityAuthentication" + param.get("authentication_method"), param); + + ClassLoader classLoader = ServicesHandler.class.getClassLoader(); + + try { + + Class securityClass = classLoader.loadClass(sanitizeClassName("edu.harvard.i2b2.pm.util.SecurityAuthentication" + param.get("authentication_method"))); + + SecurityAuthentication security = (SecurityAuthentication) securityClass.newInstance(); + + if (skipValidation == false) + security.validateUser(username, password, param); + + } catch (ClassNotFoundException e) { + log.equals("Did not find class: " + e.getMessage()); + throw new Exception ("Error loading class: " + e.getMessage()); + } + + return user; + } + + + public static String sanitizeClassName(final String AssemblyName ) throws Exception { + + + if (AssemblyName.equals("edu.harvard.i2b2.pm.util.SecurityAuthenticationBASIC")) { + + return "edu.harvard.i2b2.pm.util.SecurityAuthenticationBASIC"; // <-- hardcoded, not coming from outside of application + + } + + else if (AssemblyName.equals("edu.harvard.i2b2.pm.util.SecurityAuthenticationLDAP")) { + + return "edu.harvard.i2b2.pm.util.SecurityAuthenticationLDAP"; // <-- hardcoded, not coming from outside of application + + } + else if (AssemblyName.equals("edu.harvard.i2b2.pm.util.SecurityAuthenticationNTLM2") || + AssemblyName.equals("edu.harvard.i2b2.pm.util.SecurityAuthenticationNTLM")) { + + return "edu.harvard.i2b2.pm.util.SecurityAuthenticationNTLM2"; // <-- hardcoded, not coming from outside of application + + } + else if (AssemblyName.equals("edu.harvard.i2b2.pm.util.SecurityAuthenticationOKTA")) { + + return "edu.harvard.i2b2.pm.util.SecurityAuthenticationOKTA"; // <-- hardcoded, not coming from outside of application + + } + else if (AssemblyName.equals("edu.harvard.i2b2.pm.util.SecurityAuthenticationSAML")) { + + return "edu.harvard.i2b2.pm.util.SecurityAuthenticationSAML"; // <-- hardcoded, not coming from outside of application + + } + else + + throw new Exception("Unknown class provided"+ AssemblyName); + + } + + private boolean verifySession(PMDbDao pmDb, int timeout, String sessionId, String userId) throws Exception + { + + List response = pmDb.getSession(userId, sessionId); + + + //SessionKey k=SessionKey.Decrypt(sessionKey); + Date now=new Date(); + + Iterator it = response.iterator(); + SessionData session = null; + while (it.hasNext()) + { + log.debug("Found: " + response.size()); + session = (SessionData)it.next(); + } + + if (session == null) + return false; + + //check if the session is still valid + log.debug("checking date"); + log.debug("Now Time: "+ now.toString()); + log.debug("Current session: "+ session.getExpiredDate().toString()); + if(now.after(session.getExpiredDate())) + { + log.debug("Session Expired"); + return false; + } + log.debug("date ok"); + + // Add new timeout to it + pmDb.updateSession(userId, sessionId, timeout); + return true; + } + + public String execute() throws I2B2Exception{ + + PMDbDao pmDb = new PMDbDao(); + + log.debug("I am in the RequestHandler"); + + ConfigureType cType = new ConfigureType(); + UserType uType = new UserType(); + CellDatasType aType = new CellDatasType(); + + ResponseMessageType responseMessageType = null; + + try { + String domainId = null; + SecurityType rmt = getServicesMsg.getRequestMessageType().getMessageHeader().getSecurity(); + String project = getServicesMsg.getRequestMessageType().getMessageHeader().getProjectId(); + log.debug("My username: " + rmt.getUsername()); + + + String SQL_QUERY = null; + + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + + + //Get Enviornment Data + List response = null; + try { + response = pmDb.getEnvironment(null); + } catch (I2B2DAOException e1) { + e1.printStackTrace(); + throw new Exception ( "Database error in getting environment data"); + } catch (I2B2Exception e1) { + e1.printStackTrace(); + throw new Exception ("Database error in getting environment data"); + } + logesapi.debug("Start parsing environment results of: " + response); + + Iterator it = response.iterator(); + while (it.hasNext()) + { + cType =(ConfigureType)it.next(); + //Make sure domain is set correctly + if (!cType.getDomainName().equalsIgnoreCase(rmt.getDomain().toUpperCase())) + throw new Exception (rmt.getDomain() + " is not associated with this domain " + cType.getDomainName() + ". Please check the i2b2workbench.properties file."); + + //Get wiki and environment data + log.debug("Helpurl: " + cType.getHelpURL()); + log.debug("Environment: " + cType.getEnvironment()); + domainId = cType.getDomainName();; + } + if (cType.getEnvironment() == null) + { + throw new Exception ("Environment group has not been setup"); + } + + //Determine authentication method + log.debug("Get authentication method by using domain: " + domainId); + //String method = "", domainController= "", domain= ""; + String method = null; + for( it=pmDb.getEnvironmentData(domainId).iterator();it.hasNext();){ + HiveParamData hivedata =(HiveParamData)it.next(); + + if (hivedata.getName().equalsIgnoreCase("authentication_method")) + method = hivedata.getValue(); + } + + Hashtable params = new Hashtable(); + addParamsFromHeaders(params); // For SAML auth + + //Get params from the environment first + for( it=pmDb.getEnvironmentData(domainId).iterator();it.hasNext();){ + HiveParamData hivedata =(HiveParamData)it.next(); + params.put(hivedata.getName(), hivedata.getValue()); + } + + //Next, update the params from the user params + UserType userType = new UserType(); + userType.setUserName(rmt.getUsername()); + + for( it=pmDb.getAllParam(userType,null,null).iterator();it.hasNext();){ + UserParamData userdata =(UserParamData)it.next(); + params.put(userdata.getName(), userdata.getValue()); + + if (userdata.getName().equalsIgnoreCase("authentication_method")) + method = userdata.getValue(); + } + + String password = rmt.getPassword().getValue(); + + BodyType bodyType = getServicesMsg.getRequestType(); + Object obj = bodyType.getAny().get(0); + + + //If password begins with "SessionKey:" its a session key and decrypt it and validate it + if (password.startsWith("SessionKey:")) + { + String sessionKey=password.replace("SessionKey:", ""); + log.debug("Encrypted Session key: "+sessionKey+" passed in for validation."); + if (rmt.getPassword().getTokenMsTimeout() == null) + rmt.getPassword().setTokenMsTimeout(1800000); + if (verifySession(pmDb, rmt.getPassword().getTokenMsTimeout(), sessionKey, rmt.getUsername()) == false) + throw new Exception ("Session invalid"); + + //get the user from the service + + UserType user = null; + for( it=pmDb.getUser(rmt.getUsername(), null).iterator();it.hasNext();){ + user=(UserType)it.next(); + } + + //user = userManagerService.getUserByUserName(k.getUsername()); + if (user == null) + { + log.debug("Did not find user: " + rmt.getUsername()); + throw new Exception ("Unable to sign in"); + } + //check the password + + + //everything is good so just return the same session key and the other info + uType.setFullName(user.getFullName()); + uType.setUserName(rmt.getUsername()); + uType.setDomain(rmt.getDomain()); + uType.setEmail(user.getEmail()); + uType.setIsAdmin(user.isIsAdmin()); + PasswordType passType = new PasswordType(); + passType.setIsToken(true); + passType.setValue(password); + passType.setTokenMsTimeout(rmt.getPassword().getTokenMsTimeout()); + uType.setPassword(passType); //"SessionKey:"+sessionKey); //return the key instead of password + //uType.setKey(rmt.getPassword()); //return password so client can reaunthenticate later + } + //otherwise check username and password and generate a sessionkey for the password + else + { + + //get the user from the service + try { + log.debug("Validating user: " + rmt.getUsername()); + + boolean skipValidation = false; + if (obj instanceof JAXBElement) { + String value = null; + String name = null; + name = ((JAXBElement) obj).getName().getLocalPart(); + if (name.equalsIgnoreCase("set_password")) + skipValidation = true; + + if (rmt.getUsername().equalsIgnoreCase("AGG_SERVICE_ACCOUNT") && + (name.equalsIgnoreCase("get_user") || name.equalsIgnoreCase("set_user") || name.equalsIgnoreCase("set_user_param")) ) + skipValidation = true; + } + + UserType user = validateSuppliedPassword( rmt.getUsername(), rmt.getPassword().getValue(), params, skipValidation); + uType.setFullName(user.getFullName()); + uType.setIsAdmin(user.isIsAdmin()); + uType.setEmail(user.getEmail()); + //Dont log AGG_SERVICE_ACOUNT + if (!rmt.getUsername().equals("AGG_SERVICE_ACCOUNT")) + saveLoginAttempt(pmDb, rmt.getUsername(), "SUCCESS"); + + } catch (Exception e) + { + throw new Exception (e.getMessage()); + } + + //if password was good then set info and generate a new session key + uType.setUserName(rmt.getUsername()); + uType.setDomain(rmt.getDomain()); + + //SessionKey newKey; + + //build the date for the expiration of the key + //Calendar cal=Calendar.getInstance(); + //cal.add(Calendar.MILLISECOND, rmt.getPassword().getTokenMsTimeout()); //timeout in minutes from now + //cal.getTime(); + + //create the key in unecrypted form + //newKey=new SessionKey(rmt.getUsername(),PMUtil.getInstance().getHashedPassword(rmt.getPassword().getValue()), rmt.getDomain(), cal.getTime()); + //log.debug("Made new key for: "+rmt.getUsername()+" expires on: "+cal.getTime().toString()); + //encrypt the key + // String encryptedKey=SessionKey.Encrypt(newKey); + + log.debug("Creating new session key"); + String encryptedKey = PMUtil.getInstance().generateMessageId(); + log.debug("Saving new session key: " + encryptedKey); + int timeout = 1800000; + if (rmt.getPassword().getTokenMsTimeout() != null) + timeout = rmt.getPassword().getTokenMsTimeout(); + int result = pmDb.setSession(rmt.getUsername(), encryptedKey, timeout); + + if (result < 1) + throw new Exception("Failed to save session"); + //return the key in the password slot + PasswordType ptype = new PasswordType(); + ptype.setValue("SessionKey:" + encryptedKey); + ptype.setIsToken(true); + ptype.setTokenMsTimeout(timeout); + //ptype.sett + uType.setPassword(ptype); //password slot contains password or key + //uType.setKey(rmt.getPassword().getValue()); //"key" slot contains original password passed back so client can re-authenticate later + //for testing to undo all the previous security stuff + + } + + log.debug("Working on GetUserConfigure"); + GetUserConfigurationType userConfigurationType = (GetUserConfigurationType) helper.getObjectByClass(getServicesMsg.getRequestType().getAny(), + GetUserConfigurationType.class); + + if (userConfigurationType != null) + { + PMUtil.getInstance().convertToUppercaseStrings(userConfigurationType.getDataNeeded()); + PMUtil.getInstance().convertToUppercaseStrings(userConfigurationType.getProject()); + return runGetUserConfiguration(pmDb, userConfigurationType, rmt.getUsername(), rmt.getDomain(), cType, uType); + } + + + log.debug("Working on Rest of services: 1"); + log.debug("Working on Rest of services: " + obj); + if (obj instanceof JAXBElement) { + String value = null; + String name = null; + name = ((JAXBElement) obj).getName().getLocalPart(); + + // If admin than log entry + if (uType.isIsAdmin()) + saveLoginAttempt(pmDb, rmt.getUsername(), name); + + + log.debug("Element name is: " + name ); + if (name.equals("set_user")) + return runSetUser(pmDb, project, rmt.getUsername(), (UserType) ((JAXBElement) obj).getValue() ); + else if (name.equals("get_all_user")) + return runGetAllUser(pmDb, project, rmt.getUsername() ); + else if (name.equals("set_project")) + return runSetProject(pmDb, project, rmt.getUsername(), (ProjectType) ((JAXBElement) obj).getValue() ); + else if (name.equals("get_all_project")) + return runGetAllProject(pmDb, project, rmt.getUsername() ); + else if (name.equals("set_project_request")) + return runSetProjectRequest(pmDb, project, rmt.getUsername(), (ProjectRequestType) ((JAXBElement) obj).getValue() ); + + else if (name.equals("set_approval")) + return runSetApproval(pmDb, project, rmt.getUsername(), (ApprovalType) ((JAXBElement) obj).getValue() ); + else if (name.equals("delete_approval")) + return runDeleteApproval(pmDb, project, rmt.getUsername(), (ApprovalType) ((JAXBElement) obj).getValue() ); + else if (name.equals("get_approval")) + return runGetApproval(pmDb, project, rmt.getUsername(), (ApprovalType) ((JAXBElement) obj).getValue() ); + else if (name.equals("get_all_approval")) + return runGetAllApproval(pmDb, project, rmt.getUsername() ); + + else if (name.equals("set_cell")) + return runSetCell(pmDb, project, rmt.getUsername(), (CellDataType) ((JAXBElement) obj).getValue() ); + else if (name.equals("delete_cell")) + return runDeleteCell(pmDb, project, rmt.getUsername(), (CellDataType) ((JAXBElement) obj).getValue() ); + else if (name.equals("get_cell")) + return runGetCell(pmDb, project, rmt.getUsername(), (CellDataType) ((JAXBElement) obj).getValue() ); + else if (name.equals("get_all_cell")) + return runGetAllCell(pmDb, project, rmt.getUsername() ); + else if (name.equals("set_global")) + return runSetParam(pmDb, project, name, rmt.getUsername(), (GlobalDataType) ((JAXBElement) obj).getValue() ); + else if (name.equals("set_project_param")) + return runSetParam(pmDb, project, name, rmt.getUsername(), (ProjectType) ((JAXBElement) obj).getValue() ); + else if (name.equals("set_project_user_param")) + return runSetParam(pmDb, ((ProjectType) ((JAXBElement) obj).getValue()).getId(), name, rmt.getUsername(), (ProjectType) ((JAXBElement) obj).getValue() ); + else if (name.equals("get_all_project_user_param")) + return runGetAllParam(pmDb, project, rmt.getUsername(), (ProjectType) ((JAXBElement) obj).getValue() ); + else if (name.equals("set_user_param")) + return runSetParam(pmDb, project, name, rmt.getUsername(), (UserType) ((JAXBElement) obj).getValue() ); + else if (name.equals("set_cell_param")) + return runSetParam(pmDb, project, name, rmt.getUsername(), (CellDataType) ((JAXBElement) obj).getValue() ); + else if (name.equals("get_all_cell_param")) + return runGetAllParam(pmDb, project, rmt.getUsername(), (CellDataType) ((JAXBElement) obj).getValue() ); + else if (name.equals("get_all_user_param")) + return runGetAllParam(pmDb, project, rmt.getUsername(), (UserType) ((JAXBElement) obj).getValue() ); + else if (name.equals("set_hive_param")) + return runSetParam(pmDb, project, name, rmt.getUsername(), (ConfigureType) ((JAXBElement) obj).getValue() ); + else if (name.equals("set_role")) + return runSetParam(pmDb, project, name, rmt.getUsername(), (RoleType) ((JAXBElement) obj).getValue() ); + else if (name.equals("get_all_role")) + return runGetAllParam(pmDb, project, rmt.getUsername(), (RoleType) ((JAXBElement) obj).getValue() ); + else if (name.equals("delete_role")) + return runDeleteParam(pmDb, project, rmt.getUsername(), (RoleType) ((JAXBElement) obj).getValue() ); + else if (name.equals("get_role")) + return runGetParam(pmDb, project, rmt.getUsername(), (RoleType) ((JAXBElement) obj).getValue() ); + else if (name.equals("set_hive")) + return runSetParam(pmDb, project, name, rmt.getUsername(), (ConfigureType) ((JAXBElement) obj).getValue() ); + else if (name.equals("get_all_hive")) + return runGetAllParam(pmDb, project, rmt.getUsername(), new ConfigureType() ); + else if (name.equals("delete_hive")) + return runDeleteParam(pmDb, project, rmt.getUsername(), (ConfigureType) ((JAXBElement) obj).getValue() ); + else if (name.equals("get_hive")) + return runGetParam(pmDb, project, rmt.getUsername(), (ConfigureType) ((JAXBElement) obj).getValue() ); + else if (name.equals("delete_project")) + return runDeleteProject(pmDb, rmt.getUsername(), (ProjectType) ((JAXBElement) obj).getValue() ); + else if (name.equals("get_project")) + return runGetProject(pmDb, rmt.getUsername(), (ProjectType) ((JAXBElement) obj).getValue() ); + else if (name.equals("set_datasource")) + return runSetDatasource(pmDb, rmt.getUsername(), (DatasourceType) ((JAXBElement) obj).getValue() ); + else if (name.equals("get_all_datasource")) + return runGetAllDatasource(pmDb, project, rmt.getUsername() ); + else if (name.equals("get_user_login")) + return runUserLogin(pmDb, rmt.getUsername(), (UserLoginType) ((JAXBElement) obj).getValue() ); + + + log.debug("working on value"); + value = ((String) ((JAXBElement) obj).getValue()).trim(); + log.debug("Element is single and is: " + value); + if (name.equals("delete_user")) + return runDeleteUser(pmDb, project, rmt.getUsername(), value ); + else if (name.equals("set_password") && method != null) + throw new Exception(method + " authencation method is used, use that provider to change the password."); + else if (name.equals("set_password")) + return runSetPassword(pmDb, rmt.getUsername(), value ); + else if (name.equals("get_user")) + return runGetUser(pmDb, project, rmt.getUsername(), value ); + else if (name.equals("get_global")) + { + ParamType param = new ParamType(); + param.setId(Integer.valueOf(value)); + GlobalDataType global = new GlobalDataType(); + global.getParam().add(param); + return runGetParam(pmDb, project, rmt.getUsername(), global ); + } + else if (name.equals("get_all_global")) + { + GlobalDataType global = new GlobalDataType (); + global.setProjectPath(value); + return runGetAllParam(pmDb, project, rmt.getUsername(), global ); + } + else if (name.equals("delete_global")) + { + ParamType param = new ParamType(); + param.setId(Integer.valueOf(value)); + GlobalDataType global = new GlobalDataType(); + global.getParam().add(param); + return runDeleteParam(pmDb, project, rmt.getUsername(), global); + } + else if (name.equals("delete_project_param")) + { + ParamType param = new ParamType(); + param.setId(Integer.valueOf(value)); + ProjectType global = new ProjectType(); + global.getParam().add(param); + return runDeleteParam(pmDb, project, rmt.getUsername(), global); + } + else if (name.equals("delete_project_user_param")) + { + ParamType param = new ParamType(); + param.setId(Integer.valueOf(value)); + ProjectType global = new ProjectType(); + global.setUserName(rmt.getUsername()); + global.getParam().add(param); + return runDeleteParam(pmDb, project, rmt.getUsername(), global); + } + else if (name.equals("delete_cell_param")) + { + ParamType param = new ParamType(); + param.setId(Integer.valueOf(value)); + CellDataType global = new CellDataType(); + global.getParam().add(param); + return runDeleteParam(pmDb, project, rmt.getUsername(), global); + } + else if (name.equals("delete_hive_param")) + { + ParamType param = new ParamType(); + param.setId(Integer.valueOf(value)); + ConfigureType global = new ConfigureType(); + global.getParam().add(param); + return runDeleteParam(pmDb, project, rmt.getUsername(), global); + } + else if (name.equals("delete_user_param")) + { + ParamType param = new ParamType(); + param.setId(Integer.valueOf(value)); + UserType global = new UserType(); + global.setUserName(rmt.getUsername()); + global.getParam().add(param); + return runDeleteParam(pmDb, project, rmt.getUsername(), global); + } + + else if (name.equals("get_all_hive_param")) + { + ConfigureType lcType = new ConfigureType(); + lcType.setDomainId(value); + return runGetAllParam(pmDb, project, rmt.getUsername(),lcType);//(CellDataType) ((JAXBElement) obj).getValue() ); + } + else if (name.equals("get_all_project_param")) + { + ProjectType pType = new ProjectType(); + pType.setId(value); + return runGetAllParam(pmDb, project, rmt.getUsername(), pType ); + } + /* else if (name.equals("get_all_user_param")) + { + UserType pType = new UserType(); + pType.setUserName(value); + return runGetAllParam(pmDb, project, rmt.getUsername(), pType ); + } + */ + else if (name.equals("get_project_user_param")) + { + ParamType param = new ParamType(); + param.setId(Integer.valueOf(value)); + ProjectType global = new ProjectType(); + global.setUserName("USER"); + global.getParam().add(param); + + return runGetParam(pmDb, project, rmt.getUsername(), global ); + + // return runGetParam(pmDb, project, rmt.getUsername(), (ProjectType) ((JAXBElement) obj).getValue() ); + } + else if (name.equals("get_project_param")) + { + ParamType param = new ParamType(); + param.setId(Integer.valueOf(value)); + ProjectType global = new ProjectType(); + global.getParam().add(param); + + return runGetParam(pmDb, project, rmt.getUsername(), global ); + } + else if (name.equals("get_cell_param")) + { + ParamType param = new ParamType(); + param.setId(Integer.valueOf(value)); + CellDataType global = new CellDataType(); + global.getParam().add(param); + + return runGetParam(pmDb, project, rmt.getUsername(), global ); + } + else if (name.equals("get_user_param")) + { + ParamType param = new ParamType(); + param.setId(Integer.valueOf(value)); + UserType global = new UserType(); + global.getParam().add(param); + + return runGetParam(pmDb, project, rmt.getUsername(), global ); + } + else if (name.equals("get_hive_param")) + { + ParamType param = new ParamType(); + param.setId(Integer.valueOf(value)); + ConfigureType global = new ConfigureType(); + global.getParam().add(param); + + return runGetParam(pmDb, project, rmt.getUsername(), global ); + } + else if (name.equals("get_all_project_request")) + { + return runGetAllProjectRequest(pmDb, project, rmt.getUsername() ); + } + else if (name.equals("get_project_request")) + { + log.debug("Got this:" + value); + return null; + } + } + } + catch (Exception ee) + { + log.error(ee.getMessage()); + // throw new Exception (ee.getMessage()); + ee.printStackTrace(); + + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); + responseMessageType = MessageFactory.doBuildErrorResponse(messageHeader, + ee.getMessage()); + } + + String responseVdo = "DONE"; + try { + responseVdo = MessageFactory.convertToXMLString(responseMessageType); + } catch (I2B2Exception e) { + log.error(e.getMessage()); + } + return responseVdo; + } + + private String runUserLogin(PMDbDao pmDb, String caller, UserLoginType value) { + ResponseMessageType responseMessageType = null; + + try { + + + List response = null; + try { + response = pmDb.getUserLogin(value, caller); + } catch (I2B2DAOException e1) { + throw new Exception ( "Database error in getting user data for NTLM"); + } catch (I2B2Exception e1) { + throw new Exception ("Database error in getting user data for NTLM"); + } + + Iterator it = response.iterator(); + UserLoginsType users = new UserLoginsType(); + log.debug("Records returned: " + response.size()); + while (it.hasNext()) + { + UserLoginType user = (UserLoginType)it.next(); + users.getUserLogin().add(user); + } + //everything is good so just return the same session key and the other info + + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); + responseMessageType = MessageFactory.createBuildResponse(messageHeader,users); + + } + catch (Exception ee) + { + log.error(ee.getMessage()); + // throw new Exception (ee.getMessage()); + ee.printStackTrace(); + + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); + responseMessageType = MessageFactory.doBuildErrorResponse(messageHeader, + ee.getMessage()); + } + + String responseVdo = "DONE"; + try { + responseVdo = MessageFactory.convertToXMLString(responseMessageType); + } catch (I2B2Exception e) { + log.error(e.getMessage()); + } + return responseVdo; + } + + private String runGetAllDatasource(PMDbDao pmDb, String project, String caller) { + ResponseMessageType responseMessageType = null; + + try { + + + List response = new ArrayList(); + + //List availableDatasources = new ArrayList(); + try { + + // retrieve the mbean server + MBeanServer server = java.lang.management.ManagementFactory.getPlatformMBeanServer(); + + // key for retrieving mbeans representing LOCAL Datasource + // configuration from JMX namespace: jboss.as:subsystem=datasources (1) + + //add datasources of given type to the list + addDatasourcesForKeyName(response, server, "data-source"); + + // key for retrieving mbeans representing XA Datasource + // configuration from JMX namespace: jboss.as:subsystem=datasources (2) + addDatasourcesForKeyName(response, server, "xa-data-source"); + + } catch (Exception e) { + + throw new Exception ("Database error in getting datasources"); + } + + Iterator it = response.iterator(); + DatasourcesType users = new DatasourcesType(); + log.debug("Records returned: " + response.size()); + /* + while (it.hasNext()) + { + DataSource user = (DataSource)it.next(); + DatasourceType datasource = new DatasourceType(); + datasource.setConnectionUrl(user.getConnection().getMetaData().getURL()); + datasource.setDriverName(user.getConnection().getMetaData().getDriverName()); + datasource.setUserName(user.getConnection().getMetaData().getUserName()); + users.getDatasource().add(datasource); + //users.getProjectRequest().add(user); + } + */ + //everything is good so just return the same session key and the other info + // get list of hot deployed datasources + Context initCtx = new InitialContext(); + // NamingEnumeration namedEnum = initCtx.list("java:/"); + NamingEnumeration namedEnum = initCtx.listBindings(""); + while (namedEnum.hasMore()) + { + try { + //NameClassPair nameClassPair = (NameClassPair)namedEnum.nextElement(); + Binding nameClassPair = (Binding)namedEnum.next(); + + if (nameClassPair.getObject() instanceof DataSource) { + + DataSource user = (DataSource)nameClassPair.getObject(); + DatasourceType datasource = new DatasourceType(); + + + for(Field f : nameClassPair.getObject().getClass().getDeclaredFields()) { + try { + f.setAccessible(true); + if (f.getName().equals("jndiName")) + { + datasource.setJndiName(f.get(nameClassPair.getObject()).toString()); + datasource.setPoolName(datasource.getJndiName().substring(datasource.getJndiName().lastIndexOf("/")+1)); + try { + + Connection conn = user.getConnection(); + datasource.setActive(true); + } catch (Exception ee) + { + datasource.setActive(false); + } + } + if (f.getName().equals("delegate")) + { + Object obj = f.get(nameClassPair.getObject()); + //System.out.println(f.getName()); + + for(Field f2 : obj.getClass().getDeclaredFields()) { + f2.setAccessible(true); + + if (f2.getName().equals("defaultCRI")) + { + Object obj2 = f2.get(obj); + for(Field f3 : obj2.getClass().getDeclaredFields()) { + f3.setAccessible(true); + if (f3.getName().equals("user")) + datasource.setUserName(f3.get(obj2).toString()); + // else if (f3.getName().equals("password")) + // datasource.setPassword(f3.get(obj2).toString()); + } + } + if (f2.getName().equals("mcf")) + { + Object obj2 = f2.get(obj); + for(Field f3 : obj2.getClass().getDeclaredFields()) { + f3.setAccessible(true); + if (f3.getName().equals("connectionURL")) + datasource.setConnectionUrl(f3.get(obj2).toString()); + else if (f3.getName().equals("driverClass")) + datasource.setDriverName(f3.get(obj2).toString()); + else if (f3.getName().equals("jta")) + datasource.setJta(Boolean.valueOf(f3.get(obj2).toString())); + log.debug(f3.getName()); + } + } + } + + } + + + //System.out.println(f.get(nameClassPair.getObject())); + } catch(IllegalAccessException e) { + e.printStackTrace(); + } + } + users.getDatasource().add(datasource); + } + } catch (Exception e) + { + //e.printStackTrace(); + //throw new Exception ("Database error in getting datasources, " + e.getMessage()); + + } + } + + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); + responseMessageType = MessageFactory.createBuildResponse(messageHeader,users); + + } + catch (Exception ee) + { + log.error(ee.getMessage()); + // throw new Exception (ee.getMessage()); + ee.printStackTrace(); + + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); + responseMessageType = MessageFactory.doBuildErrorResponse(messageHeader, + ee.getMessage()); + } + + String responseVdo = "DONE"; + try { + responseVdo = MessageFactory.convertToXMLString(responseMessageType); + } catch (I2B2Exception e) { + log.error(e.getMessage()); + } + return responseVdo; + } + + private void addDatasourcesForKeyName(List availableDatasources, MBeanServer server, String dataSourceKeyName) throws MalformedObjectNameException, NamingException, AttributeNotFoundException, InstanceNotFoundException, MBeanException, ReflectionException { + + // Get the starting point of the namespace + Context ctx = new InitialContext(); + + // create jmx filter name eg. (3) + // "jboss.as:subsystem=datasources,xa-data-source=*" + final ObjectName filterName = new ObjectName("jboss.as:subsystem=datasources," + dataSourceKeyName + "=*"); + + // get the results matching given filter. (4) + final Set mBeans = server.queryMBeans(filterName, null); + + // iterate over mbeans and retrieve information about jndi-name of datasource + for (final ObjectInstance mBean : mBeans) { + + // get name for mbean describing current datasource mbean + ObjectName mbeanName = mBean.getObjectName(); + + // one of the attributes of mbean is + // "jndiName" , we will read that attribute now:(5) + String bindName = (String) server.getAttribute(mbeanName, "jndiName"); + + // having the jndi-name, we can look up the datasource instance + DataSource ds = (DataSource) ctx.lookup(bindName); + availableDatasources.add(ds); + } + } + + private String runSetDatasource(PMDbDao pmDb, String username, DatasourceType value) { + ResponseMessageType responseMessageType = null; + + try { + + ModelControllerClient client = ModelControllerClient.Factory.create(InetAddress.getByName("localhost"), 9990); + + ModelNode request = new ModelNode(); + request.get(ClientConstants.OP).set(ClientConstants.ADD); + request.get(ClientConstants.OP_ADDR).add("subsystem","datasources"); + request.get(ClientConstants.OP_ADDR).add("data-source",value.getDataSource()); + request.get("jta").set(false); + request.get("jndi-name").set("java:/" + value.getDataSource()); + request.get("pool-name").set(value.getPoolName()); + request.get("use-java-context").set(true); + request.get("use-ccm").set(false); + + request.get("connection-url").set(value.getConnectionUrl()); + request.get("driver-name").set(value.getDriverName()); + request.get("transaction-isolation").set("TRANSACTION_READ_COMMITTED"); + + request.get("min-pool-size").set(5); + request.get("max-pool-size").set(20); + request.get("pool-prefill").set(true); + request.get("pool-use-strict-min").set(false); + request.get("flush-strategy").set("FailingConnectionOnly"); + + request.get("user-name").set(value.getUserName()); + request.get("password").set(value.getPassword()); + + request.get("prepared-statements-cache-size").set(32); + request.get("share-prepared-statements").set(false); + + client.execute(new OperationBuilder(request).build()); + client.close(); + + ResultStatusType results = new ResultStatusType(); + StatusType status = new StatusType(); + status.setValue("1 records"); + results.setStatus(status); + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); + responseMessageType = MessageFactory.createBuildResponse(messageHeader,results); + } + catch (Exception ee) + { + log.error(ee.getMessage()); + // throw new Exception (ee.getMessage()); + ee.printStackTrace(); + + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); + responseMessageType = MessageFactory.doBuildErrorResponse(messageHeader, + ee.getMessage()); + } + + String responseVdo = "DONE"; + try { + responseVdo = MessageFactory.convertToXMLString(responseMessageType); + } catch (I2B2Exception e) { + log.error(e.getMessage()); + } + return responseVdo; + } + + //All Param process + private String runDeleteParam(PMDbDao pmDb, String project, String caller, + Object utype) { + ResponseMessageType responseMessageType = null; + + try { + int result = -1; + result = pmDb.deleteParam(utype, project, caller); + + ResultStatusType results = new ResultStatusType(); + StatusType status = new StatusType(); + status.setValue(result + " records"); + results.setStatus(status); + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); + responseMessageType = MessageFactory.createBuildResponse(messageHeader,results); + + } + catch (Exception ee) + { + log.error(ee.getMessage()); + // throw new Exception (ee.getMessage()); + ee.printStackTrace(); + + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); + responseMessageType = MessageFactory.doBuildErrorResponse(messageHeader, + ee.getMessage()); + } + + String responseVdo = "DONE"; + try { + responseVdo = MessageFactory.convertToXMLString(responseMessageType); + } catch (I2B2Exception e) { + log.error(e.getMessage()); + } + return responseVdo; + } + + private String runSetParam(PMDbDao pmDb, String project, String name, String caller, + Object utype) { + ResponseMessageType responseMessageType = null; + + try { + + //String SQL_QUERY ="from UserData where oid='" + username + "'"; + + log.debug("Start of setParam"); + int result = -1; + result = pmDb.setParam(utype,project, name, caller); + + ResultStatusType results = new ResultStatusType(); + StatusType status = new StatusType(); + status.setValue(result + " records"); + results.setStatus(status); + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); + responseMessageType = MessageFactory.createBuildResponse(messageHeader,results); + + } + catch (Exception ee) + { + log.error(ee.getMessage()); + // throw new Exception (ee.getMessage()); + ee.printStackTrace(); + + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); + responseMessageType = MessageFactory.doBuildErrorResponse(messageHeader, + ee.getMessage()); + } + + String responseVdo = "DONE"; + try { + responseVdo = MessageFactory.convertToXMLString(responseMessageType); + } catch (I2B2Exception e) { + log.error(e.getMessage()); + } + return responseVdo; + } + + + + + private String runGetAllProjectRequest(PMDbDao pmDb, String project, String caller) { + ResponseMessageType responseMessageType = null; + + try { + + + List response = null; + try { + response = pmDb.getAllProjectRequest(project, caller); + } catch (I2B2DAOException e1) { + throw new Exception ( "Database error in getting user data for NTLM"); + } catch (I2B2Exception e1) { + throw new Exception ("Database error in getting user data for NTLM"); + } + + Iterator it = response.iterator(); + ProjectRequestsType users = new ProjectRequestsType(); + log.debug("Records returned: " + response.size()); + while (it.hasNext()) + { + ProjectRequestType user = (ProjectRequestType)it.next(); + users.getProjectRequest().add(user); + } + //everything is good so just return the same session key and the other info + + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); + responseMessageType = MessageFactory.createBuildResponse(messageHeader,users); + + } + catch (Exception ee) + { + log.error(ee.getMessage()); + // throw new Exception (ee.getMessage()); + ee.printStackTrace(); + + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); + responseMessageType = MessageFactory.doBuildErrorResponse(messageHeader, + ee.getMessage()); + } + + String responseVdo = "DONE"; + try { + responseVdo = MessageFactory.convertToXMLString(responseMessageType); + } catch (I2B2Exception e) { + log.error(e.getMessage()); + } + return responseVdo; + } + + private String runSetProjectRequest(PMDbDao pmDb, String project, String caller, + ProjectRequestType value) { + ResponseMessageType responseMessageType = null; + + try { + + //String SQL_QUERY ="from UserData where oid='" + username + "'"; + + log.debug("Start of setProjectRequest"); + + String result = ""; + + + List response = null; + try { + response = pmDb.setProjectRequest(value,project, caller); + } catch (I2B2DAOException e1) { + e1.printStackTrace(); + throw new Exception ( "Database error in setting Projet Request: " + e1.getMessage()); + } catch (I2B2Exception e1) { + e1.printStackTrace(); + throw new Exception ("Database error in setting Projet Request: " + e1.getMessage()); + } + + Iterator it = response.iterator(); + log.debug("Records returned: " + response.size()); + while (it.hasNext()) + { + ProjectRequestType user = (ProjectRequestType)it.next(); + result = user.getId(); + log.debug("added ID: " + user.getId()); + } + + ResultStatusType results = new ResultStatusType(); + StatusType status = new StatusType(); + status.setValue(result); + results.setStatus(status); + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); + responseMessageType = MessageFactory.createBuildResponse(messageHeader,results); + + } + catch (Exception ee) + { + log.error(ee.getMessage()); + // throw new Exception (ee.getMessage()); + ee.printStackTrace(); + + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); + responseMessageType = MessageFactory.doBuildErrorResponse(messageHeader, + ee.getMessage()); + } + + String responseVdo = "DONE"; + try { + responseVdo = MessageFactory.convertToXMLString(responseMessageType); + } catch (I2B2Exception e) { + log.error(e.getMessage()); + } + return responseVdo; + } + + private String runGetAllParam(PMDbDao pmDb, String project, String caller, Object utype) { + ResponseMessageType responseMessageType = null; + + //ParamsType users = new ParamsType();; + Object users = null; + try { + + + List response = null; + try { + int result = -1; + //response = pmDb.getAllParam(utype,project, caller); + + //Iterator it = response.iterator(); + // users = new Para(); + + + if (utype instanceof RoleType) + { + response = pmDb.getAllParam(utype,project, caller); + + log.debug("Records returned: " + response.size()); + Iterator it = response.iterator(); + users = new RolesType(); + //ParamsType user = null; + + + while (it.hasNext()) + { + RoleType user = (RoleType)it.next(); + ((RolesType) users).getRole().add(user); + } + + } else if ((utype instanceof ConfigureType) && + ((((ConfigureType) utype).getDomainId() == null))) + { + response = pmDb.getAllParam(utype,project, caller); + + log.debug("Records returned: " + response.size()); + Iterator it = response.iterator(); + users = new ConfiguresType(); + //ParamsType user = null; + while (it.hasNext()) + { + ConfigureType user = (ConfigureType)it.next(); + ((ConfiguresType) users).getHive().add(user); + } + } else if (utype instanceof UserType) + { + response = pmDb.getAllParam(utype,project, caller); + + log.debug("Records returned: " + response.size()); + Iterator it = response.iterator(); + + users = new UsersType(); + + UserType userType = new UserType(); + + while (it.hasNext()) + { + UserParamData user = (UserParamData)it.next(); + + if (((UserType)userType).getUserName() != null && !user.getUser().equals(((UserType)userType).getUserName())) + { + log.debug("adding user: " + ((UserType)userType).getUserName()); + ((UsersType)users).getUser().add(userType); + userType = new UserType(); + } + + ParamType param = new ParamType(); + param.setName(user.getName()); + param.setId(user.getId()); + param.setDatatype(user.getDatatype()); + param.setValue(user.getValue()); + ((UserType)userType).setUserName(user.getUser()); + ((UserType)userType).getParam().add(param); + log.debug("adding param: " + param.getName()); + } + ((UsersType)users).getUser().add(userType); + // } + } else + { + response = pmDb.getAllParam(utype,project, caller); + + log.debug("Records returned: " + response.size()); + Iterator it = response.iterator(); + users = new ParamsType(); + //ParamsType user = null; + + + while (it.hasNext()) + { + ParamType user = (ParamType)it.next(); + ((ParamsType) users).getParam().add(user); + //((ParamType) users)..getRole().add(user); + } + } + + } catch (I2B2DAOException e1) { + throw new Exception ( "Database error in getting user data for NTLM"); + } catch (I2B2Exception e1) { + throw new Exception ("Database error in getting user data for NTLM"); + } + + + //everything is good so just return the same session key and the other info + + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); + responseMessageType = MessageFactory.createBuildResponse(messageHeader,users); + + } + catch (Exception ee) + { + log.error(ee.getMessage()); + // throw new Exception (ee.getMessage()); + ee.printStackTrace(); + + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); + responseMessageType = MessageFactory.doBuildErrorResponse(messageHeader, + ee.getMessage()); + } + + String responseVdo = "DONE"; + try { + responseVdo = MessageFactory.convertToXMLString(responseMessageType); + } catch (I2B2Exception e) { + log.error(e.getMessage()); + } + return responseVdo; + } + + private String runGetParam(PMDbDao pmDb, String project, String caller, + Object utype) { + ResponseMessageType responseMessageType = null; + + Object users = null; + + try { + + log.debug("In GetGlobal"); + List response = null; + try { + int result = -1; + if (utype instanceof RoleType) + { + response = pmDb.getParam(utype, true); + + Iterator it = response.iterator(); + //ParamsType user = null; + users = new RolesType(); + while (it.hasNext()) + { + RoleType user = (RoleType)it.next(); + ((RolesType) users).getRole().add(user); + } + } else if (utype instanceof ConfigureType) + { + response = pmDb.getParam(utype, true); + + Iterator it = response.iterator(); + //ParamsType user = null; + while (it.hasNext()) + users = (ConfigureType)it.next(); + } else if (utype instanceof GlobalDataType) + { + response = pmDb.getParam(utype, true); + + Iterator it = response.iterator(); + //ParamsType user = null; + while (it.hasNext()) + users = (GlobalDataType)it.next(); + } else { + response = pmDb.getParam(utype, true); + + Iterator it = response.iterator(); + //ParamsType user = null; + while (it.hasNext()) + users = (ParamType)it.next(); + + } + } catch (I2B2DAOException e1) { + throw new Exception ( "Database error in getting user data for NTLM"); + } catch (I2B2Exception e1) { + throw new Exception ("Database error in getting user data for NTLM"); + } + + + + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); + responseMessageType = MessageFactory.createBuildResponse(messageHeader,users); + + } + catch (Exception ee) + { + log.error(ee.getMessage()); + // throw new Exception (ee.getMessage()); + ee.printStackTrace(); + + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); + responseMessageType = MessageFactory.doBuildErrorResponse(messageHeader, + ee.getMessage()); + } + + String responseVdo = "DONE"; + try { + responseVdo = MessageFactory.convertToXMLString(responseMessageType); + } catch (I2B2Exception e) { + log.error(e.getMessage()); + } + return responseVdo; + } + + + //All Users process + private String runDeleteUser(PMDbDao pmDb, String project, String caller, + String user) { + ResponseMessageType responseMessageType = null; + + try { + int result = pmDb.deleteUser(user, caller); + + ResultStatusType results = new ResultStatusType(); + StatusType status = new StatusType(); + status.setValue(result + " records"); + results.setStatus(status); + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); + responseMessageType = MessageFactory.createBuildResponse(messageHeader,results); + + } + catch (Exception ee) + { + log.error(ee.getMessage()); + // throw new Exception (ee.getMessage()); + ee.printStackTrace(); + + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); + responseMessageType = MessageFactory.doBuildErrorResponse(messageHeader, + ee.getMessage()); + } + + String responseVdo = "DONE"; + try { + responseVdo = MessageFactory.convertToXMLString(responseMessageType); + } catch (I2B2Exception e) { + log.error(e.getMessage()); + } + return responseVdo; + } + + + private String runSetPassword(PMDbDao pmDb, String caller, String password) { + ResponseMessageType responseMessageType = null; + + try { + + int result = pmDb.setPassword(password, caller); + + ResultStatusType results = new ResultStatusType(); + StatusType status = new StatusType(); + status.setValue(result + " records"); + results.setStatus(status); + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); + responseMessageType = MessageFactory.createBuildResponse(messageHeader,results); + + } + catch (Exception ee) + { + log.error(ee.getMessage()); + // throw new Exception (ee.getMessage()); + ee.printStackTrace(); + + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); + responseMessageType = MessageFactory.doBuildErrorResponse(messageHeader, + ee.getMessage()); + } + + String responseVdo = "DONE"; + try { + responseVdo = MessageFactory.convertToXMLString(responseMessageType); + } catch (I2B2Exception e) { + log.error(e.getMessage()); + } + return responseVdo; + } + + private String runSetUser(PMDbDao pmDb, String project, String caller, + UserType utype) { + ResponseMessageType responseMessageType = null; + + try { + int result = pmDb.setUser(utype, caller); + + ResultStatusType results = new ResultStatusType(); + StatusType status = new StatusType(); + status.setValue(result + " records"); + results.setStatus(status); + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); + responseMessageType = MessageFactory.createBuildResponse(messageHeader,results); + + } + catch (Exception ee) + { + log.error(ee.getMessage()); + // throw new Exception (ee.getMessage()); + ee.printStackTrace(); + + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); + responseMessageType = MessageFactory.doBuildErrorResponse(messageHeader, + ee.getMessage()); + } + + String responseVdo = "DONE"; + try { + responseVdo = MessageFactory.convertToXMLString(responseMessageType); + } catch (I2B2Exception e) { + log.error(e.getMessage()); + } + return responseVdo; + } + + + private String runGetAllUser(PMDbDao pmDb, String project, String caller) { + ResponseMessageType responseMessageType = null; + + try { + + + List response = null; + try { + response = pmDb.getAllUser(project, caller); + } catch (I2B2DAOException e1) { + throw new Exception ( "Database error in getting user data for NTLM"); + } catch (I2B2Exception e1) { + throw new Exception ("Database error in getting user data for NTLM"); + } + + Iterator it = response.iterator(); + UsersType users = new UsersType(); + log.debug("Records returned: " + response.size()); + while (it.hasNext()) + { + UserType user = (UserType)it.next(); + users.getUser().add(user); + log.debug("added: " + user.getUserName()); + } + //everything is good so just return the same session key and the other info + + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); + responseMessageType = MessageFactory.createBuildResponse(messageHeader,users); + + } + catch (Exception ee) + { + log.error(ee.getMessage()); + // throw new Exception (ee.getMessage()); + ee.printStackTrace(); + + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); + responseMessageType = MessageFactory.doBuildErrorResponse(messageHeader, + ee.getMessage()); + } + + String responseVdo = "DONE"; + try { + responseVdo = MessageFactory.convertToXMLString(responseMessageType); + } catch (I2B2Exception e) { + log.error(e.getMessage()); + } + return responseVdo; + } + + private String runGetUser(PMDbDao pmDb, String project, String caller, + String username) { + ResponseMessageType responseMessageType = null; + + try { + + + List response = null; + try { + response = pmDb.getUser(username, caller); + } catch (I2B2DAOException e1) { + throw new Exception ( "Database error in getting user data for NTLM"); + } catch (I2B2Exception e1) { + throw new Exception ("Database error in getting user data for NTLM"); + } + + Iterator it = response.iterator(); + UserType user = null; + while (it.hasNext()) + user = (UserType)it.next(); + + //user = userManagerService.getUserByUserName(k.getUsername()); + if (user == null) + throw new Exception ("Unable to sign in"); + + + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); + responseMessageType = MessageFactory.createBuildResponse(messageHeader,user); + + } + catch (Exception ee) + { + log.error(ee.getMessage()); + // throw new Exception (ee.getMessage()); + ee.printStackTrace(); + + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); + responseMessageType = MessageFactory.doBuildErrorResponse(messageHeader, + ee.getMessage()); + } + + String responseVdo = "DONE"; + try { + responseVdo = MessageFactory.convertToXMLString(responseMessageType); + } catch (I2B2Exception e) { + log.error(e.getMessage()); + } + return responseVdo; + } + + //All Cell process + private String runDeleteCell(PMDbDao pmDb, String project, String caller, CellDataType utype) { + ResponseMessageType responseMessageType = null; + + try { + int result = pmDb.deleteCell(utype.getId(), utype.getProjectPath(), caller); + + ResultStatusType results = new ResultStatusType(); + StatusType status = new StatusType(); + status.setValue(result + " records"); + results.setStatus(status); + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); + responseMessageType = MessageFactory.createBuildResponse(messageHeader,results); + + } + catch (Exception ee) + { + log.error(ee.getMessage()); + // throw new Exception (ee.getMessage()); + ee.printStackTrace(); + + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); + responseMessageType = MessageFactory.doBuildErrorResponse(messageHeader, + ee.getMessage()); + } + + String responseVdo = "DONE"; + try { + responseVdo = MessageFactory.convertToXMLString(responseMessageType); + } catch (I2B2Exception e) { + log.error(e.getMessage()); + } + return responseVdo; + } + + private String runSetCell(PMDbDao pmDb, String project, String caller, + CellDataType utype) { + ResponseMessageType responseMessageType = null; + + try { + + //String SQL_QUERY ="from UserData where oid='" + username + "'"; + + int result = pmDb.setCell(utype, project, caller); + + ResultStatusType results = new ResultStatusType(); + StatusType status = new StatusType(); + status.setValue(result + " records"); + results.setStatus(status); + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); + responseMessageType = MessageFactory.createBuildResponse(messageHeader,results); + + } + catch (Exception ee) + { + log.error(ee.getMessage()); + // throw new Exception (ee.getMessage()); + ee.printStackTrace(); + + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); + responseMessageType = MessageFactory.doBuildErrorResponse(messageHeader, + ee.getMessage()); + } + + String responseVdo = "DONE"; + try { + responseVdo = MessageFactory.convertToXMLString(responseMessageType); + } catch (I2B2Exception e) { + log.error(e.getMessage()); + } + return responseVdo; + } + + + private String runGetAllCell(PMDbDao pmDb, String project, String caller) { + ResponseMessageType responseMessageType = null; + + try { + + + List response = null; + try { + response = pmDb.getAllCell(project, caller); + } catch (I2B2DAOException e1) { + throw new Exception ( "Database error in getting user data for NTLM"); + } catch (I2B2Exception e1) { + throw new Exception ("Database error in getting user data for NTLM"); + } + + Iterator it = response.iterator(); + CellDatasType users = new CellDatasType(); + log.debug("Records returned: " + response.size()); + while (it.hasNext()) + { + CellDataType user = (CellDataType)it.next(); + users.getCellData().add(user); + log.debug("added: " + user.getName()); + } + //everything is good so just return the same session key and the other info + + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); + responseMessageType = MessageFactory.createBuildResponse(messageHeader,users); + + } + catch (Exception ee) + { + log.error(ee.getMessage()); + // throw new Exception (ee.getMessage()); + ee.printStackTrace(); + + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); + responseMessageType = MessageFactory.doBuildErrorResponse(messageHeader, + ee.getMessage()); + } + + String responseVdo = "DONE"; + try { + responseVdo = MessageFactory.convertToXMLString(responseMessageType); + } catch (I2B2Exception e) { + log.error(e.getMessage()); + } + return responseVdo; + } + + private String runGetCell(PMDbDao pmDb, String project, + String owner, CellDataType utype) { + ResponseMessageType responseMessageType = null; + + try { + + log.debug("In runGetCell, with cell of: " + utype.getId() + " | " +utype.getProjectPath()); + + List response = null; + try { + response = pmDb.getCell(utype.getId(), utype.getProjectPath(), true); + } catch (I2B2DAOException e1) { + throw new Exception ( "Database error in getting user data for NTLM"); + } catch (I2B2Exception e1) { + throw new Exception ("Database error in getting user data for NTLM"); + } + + Iterator it = response.iterator(); + CellDataType user = null; + while (it.hasNext()) + user = (CellDataType)it.next(); + + //user = userManagerService.getUserByUserName(k.getUsername()); + if (user == null) + throw new Exception ("Cell does not exist"); + + + + + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); + responseMessageType = MessageFactory.createBuildResponse(messageHeader,user); + + } + catch (Exception ee) + { + log.error(ee.getMessage()); + // throw new Exception (ee.getMessage()); + ee.printStackTrace(); + + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); + responseMessageType = MessageFactory.doBuildErrorResponse(messageHeader, + ee.getMessage()); + } + + String responseVdo = "DONE"; + try { + responseVdo = MessageFactory.convertToXMLString(responseMessageType); + } catch (I2B2Exception e) { + log.error(e.getMessage()); + } + return responseVdo; + } + + + + //All Approval process + private String runDeleteApproval(PMDbDao pmDb, String project, String caller, ApprovalType utype) { + ResponseMessageType responseMessageType = null; + + try { + int result = pmDb.deleteApproval(utype.getId(), project, caller); + + ResultStatusType results = new ResultStatusType(); + StatusType status = new StatusType(); + status.setValue(result + " records"); + results.setStatus(status); + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); + responseMessageType = MessageFactory.createBuildResponse(messageHeader,results); + + } + catch (Exception ee) + { + log.error(ee.getMessage()); + // throw new Exception (ee.getMessage()); + ee.printStackTrace(); + + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); + responseMessageType = MessageFactory.doBuildErrorResponse(messageHeader, + ee.getMessage()); + } + + String responseVdo = "DONE"; + try { + responseVdo = MessageFactory.convertToXMLString(responseMessageType); + } catch (I2B2Exception e) { + log.error(e.getMessage()); + } + return responseVdo; + } + + private String runSetApproval(PMDbDao pmDb, String project, String caller, + ApprovalType utype) { + ResponseMessageType responseMessageType = null; + + try { + + //String SQL_QUERY ="from UserData where oid='" + username + "'"; + + int result = pmDb.setApproval(utype, project, caller); + + ResultStatusType results = new ResultStatusType(); + StatusType status = new StatusType(); + status.setValue(result + ""); + results.setStatus(status); + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); + responseMessageType = MessageFactory.createBuildResponse(messageHeader,results); + + } + catch (Exception ee) + { + log.error(ee.getMessage()); + // throw new Exception (ee.getMessage()); + ee.printStackTrace(); + + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); + responseMessageType = MessageFactory.doBuildErrorResponse(messageHeader, + ee.getMessage()); + } + + String responseVdo = "DONE"; + try { + responseVdo = MessageFactory.convertToXMLString(responseMessageType); + } catch (I2B2Exception e) { + log.error(e.getMessage()); + } + return responseVdo; + } + + + private String runGetAllApproval(PMDbDao pmDb, String project, String caller) { + ResponseMessageType responseMessageType = null; + + try { + + + List response = null; + try { + response = pmDb.getAllApproval(project, caller); + } catch (I2B2DAOException e1) { + throw new Exception ( "Database error in getting user data for NTLM"); + } catch (I2B2Exception e1) { + throw new Exception ("Database error in getting user data for NTLM"); + } + + Iterator it = response.iterator(); + ApprovalsType users = new ApprovalsType(); + log.debug("Records returned: " + response.size()); + while (it.hasNext()) + { + ApprovalType user = (ApprovalType)it.next(); + users.getApproval().add(user); + log.debug("added: " + user.getName()); + } + //everything is good so just return the same session key and the other info + + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); + responseMessageType = MessageFactory.createBuildResponse(messageHeader,users); + + } + catch (Exception ee) + { + log.error(ee.getMessage()); + // throw new Exception (ee.getMessage()); + ee.printStackTrace(); + + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); + responseMessageType = MessageFactory.doBuildErrorResponse(messageHeader, + ee.getMessage()); + } + + String responseVdo = "DONE"; + try { + responseVdo = MessageFactory.convertToXMLString(responseMessageType); + } catch (I2B2Exception e) { + log.error(e.getMessage()); + } + return responseVdo; + } + + private String runGetApproval(PMDbDao pmDb, String project, + String owner, ApprovalType utype) { + ResponseMessageType responseMessageType = null; + + try { + + List response = null; + try { + response = pmDb.getApproval(utype, true); + } catch (I2B2DAOException e1) { + throw new Exception ( "Database error in getting user data for NTLM"); + } catch (I2B2Exception e1) { + throw new Exception ("Database error in getting user data for NTLM"); + } + + + Iterator it = response.iterator(); + ApprovalsType users = new ApprovalsType(); + log.debug("Records returned: " + response.size()); + while (it.hasNext()) + { + ApprovalType user = (ApprovalType)it.next(); + users.getApproval().add(user); + log.debug("added: " + user.getName()); + } + + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); + responseMessageType = MessageFactory.createBuildResponse(messageHeader,users); + + } + catch (Exception ee) + { + log.error(ee.getMessage()); + // throw new Exception (ee.getMessage()); + ee.printStackTrace(); + + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); + responseMessageType = MessageFactory.doBuildErrorResponse(messageHeader, + ee.getMessage()); + } + + String responseVdo = "DONE"; + try { + responseVdo = MessageFactory.convertToXMLString(responseMessageType); + } catch (I2B2Exception e) { + log.error(e.getMessage()); + } + return responseVdo; + } + + + + //All Project process + private String runDeleteProject(PMDbDao pmDb, String caller, Object project) { + ResponseMessageType responseMessageType = null; + + try { + int result = pmDb.deleteProject(project, caller); + + ResultStatusType results = new ResultStatusType(); + StatusType status = new StatusType(); + status.setValue(result + " records"); + results.setStatus(status); + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); + responseMessageType = MessageFactory.createBuildResponse(messageHeader,results); + + } + catch (Exception ee) + { + log.error(ee.getMessage()); + // throw new Exception (ee.getMessage()); + ee.printStackTrace(); + + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); + responseMessageType = MessageFactory.doBuildErrorResponse(messageHeader, + ee.getMessage()); + } + + String responseVdo = "DONE"; + try { + responseVdo = MessageFactory.convertToXMLString(responseMessageType); + } catch (I2B2Exception e) { + log.error(e.getMessage()); + } + return responseVdo; + } + + private String runSetProject(PMDbDao pmDb, String project, String caller, + ProjectType utype) { + ResponseMessageType responseMessageType = null; + + try { + + //String SQL_QUERY ="from UserData where oid='" + username + "'"; + + int result = pmDb.setProject(utype, caller); + + ResultStatusType results = new ResultStatusType(); + StatusType status = new StatusType(); + status.setValue(result + " records"); + results.setStatus(status); + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); + responseMessageType = MessageFactory.createBuildResponse(messageHeader,results); + + } + catch (Exception ee) + { + log.error(ee.getMessage()); + // throw new Exception (ee.getMessage()); + ee.printStackTrace(); + + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); + responseMessageType = MessageFactory.doBuildErrorResponse(messageHeader, + ee.getMessage()); + } + + String responseVdo = "DONE"; + try { + responseVdo = MessageFactory.convertToXMLString(responseMessageType); + } catch (I2B2Exception e) { + log.error(e.getMessage()); + } + return responseVdo; + } + + + private String runGetAllProject(PMDbDao pmDb, String project, String caller) { + ResponseMessageType responseMessageType = null; + + try { + + + List response = null; + try { + response = pmDb.getAllProject(project, caller); + } catch (I2B2DAOException e1) { + throw new Exception ( "Database error in getting user data for NTLM"); + } catch (I2B2Exception e1) { + throw new Exception ("Database error in getting user data for NTLM"); + } + + Iterator it = response.iterator(); + ProjectsType users = new ProjectsType(); + log.debug("Records returned: " + response.size()); + while (it.hasNext()) + { + ProjectType user = (ProjectType)it.next(); + + users.getProject().add(user); + log.debug("added: " + user.getName()); + } + //everything is good so just return the same session key and the other info + + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); + responseMessageType = MessageFactory.createBuildResponse(messageHeader,users); + + } + catch (Exception ee) + { + log.error(ee.getMessage()); + // throw new Exception (ee.getMessage()); + ee.printStackTrace(); + + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); + responseMessageType = MessageFactory.doBuildErrorResponse(messageHeader, + ee.getMessage()); + } + + String responseVdo = "DONE"; + try { + responseVdo = MessageFactory.convertToXMLString(responseMessageType); + } catch (I2B2Exception e) { + log.error(e.getMessage()); + } + return responseVdo; + } + + private String runGetProject(PMDbDao pmDb, String caller, Object utype) { + ResponseMessageType responseMessageType = null; + + try { + + List response = null; + try { + response = pmDb.getProject(utype, true); + } catch (I2B2DAOException e1) { + throw new Exception ( "Database error in getting user data for NTLM"); + } catch (I2B2Exception e1) { + throw new Exception ("Database error in getting user data for NTLM"); + } + + Iterator it = response.iterator(); + ProjectType user = null; + while (it.hasNext()) + user = (ProjectType)it.next(); + + //user = userManagerService.getUserByUserName(k.getUsername()); + if (user == null) + throw new Exception ("Project does not exist"); + + + //everything is good so just return the same session key and the other info + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); + responseMessageType = MessageFactory.createBuildResponse(messageHeader,user); + + } + catch (Exception ee) + { + log.error(ee.getMessage()); + // throw new Exception (ee.getMessage()); + ee.printStackTrace(); + + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(getServicesMsg.getRequestMessageType().getMessageHeader()); + responseMessageType = MessageFactory.doBuildErrorResponse(messageHeader, + ee.getMessage()); + } + + String responseVdo = "DONE"; + try { + responseVdo = MessageFactory.convertToXMLString(responseMessageType); + } catch (I2B2Exception e) { + log.error(e.getMessage()); + } + return responseVdo; + } + + + + private String runGetUserConfiguration(PMDbDao pmDb, GetUserConfigurationType userType, + String username, String domain, ConfigureType cType, UserType uType) { + + //ConfigureType cType = new ConfigureType(); + //UserType uType = new UserType(); + CellDatasType aType = new CellDatasType(); + + ResponseMessageType responseMessageType = null; + + try { + //Get user Data + cType.setUser(uType); + + if ((userType.getDataNeeded() == null) || (userType.getDataNeeded().size() == 0) || (userType.getDataNeeded().contains("USER"))) + { + + + Iterator itsg = pmDb.getUserProject(username).iterator(); + if (itsg == null) + throw new Exception (username + " is not associated with any groups"); + while (itsg.hasNext()) { + ProjectType pType = (ProjectType)itsg.next(); + + + //Get Variables for the project + for(Iterator it2=pmDb.getProjectParams(pType.getId()).iterator();it2.hasNext();){ + ParamType vardata =(ParamType)it2.next(); + log.debug("Added Project Param: " + vardata.getName()); + pType.getParam().add(vardata); + } + //Get user project params for the project + ProjectType tempptype = new ProjectType(); + tempptype.setId(pType.getId()); + tempptype.setUserName(uType.getUserName()); + for(Iterator it2=pmDb.getAllParam(tempptype, null, username).iterator();it2.hasNext();){ + ParamType vardata =(ParamType)it2.next(); + log.debug("Added Project Param: " + vardata.getName()); + pType.getParam().add(vardata); + } + + //Get Roles for the project + for(Iterator it2=pmDb.getRole(username, pType.getId()).iterator();it2.hasNext();){ + RoleType g = (RoleType) it2.next(); + + log.debug("got Role: " + g.getRole()); + pType.getRole().add(g.getRole()); + + } + //Get ADMIN @ role + for (Iterator it2=pmDb.getRole(username, "@").iterator();it2.hasNext();){ + RoleType g = (RoleType) it2.next(); + + log.debug("got Role: " + g.getRole()); + if (g.getRole().equals("ADMIN")) + uType.setIsAdmin(true); + + } + + + uType.getProject().add(pType); + + } + + + //OLD CODE + /* + + Iterator itsg = pmDb.getRole(username).iterator(); + if (itsg == null) + throw new Exception (username + " is not associated with any groups"); + boolean found = false; + String origProject = ""; + while (itsg.hasNext()) { + found = true; + ProjectType pType = new ProjectType(); + + RoleData g = (RoleData) itsg.next(); + + pType.getRole().add(g.getRole()); + + log.debug("got Role: " + g.getRole()); + if (g.getProject().equals(origProject)) + { + // Project is the same, just a new role. So add it and continue + continue; + } + + + origProject = g.getProject(); + + log.debug("pdata: " + g.getProject()); + + //Only get valid projects, + + //GroupData pData = globaldataservice.getGroupDataByOid(g.getName()); + + for(Iterator it=pmDb.getProject(g.getProject()).iterator();it.hasNext();){ + ProjectType pData =(ProjectType)it.next(); + + //Get Variables for the group + for(Iterator it2=pmDb.getProjectParams(g.getProject()).iterator();it2.hasNext();){ + ParamType vardata =(ParamType)it2.next(); + log.debug("Added Project Param: " + vardata.getName()); + pType.getParam().add(vardata); + } + + pType.setChangeDate(pData.getChangeDate()); + pType.setEntryDate(pData.getEntryDate()); + pType.setKey(pData.getKey()); + pType.setId(pData.getId()); + pType.setName(pData.getName()); + pType.setStatus(pData.getStatus()); + pType.setWiki(pData.getWiki()); + log.debug("Added Project: " + pData.getId()); + //uType.getProject().add(pData); + } + + + + //Get user variables for the group + for(Iterator it=pmDb.getProjectUserParams(g.getProject(), username).iterator();it.hasNext();){ + + ParamType vardata =(ParamType)it.next(); + log.debug("Added Project User Param: " + vardata.getName()); + pType.getParam().add(vardata); + } + uType.getProject().add(pType); + + + // Set project only if null or requested + // log.debug("Adding Project: " + userType.getProject()); + // if ((userType.getProject() == null) || (userType.getProject().size() == 0) || (userType.getProject().contains(pType.getId().toUpperCase()))) + // uType.getProject().add(pType); + + log.debug("Adding usertype"); + cType.setUser(uType); + } + */ + if (cType.getUser() == null) + throw new Exception ("Group Data has not been filled out"); + //if (found == false) + // throw new Exception (username + " is not part of project " + domain); + } + + + + + + //Get Cell Data + if ((userType.getDataNeeded() == null) || (userType.getDataNeeded().size() == 0) || (userType.getDataNeeded().contains("CELL_DATA"))) + { + + // Get all cells + for(Iterator it=pmDb.getCell("@", "/", true).iterator();it.hasNext();){ + CellDataType cell =(CellDataType)it.next(); + + + if (cell == null) + { + throw new Exception ("No cells are be registered yet"); + } + + log.debug("my url is " + cell.getUrl()); + + + for(Iterator it2=pmDb.getCellParam(cell.getId(),"/").iterator();it2.hasNext();){ + ParamType cellParam =(ParamType)it2.next(); + cell.getParam().add(cellParam); + } + aType.getCellData().add(cell); + } + + // Get project specific cells + for (ProjectType p : uType.getProject()) { + log.debug("Searching cells for: " + p.getId() + ":" + p.getPath()); + if (p.getPath() != null) + for(Iterator it=pmDb.getCell("@", p.getPath(), true).iterator();it.hasNext();){ + CellDataType cell =(CellDataType)it.next(); + + + if (cell == null) + { + throw new Exception ("No cells are be registered yet"); + } + + log.debug("my url is " + cell.getUrl()); + + + for(Iterator it2=pmDb.getCellParam(cell.getId(),"/").iterator();it2.hasNext();){ + ParamType cellParam =(ParamType)it2.next(); + cell.getParam().add(cellParam); + } + + aType.getCellData().add(cell); + } + } + + cType.setCellDatas(aType); + } + + //Get User Params + + for(Iterator it2=pmDb.getAllParam(uType,null,null).iterator();it2.hasNext();){ + UserParamData p = (UserParamData)it2.next(); + ParamType param = new ParamType(); + param.setName(p.getName()); + param.setValue(p.getValue()); + uType.getParam().add(param); + } + // + + // Get Global Data + GlobalDataType globaldata = new GlobalDataType(); + + for(Iterator it=pmDb.getAllParam(new GlobalDataType(), null, null).iterator();it.hasNext();){ + + //GlobalDataType globaldata =(GlobalDataType)it.next(); + + // List gData = globaldataservice.getGlobalData(); + // GlobalDataType gValue = new GlobalDataType(); + + // if (gData!=null) { + // for (int i=0;ihttp://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2007.04.26 at 10:28:57 AM EDT -// - - -package edu.harvard.i2b2.pm.services; - -import jakarta.xml.bind.annotation.XmlAccessType; -import jakarta.xml.bind.annotation.XmlAccessorType; -import jakarta.xml.bind.annotation.XmlAttribute; -import jakarta.xml.bind.annotation.XmlType; -import jakarta.xml.bind.annotation.XmlValue; - - -/** - *

    Java class for paramType complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="paramType">
    - *   <simpleContent>
    - *     <extension base="<http://www.w3.org/2001/XMLSchema>string">
    - *       <attribute name="name" type="{http://www.w3.org/2001/XMLSchema}string" />
    - *     </extension>
    - *   </simpleContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "paramType", propOrder = { - "value" -}) -public class ParamType { - - @XmlValue - protected String value; - @XmlAttribute - protected String name; - - /** - * Gets the value of the value property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getValue() { - return value; - } - - /** - * Sets the value of the value property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setValue(String value) { - this.value = value; - } - - /** - * Gets the value of the name property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getName() { - return name; - } - - /** - * Sets the value of the name property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setName(String value) { - this.name = value; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.1.2-b01-fcs +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2007.04.26 at 10:28:57 AM EDT +// + + +package edu.harvard.i2b2.pm.services; + +import jakarta.xml.bind.annotation.XmlAccessType; +import jakarta.xml.bind.annotation.XmlAccessorType; +import jakarta.xml.bind.annotation.XmlAttribute; +import jakarta.xml.bind.annotation.XmlType; +import jakarta.xml.bind.annotation.XmlValue; + + +/** + *

    Java class for paramType complex type. + * + *

    The following schema fragment specifies the expected content contained within this class. + * + *

    + * <complexType name="paramType">
    + *   <simpleContent>
    + *     <extension base="<http://www.w3.org/2001/XMLSchema>string">
    + *       <attribute name="name" type="{http://www.w3.org/2001/XMLSchema}string" />
    + *     </extension>
    + *   </simpleContent>
    + * </complexType>
    + * 
    + * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "paramType", propOrder = { + "value" +}) +public class ParamType { + + @XmlValue + protected String value; + @XmlAttribute + protected String name; + + /** + * Gets the value of the value property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getValue() { + return value; + } + + /** + * Sets the value of the value property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setValue(String value) { + this.value = value; + } + + /** + * Gets the value of the name property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getName() { + return name; + } + + /** + * Sets the value of the name property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setName(String value) { + this.name = value; + } + +} diff --git a/edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/services/ProjectUserParamData.java b/edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/services/ProjectUserParamData.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/services/ProjectUserParamData.java rename to edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/services/ProjectUserParamData.java diff --git a/edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/services/ProjectUserParamDataPK.java b/edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/services/ProjectUserParamDataPK.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/services/ProjectUserParamDataPK.java rename to edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/services/ProjectUserParamDataPK.java diff --git a/edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/services/RegisteredCell.java b/edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/services/RegisteredCell.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/services/RegisteredCell.java rename to edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/services/RegisteredCell.java diff --git a/edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/services/RegisteredCellPK.java b/edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/services/RegisteredCellPK.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/services/RegisteredCellPK.java rename to edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/services/RegisteredCellPK.java diff --git a/edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/services/RegisteredCellParam.java b/edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/services/RegisteredCellParam.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/services/RegisteredCellParam.java rename to edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/services/RegisteredCellParam.java diff --git a/edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/services/RegisteredCellParamPK.java b/edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/services/RegisteredCellParamPK.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/services/RegisteredCellParamPK.java rename to edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/services/RegisteredCellParamPK.java diff --git a/edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/services/RoleData.java b/edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/services/RoleData.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/services/RoleData.java rename to edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/services/RoleData.java diff --git a/edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/services/RoleDataPK.java b/edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/services/RoleDataPK.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/services/RoleDataPK.java rename to edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/services/RoleDataPK.java diff --git a/edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/services/SessionData.java b/edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/services/SessionData.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/services/SessionData.java rename to edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/services/SessionData.java diff --git a/edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/services/UserData.java b/edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/services/UserData.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/services/UserData.java rename to edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/services/UserData.java diff --git a/edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/services/UserLoginData.java b/edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/services/UserLoginData.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/services/UserLoginData.java rename to edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/services/UserLoginData.java diff --git a/edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/services/UserParamData.java b/edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/services/UserParamData.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/services/UserParamData.java rename to edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/services/UserParamData.java diff --git a/edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/services/UserParamDataPK.java b/edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/services/UserParamDataPK.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/services/UserParamDataPK.java rename to edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/services/UserParamDataPK.java diff --git a/edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/services/VariableData.java b/edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/services/VariableData.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/services/VariableData.java rename to edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/services/VariableData.java diff --git a/edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/services/VariableDataPK.java b/edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/services/VariableDataPK.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/services/VariableDataPK.java rename to edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/services/VariableDataPK.java diff --git a/edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/upgrade/UpdateCells.java b/edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/upgrade/UpdateCells.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/upgrade/UpdateCells.java rename to edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/upgrade/UpdateCells.java diff --git a/edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/util/AppVersion.java b/edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/util/AppVersion.java similarity index 100% rename from edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/util/AppVersion.java rename to edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/util/AppVersion.java diff --git a/edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/util/DateUtil.java b/edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/util/DateUtil.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/util/DateUtil.java rename to edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/util/DateUtil.java diff --git a/edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/util/JAXBConstant.java b/edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/util/JAXBConstant.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/util/JAXBConstant.java rename to edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/util/JAXBConstant.java diff --git a/edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/util/PMJAXBUtil.java b/edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/util/PMJAXBUtil.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/util/PMJAXBUtil.java rename to edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/util/PMJAXBUtil.java diff --git a/edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/util/PMUtil.java b/edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/util/PMUtil.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/util/PMUtil.java rename to edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/util/PMUtil.java diff --git a/edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/util/SecurityAuthentication.java b/edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/util/SecurityAuthentication.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/util/SecurityAuthentication.java rename to edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/util/SecurityAuthentication.java diff --git a/edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/util/SecurityAuthenticationBASIC.java b/edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/util/SecurityAuthenticationBASIC.java similarity index 100% rename from edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/util/SecurityAuthenticationBASIC.java rename to edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/util/SecurityAuthenticationBASIC.java diff --git a/edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/util/SecurityAuthenticationLDAP.java b/edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/util/SecurityAuthenticationLDAP.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/util/SecurityAuthenticationLDAP.java rename to edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/util/SecurityAuthenticationLDAP.java diff --git a/edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/util/SecurityAuthenticationNTLM2.java b/edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/util/SecurityAuthenticationNTLM2.java similarity index 100% rename from edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/util/SecurityAuthenticationNTLM2.java rename to edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/util/SecurityAuthenticationNTLM2.java diff --git a/edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/util/SecurityAuthenticationOKTA.java b/edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/util/SecurityAuthenticationOKTA.java similarity index 100% rename from edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/util/SecurityAuthenticationOKTA.java rename to edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/util/SecurityAuthenticationOKTA.java diff --git a/edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/util/SecurityAuthenticationSAML.java b/edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/util/SecurityAuthenticationSAML.java similarity index 100% rename from edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/util/SecurityAuthenticationSAML.java rename to edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/util/SecurityAuthenticationSAML.java diff --git a/edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/util/SessionKey.java b/edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/util/SessionKey.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/util/SessionKey.java rename to edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/util/SessionKey.java diff --git a/edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/util/StringUtil.java b/edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/util/StringUtil.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/util/StringUtil.java rename to edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/util/StringUtil.java diff --git a/edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/ws/ExecutorRunnable.java b/edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/ws/ExecutorRunnable.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/ws/ExecutorRunnable.java rename to edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/ws/ExecutorRunnable.java diff --git a/edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/ws/MessageFactory.java b/edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/ws/MessageFactory.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/ws/MessageFactory.java rename to edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/ws/MessageFactory.java diff --git a/edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/ws/PMService.java b/edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/ws/PMService.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/ws/PMService.java rename to edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/ws/PMService.java index 26fcd242..861b7b1f --- a/edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/ws/PMService.java +++ b/edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/ws/PMService.java @@ -1,366 +1,366 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Mike Mendis - initial API and implementation - */ - -package edu.harvard.i2b2.pm.ws; - -import java.nio.file.FileStore; -import java.nio.file.FileSystems; -import java.nio.file.Files; -import java.nio.file.Path; -import java.text.NumberFormat; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.xml.stream.XMLStreamException; - -import org.apache.axiom.om.OMElement; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.pm.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.pm.delegate.ServicesHandler; -import edu.harvard.i2b2.pm.util.AppVersion; -import edu.harvard.i2b2.pm.util.StringUtil; -//import javax.servlet.http.HttpServletRequest; -import org.apache.axis2.context.MessageContext; -import org.apache.axis2.kernel.http.HTTPConstants; - -import jakarta.servlet.http.HttpServletRequest; - -/** - * This is webservice skeleton class. It passes incoming report to PFT parser - * and collects parsed pft concepts. Then these parsed concepts returned back to - * webservice client in Patient Data Object XML format. - * - */ -public class PMService { - private static Log log = LogFactory.getLog(PMService.class); - - protected static Log logesapi = LogFactory.getLog(PMService.class); - - private static String msgVersion = "1.1"; - private static String i2b2Version = "1.8.2"; - - public String getVersion() - { - return i2b2Version; - } - - public String getMessageVersion() - { - return msgVersion; - } - - public OMElement getVersion(OMElement getPMDataElement) - throws I2B2Exception, JAXBUtilException { - - Pattern p = Pattern.compile(".+"); - Matcher m = p.matcher(getPMDataElement.toString()); - String outString = m.replaceAll("*********"); - - p = Pattern.compile(">.+"); - m = p.matcher(outString); - outString = m.replaceAll(">*********"); - logesapi.debug("Received Request PM Element " + outString); - - OMElement returnElement = null; - - - if (getPMDataElement == null) { - log.error("Incoming Version request is null"); - throw new I2B2Exception("Incoming Version request is null"); - } - - String messageBody = "get_i2b2_message_version"; - - try { - messageBody = outString.toLowerCase().substring(outString.indexOf("message_body")); - } catch (Exception e){} - - edu.harvard.i2b2.pm.datavo.i2b2versionmessage.ResponseMessageType pmDataResponse = new edu.harvard.i2b2.pm.datavo.i2b2versionmessage.ResponseMessageType(); - - edu.harvard.i2b2.pm.datavo.i2b2versionmessage.ResponseMessageType.MessageBody mb = new edu.harvard.i2b2.pm.datavo.i2b2versionmessage.ResponseMessageType.MessageBody(); - if (messageBody.contains("get_i2b2_message_version") || (messageBody.contains("get_message_version"))) - mb.setI2B2MessageVersion(msgVersion); - if (messageBody.contains("get_i2b2_version")) - mb.setI2B2Version(i2b2Version); - if (messageBody.contains("get_jdk_version")) - mb.setJdkVersion(System.getProperty("java.vendor") + " Java " + System.getProperty("java.version")); - if (messageBody.contains("get_os_version")) - mb.setOsVersion( System.getProperty("os.name") + " " + System.getProperty("os.arch") + " " + System.getProperty("os.version")); - if (messageBody.contains("get_java_memory")) - { - Runtime r = Runtime.getRuntime(); - String result = "Total Memory: " + StringUtil.humanReadableByteCount(r.totalMemory(), true); - result += "\nMax Memory: " + StringUtil.humanReadableByteCount( r.maxMemory(), true); - result += "\nUsed Memory: " + StringUtil.humanReadableByteCount((r.maxMemory() - r.freeMemory()), true); - result += "\nFree Memory: " + StringUtil.humanReadableByteCount(r.freeMemory(), true); - - mb.setJavaMemory(result); - } - if (messageBody.contains("app_server_version")) - { - try { - mb.setAppServerVersion(AppVersion.appServerRunningVersion()); - } catch (Exception e) - { - mb.setAppServerVersion(e.getMessage()); - } - } - if (messageBody.contains("get_disk_usage")) - { - String result = ""; - NumberFormat nf = NumberFormat.getNumberInstance(); - for (Path root : FileSystems.getDefault().getRootDirectories()) { - try { - FileStore store = Files.getFileStore(root); - result += "\nTotal Space for " + root + ": " + StringUtil.humanReadableByteCount(store.getTotalSpace(), true); - result += "\nUnallocated Space for " + root + ": " + StringUtil.humanReadableByteCount(store.getUnallocatedSpace(), true); - result += "\nUsable Space for " + root + ": " + StringUtil.humanReadableByteCount(store.getUsableSpace(), true); - } catch (Exception e) - { - result += "Erron on " + root; - } - } - if (result.length() > 2) - result = result.substring(1); - mb.setDiskUsage(result); - } - if (messageBody.contains("get_axis2_version")) - { - mb.setAxis2Version(org.apache.axis2.Version.getVersionText()); - } - pmDataResponse.setMessageBody(mb); - - String xmlMsg = MessageFactory.convertToXMLString(pmDataResponse); - - try { - returnElement = edu.harvard.i2b2.common.util.axis2.ServiceClient.getPayLoad(xmlMsg); - - log.debug("my pm repsonse is: " + pmDataResponse); - log.debug("my return is: " + returnElement); - } catch (Exception e) { - log.error("Error creating OMElement from response string " + - pmDataResponse, e); - } - - - return returnElement; - - } - - /** - * This function is main webservice interface to get pulmonary data from - * pulmonary report. It uses AXIOM elements(OMElement) to conveniently parse - * xml messages. - * - * It excepts incoming request in i2b2 message format, which wraps PFT - * report inside patientdata object. The response is also will be in i2b2 - * message, which will wrap patientdata object. Patient data object will - * have all the extracted pft concepts from the report. - * - * - * @param getServices - * @return OMElement in i2b2message format - * @throws PortletServiceNotFoundException - * @throws PortletServiceUnavailableException - * @throws Exception - */ - public OMElement getServices(OMElement getPMDataElement) - throws Exception { - /* - // OMElement returnElement = null; - String pmDataResponse = null; - String unknownErrorMessage = "Error message delivered from the remote server \n" + - "You may wish to retry your last action"; - - if (getPMDataElement == null) { - log.error("Incoming Workplace request is null"); - - ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, - unknownErrorMessage); - pmDataResponse = MessageFactory.convertToXMLString(responseMsgType); - //return MessageFactory.createResponseOMElementFromString(pmDataResponse); - throw new I2B2Exception("Incoming PM request is null"); - } - - ServicesMessage servicesMsg = new ServicesMessage(getPMDataElement.toString()); - - String requestElementString = getPMDataElement.toString(); - // log.info(requestElementString); - //foldersDataMsg.setRequestMessageType(requestElementString); - - long waitTime = 0; - if ((servicesMsg.getRequestMessageType() != null) && (servicesMsg.getRequestMessageType().getRequestHeader() != null)) { - waitTime = servicesMsg.getRequestMessageType() - .getRequestHeader() - .getResultWaittimeMs(); - } - - //do Workplace query processing inside thread, so that - // service could sends back message with timeout error. - - // ExecutorRunnable er = new ExecutorRunnable(); - return edu.harvard.i2b2.common.util.axis2.ServiceClient.getPayLoad(pmDataResponse); - //execute(new GetFoldersByProjectHandler(servicesMsg), waitTime); - - */ - - - - - - - - - - - - - - - MessageContext messageContext = MessageContext.getCurrentMessageContext(); - HttpServletRequest req = (HttpServletRequest) messageContext.getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST); - - OMElement returnElement = null; - - - if (getPMDataElement == null) { - log.error("Incoming PM request is null"); - throw new I2B2Exception("Incoming PM request is null"); - } - - Pattern p = Pattern.compile(".+"); - Matcher m = p.matcher(getPMDataElement.toString()); - String outString = m.replaceAll("*********"); - - p = Pattern.compile(">.+"); - m = p.matcher(outString); - outString = m.replaceAll(">*********"); - logesapi.debug("Received Request PM Element " + outString); - - - log.debug("Begin getting servicesMsg"); - ServicesMessage servicesMsg = new ServicesMessage(getPMDataElement.toString()); - long waitTime = 0; - - if ((servicesMsg.getRequestMessageType() != null) && (servicesMsg.getRequestMessageType().getRequestHeader() != null)) { - waitTime = servicesMsg.getRequestMessageType() - .getRequestHeader() - .getResultWaittimeMs(); - } - - log.debug("Completed getting servicesMsg, waittime is: " + waitTime); - - //do PM processing inside thread, so that - // service could sends back message with timeout error. - - String pmDataResponse = null; - try { - ExecutorRunnable er = new ExecutorRunnable(); - //er.setInputString(requestElementString); - log.debug("begin setRequestHandler, my servicesMsg: " + servicesMsg); - - er.setRequestHandler(new ServicesHandler(servicesMsg, req)); - log.debug("middle setRequestHandler"); - - - log.debug("end setRequestHandler"); - - - Thread t = new Thread(er); - - ResponseMessageType responseMsgType = null; - - synchronized (t) { - t.start(); - - try { - //if (waitTime > 0) { - // t.wait(waitTime); - //} else { - // t.wait(); - //} - - long startTime = System.currentTimeMillis(); - long deltaTime = -1; - while((er.isJobCompleteFlag() == false)&& (deltaTime < waitTime)){ - if (waitTime > 0) { - t.wait(waitTime - deltaTime); - deltaTime = System.currentTimeMillis() - startTime; - } else { - t.wait(); - } - } - pmDataResponse = er.getOutputString(); - - if (pmDataResponse == null) { - if (er.getJobException() != null) { - pmDataResponse = ""; - throw new I2B2Exception("Portal is not property configured."); - } - else if (er.isJobCompleteFlag() == false) { - String timeOuterror = "Result waittime millisecond :" + - waitTime + - " elapsed, try again with increased value"; - log.debug(timeOuterror); - - responseMsgType = MessageFactory.doBuildErrorResponse(null, - timeOuterror); - pmDataResponse = MessageFactory.convertToXMLString(responseMsgType); - } - } - } catch (InterruptedException e) { - log.error("Error in thread: " + e.getMessage()); - - e.printStackTrace(); - throw new I2B2Exception("Thread error while running PM job " + - getPMDataElement, e); - } finally { - t.interrupt(); - er = null; - t = null; - } - } - - } catch (Exception e) { - log.error("Error: " + e.getMessage()); - e.printStackTrace(); - } - try { - returnElement = edu.harvard.i2b2.common.util.axis2.ServiceClient.getPayLoad(pmDataResponse); - - log.debug("my pm repsonse is: " + pmDataResponse); - log.debug("my return is: " + returnElement); - } catch (Exception e) { - log.error("Error creating OMElement from response string " + - pmDataResponse, e); - } - - return returnElement; - - } -} - - - - - - - +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Mike Mendis - initial API and implementation + */ + +package edu.harvard.i2b2.pm.ws; + +import java.nio.file.FileStore; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.nio.file.Path; +import java.text.NumberFormat; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.xml.stream.XMLStreamException; + +import org.apache.axiom.om.OMElement; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.pm.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.pm.delegate.ServicesHandler; +import edu.harvard.i2b2.pm.util.AppVersion; +import edu.harvard.i2b2.pm.util.StringUtil; +//import javax.servlet.http.HttpServletRequest; +import org.apache.axis2.context.MessageContext; +import org.apache.axis2.kernel.http.HTTPConstants; + +import jakarta.servlet.http.HttpServletRequest; + +/** + * This is webservice skeleton class. It passes incoming report to PFT parser + * and collects parsed pft concepts. Then these parsed concepts returned back to + * webservice client in Patient Data Object XML format. + * + */ +public class PMService { + private static Log log = LogFactory.getLog(PMService.class); + + protected static Log logesapi = LogFactory.getLog(PMService.class); + + private static String msgVersion = "1.1"; + private static String i2b2Version = "1.8.2"; + + public String getVersion() + { + return i2b2Version; + } + + public String getMessageVersion() + { + return msgVersion; + } + + public OMElement getVersion(OMElement getPMDataElement) + throws I2B2Exception, JAXBUtilException { + + Pattern p = Pattern.compile(".+"); + Matcher m = p.matcher(getPMDataElement.toString()); + String outString = m.replaceAll("*********"); + + p = Pattern.compile(">.+"); + m = p.matcher(outString); + outString = m.replaceAll(">*********"); + logesapi.debug("Received Request PM Element " + outString); + + OMElement returnElement = null; + + + if (getPMDataElement == null) { + log.error("Incoming Version request is null"); + throw new I2B2Exception("Incoming Version request is null"); + } + + String messageBody = "get_i2b2_message_version"; + + try { + messageBody = outString.toLowerCase().substring(outString.indexOf("message_body")); + } catch (Exception e){} + + edu.harvard.i2b2.pm.datavo.i2b2versionmessage.ResponseMessageType pmDataResponse = new edu.harvard.i2b2.pm.datavo.i2b2versionmessage.ResponseMessageType(); + + edu.harvard.i2b2.pm.datavo.i2b2versionmessage.ResponseMessageType.MessageBody mb = new edu.harvard.i2b2.pm.datavo.i2b2versionmessage.ResponseMessageType.MessageBody(); + if (messageBody.contains("get_i2b2_message_version") || (messageBody.contains("get_message_version"))) + mb.setI2B2MessageVersion(msgVersion); + if (messageBody.contains("get_i2b2_version")) + mb.setI2B2Version(i2b2Version); + if (messageBody.contains("get_jdk_version")) + mb.setJdkVersion(System.getProperty("java.vendor") + " Java " + System.getProperty("java.version")); + if (messageBody.contains("get_os_version")) + mb.setOsVersion( System.getProperty("os.name") + " " + System.getProperty("os.arch") + " " + System.getProperty("os.version")); + if (messageBody.contains("get_java_memory")) + { + Runtime r = Runtime.getRuntime(); + String result = "Total Memory: " + StringUtil.humanReadableByteCount(r.totalMemory(), true); + result += "\nMax Memory: " + StringUtil.humanReadableByteCount( r.maxMemory(), true); + result += "\nUsed Memory: " + StringUtil.humanReadableByteCount((r.maxMemory() - r.freeMemory()), true); + result += "\nFree Memory: " + StringUtil.humanReadableByteCount(r.freeMemory(), true); + + mb.setJavaMemory(result); + } + if (messageBody.contains("app_server_version")) + { + try { + mb.setAppServerVersion(AppVersion.appServerRunningVersion()); + } catch (Exception e) + { + mb.setAppServerVersion(e.getMessage()); + } + } + if (messageBody.contains("get_disk_usage")) + { + String result = ""; + NumberFormat nf = NumberFormat.getNumberInstance(); + for (Path root : FileSystems.getDefault().getRootDirectories()) { + try { + FileStore store = Files.getFileStore(root); + result += "\nTotal Space for " + root + ": " + StringUtil.humanReadableByteCount(store.getTotalSpace(), true); + result += "\nUnallocated Space for " + root + ": " + StringUtil.humanReadableByteCount(store.getUnallocatedSpace(), true); + result += "\nUsable Space for " + root + ": " + StringUtil.humanReadableByteCount(store.getUsableSpace(), true); + } catch (Exception e) + { + result += "Erron on " + root; + } + } + if (result.length() > 2) + result = result.substring(1); + mb.setDiskUsage(result); + } + if (messageBody.contains("get_axis2_version")) + { + mb.setAxis2Version(org.apache.axis2.Version.getVersionText()); + } + pmDataResponse.setMessageBody(mb); + + String xmlMsg = MessageFactory.convertToXMLString(pmDataResponse); + + try { + returnElement = edu.harvard.i2b2.common.util.axis2.ServiceClient.getPayLoad(xmlMsg); + + log.debug("my pm repsonse is: " + pmDataResponse); + log.debug("my return is: " + returnElement); + } catch (Exception e) { + log.error("Error creating OMElement from response string " + + pmDataResponse, e); + } + + + return returnElement; + + } + + /** + * This function is main webservice interface to get pulmonary data from + * pulmonary report. It uses AXIOM elements(OMElement) to conveniently parse + * xml messages. + * + * It excepts incoming request in i2b2 message format, which wraps PFT + * report inside patientdata object. The response is also will be in i2b2 + * message, which will wrap patientdata object. Patient data object will + * have all the extracted pft concepts from the report. + * + * + * @param getServices + * @return OMElement in i2b2message format + * @throws PortletServiceNotFoundException + * @throws PortletServiceUnavailableException + * @throws Exception + */ + public OMElement getServices(OMElement getPMDataElement) + throws Exception { + /* + // OMElement returnElement = null; + String pmDataResponse = null; + String unknownErrorMessage = "Error message delivered from the remote server \n" + + "You may wish to retry your last action"; + + if (getPMDataElement == null) { + log.error("Incoming Workplace request is null"); + + ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, + unknownErrorMessage); + pmDataResponse = MessageFactory.convertToXMLString(responseMsgType); + //return MessageFactory.createResponseOMElementFromString(pmDataResponse); + throw new I2B2Exception("Incoming PM request is null"); + } + + ServicesMessage servicesMsg = new ServicesMessage(getPMDataElement.toString()); + + String requestElementString = getPMDataElement.toString(); + // log.info(requestElementString); + //foldersDataMsg.setRequestMessageType(requestElementString); + + long waitTime = 0; + if ((servicesMsg.getRequestMessageType() != null) && (servicesMsg.getRequestMessageType().getRequestHeader() != null)) { + waitTime = servicesMsg.getRequestMessageType() + .getRequestHeader() + .getResultWaittimeMs(); + } + + //do Workplace query processing inside thread, so that + // service could sends back message with timeout error. + + // ExecutorRunnable er = new ExecutorRunnable(); + return edu.harvard.i2b2.common.util.axis2.ServiceClient.getPayLoad(pmDataResponse); + //execute(new GetFoldersByProjectHandler(servicesMsg), waitTime); + + */ + + + + + + + + + + + + + + + MessageContext messageContext = MessageContext.getCurrentMessageContext(); + HttpServletRequest req = (HttpServletRequest) messageContext.getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST); + + OMElement returnElement = null; + + + if (getPMDataElement == null) { + log.error("Incoming PM request is null"); + throw new I2B2Exception("Incoming PM request is null"); + } + + Pattern p = Pattern.compile(".+"); + Matcher m = p.matcher(getPMDataElement.toString()); + String outString = m.replaceAll("*********"); + + p = Pattern.compile(">.+"); + m = p.matcher(outString); + outString = m.replaceAll(">*********"); + logesapi.debug("Received Request PM Element " + outString); + + + log.debug("Begin getting servicesMsg"); + ServicesMessage servicesMsg = new ServicesMessage(getPMDataElement.toString()); + long waitTime = 0; + + if ((servicesMsg.getRequestMessageType() != null) && (servicesMsg.getRequestMessageType().getRequestHeader() != null)) { + waitTime = servicesMsg.getRequestMessageType() + .getRequestHeader() + .getResultWaittimeMs(); + } + + log.debug("Completed getting servicesMsg, waittime is: " + waitTime); + + //do PM processing inside thread, so that + // service could sends back message with timeout error. + + String pmDataResponse = null; + try { + ExecutorRunnable er = new ExecutorRunnable(); + //er.setInputString(requestElementString); + log.debug("begin setRequestHandler, my servicesMsg: " + servicesMsg); + + er.setRequestHandler(new ServicesHandler(servicesMsg, req)); + log.debug("middle setRequestHandler"); + + + log.debug("end setRequestHandler"); + + + Thread t = new Thread(er); + + ResponseMessageType responseMsgType = null; + + synchronized (t) { + t.start(); + + try { + //if (waitTime > 0) { + // t.wait(waitTime); + //} else { + // t.wait(); + //} + + long startTime = System.currentTimeMillis(); + long deltaTime = -1; + while((er.isJobCompleteFlag() == false)&& (deltaTime < waitTime)){ + if (waitTime > 0) { + t.wait(waitTime - deltaTime); + deltaTime = System.currentTimeMillis() - startTime; + } else { + t.wait(); + } + } + pmDataResponse = er.getOutputString(); + + if (pmDataResponse == null) { + if (er.getJobException() != null) { + pmDataResponse = ""; + throw new I2B2Exception("Portal is not property configured."); + } + else if (er.isJobCompleteFlag() == false) { + String timeOuterror = "Result waittime millisecond :" + + waitTime + + " elapsed, try again with increased value"; + log.debug(timeOuterror); + + responseMsgType = MessageFactory.doBuildErrorResponse(null, + timeOuterror); + pmDataResponse = MessageFactory.convertToXMLString(responseMsgType); + } + } + } catch (InterruptedException e) { + log.error("Error in thread: " + e.getMessage()); + + e.printStackTrace(); + throw new I2B2Exception("Thread error while running PM job " + + getPMDataElement, e); + } finally { + t.interrupt(); + er = null; + t = null; + } + } + + } catch (Exception e) { + log.error("Error: " + e.getMessage()); + e.printStackTrace(); + } + try { + returnElement = edu.harvard.i2b2.common.util.axis2.ServiceClient.getPayLoad(pmDataResponse); + + log.debug("my pm repsonse is: " + pmDataResponse); + log.debug("my return is: " + returnElement); + } catch (Exception e) { + log.error("Error creating OMElement from response string " + + pmDataResponse, e); + } + + return returnElement; + + } +} + + + + + + + diff --git a/edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/ws/ServicesMessage.java b/edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/ws/ServicesMessage.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/ws/ServicesMessage.java rename to edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/ws/ServicesMessage.java index aa350b88..11a792c0 --- a/edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/ws/ServicesMessage.java +++ b/edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/ws/ServicesMessage.java @@ -1,97 +1,97 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Mike Mendis - initial API and implementation - */ - -package edu.harvard.i2b2.pm.ws; - -import jakarta.xml.bind.JAXBElement; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.pm.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.pm.datavo.i2b2message.RequestMessageType; - - -/** - * The PatientDataMessage class is a helper class to build PFT messages in the - * i2b2 format - */ -public class ServicesMessage { - private static Log log = LogFactory.getLog(ServicesMessage.class); - // private JAXBUtil jaxbUtil = null; - RequestMessageType reqMessageType = null; - - /** - * The constructor - */ - public ServicesMessage(String requestPdo) throws I2B2Exception { - JAXBUtil jaxbUtil = MessageFactory.getJAXBUtil(); - //new JAXBUtil(JAXBConstant.DEFAULT_PACKAGE_NAME); - - try { - log.debug("Begin unmarshall of XML"); - JAXBElement jaxbElement = jaxbUtil.unMashallFromString(requestPdo); - - if (jaxbElement == null) { - throw new I2B2Exception( - "Null value from unmashall for PDO xml : " + requestPdo); - } - - log.debug("Finished unmarshall of XML"); - this.reqMessageType = (RequestMessageType) jaxbElement.getValue(); - - } catch (JAXBUtilException e) { - e.printStackTrace(); - log.error(e.getMessage(), e); - throw new I2B2Exception("Umashaller error: " + e.getMessage() + - requestPdo, e); - } - } - - /** - * Function to get RequestData object from i2b2 request message type - * @return - * @throws JAXBUtilException - */ - - public BodyType getRequestType() throws JAXBUtilException { - BodyType bodyType = reqMessageType.getMessageBody(); - // JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - // Object requestType = helper.getObjectByClass(bodyType.getAny(), -// GetUserConfigurationType.class); - - return bodyType; - } - - - /* - public GetUserConfigurationType getRequestType() throws JAXBUtilException { - BodyType bodyType = reqMessageType.getMessageBody(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - GetUserConfigurationType requestType = (GetUserConfigurationType) helper.getObjectByClass(bodyType.getAny(), - GetUserConfigurationType.class); - - return requestType; - } - */ - - - public RequestMessageType getRequestMessageType() { - return reqMessageType; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Mike Mendis - initial API and implementation + */ + +package edu.harvard.i2b2.pm.ws; + +import jakarta.xml.bind.JAXBElement; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.pm.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.pm.datavo.i2b2message.RequestMessageType; + + +/** + * The PatientDataMessage class is a helper class to build PFT messages in the + * i2b2 format + */ +public class ServicesMessage { + private static Log log = LogFactory.getLog(ServicesMessage.class); + // private JAXBUtil jaxbUtil = null; + RequestMessageType reqMessageType = null; + + /** + * The constructor + */ + public ServicesMessage(String requestPdo) throws I2B2Exception { + JAXBUtil jaxbUtil = MessageFactory.getJAXBUtil(); + //new JAXBUtil(JAXBConstant.DEFAULT_PACKAGE_NAME); + + try { + log.debug("Begin unmarshall of XML"); + JAXBElement jaxbElement = jaxbUtil.unMashallFromString(requestPdo); + + if (jaxbElement == null) { + throw new I2B2Exception( + "Null value from unmashall for PDO xml : " + requestPdo); + } + + log.debug("Finished unmarshall of XML"); + this.reqMessageType = (RequestMessageType) jaxbElement.getValue(); + + } catch (JAXBUtilException e) { + e.printStackTrace(); + log.error(e.getMessage(), e); + throw new I2B2Exception("Umashaller error: " + e.getMessage() + + requestPdo, e); + } + } + + /** + * Function to get RequestData object from i2b2 request message type + * @return + * @throws JAXBUtilException + */ + + public BodyType getRequestType() throws JAXBUtilException { + BodyType bodyType = reqMessageType.getMessageBody(); + // JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + // Object requestType = helper.getObjectByClass(bodyType.getAny(), +// GetUserConfigurationType.class); + + return bodyType; + } + + + /* + public GetUserConfigurationType getRequestType() throws JAXBUtilException { + BodyType bodyType = reqMessageType.getMessageBody(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + GetUserConfigurationType requestType = (GetUserConfigurationType) helper.getObjectByClass(bodyType.getAny(), + GetUserConfigurationType.class); + + return requestType; + } + */ + + + public RequestMessageType getRequestMessageType() { + return reqMessageType; + } +} diff --git a/edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/ws/VersionMessage.java b/edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/ws/VersionMessage.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/ws/VersionMessage.java rename to edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/ws/VersionMessage.java index 82f78b99..8fafb9e4 --- a/edu.harvard.i2b2.pm/src/edu/harvard/i2b2/pm/ws/VersionMessage.java +++ b/edu.harvard.i2b2.pm/src/main/java/edu/harvard/i2b2/pm/ws/VersionMessage.java @@ -1,81 +1,81 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Mike Mendis - initial API and implementation - */ - -package edu.harvard.i2b2.pm.ws; - -import jakarta.xml.bind.JAXBElement; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.pm.datavo.i2b2versionmessage.RequestMessageType; -import edu.harvard.i2b2.pm.util.JAXBConstant; - - -/** - * The PatientDataMessage class is a helper class to build PFT messages in the - * i2b2 format - */ -public class VersionMessage { - private static Log log = LogFactory.getLog(VersionMessage.class); - private JAXBUtil jaxbUtil = null; - RequestMessageType reqMessageType = null; - - /** - * The constructor - */ - public VersionMessage(String requestPdo) throws I2B2Exception { - jaxbUtil = new JAXBUtil(JAXBConstant.VERSION_PACKAGE_NAME); - - try { - JAXBElement jaxbElement = jaxbUtil.unMashallFromString(requestPdo); - - if (jaxbElement == null) { - throw new I2B2Exception( - "Null value from unmashall for PDO xml : " + requestPdo); - } - - this.reqMessageType = (RequestMessageType) jaxbElement.getValue(); - - } catch (JAXBUtilException e) { - e.printStackTrace(); - log.error(e.getMessage(), e); - throw new I2B2Exception("Umashaller error: " + e.getMessage() + - requestPdo, e); - } - } - - /** - * Function to get RequestData object from i2b2 request message type - * @return - * @throws JAXBUtilException - public GetUserConfigurationType getRequestType() throws JAXBUtilException { - BodyType bodyType = reqMessageType.getMessageBody(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - GetUserConfigurationType requestType = (GetUserConfigurationType) helper.getObjectByClass(bodyType.getAny(), - GetUserConfigurationType.class); - - return requestType; - } - */ - - - public RequestMessageType getRequestMessageType() { - return reqMessageType; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Mike Mendis - initial API and implementation + */ + +package edu.harvard.i2b2.pm.ws; + +import jakarta.xml.bind.JAXBElement; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.pm.datavo.i2b2versionmessage.RequestMessageType; +import edu.harvard.i2b2.pm.util.JAXBConstant; + + +/** + * The PatientDataMessage class is a helper class to build PFT messages in the + * i2b2 format + */ +public class VersionMessage { + private static Log log = LogFactory.getLog(VersionMessage.class); + private JAXBUtil jaxbUtil = null; + RequestMessageType reqMessageType = null; + + /** + * The constructor + */ + public VersionMessage(String requestPdo) throws I2B2Exception { + jaxbUtil = new JAXBUtil(JAXBConstant.VERSION_PACKAGE_NAME); + + try { + JAXBElement jaxbElement = jaxbUtil.unMashallFromString(requestPdo); + + if (jaxbElement == null) { + throw new I2B2Exception( + "Null value from unmashall for PDO xml : " + requestPdo); + } + + this.reqMessageType = (RequestMessageType) jaxbElement.getValue(); + + } catch (JAXBUtilException e) { + e.printStackTrace(); + log.error(e.getMessage(), e); + throw new I2B2Exception("Umashaller error: " + e.getMessage() + + requestPdo, e); + } + } + + /** + * Function to get RequestData object from i2b2 request message type + * @return + * @throws JAXBUtilException + public GetUserConfigurationType getRequestType() throws JAXBUtilException { + BodyType bodyType = reqMessageType.getMessageBody(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + GetUserConfigurationType requestType = (GetUserConfigurationType) helper.getObjectByClass(bodyType.getAny(), + GetUserConfigurationType.class); + + return requestType; + } + */ + + + public RequestMessageType getRequestMessageType() { + return reqMessageType; + } +} diff --git a/edu.harvard.i2b2.server-common/.classpath b/edu.harvard.i2b2.server-common/.classpath index cd194c99..f7e4a1dd 100755 --- a/edu.harvard.i2b2.server-common/.classpath +++ b/edu.harvard.i2b2.server-common/.classpath @@ -1,148 +1,40 @@ - - - + - + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/edu.harvard.i2b2.server-common/.cvsignore b/edu.harvard.i2b2.server-common/.cvsignore deleted file mode 100755 index ded37de3..00000000 --- a/edu.harvard.i2b2.server-common/.cvsignore +++ /dev/null @@ -1,4 +0,0 @@ -dist -genlib -gensrc -classes diff --git a/edu.harvard.i2b2.server-common/.gitignore b/edu.harvard.i2b2.server-common/.gitignore deleted file mode 100644 index 840e7d31..00000000 --- a/edu.harvard.i2b2.server-common/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/classes/ diff --git a/edu.harvard.i2b2.server-common/.project b/edu.harvard.i2b2.server-common/.project index 1e0959a3..58f8e77b 100755 --- a/edu.harvard.i2b2.server-common/.project +++ b/edu.harvard.i2b2.server-common/.project @@ -11,18 +11,13 @@ - org.eclipse.pde.ManifestBuilder - - - - - org.eclipse.pde.SchemaBuilder + org.eclipse.m2e.core.maven2Builder - org.eclipse.pde.PluginNature org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature diff --git a/edu.harvard.i2b2.server-common/.settings/org.eclipse.jdt.core.prefs b/edu.harvard.i2b2.server-common/.settings/org.eclipse.jdt.core.prefs index c59d0c6a..cb635b1c 100644 --- a/edu.harvard.i2b2.server-common/.settings/org.eclipse.jdt.core.prefs +++ b/edu.harvard.i2b2.server-common/.settings/org.eclipse.jdt.core.prefs @@ -1,15 +1,8 @@ eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 -org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve org.eclipse.jdt.core.compiler.compliance=1.8 -org.eclipse.jdt.core.compiler.debug.lineNumber=generate -org.eclipse.jdt.core.compiler.debug.localVariable=generate -org.eclipse.jdt.core.compiler.debug.sourceFile=generate -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=warning +org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning +org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=ignore org.eclipse.jdt.core.compiler.release=disabled org.eclipse.jdt.core.compiler.source=1.8 diff --git a/edu.harvard.i2b2.server-common/.settings/org.jboss.ide.eclipse.as.core.prefs b/edu.harvard.i2b2.server-common/.settings/org.jboss.ide.eclipse.as.core.prefs deleted file mode 100755 index cf3aa3a9..00000000 --- a/edu.harvard.i2b2.server-common/.settings/org.jboss.ide.eclipse.as.core.prefs +++ /dev/null @@ -1,2 +0,0 @@ -eclipse.preferences.version=1 -org.jboss.ide.eclipse.as.core.singledeployable.deployableList= diff --git a/edu.harvard.i2b2.server-common/LICENSE.txt b/edu.harvard.i2b2.server-common/LICENSE.txt deleted file mode 100755 index e5a5569a..00000000 --- a/edu.harvard.i2b2.server-common/LICENSE.txt +++ /dev/null @@ -1,406 +0,0 @@ -#------------------------------------------------------------------------------- -# Copyright (c) 2006-2018 Massachusetts General Hospital -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Mozilla Public License, -# v. 2.0. If a copy of the MPL was not distributed with this file, You can -# obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under -# the terms of the Healthcare Disclaimer. -#------------------------------------------------------------------------------- -Mozilla Public License, version 2.0 - -1. Definitions - -1.1. "Contributor" - - means each individual or legal entity that creates, contributes to the - creation of, or owns Covered Software. - -1.2. "Contributor Version" - - means the combination of the Contributions of others (if any) used by a - Contributor and that particular Contributor's Contribution. - -1.3. "Contribution" - - means Covered Software of a particular Contributor. - -1.4. "Covered Software" - - means Source Code Form to which the initial Contributor has attached the - notice in Exhibit A, the Executable Form of such Source Code Form, and - Modifications of such Source Code Form, in each case including portions - thereof. - -1.5. "Incompatible With Secondary Licenses" - means - - a. that the initial Contributor has attached the notice described in - Exhibit B to the Covered Software; or - - b. that the Covered Software was made available under the terms of - version 1.1 or earlier of the License, but not also under the terms of - a Secondary License. - -1.6. "Executable Form" - - means any form of the work other than Source Code Form. - -1.7. "Larger Work" - - means a work that combines Covered Software with other material, in a - separate file or files, that is not Covered Software. - -1.8. "License" - - means this document. - -1.9. "Licensable" - - means having the right to grant, to the maximum extent possible, whether - at the time of the initial grant or subsequently, any and all of the - rights conveyed by this License. - -1.10. "Modifications" - - means any of the following: - - a. any file in Source Code Form that results from an addition to, - deletion from, or modification of the contents of Covered Software; or - - b. any new file in Source Code Form that contains any Covered Software. - -1.11. "Patent Claims" of a Contributor - - means any patent claim(s), including without limitation, method, - process, and apparatus claims, in any patent Licensable by such - Contributor that would be infringed, but for the grant of the License, - by the making, using, selling, offering for sale, having made, import, - or transfer of either its Contributions or its Contributor Version. - -1.12. "Secondary License" - - means either the GNU General Public License, Version 2.0, the GNU Lesser - General Public License, Version 2.1, the GNU Affero General Public - License, Version 3.0, or any later versions of those licenses. - -1.13. "Source Code Form" - - means the form of the work preferred for making modifications. - -1.14. "You" (or "Your") - - means an individual or a legal entity exercising rights under this - License. For legal entities, "You" includes any entity that controls, is - controlled by, or is under common control with You. For purposes of this - definition, "control" means (a) the power, direct or indirect, to cause - the direction or management of such entity, whether by contract or - otherwise, or (b) ownership of more than fifty percent (50%) of the - outstanding shares or beneficial ownership of such entity. - - -2. License Grants and Conditions - -2.1. Grants - - Each Contributor hereby grants You a world-wide, royalty-free, - non-exclusive license: - - a. under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or - as part of a Larger Work; and - - b. under Patent Claims of such Contributor to make, use, sell, offer for - sale, have made, import, and otherwise transfer either its - Contributions or its Contributor Version. - -2.2. Effective Date - - The licenses granted in Section 2.1 with respect to any Contribution - become effective for each Contribution on the date the Contributor first - distributes such Contribution. - -2.3. Limitations on Grant Scope - - The licenses granted in this Section 2 are the only rights granted under - this License. No additional rights or licenses will be implied from the - distribution or licensing of Covered Software under this License. - Notwithstanding Section 2.1(b) above, no patent license is granted by a - Contributor: - - a. for any code that a Contributor has removed from Covered Software; or - - b. for infringements caused by: (i) Your and any other third party's - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - - c. under Patent Claims infringed by Covered Software in the absence of - its Contributions. - - This License does not grant any rights in the trademarks, service marks, - or logos of any Contributor (except as may be necessary to comply with - the notice requirements in Section 3.4). - -2.4. Subsequent Licenses - - No Contributor makes additional grants as a result of Your choice to - distribute the Covered Software under a subsequent version of this - License (see Section 10.2) or under the terms of a Secondary License (if - permitted under the terms of Section 3.3). - -2.5. Representation - - Each Contributor represents that the Contributor believes its - Contributions are its original creation(s) or it has sufficient rights to - grant the rights to its Contributions conveyed by this License. - -2.6. Fair Use - - This License is not intended to limit any rights You have under - applicable copyright doctrines of fair use, fair dealing, or other - equivalents. - -2.7. Conditions - - Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in - Section 2.1. - - -3. Responsibilities - -3.1. Distribution of Source Form - - All distribution of Covered Software in Source Code Form, including any - Modifications that You create or to which You contribute, must be under - the terms of this License. You must inform recipients that the Source - Code Form of the Covered Software is governed by the terms of this - License, and how they can obtain a copy of this License. You may not - attempt to alter or restrict the recipients' rights in the Source Code - Form. - -3.2. Distribution of Executable Form - - If You distribute Covered Software in Executable Form then: - - a. such Covered Software must also be made available in Source Code Form, - as described in Section 3.1, and You must inform recipients of the - Executable Form how they can obtain a copy of such Source Code Form by - reasonable means in a timely manner, at a charge no more than the cost - of distribution to the recipient; and - - b. You may distribute such Executable Form under the terms of this - License, or sublicense it under different terms, provided that the - license for the Executable Form does not attempt to limit or alter the - recipients' rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - - You may create and distribute a Larger Work under terms of Your choice, - provided that You also comply with the requirements of this License for - the Covered Software. If the Larger Work is a combination of Covered - Software with a work governed by one or more Secondary Licenses, and the - Covered Software is not Incompatible With Secondary Licenses, this - License permits You to additionally distribute such Covered Software - under the terms of such Secondary License(s), so that the recipient of - the Larger Work may, at their option, further distribute the Covered - Software under the terms of either this License or such Secondary - License(s). - -3.4. Notices - - You may not remove or alter the substance of any license notices - (including copyright notices, patent notices, disclaimers of warranty, or - limitations of liability) contained within the Source Code Form of the - Covered Software, except that You may alter any license notices to the - extent required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - - You may choose to offer, and to charge a fee for, warranty, support, - indemnity or liability obligations to one or more recipients of Covered - Software. However, You may do so only on Your own behalf, and not on - behalf of any Contributor. You must make it absolutely clear that any - such warranty, support, indemnity, or liability obligation is offered by - You alone, and You hereby agree to indemnify every Contributor for any - liability incurred by such Contributor as a result of warranty, support, - indemnity or liability terms You offer. You may include additional - disclaimers of warranty and limitations of liability specific to any - jurisdiction. - -4. Inability to Comply Due to Statute or Regulation - - If it is impossible for You to comply with any of the terms of this License - with respect to some or all of the Covered Software due to statute, - judicial order, or regulation then You must: (a) comply with the terms of - this License to the maximum extent possible; and (b) describe the - limitations and the code they affect. Such description must be placed in a - text file included with all distributions of the Covered Software under - this License. Except to the extent prohibited by statute or regulation, - such description must be sufficiently detailed for a recipient of ordinary - skill to be able to understand it. - -5. Termination - -5.1. The rights granted under this License will terminate automatically if You - fail to comply with any of its terms. However, if You become compliant, - then the rights granted under this License from a particular Contributor - are reinstated (a) provisionally, unless and until such Contributor - explicitly and finally terminates Your grants, and (b) on an ongoing - basis, if such Contributor fails to notify You of the non-compliance by - some reasonable means prior to 60 days after You have come back into - compliance. Moreover, Your grants from a particular Contributor are - reinstated on an ongoing basis if such Contributor notifies You of the - non-compliance by some reasonable means, this is the first time You have - received notice of non-compliance with this License from such - Contributor, and You become compliant prior to 30 days after Your receipt - of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent - infringement claim (excluding declaratory judgment actions, - counter-claims, and cross-claims) alleging that a Contributor Version - directly or indirectly infringes any patent, then the rights granted to - You by any and all Contributors for the Covered Software under Section - 2.1 of this License shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user - license agreements (excluding distributors and resellers) which have been - validly granted by You or Your distributors under this License prior to - termination shall survive termination. - -6. Disclaimer of Warranty - - Covered Software is provided under this License on an "as is" basis, - without warranty of any kind, either expressed, implied, or statutory, - including, without limitation, warranties that the Covered Software is free - of defects, merchantable, fit for a particular purpose or non-infringing. - The entire risk as to the quality and performance of the Covered Software - is with You. Should any Covered Software prove defective in any respect, - You (not any Contributor) assume the cost of any necessary servicing, - repair, or correction. This disclaimer of warranty constitutes an essential - part of this License. No use of any Covered Software is authorized under - this License except under this disclaimer. - -7. Limitation of Liability - - Under no circumstances and under no legal theory, whether tort (including - negligence), contract, or otherwise, shall any Contributor, or anyone who - distributes Covered Software as permitted above, be liable to You for any - direct, indirect, special, incidental, or consequential damages of any - character including, without limitation, damages for lost profits, loss of - goodwill, work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses, even if such party shall have been - informed of the possibility of such damages. This limitation of liability - shall not apply to liability for death or personal injury resulting from - such party's negligence to the extent applicable law prohibits such - limitation. Some jurisdictions do not allow the exclusion or limitation of - incidental or consequential damages, so this exclusion and limitation may - not apply to You. - -8. Litigation - - Any litigation relating to this License may be brought only in the courts - of a jurisdiction where the defendant maintains its principal place of - business and such litigation shall be governed by laws of that - jurisdiction, without reference to its conflict-of-law provisions. Nothing - in this Section shall prevent a party's ability to bring cross-claims or - counter-claims. - -9. Miscellaneous - - This License represents the complete agreement concerning the subject - matter hereof. If any provision of this License is held to be - unenforceable, such provision shall be reformed only to the extent - necessary to make it enforceable. Any law or regulation which provides that - the language of a contract shall be construed against the drafter shall not - be used to construe this License against a Contributor. - - -10. Versions of the License - -10.1. New Versions - - Mozilla Foundation is the license steward. Except as provided in Section - 10.3, no one other than the license steward has the right to modify or - publish new versions of this License. Each version will be given a - distinguishing version number. - -10.2. Effect of New Versions - - You may distribute the Covered Software under the terms of the version - of the License under which You originally received the Covered Software, - or under the terms of any subsequent version published by the license - steward. - -10.3. Modified Versions - - If you create software not governed by this License, and you want to - create a new license for such software, you may create and use a - modified version of this License if you rename the license and remove - any references to the name of the license steward (except to note that - such modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary - Licenses If You choose to distribute Source Code Form that is - Incompatible With Secondary Licenses under the terms of this version of - the License, the notice described in Exhibit B of this License must be - attached. - -Exhibit A - Source Code Form License Notice - - This Source Code Form is subject to the - terms of the Mozilla Public License, v. - 2.0. If a copy of the MPL was not - distributed with this file, You can - obtain one at - http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular file, -then You may include the notice in a location (such as a LICENSE file in a -relevant directory) where a recipient would be likely to look for such a -notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - "Incompatible With Secondary Licenses" Notice - - This Source Code Form is "Incompatible - With Secondary Licenses", as defined by - the Mozilla Public License, v. 2.0. - ---------------------- - -Healthcare Disclaimer - -In the United States, or any other jurisdictions where they may apply, the -following additional disclaimer of warranty and limitation of liability are -hereby incorporated into the terms and conditions of MPL 2.0: - -1. No warranties of any kind whatsoever are made as to the results that - You will obtain from relying upon the covered code (or any information - or content obtained by way of the covered code), including but not - limited to compliance with privacy laws or regulations or clinical - care industry standards and protocols. Use of the covered code is not - a substitute for a health care provider’s standard practice or - professional judgment. Any decision with regard to the appropriateness - of treatment, or the validity or reliability of information or content - made available by the covered code, is the sole responsibility of the - health care provider. Consequently, it is incumbent upon each health - care provider to verify all medical history and treatment plans with - each patient. - -2. Under no circumstances and under no legal theory, whether tort - (including negligence), contract, or otherwise, shall any Contributor, - or anyone who distributes Covered Software as permitted by the - license, be liable to You for any indirect, special, incidental, - consequential damages of any character including, without limitation, - damages for loss of goodwill, work stoppage, computer failure or - malfunction, or any and all other damages or losses, of any nature - whatsoever (direct or otherwise) on account of or associated with the - use or inability to use the covered content (including, without - limitation, the use of information or content made available by the - covered code, all documentation associated therewith, and the failure - of the covered code to comply with privacy laws and regulations or - clinical care industry standards and protocols), even if such party - shall have been informed of the possibility of such damages. diff --git a/edu.harvard.i2b2.server-common/build.properties b/edu.harvard.i2b2.server-common/build.properties deleted file mode 100755 index ec89d847..00000000 --- a/edu.harvard.i2b2.server-common/build.properties +++ /dev/null @@ -1,8 +0,0 @@ -#Ant build property file - -## JBOSS HOME -jboss.home=/opt/wildfly-33.0.2.Final -axis2.war.name=i2b2.war -bin.includes = lib/jdom/jdom.jar - - diff --git a/edu.harvard.i2b2.server-common/build.xml b/edu.harvard.i2b2.server-common/build.xml deleted file mode 100755 index f004cd4d..00000000 --- a/edu.harvard.i2b2.server-common/build.xml +++ /dev/null @@ -1,275 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Copying to ${jboss.home} deployment directory - - - - - - - - - Copying to ${jboss.home} directory - - - - - - - - - - - - - - Copying to ${jboss.home} directory - - - - - - - - - - - - - - - - - - - - - - - - - - - - Copying to ${jboss.home} directory - - - - - - - - - - - - Deploy Target - - - - - - - - - - Deploy WAR - - - - - - diff --git a/edu.harvard.i2b2.server-common/common_build.xml b/edu.harvard.i2b2.server-common/common_build.xml deleted file mode 100755 index 6b48e677..00000000 --- a/edu.harvard.i2b2.server-common/common_build.xml +++ /dev/null @@ -1,112 +0,0 @@ - - - - The common-build file is meant for including, not running - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/META-INF/MANIFEST.MF b/edu.harvard.i2b2.server-common/lib/axis2.war/META-INF/MANIFEST.MF deleted file mode 100644 index c370c0df..00000000 --- a/edu.harvard.i2b2.server-common/lib/axis2.war/META-INF/MANIFEST.MF +++ /dev/null @@ -1,4 +0,0 @@ -Manifest-Version: 1.0 -Created-By: Maven WAR Plugin 3.4.0 -Build-Jdk-Spec: 17 - diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/classes/META-INF/DEPENDENCIES b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/classes/META-INF/DEPENDENCIES deleted file mode 100644 index 90dd6a99..00000000 --- a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/classes/META-INF/DEPENDENCIES +++ /dev/null @@ -1,537 +0,0 @@ -// ------------------------------------------------------------------ -// Transitive dependencies of this project determined from the -// maven pom organized by organization. -// ------------------------------------------------------------------ - -Apache Axis2 - Web Application module - - -From: 'an unknown organization' - - - AntLR Parser Generator (http://www.antlr.org/) antlr:antlr:jar:2.7.7 - License: BSD License (http://www.antlr.org/license.html) - - - FindBugs-jsr305 (http://findbugs.sourceforge.net/) com.google.code.findbugs:jsr305:jar:3.0.2 - License: The Apache Software License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0.txt) - - - Gson (https://github.com/google/gson) com.google.code.gson:gson:jar:2.11.0 - License: Apache-2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) - - - Error Prone shaded javac (https://github.com/google/error-prone-javac) com.google.errorprone:javac-shaded:jar:9+181-r4173-1 - License: GNU General Public License, version 2, with the Classpath Exception (http://openjdk.java.net/legal/gplv2+ce.html) - - - Guava InternalFutureFailureAccess and InternalFutures (https://github.com/google/guava/failureaccess) com.google.guava:failureaccess:bundle:1.0.2 - License: The Apache Software License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0.txt) - - - Guava: Google Core Libraries for Java (https://github.com/google/guava) com.google.guava:guava:bundle:33.3.1-jre - License: Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0.txt) - - - Guava ListenableFuture only (https://github.com/google/guava/listenablefuture) com.google.guava:listenablefuture:jar:9999.0-empty-to-avoid-conflict-with-guava - License: The Apache Software License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0.txt) - - - J2ObjC Annotations (https://github.com/google/j2objc/) com.google.j2objc:j2objc-annotations:jar:3.0.0 - License: Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0.txt) - - - moshi (https://github.com/square/moshi/) com.squareup.moshi:moshi:jar:1.15.1 - License: The Apache Software License, Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) - - - moshi-adapters (https://github.com/square/moshi/) com.squareup.moshi:moshi-adapters:jar:1.15.1 - License: The Apache Software License, Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) - - - okio (https://github.com/square/okio/) com.squareup.okio:okio-jvm:jar:3.7.0 - License: The Apache Software License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0.txt) - - - micrometer-commons (https://github.com/micrometer-metrics/micrometer) io.micrometer:micrometer-commons:jar:1.12.2 - License: The Apache Software License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0.txt) - - - micrometer-observation (https://github.com/micrometer-metrics/micrometer) io.micrometer:micrometer-observation:jar:1.12.2 - License: The Apache Software License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0.txt) - - - tomcat-juli (https://tomcat.apache.org/) org.apache.tomcat:tomcat-juli:jar:11.0.0 - License: Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0.txt) - - - tomcat-tribes (https://tomcat.apache.org/) org.apache.tomcat:tomcat-tribes:jar:11.0.0 - License: Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0.txt) - - - Checker Qual (https://checkerframework.org/) org.checkerframework:checker-qual:jar:3.43.0 - License: The MIT License (http://opensource.org/licenses/MIT) - - - Jettison (https://github.com/jettison-json/jettison) org.codehaus.jettison:jettison:bundle:1.5.4 - License: Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0) - - - Hamcrest Core (https://github.com/hamcrest/JavaHamcrest/hamcrest-core) org.hamcrest:hamcrest-core:jar:1.3 - License: New BSD License (http://www.opensource.org/licenses/bsd-license.php) - - - IntelliJ IDEA Annotations (http://www.jetbrains.org) org.jetbrains:annotations:jar:13.0 - License: The Apache Software License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0.txt) - - - Kotlin Stdlib (https://kotlinlang.org/) org.jetbrains.kotlin:kotlin-stdlib:jar:1.9.21 - License: The Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0.txt) - - - Kotlin Stdlib Jdk7 (https://kotlinlang.org/) org.jetbrains.kotlin:kotlin-stdlib-jdk7:jar:1.8.21 - License: The Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0.txt) - - - Kotlin Stdlib Jdk8 (https://kotlinlang.org/) org.jetbrains.kotlin:kotlin-stdlib-jdk8:jar:1.8.21 - License: The Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0.txt) - - - Rhino (http://www.mozilla.org/rhino/) rhino:js:jar:1.6R7 - License: Mozilla Public License version 1.1 (http://www.mozilla.org/MPL/MPL-1.1.html) - - - WSDL4J (http://sf.net/projects/wsdl4j) wsdl4j:wsdl4j:jar:1.6.3 - License: CPL (http://www.opensource.org/licenses/cpl1.0.txt) - - - xpp3 (http://www.extreme.indiana.edu/xgws/xsoap/xpp/mxp1/) xpp3:xpp3:jar:1.1.3.4.O - - -From: 'Apache Software Foundation' (http://www.apache.org) - - - Annotation 1.0 (http://geronimo.apache.org/specs/geronimo-annotation_1.0_spec) org.apache.geronimo.specs:geronimo-annotation_1.0_spec:jar:1.1.1 - License: The Apache Software License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0.txt) - - -From: 'Apache Software Foundation' (http://www.apache.org/) - - - Bean Scripting Framework (http://jakarta.apache.org/bsf) bsf:bsf:jar:2.4.0 - License: The Apache Software License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0.txt) - - - Woden - Core (http://ws.apache.org/woden/woden-core/) org.apache.woden:woden-core:bundle:1.0M10 - License: The Apache Software License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0.txt) - - - XML Commons Resolver Component (http://xml.apache.org/commons/components/resolver/) xml-resolver:xml-resolver:jar:1.2 - License: The Apache Software License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0.txt) - - -From: 'Eclipse Foundation' (https://www.eclipse.org) - - - istack common utility code runtime (https://projects.eclipse.org/projects/ee4j/istack-commons/istack-commons-runtime) com.sun.istack:istack-commons-runtime:jar:4.1.2 - License: Eclipse Distribution License - v 1.0 (http://www.eclipse.org/org/documents/edl-v10.php) - - - istack common utility code tools (https://projects.eclipse.org/projects/ee4j/istack-commons/istack-commons-tools) com.sun.istack:istack-commons-tools:jar:4.1.2 - License: Eclipse Distribution License - v 1.0 (http://www.eclipse.org/org/documents/edl-v10.php) - - - Old JAXB Core (https://eclipse-ee4j.github.io/jaxb-ri/) com.sun.xml.bind:jaxb-core:jar:4.0.5 - License: Eclipse Distribution License - v 1.0 (http://www.eclipse.org/org/documents/edl-v10.php) - - - Old JAXB Runtime (https://eclipse-ee4j.github.io/jaxb-ri/) com.sun.xml.bind:jaxb-impl:jar:4.0.5 - License: Eclipse Distribution License - v 1.0 (http://www.eclipse.org/org/documents/edl-v10.php) - - - Old JAXB JXC (https://eclipse-ee4j.github.io/jaxb-ri/) com.sun.xml.bind:jaxb-jxc:jar:4.0.5 - License: Eclipse Distribution License - v 1.0 (http://www.eclipse.org/org/documents/edl-v10.php) - - - RelaxNG Datatype (https://eclipse-ee4j.github.io/jaxb-ri/) com.sun.xml.bind.external:relaxng-datatype:jar:4.0.3 - License: Eclipse Distribution License - v 1.0 (http://www.eclipse.org/org/documents/edl-v10.php) - - - RNGOM (https://eclipse-ee4j.github.io/jaxb-ri/) com.sun.xml.bind.external:rngom:jar:4.0.3 - License: Eclipse Distribution License - v 1.0 (http://www.eclipse.org/org/documents/edl-v10.php) - - - DTD Parser (https://github.com/eclipse-ee4j/jaxb-dtd-parser) com.sun.xml.dtd-parser:dtd-parser:jar:1.5.0 - License: Eclipse Distribution License - v 1.0 (http://www.eclipse.org/org/documents/edl-v10.php) - - - fastinfoset (https://projects.eclipse.org/projects/ee4j.jaxb-impl/FastInfoset) com.sun.xml.fastinfoset:FastInfoset:jar:2.1.1 - License: Apache License, Version 2.0 (http://www.opensource.org/licenses/apache2.0.php) - License: Eclipse Distribution License - v 1.0 (http://www.eclipse.org/org/documents/edl-v10.php) - - - Jakarta SOAP Implementation (https://projects.eclipse.org/projects/ee4j/metro-saaj/saaj-impl) com.sun.xml.messaging.saaj:saaj-impl:jar:3.0.2 - License: Eclipse Distribution License - v 1.0 (http://www.eclipse.org/org/documents/edl-v10.php) - - - xmlstreambuffer (https://github.com/eclipse-ee4j/metro-xmlstreambuffer) com.sun.xml.stream.buffer:streambuffer:jar:2.1.0 - License: Eclipse Distribution License - v 1.0 (http://www.eclipse.org/org/documents/edl-v10.php) - - - JAX-WS RI Runtime (jaxws-rt) (https://projects.eclipse.org/projects/ee4j/jaxws-ri-bom/jaxws-ri-bom-ext/project/bundles/jaxws-rt) com.sun.xml.ws:jaxws-rt:jar:4.0.3 - License: Eclipse Distribution License - v 1.0 (http://www.eclipse.org/org/documents/edl-v10.php) - - - JAX-WS RI Tools (jaxws-tools) (https://projects.eclipse.org/projects/ee4j/jaxws-ri-bom/jaxws-ri-bom-ext/project/bundles/jaxws-tools) com.sun.xml.ws:jaxws-tools:jar:4.0.3 - License: Eclipse Distribution License - v 1.0 (http://www.eclipse.org/org/documents/edl-v10.php) - - - Jakarta Activation API (https://github.com/jakartaee/jaf-api) jakarta.activation:jakarta.activation-api:jar:2.1.2 - License: EDL 1.0 (http://www.eclipse.org/org/documents/edl-v10.php) - - - Jakarta Annotations API (https://projects.eclipse.org/projects/ee4j.ca) jakarta.annotation:jakarta.annotation-api:jar:3.0.0 - License: EPL 2.0 (https://www.eclipse.org/legal/epl-2.0) - License: GPL2 w/ CPE (https://www.gnu.org/software/classpath/license.html) - - - Jakarta Expression Language API (https://projects.eclipse.org/projects/ee4j.el) jakarta.el:jakarta.el-api:jar:5.0.0 - License: Eclipse Public License v. 2.0 (https://www.eclipse.org/org/documents/epl-2.0/EPL-2.0.txt) - License: GNU General Public License, version 2 with the GNU Classpath Exception (https://www.gnu.org/software/classpath/license.html) - - - Jakarta Messaging API (https://projects.eclipse.org/projects/ee4j.jms) jakarta.jms:jakarta.jms-api:jar:3.1.0 - License: Eclipse Public License 2.0 (https://projects.eclipse.org/license/epl-2.0) - License: GNU General Public License, version 2 with the GNU Classpath Exception (https://projects.eclipse.org/license/secondary-gpl-2.0-cp) - - - Jakarta Mail API (https://projects.eclipse.org/projects/ee4j/jakarta.mail-api) jakarta.mail:jakarta.mail-api:jar:2.1.3 - License: EPL 2.0 (http://www.eclipse.org/legal/epl-2.0) - License: GPL2 w/ CPE (https://www.gnu.org/software/classpath/license.html) - License: EDL 1.0 (http://www.eclipse.org/org/documents/edl-v10.php) - - - Jakarta Standard Tag Library API (https://projects.eclipse.org/projects/ee4j.jstl) jakarta.servlet.jsp.jstl:jakarta.servlet.jsp.jstl-api:jar:3.0.2 - License: EPL 2.0 (http://www.eclipse.org/legal/epl-2.0) - License: GPL2 w/ CPE (https://www.gnu.org/software/classpath/license.html) - - - Jakarta XML Binding API (https://github.com/eclipse-ee4j/jaxb-api/jakarta.xml.bind-api) jakarta.xml.bind:jakarta.xml.bind-api:jar:4.0.1 - License: Eclipse Distribution License - v 1.0 (http://www.eclipse.org/org/documents/edl-v10.php) - - - Jakarta SOAP with Attachments API (https://github.com/eclipse-ee4j/saaj-api) jakarta.xml.soap:jakarta.xml.soap-api:jar:3.0.0 - License: Eclipse Distribution License - v 1.0 (http://www.eclipse.org/org/documents/edl-v10.php) - - - Jakarta XML Web Services API (https://github.com/eclipse-ee4j/jax-ws-api) jakarta.xml.ws:jakarta.xml.ws-api:jar:4.0.0 - License: Eclipse Distribution License - v 1.0 (http://www.eclipse.org/org/documents/edl-v10.php) - - - Angus Activation Registries (https://github.com/eclipse-ee4j/angus-activation/angus-activation) org.eclipse.angus:angus-activation:jar:2.0.2 - License: EDL 1.0 (http://www.eclipse.org/org/documents/edl-v10.php) - - - Angus Mail Provider (http://eclipse-ee4j.github.io/angus-mail/angus-mail) org.eclipse.angus:angus-mail:jar:2.0.3 - License: EPL 2.0 (http://www.eclipse.org/legal/epl-2.0) - License: GPL2 w/ CPE (https://www.gnu.org/software/classpath/license.html) - License: EDL 1.0 (http://www.eclipse.org/org/documents/edl-v10.php) - - - management-api (https://github.com/eclipse-ee4j/orb-gmbal-commons) org.glassfish.external:management-api:jar:3.2.3 - License: EDL 1.0 (http://www.eclipse.org/org/documents/edl-v10.php) - - - GMBAL (API only) (https://projects.eclipse.org/projects/ee4j.orb/gmbal-api-only) org.glassfish.gmbal:gmbal-api-only:jar:4.0.3 - License: EDL 1.0 (http://www.eclipse.org/org/documents/edl-v10.php) - - - GlassFish High Availability APIs and SPI (https://projects.eclipse.org/projects/ee4j/ha-api) org.glassfish.ha:ha-api:jar:3.1.13 - License: EPL 2.0 (http://www.eclipse.org/legal/epl-2.0) - License: GPL2 w/ CPE (https://www.gnu.org/software/classpath/license.html) - - - Codemodel Core (https://eclipse-ee4j.github.io/jaxb-ri/) org.glassfish.jaxb:codemodel:jar:4.0.3 - License: Eclipse Distribution License - v 1.0 (http://www.eclipse.org/org/documents/edl-v10.php) - - - JAXB Core (https://eclipse-ee4j.github.io/jaxb-ri/) org.glassfish.jaxb:jaxb-core:jar:4.0.3 - License: Eclipse Distribution License - v 1.0 (http://www.eclipse.org/org/documents/edl-v10.php) - - - JAXB Runtime (https://eclipse-ee4j.github.io/jaxb-ri/) org.glassfish.jaxb:jaxb-runtime:jar:4.0.3 - License: Eclipse Distribution License - v 1.0 (http://www.eclipse.org/org/documents/edl-v10.php) - - - JAXB XJC (https://eclipse-ee4j.github.io/jaxb-ri/) org.glassfish.jaxb:jaxb-xjc:jar:4.0.3 - License: Eclipse Distribution License - v 1.0 (http://www.eclipse.org/org/documents/edl-v10.php) - - - TXW2 Runtime (https://eclipse-ee4j.github.io/jaxb-ri/) org.glassfish.jaxb:txw2:jar:4.0.3 - License: Eclipse Distribution License - v 1.0 (http://www.eclipse.org/org/documents/edl-v10.php) - - - XSOM (https://eclipse-ee4j.github.io/jaxb-ri/) org.glassfish.jaxb:xsom:jar:4.0.3 - License: Eclipse Distribution License - v 1.0 (http://www.eclipse.org/org/documents/edl-v10.php) - - - Jakarta Standard Tag Library Implementation (https://projects.eclipse.org/projects/ee4j.jstl) org.glassfish.web:jakarta.servlet.jsp.jstl:jar:3.0.1 - License: EPL 2.0 (http://www.eclipse.org/legal/epl-2.0) - License: GPL2 w/ CPE (https://www.gnu.org/software/classpath/license.html) - - - MIME streaming extension (https://github.com/eclipse-ee4j/metro-mimepull) org.jvnet.mimepull:mimepull:jar:1.10.0 - License: Eclipse Distribution License - v 1.0 (http://www.eclipse.org/org/documents/edl-v10.php) - - - Extended StAX API (https://projects.eclipse.org/projects/ee4j/stax-ex) org.jvnet.staxex:stax-ex:jar:2.1.0 - License: Eclipse Distribution License - v 1.0 (http://www.eclipse.org/org/documents/edl-v10.php) - - -From: 'Eclipse Foundation' (https://www.eclipse.org/org/foundation/) - - - Jakarta RESTful WS API (https://github.com/jakartaee/rest/jakarta.ws.rs-api) jakarta.ws.rs:jakarta.ws.rs-api:bundle:4.0.0 - License: EPL-2.0 (https://www.eclipse.org/legal/epl-2.0) - License: GPL-2.0-with-classpath-exception (https://www.gnu.org/software/classpath/license.html) - - -From: 'FasterXML' (http://fasterxml.com) - - - Woodstox (https://github.com/FasterXML/woodstox) com.fasterxml.woodstox:woodstox-core:bundle:7.0.0 - License: The Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0.txt) - - -From: 'fasterxml.com' (http://fasterxml.com) - - - Stax2 API (http://github.com/FasterXML/stax2-api) org.codehaus.woodstox:stax2-api:bundle:4.2.2 - License: The BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) - - -From: 'GlassFish Community' (https://glassfish.java.net) - - - javax.transaction API (http://jta-spec.java.net) javax.transaction:javax.transaction-api:jar:1.3 - License: CDDL + GPLv2 with classpath exception (https://github.com/javaee/javax.transaction/blob/master/LICENSE) - - -From: 'Google Inc.' (http://www.google.com/) - - - Google Java Format (https://github.com/google/google-java-format/google-java-format) com.google.googlejavaformat:google-java-format:jar:1.7 - License: The Apache Software License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0.txt) - - -From: 'Google LLC' (http://www.google.com) - - - error-prone annotations (https://errorprone.info/error_prone_annotations) com.google.errorprone:error_prone_annotations:jar:2.27.0 - License: Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0.txt) - - -From: 'jibx.org' (http://www.jibx.org) - - - jibx-run - JiBX runtime (http://www.jibx.org/core-reactor/main-reactor/jibx-run) org.jibx:jibx-run:bundle:1.4.2 - License: BSD (http://jibx.sourceforge.net/jibx-license.html) - - -From: 'Joda.org' (https://www.joda.org) - - - Joda-Time (https://www.joda.org/joda-time/) joda-time:joda-time:jar:2.10.14 - License: Apache License, Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) - - -From: 'JUnit' (http://www.junit.org) - - - JUnit (http://junit.org) junit:junit:jar:4.13.2 - License: Eclipse Public License 1.0 (http://www.eclipse.org/legal/epl-v10.html) - - -From: 'Mort Bay Consulting' (http://www.mortbay.com) - - - Jetty :: Jakarta Servlet API and Schemas for JPMS and OSGi (https://eclipse.org/jetty/jetty-jakarta-servlet-api) org.eclipse.jetty.toolchain:jetty-jakarta-servlet-api:jar:5.0.2 - License: Apache Software License - Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0) - License: Eclipse Public License - Version 1.0 (http://www.eclipse.org/org/documents/epl-v10.php) - - -From: 'OWASP (Open Web-Application Security Project)' (https://www.owasp.org/) - - - Java Encoder (https://www.owasp.org/index.php/OWASP_Java_Encoder_Project/encoder) org.owasp.encoder:encoder:jar:1.3.1 - License: The BSD 3-Clause License (http://www.opensource.org/licenses/BSD-3-Clause) - - -From: 'QOS.ch' (http://www.qos.ch) - - - SLF4J API Module (http://www.slf4j.org) org.slf4j:slf4j-api:jar:2.0.16 - License: MIT License (http://www.opensource.org/licenses/mit-license.php) - - -From: 'Spring IO' (https://spring.io/projects/spring-framework) - - - Spring AOP (https://github.com/spring-projects/spring-framework) org.springframework:spring-aop:jar:6.1.3 - License: Apache License, Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0) - - - Spring Beans (https://github.com/spring-projects/spring-framework) org.springframework:spring-beans:jar:6.1.3 - License: Apache License, Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0) - - - Spring Context (https://github.com/spring-projects/spring-framework) org.springframework:spring-context:jar:6.1.3 - License: Apache License, Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0) - - - Spring Core (https://github.com/spring-projects/spring-framework) org.springframework:spring-core:jar:6.1.3 - License: Apache License, Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0) - - - Spring Expression Language (SpEL) (https://github.com/spring-projects/spring-framework) org.springframework:spring-expression:jar:6.1.3 - License: Apache License, Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0) - - - Spring Commons Logging Bridge (https://github.com/spring-projects/spring-framework) org.springframework:spring-jcl:jar:6.1.3 - License: Apache License, Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0) - - - Spring Web (https://github.com/spring-projects/spring-framework) org.springframework:spring-web:jar:6.1.3 - License: Apache License, Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0) - - -From: 'The Apache Software Foundation' (http://www.apache.org) - - - Apache Geronimo JAX-WS Spec 2.2 (http://geronimo.apache.org/maven/specs/geronimo-jaxws_2.2_spec/1.2) org.apache.geronimo.specs:geronimo-jaxws_2.2_spec:bundle:1.2 - License: The Apache Software License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0.txt) - - - Web Services Metadata 2.0 (http://geronimo.apache.org/maven/specs/geronimo-ws-metadata_2.0_spec/1.1.3) org.apache.geronimo.specs:geronimo-ws-metadata_2.0_spec:bundle:1.1.3 - License: The Apache Software License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0.txt) - - -From: 'The Apache Software Foundation' (https://www.apache.org/) - - - Apache Commons IO (https://commons.apache.org/proper/commons-io/) commons-io:commons-io:jar:2.17.0 - License: Apache-2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) - - - Apache Commons Logging (https://commons.apache.org/proper/commons-logging/) commons-logging:commons-logging:jar:1.3.4 - License: Apache-2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) - - - Apache Axis2 - Addressing (http://axis.apache.org/axis2/java/core/) org.apache.axis2:addressing:mar:2.0.0-SNAPSHOT - License: Apache-2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) - - - Apache Axis2 - Data Binding (http://axis.apache.org/axis2/java/core/) org.apache.axis2:axis2-adb:jar:2.0.0-SNAPSHOT - License: Apache-2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) - - - Apache Axis2 - Clustering (http://axis.apache.org/axis2/java/core/) org.apache.axis2:axis2-clustering:jar:2.0.0-SNAPSHOT - License: Apache-2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) - - - Apache Axis2 - Code Generation (http://axis.apache.org/axis2/java/core/) org.apache.axis2:axis2-codegen:jar:2.0.0-SNAPSHOT - License: Apache-2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) - - - Apache Axis2 - CORBA (http://axis.apache.org/axis2/java/core/) org.apache.axis2:axis2-corba:jar:2.0.0-SNAPSHOT - License: Apache-2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) - - - Apache Axis2 - Fast Infoset (http://axis.apache.org/axis2/java/core/) org.apache.axis2:axis2-fastinfoset:jar:2.0.0-SNAPSHOT - License: Apache-2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) - - - Apache Axis2 - JAXWS (http://axis.apache.org/axis2/java/core/) org.apache.axis2:axis2-jaxws:jar:2.0.0-SNAPSHOT - License: Apache-2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) - - - Apache Axis2 - JAXWS (mar) (http://axis.apache.org/axis2/java/core/) org.apache.axis2:axis2-jaxws-mar:mar:2.0.0-SNAPSHOT - License: Apache-2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) - - - Apache Axis2 - JiBX Data Binding (http://axis.apache.org/axis2/java/core/) org.apache.axis2:axis2-jibx:jar:2.0.0-SNAPSHOT - License: Apache-2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) - - - Apache Axis2 - JSON (http://axis.apache.org/axis2/java/core/) org.apache.axis2:axis2-json:jar:2.0.0-SNAPSHOT - License: Apache-2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) - - - Apache Axis2 - Kernel (http://axis.apache.org/axis2/java/core/) org.apache.axis2:axis2-kernel:jar:2.0.0-SNAPSHOT - License: Apache-2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) - - - Apache Axis2 - Metadata (http://axis.apache.org/axis2/java/core/) org.apache.axis2:axis2-metadata:jar:2.0.0-SNAPSHOT - License: Apache-2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) - - - Apache Axis2 - MTOM Policy (http://axis.apache.org/axis2/java/core/) org.apache.axis2:axis2-mtompolicy:jar:2.0.0-SNAPSHOT - License: Apache-2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) - - - Apache Axis2 - SAAJ (http://axis.apache.org/axis2/java/core/) org.apache.axis2:axis2-saaj:jar:2.0.0-SNAPSHOT - License: Apache-2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) - - - Apache Axis2 - SOAP Monitor Servlet (http://axis.apache.org/axis2/java/core/) org.apache.axis2:axis2-soapmonitor-servlet:jar:2.0.0-SNAPSHOT - License: Apache-2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) - - - Apache Axis2 - spring (http://axis.apache.org/axis2/java/core/) org.apache.axis2:axis2-spring:jar:2.0.0-SNAPSHOT - License: Apache-2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) - - - Apache Axis2 - Transport - Base (http://axis.apache.org/axis2/java/core/) org.apache.axis2:axis2-transport-base:bundle:2.0.0-SNAPSHOT - License: Apache-2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) - - - Apache Axis2 - Transport - HTTP (http://axis.apache.org/axis2/java/core/) org.apache.axis2:axis2-transport-http:jar:2.0.0-SNAPSHOT - License: Apache-2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) - - - Apache Axis2 - Transport - JMS (http://axis.apache.org/axis2/java/core/) org.apache.axis2:axis2-transport-jms:bundle:2.0.0-SNAPSHOT - License: Apache-2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) - - - Apache Axis2 - Transport - Local (http://axis.apache.org/axis2/java/core/) org.apache.axis2:axis2-transport-local:bundle:2.0.0-SNAPSHOT - License: Apache-2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) - - - Apache Axis2 - Transport - Mail (http://axis.apache.org/axis2/java/core/) org.apache.axis2:axis2-transport-mail:bundle:2.0.0-SNAPSHOT - License: Apache-2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) - - - Apache Axis2 - Transport - TCP (http://axis.apache.org/axis2/java/core/) org.apache.axis2:axis2-transport-tcp:bundle:2.0.0-SNAPSHOT - License: Apache-2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) - - - Apache Axis2 - Transport - UDP (http://axis.apache.org/axis2/java/core/) org.apache.axis2:axis2-transport-udp:bundle:2.0.0-SNAPSHOT - License: Apache-2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) - - - Apache Axis2 - Transport - XMPP (http://axis.apache.org/axis2/java/core/) org.apache.axis2:axis2-transport-xmpp:bundle:2.0.0-SNAPSHOT - License: Apache-2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) - - - Apache Axis2 - XMLBeans Data Binding (http://axis.apache.org/axis2/java/core/) org.apache.axis2:axis2-xmlbeans:jar:2.0.0-SNAPSHOT - License: Apache-2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) - - - Apache Axis2 - MEX (http://axis.apache.org/axis2/java/core/) org.apache.axis2:mex:mar:2.0.0-SNAPSHOT - License: Apache-2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) - - - Apache Axis2 - MEX (http://axis.apache.org/axis2/java/core/) org.apache.axis2:mex:mar:2.0.0-SNAPSHOT - License: Apache-2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) - - - Apache Axis2 - MTOM Policy module (http://axis.apache.org/axis2/java/core/) org.apache.axis2:mtompolicy:mar:2.0.0-SNAPSHOT - License: Apache-2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) - - - Apache Axis2 - Ping (http://axis.apache.org/axis2/java/core/) org.apache.axis2:ping:mar:2.0.0-SNAPSHOT - License: Apache-2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) - - - Apache Axis2 - Scripting (http://axis.apache.org/axis2/java/core/) org.apache.axis2:scripting:mar:2.0.0-SNAPSHOT - License: Apache-2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) - - - Apache Axis2 - SOAP Monitor Module (http://axis.apache.org/axis2/java/core/) org.apache.axis2:soapmonitor:mar:2.0.0-SNAPSHOT - License: Apache-2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) - - - Apache Axis2 - Version Service (http://axis.apache.org/axis2/java/core/) org.apache.axis2:version:aar:2.0.0-SNAPSHOT - License: Apache-2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) - - - Apache Commons FileUpload Core (https://commons.apache.org/proper/commons-fileupload/commons-fileupload2-core/) org.apache.commons:commons-fileupload2-core:jar:2.0.0-M2 - License: Apache-2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) - - - Apache Commons FileUpload Jakarta Servlet 6 (https://commons.apache.org/proper/commons-fileupload/commons-fileupload2-jakarta-servlet6/) org.apache.commons:commons-fileupload2-jakarta-servlet6:jar:2.0.0-M2 - License: Apache-2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) - - - Apache Commons Lang (https://commons.apache.org/proper/commons-lang/) org.apache.commons:commons-lang3:jar:3.17.0 - License: Apache-2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) - - - Apache HttpClient (https://hc.apache.org/httpcomponents-client-5.4.x/5.4/httpclient5/) org.apache.httpcomponents.client5:httpclient5:jar:5.4 - License: Apache License, Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) - - - Apache HttpComponents Core HTTP/1.1 (https://hc.apache.org/httpcomponents-core-5.3.x/5.3/httpcore5/) org.apache.httpcomponents.core5:httpcore5:jar:5.3 - License: Apache License, Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) - - - Apache HttpComponents Core HTTP/2 (https://hc.apache.org/httpcomponents-core-5.3.x/5.3/httpcore5-h2/) org.apache.httpcomponents.core5:httpcore5-h2:jar:5.3 - License: Apache License, Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) - - - Apache James :: Mime4j :: Core (http://james.apache.org/mime4j/apache-mime4j-core) org.apache.james:apache-mime4j-core:bundle:0.8.11 - License: Apache License, Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) - - - Apache Log4j API (https://logging.apache.org/log4j/2.x/log4j-api/) org.apache.logging.log4j:log4j-api:jar:2.20.0 - License: Apache License, Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) - - - Apache Log4j Core (https://logging.apache.org/log4j/2.x/log4j-core/) org.apache.logging.log4j:log4j-core:jar:2.20.0 - License: Apache License, Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) - - - Apache Log4j Commons Logging Bridge (https://logging.apache.org/log4j/2.x/log4j-jcl/) org.apache.logging.log4j:log4j-jcl:jar:2.20.0 - License: Apache License, Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) - - - Apache Neethi (https://ws.apache.org/neethi/) org.apache.neethi:neethi:bundle:3.2.0 - License: Apache License, Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) - - - Axiom API (http://ws.apache.org/axiom/) org.apache.ws.commons.axiom:axiom-api:bundle:2.0.0-SNAPSHOT - License: Apache-2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) - - - DOOM (http://ws.apache.org/axiom/implementations/axiom-dom/) org.apache.ws.commons.axiom:axiom-dom:bundle:2.0.0-SNAPSHOT - License: Apache-2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) - - - LLOM (http://ws.apache.org/axiom/implementations/axiom-impl/) org.apache.ws.commons.axiom:axiom-impl:bundle:2.0.0-SNAPSHOT - License: Apache-2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) - - - axiom-jakarta-activation (http://ws.apache.org/axiom/) org.apache.ws.commons.axiom:axiom-jakarta-activation:bundle:2.0.0-SNAPSHOT - License: Apache-2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) - - - Axiom JAXB Integration (http://ws.apache.org/axiom/) org.apache.ws.commons.axiom:axiom-jakarta-jaxb:bundle:2.0.0-SNAPSHOT - License: Apache-2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) - - - axiom-legacy-attachments (http://ws.apache.org/axiom/) org.apache.ws.commons.axiom:axiom-legacy-attachments:bundle:2.0.0-SNAPSHOT - License: Apache-2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) - - - XmlSchema Core (https://ws.apache.org/commons/xmlschema20/xmlschema-core/) org.apache.ws.xmlschema:xmlschema-core:bundle:2.3.1 - License: Apache License, Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) - - -From: 'The Jaxen Project' (https://www.cafeconleche.org/jaxen) - - - jaxen (http://www.cafeconleche.org/jaxen/jaxen) jaxen:jaxen:bundle:2.0.0 - License: BSD License 2.0 (https://raw.githubusercontent.com/jaxen-xpath/jaxen/master/LICENSE.txt) - - -From: 'Webtide' (https://webtide.com) - - - Core :: HTTP (https://eclipse.dev/jetty/jetty-core/jetty-http) org.eclipse.jetty:jetty-http:jar:12.0.7 - License: Eclipse Public License - Version 2.0 (https://www.eclipse.org/legal/epl-2.0/) - License: Apache Software License - Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0) - - - Core :: IO (https://eclipse.dev/jetty/jetty-core/jetty-io) org.eclipse.jetty:jetty-io:jar:12.0.7 - License: Eclipse Public License - Version 2.0 (https://www.eclipse.org/legal/epl-2.0/) - License: Apache Software License - Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0) - - - Core :: Security (https://eclipse.dev/jetty/jetty-core/jetty-security) org.eclipse.jetty:jetty-security:jar:12.0.7 - License: Eclipse Public License - Version 2.0 (https://www.eclipse.org/legal/epl-2.0/) - License: Apache Software License - Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0) - - - Core :: Server (https://eclipse.dev/jetty/jetty-core/jetty-server) org.eclipse.jetty:jetty-server:jar:12.0.7 - License: Eclipse Public License - Version 2.0 (https://www.eclipse.org/legal/epl-2.0/) - License: Apache Software License - Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0) - - - Core :: Sessions (https://eclipse.dev/jetty/jetty-core/jetty-session) org.eclipse.jetty:jetty-session:jar:12.0.7 - License: Eclipse Public License - Version 2.0 (https://www.eclipse.org/legal/epl-2.0/) - License: Apache Software License - Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0) - - - Core :: Utilities (https://eclipse.dev/jetty/jetty-core/jetty-util) org.eclipse.jetty:jetty-util:jar:12.0.7 - License: Eclipse Public License - Version 2.0 (https://www.eclipse.org/legal/epl-2.0/) - License: Apache Software License - Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0) - - - EE9 :: Nested (https://eclipse.dev/jetty/jetty-ee9/jetty-ee9-nested) org.eclipse.jetty.ee9:jetty-ee9-nested:jar:12.0.7 - License: Eclipse Public License - Version 2.0 (https://www.eclipse.org/legal/epl-2.0/) - License: Apache Software License - Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0) - - -From: 'XmlBeans' (https://xmlbeans.apache.org/) - - - XmlBeans (https://xmlbeans.apache.org/) org.apache.xmlbeans:xmlbeans:jar:3.0.1 - License: The Apache Software License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0.txt) - - - - - diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/classes/META-INF/LICENSE b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/classes/META-INF/LICENSE deleted file mode 100644 index 6b0b1270..00000000 --- a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/classes/META-INF/LICENSE +++ /dev/null @@ -1,203 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/classes/META-INF/NOTICE b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/classes/META-INF/NOTICE deleted file mode 100644 index bd396930..00000000 --- a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/classes/META-INF/NOTICE +++ /dev/null @@ -1,26 +0,0 @@ -========================================================================= -== NOTICE file corresponding to the section 4 d of == -== the Apache License, Version 2.0, == -== in this case for the Apache Axis2 distribution. == -========================================================================= - -This product includes software developed by -The Apache Software Foundation (http://www.apache.org/). -Portions Copyright 2006 International Business Machines Corp. -Portions Copyright 2005-2007 WSO2, Inc. - -This product also includes schemas and specification developed by: -- the W3C consortium (http://www.w3c.org) - -This product also includes WS-* schemas developed by International -Business Machines Corporation, Microsoft Corporation, BEA Systems, -TIBCO Software, SAP AG, Sonic Software, and VeriSign - -This product also includes a WSDL developed by salesforce.com -- Copyright 1999-2006 salesforce.com, inc. - -Portions of the included xmlbeans library were originally based on the following: -- software copyright (c) 2000-2003, BEA Systems, . - -Please read the different LICENSE files present in the lib directory of -this distribution. diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/classes/commons-logging.properties b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/classes/commons-logging.properties deleted file mode 100644 index 1e570d65..00000000 --- a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/classes/commons-logging.properties +++ /dev/null @@ -1,30 +0,0 @@ -# -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# - -# This is the logging properties that goes to the war, there are two logging conf kept at the -# svn, one for developement (one at src/test-resources) and other for producation - -# Uncomment the next line to disable all logging. -#org.apache.commons.logging.Log=org.apache.commons.logging.impl.NoOpLog - -# Uncomment the next line to enable the simple log based logging -#org.apache.commons.logging.Log=org.apache.commons.logging.impl.SimpleLog - -# Uncomment the next line to enable log4j based logging -org.apache.commons.logging.Log=org.apache.commons.logging.impl.Log4JLogger diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/classes/log4j2.xml b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/classes/log4j2.xml deleted file mode 100644 index 137b3b1c..00000000 --- a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/classes/log4j2.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - - - - diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/classes/org/apache/axis2/transport/http/AxisAdminServlet.class b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/classes/org/apache/axis2/transport/http/AxisAdminServlet.class deleted file mode 100644 index 9e6c06d8..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/classes/org/apache/axis2/transport/http/AxisAdminServlet.class and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/classes/org/apache/axis2/webapp/Action.class b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/classes/org/apache/axis2/webapp/Action.class deleted file mode 100644 index d23bd2f8..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/classes/org/apache/axis2/webapp/Action.class and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/classes/org/apache/axis2/webapp/ActionHandler.class b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/classes/org/apache/axis2/webapp/ActionHandler.class deleted file mode 100644 index b24b5b04..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/classes/org/apache/axis2/webapp/ActionHandler.class and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/classes/org/apache/axis2/webapp/ActionResult.class b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/classes/org/apache/axis2/webapp/ActionResult.class deleted file mode 100644 index 1892b6d5..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/classes/org/apache/axis2/webapp/ActionResult.class and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/classes/org/apache/axis2/webapp/AdminActions.class b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/classes/org/apache/axis2/webapp/AdminActions.class deleted file mode 100644 index 365e5954..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/classes/org/apache/axis2/webapp/AdminActions.class and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/classes/org/apache/axis2/webapp/AxisAdminServlet.class b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/classes/org/apache/axis2/webapp/AxisAdminServlet.class deleted file mode 100644 index 293678bc..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/classes/org/apache/axis2/webapp/AxisAdminServlet.class and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/classes/org/apache/axis2/webapp/CSRFPreventionResponseWrapper.class b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/classes/org/apache/axis2/webapp/CSRFPreventionResponseWrapper.class deleted file mode 100644 index 8a0275ec..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/classes/org/apache/axis2/webapp/CSRFPreventionResponseWrapper.class and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/classes/org/apache/axis2/webapp/CSRFTokenCache.class b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/classes/org/apache/axis2/webapp/CSRFTokenCache.class deleted file mode 100644 index afdfc46f..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/classes/org/apache/axis2/webapp/CSRFTokenCache.class and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/classes/org/apache/axis2/webapp/Redirect.class b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/classes/org/apache/axis2/webapp/Redirect.class deleted file mode 100644 index c1a22168..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/classes/org/apache/axis2/webapp/Redirect.class and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/classes/org/apache/axis2/webapp/Status.class b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/classes/org/apache/axis2/webapp/Status.class deleted file mode 100644 index 9e1e4465..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/classes/org/apache/axis2/webapp/Status.class and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/classes/org/apache/axis2/webapp/StatusCache$1.class b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/classes/org/apache/axis2/webapp/StatusCache$1.class deleted file mode 100644 index 981f5b7a..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/classes/org/apache/axis2/webapp/StatusCache$1.class and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/classes/org/apache/axis2/webapp/StatusCache.class b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/classes/org/apache/axis2/webapp/StatusCache.class deleted file mode 100644 index bf277f29..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/classes/org/apache/axis2/webapp/StatusCache.class and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/classes/org/apache/axis2/webapp/View.class b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/classes/org/apache/axis2/webapp/View.class deleted file mode 100644 index bfd81655..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/classes/org/apache/axis2/webapp/View.class and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/angus-activation-2.0.2.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/angus-activation-2.0.2.jar deleted file mode 100644 index 93c7aad5..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/angus-activation-2.0.2.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/angus-mail-2.0.3.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/angus-mail-2.0.3.jar deleted file mode 100644 index 39552573..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/angus-mail-2.0.3.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/annotations-13.0.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/annotations-13.0.jar deleted file mode 100644 index fb794be9..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/annotations-13.0.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/antlr-2.7.7.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/antlr-2.7.7.jar deleted file mode 100644 index 5e5f14b3..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/antlr-2.7.7.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/apache-mime4j-core-0.8.11.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/apache-mime4j-core-0.8.11.jar deleted file mode 100644 index 0129f2f2..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/apache-mime4j-core-0.8.11.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axiom-api-2.0.0-SNAPSHOT.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axiom-api-2.0.0-SNAPSHOT.jar deleted file mode 100644 index 3ce701b1..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axiom-api-2.0.0-SNAPSHOT.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axiom-dom-2.0.0-SNAPSHOT.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axiom-dom-2.0.0-SNAPSHOT.jar deleted file mode 100644 index d03ebb2b..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axiom-dom-2.0.0-SNAPSHOT.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axiom-impl-2.0.0-SNAPSHOT.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axiom-impl-2.0.0-SNAPSHOT.jar deleted file mode 100644 index 721ef0e0..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axiom-impl-2.0.0-SNAPSHOT.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axiom-jakarta-activation-2.0.0-SNAPSHOT.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axiom-jakarta-activation-2.0.0-SNAPSHOT.jar deleted file mode 100644 index fb957392..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axiom-jakarta-activation-2.0.0-SNAPSHOT.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axiom-jakarta-jaxb-2.0.0-SNAPSHOT.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axiom-jakarta-jaxb-2.0.0-SNAPSHOT.jar deleted file mode 100644 index 5b3547f6..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axiom-jakarta-jaxb-2.0.0-SNAPSHOT.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axiom-legacy-attachments-2.0.0-SNAPSHOT.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axiom-legacy-attachments-2.0.0-SNAPSHOT.jar deleted file mode 100644 index 69d5168a..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axiom-legacy-attachments-2.0.0-SNAPSHOT.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-adb-2.0.0-SNAPSHOT.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-adb-2.0.0-SNAPSHOT.jar deleted file mode 100644 index 92def423..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-adb-2.0.0-SNAPSHOT.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-clustering-2.0.0-SNAPSHOT.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-clustering-2.0.0-SNAPSHOT.jar deleted file mode 100644 index 588fbfc7..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-clustering-2.0.0-SNAPSHOT.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-codegen-2.0.0-SNAPSHOT.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-codegen-2.0.0-SNAPSHOT.jar deleted file mode 100644 index 1ae6eb38..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-codegen-2.0.0-SNAPSHOT.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-corba-2.0.0-SNAPSHOT.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-corba-2.0.0-SNAPSHOT.jar deleted file mode 100644 index ea99bd0d..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-corba-2.0.0-SNAPSHOT.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-fastinfoset-2.0.0-SNAPSHOT.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-fastinfoset-2.0.0-SNAPSHOT.jar deleted file mode 100644 index f965907e..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-fastinfoset-2.0.0-SNAPSHOT.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-jaxws-2.0.0-SNAPSHOT.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-jaxws-2.0.0-SNAPSHOT.jar deleted file mode 100644 index 6fcbe096..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-jaxws-2.0.0-SNAPSHOT.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-jibx-2.0.0-SNAPSHOT.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-jibx-2.0.0-SNAPSHOT.jar deleted file mode 100644 index a0bc63ca..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-jibx-2.0.0-SNAPSHOT.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-json-2.0.0-SNAPSHOT.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-json-2.0.0-SNAPSHOT.jar deleted file mode 100644 index c08ec7dc..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-json-2.0.0-SNAPSHOT.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-kernel-2.0.0-SNAPSHOT.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-kernel-2.0.0-SNAPSHOT.jar deleted file mode 100644 index 6f48a990..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-kernel-2.0.0-SNAPSHOT.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-metadata-2.0.0-SNAPSHOT.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-metadata-2.0.0-SNAPSHOT.jar deleted file mode 100644 index 42ede7a6..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-metadata-2.0.0-SNAPSHOT.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-mtompolicy-2.0.0-SNAPSHOT.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-mtompolicy-2.0.0-SNAPSHOT.jar deleted file mode 100644 index eb9d0ef9..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-mtompolicy-2.0.0-SNAPSHOT.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-saaj-2.0.0-SNAPSHOT.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-saaj-2.0.0-SNAPSHOT.jar deleted file mode 100644 index 476ee0c0..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-saaj-2.0.0-SNAPSHOT.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-soapmonitor-servlet-2.0.0-SNAPSHOT.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-soapmonitor-servlet-2.0.0-SNAPSHOT.jar deleted file mode 100644 index e8a4da4f..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-soapmonitor-servlet-2.0.0-SNAPSHOT.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-spring-2.0.0-SNAPSHOT.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-spring-2.0.0-SNAPSHOT.jar deleted file mode 100644 index 6b17c0f7..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-spring-2.0.0-SNAPSHOT.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-transport-base-2.0.0-SNAPSHOT.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-transport-base-2.0.0-SNAPSHOT.jar deleted file mode 100644 index af0bf17e..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-transport-base-2.0.0-SNAPSHOT.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-transport-http-2.0.0-SNAPSHOT.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-transport-http-2.0.0-SNAPSHOT.jar deleted file mode 100644 index a88c1bb1..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-transport-http-2.0.0-SNAPSHOT.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-transport-jms-2.0.0-SNAPSHOT.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-transport-jms-2.0.0-SNAPSHOT.jar deleted file mode 100644 index 7b280ae6..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-transport-jms-2.0.0-SNAPSHOT.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-transport-local-2.0.0-SNAPSHOT.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-transport-local-2.0.0-SNAPSHOT.jar deleted file mode 100644 index e09f56bb..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-transport-local-2.0.0-SNAPSHOT.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-transport-mail-2.0.0-SNAPSHOT.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-transport-mail-2.0.0-SNAPSHOT.jar deleted file mode 100644 index 610dca7c..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-transport-mail-2.0.0-SNAPSHOT.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-transport-tcp-2.0.0-SNAPSHOT.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-transport-tcp-2.0.0-SNAPSHOT.jar deleted file mode 100644 index a828d5b1..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-transport-tcp-2.0.0-SNAPSHOT.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-transport-udp-2.0.0-SNAPSHOT.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-transport-udp-2.0.0-SNAPSHOT.jar deleted file mode 100644 index ba5f35b3..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-transport-udp-2.0.0-SNAPSHOT.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-transport-xmpp-2.0.0-SNAPSHOT.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-transport-xmpp-2.0.0-SNAPSHOT.jar deleted file mode 100644 index f4c8fd87..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-transport-xmpp-2.0.0-SNAPSHOT.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-xmlbeans-2.0.0-SNAPSHOT.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-xmlbeans-2.0.0-SNAPSHOT.jar deleted file mode 100644 index 11dab3b3..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/axis2-xmlbeans-2.0.0-SNAPSHOT.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/checker-qual-3.43.0.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/checker-qual-3.43.0.jar deleted file mode 100644 index cbb34f88..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/checker-qual-3.43.0.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/codemodel-4.0.3.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/codemodel-4.0.3.jar deleted file mode 100644 index bac755ff..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/codemodel-4.0.3.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/commons-fileupload2-core-2.0.0-M2.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/commons-fileupload2-core-2.0.0-M2.jar deleted file mode 100644 index 8db3d10b..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/commons-fileupload2-core-2.0.0-M2.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/commons-fileupload2-jakarta-servlet6-2.0.0-M2.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/commons-fileupload2-jakarta-servlet6-2.0.0-M2.jar deleted file mode 100644 index 0025881d..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/commons-fileupload2-jakarta-servlet6-2.0.0-M2.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/commons-io-2.17.0.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/commons-io-2.17.0.jar deleted file mode 100644 index ad00ddc4..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/commons-io-2.17.0.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/commons-lang3-3.17.0.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/commons-lang3-3.17.0.jar deleted file mode 100644 index f6486b4d..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/commons-lang3-3.17.0.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/commons-logging-1.3.4.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/commons-logging-1.3.4.jar deleted file mode 100644 index b6339bb0..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/commons-logging-1.3.4.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/dtd-parser-1.5.0.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/dtd-parser-1.5.0.jar deleted file mode 100644 index e2b57a13..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/dtd-parser-1.5.0.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/encoder-1.3.1.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/encoder-1.3.1.jar deleted file mode 100644 index 8aca2922..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/encoder-1.3.1.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/error_prone_annotations-2.27.0.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/error_prone_annotations-2.27.0.jar deleted file mode 100644 index 4ea471fc..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/error_prone_annotations-2.27.0.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/failureaccess-1.0.2.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/failureaccess-1.0.2.jar deleted file mode 100644 index d73ab80b..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/failureaccess-1.0.2.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/geronimo-annotation_1.0_spec-1.1.1.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/geronimo-annotation_1.0_spec-1.1.1.jar deleted file mode 100644 index 2cdc01be..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/geronimo-annotation_1.0_spec-1.1.1.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/geronimo-jaxws_2.2_spec-1.2.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/geronimo-jaxws_2.2_spec-1.2.jar deleted file mode 100644 index 8b7cb94c..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/geronimo-jaxws_2.2_spec-1.2.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/geronimo-ws-metadata_2.0_spec-1.1.3.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/geronimo-ws-metadata_2.0_spec-1.1.3.jar deleted file mode 100644 index 66dc1e22..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/geronimo-ws-metadata_2.0_spec-1.1.3.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/gmbal-api-only-4.0.3.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/gmbal-api-only-4.0.3.jar deleted file mode 100644 index b0ce7bef..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/gmbal-api-only-4.0.3.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/google-java-format-1.7.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/google-java-format-1.7.jar deleted file mode 100644 index 953541cf..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/google-java-format-1.7.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/gson-2.11.0.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/gson-2.11.0.jar deleted file mode 100644 index 18e59c8c..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/gson-2.11.0.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/guava-33.3.1-jre.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/guava-33.3.1-jre.jar deleted file mode 100644 index 9a88e167..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/guava-33.3.1-jre.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/ha-api-3.1.13.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/ha-api-3.1.13.jar deleted file mode 100644 index f9d46739..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/ha-api-3.1.13.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/hamcrest-core-1.3.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/hamcrest-core-1.3.jar deleted file mode 100644 index 9d5fe16e..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/hamcrest-core-1.3.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/httpclient5-5.4.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/httpclient5-5.4.jar deleted file mode 100644 index f6831999..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/httpclient5-5.4.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/httpcore5-5.3.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/httpcore5-5.3.jar deleted file mode 100644 index abd2a4ed..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/httpcore5-5.3.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/httpcore5-h2-5.3.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/httpcore5-h2-5.3.jar deleted file mode 100644 index 2201b809..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/httpcore5-h2-5.3.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/istack-commons-runtime-4.1.2.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/istack-commons-runtime-4.1.2.jar deleted file mode 100644 index d1a642b1..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/istack-commons-runtime-4.1.2.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/istack-commons-tools-4.1.2.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/istack-commons-tools-4.1.2.jar deleted file mode 100644 index 6967a103..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/istack-commons-tools-4.1.2.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/j2objc-annotations-3.0.0.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/j2objc-annotations-3.0.0.jar deleted file mode 100644 index c293336f..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/j2objc-annotations-3.0.0.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jakarta.activation-api-2.1.2.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jakarta.activation-api-2.1.2.jar deleted file mode 100644 index ea57b3ed..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jakarta.activation-api-2.1.2.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jakarta.annotation-api-3.0.0.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jakarta.annotation-api-3.0.0.jar deleted file mode 100644 index 34c1d439..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jakarta.annotation-api-3.0.0.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jakarta.el-api-5.0.0.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jakarta.el-api-5.0.0.jar deleted file mode 100644 index 5a2fd40d..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jakarta.el-api-5.0.0.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jakarta.jms-api-3.1.0.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jakarta.jms-api-3.1.0.jar deleted file mode 100644 index b89e12e2..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jakarta.jms-api-3.1.0.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jakarta.mail-api-2.1.3.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jakarta.mail-api-2.1.3.jar deleted file mode 100644 index 6b367795..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jakarta.mail-api-2.1.3.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jakarta.servlet.jsp.jstl-3.0.1.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jakarta.servlet.jsp.jstl-3.0.1.jar deleted file mode 100644 index 6b2f43f2..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jakarta.servlet.jsp.jstl-3.0.1.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jakarta.servlet.jsp.jstl-api-3.0.2.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jakarta.servlet.jsp.jstl-api-3.0.2.jar deleted file mode 100644 index f2d2c825..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jakarta.servlet.jsp.jstl-api-3.0.2.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jakarta.ws.rs-api-4.0.0.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jakarta.ws.rs-api-4.0.0.jar deleted file mode 100644 index 22f5fb9f..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jakarta.ws.rs-api-4.0.0.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jakarta.xml.bind-api-4.0.1.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jakarta.xml.bind-api-4.0.1.jar deleted file mode 100644 index c79fdfda..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jakarta.xml.bind-api-4.0.1.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jakarta.xml.soap-api-3.0.0.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jakarta.xml.soap-api-3.0.0.jar deleted file mode 100644 index a54dad71..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jakarta.xml.soap-api-3.0.0.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jakarta.xml.ws-api-4.0.0.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jakarta.xml.ws-api-4.0.0.jar deleted file mode 100644 index 899ad0bd..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jakarta.xml.ws-api-4.0.0.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/javac-shaded-9+181-r4173-1.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/javac-shaded-9+181-r4173-1.jar deleted file mode 100644 index 3de68343..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/javac-shaded-9+181-r4173-1.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/javax.transaction-api-1.3.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/javax.transaction-api-1.3.jar deleted file mode 100644 index a253bfa9..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/javax.transaction-api-1.3.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jaxb-core-4.0.3.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jaxb-core-4.0.3.jar deleted file mode 100644 index 4aa79a33..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jaxb-core-4.0.3.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jaxb-core-4.0.5.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jaxb-core-4.0.5.jar deleted file mode 100644 index 92ac626a..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jaxb-core-4.0.5.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jaxb-impl-4.0.5.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jaxb-impl-4.0.5.jar deleted file mode 100644 index 781a4513..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jaxb-impl-4.0.5.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jaxb-jxc-4.0.5.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jaxb-jxc-4.0.5.jar deleted file mode 100644 index 746f2121..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jaxb-jxc-4.0.5.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jaxb-runtime-4.0.3.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jaxb-runtime-4.0.3.jar deleted file mode 100644 index 245dc72d..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jaxb-runtime-4.0.3.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jaxb-xjc-4.0.3.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jaxb-xjc-4.0.3.jar deleted file mode 100644 index 6038567d..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jaxb-xjc-4.0.3.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jaxen-2.0.0.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jaxen-2.0.0.jar deleted file mode 100644 index 17030697..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jaxen-2.0.0.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jaxws-rt-4.0.3.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jaxws-rt-4.0.3.jar deleted file mode 100644 index ec1fcb3e..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jaxws-rt-4.0.3.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jaxws-tools-4.0.3.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jaxws-tools-4.0.3.jar deleted file mode 100644 index 13813e46..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jaxws-tools-4.0.3.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jettison-1.5.4.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jettison-1.5.4.jar deleted file mode 100644 index 17c57352..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jettison-1.5.4.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jetty-ee9-nested-12.0.7.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jetty-ee9-nested-12.0.7.jar deleted file mode 100644 index efb98b6e..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jetty-ee9-nested-12.0.7.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jetty-http-12.0.7.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jetty-http-12.0.7.jar deleted file mode 100644 index 595cf0a4..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jetty-http-12.0.7.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jetty-io-12.0.7.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jetty-io-12.0.7.jar deleted file mode 100644 index d4e1f1b8..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jetty-io-12.0.7.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jetty-jakarta-servlet-api-5.0.2.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jetty-jakarta-servlet-api-5.0.2.jar deleted file mode 100644 index 34782779..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jetty-jakarta-servlet-api-5.0.2.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jetty-security-12.0.7.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jetty-security-12.0.7.jar deleted file mode 100644 index 5e5c04dd..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jetty-security-12.0.7.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jetty-server-12.0.7.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jetty-server-12.0.7.jar deleted file mode 100644 index fb62074e..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jetty-server-12.0.7.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jetty-session-12.0.7.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jetty-session-12.0.7.jar deleted file mode 100644 index fcfccdae..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jetty-session-12.0.7.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jetty-util-12.0.7.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jetty-util-12.0.7.jar deleted file mode 100644 index 72fed198..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jetty-util-12.0.7.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jibx-run-1.4.2.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jibx-run-1.4.2.jar deleted file mode 100644 index 186862e8..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jibx-run-1.4.2.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/joda-time-2.10.14.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/joda-time-2.10.14.jar deleted file mode 100644 index cb09f6a4..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/joda-time-2.10.14.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jsr305-3.0.2.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jsr305-3.0.2.jar deleted file mode 100644 index 59222d9c..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/jsr305-3.0.2.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/junit-4.13.2.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/junit-4.13.2.jar deleted file mode 100644 index 6da55d8b..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/junit-4.13.2.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/kotlin-stdlib-1.9.21.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/kotlin-stdlib-1.9.21.jar deleted file mode 100644 index 533091c6..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/kotlin-stdlib-1.9.21.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/kotlin-stdlib-jdk7-1.8.21.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/kotlin-stdlib-jdk7-1.8.21.jar deleted file mode 100644 index b86ecd51..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/kotlin-stdlib-jdk7-1.8.21.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/kotlin-stdlib-jdk8-1.8.21.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/kotlin-stdlib-jdk8-1.8.21.jar deleted file mode 100644 index 72acadb8..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/kotlin-stdlib-jdk8-1.8.21.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/listenablefuture-9999.0-empty-to-avoid-conflict-with-guava.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/listenablefuture-9999.0-empty-to-avoid-conflict-with-guava.jar deleted file mode 100644 index 45832c05..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/listenablefuture-9999.0-empty-to-avoid-conflict-with-guava.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/log4j-api-2.20.0.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/log4j-api-2.20.0.jar deleted file mode 100644 index 29d1b52a..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/log4j-api-2.20.0.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/log4j-core-2.20.0.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/log4j-core-2.20.0.jar deleted file mode 100644 index 54dafcd0..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/log4j-core-2.20.0.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/log4j-jcl-2.20.0.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/log4j-jcl-2.20.0.jar deleted file mode 100644 index 07da6ab4..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/log4j-jcl-2.20.0.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/management-api-3.2.3.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/management-api-3.2.3.jar deleted file mode 100644 index 22a39b0b..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/management-api-3.2.3.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/mex-2.0.0-SNAPSHOT-impl.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/mex-2.0.0-SNAPSHOT-impl.jar deleted file mode 100644 index 33771b21..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/mex-2.0.0-SNAPSHOT-impl.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/micrometer-commons-1.12.2.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/micrometer-commons-1.12.2.jar deleted file mode 100644 index 6ded9e3e..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/micrometer-commons-1.12.2.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/micrometer-observation-1.12.2.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/micrometer-observation-1.12.2.jar deleted file mode 100644 index 6099f896..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/micrometer-observation-1.12.2.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/mimepull-1.10.0.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/mimepull-1.10.0.jar deleted file mode 100644 index 986a8026..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/mimepull-1.10.0.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/moshi-1.15.1.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/moshi-1.15.1.jar deleted file mode 100644 index 6dc97e65..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/moshi-1.15.1.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/moshi-adapters-1.15.1.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/moshi-adapters-1.15.1.jar deleted file mode 100644 index 6bbe0d26..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/moshi-adapters-1.15.1.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/neethi-3.2.0.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/neethi-3.2.0.jar deleted file mode 100644 index 840bf4f0..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/neethi-3.2.0.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/okio-jvm-3.7.0.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/okio-jvm-3.7.0.jar deleted file mode 100644 index 8da081a9..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/okio-jvm-3.7.0.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/relaxng-datatype-4.0.3.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/relaxng-datatype-4.0.3.jar deleted file mode 100644 index 8c63a5ef..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/relaxng-datatype-4.0.3.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/rngom-4.0.3.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/rngom-4.0.3.jar deleted file mode 100644 index 13b9d0aa..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/rngom-4.0.3.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/saaj-impl-3.0.2.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/saaj-impl-3.0.2.jar deleted file mode 100644 index fb6dcac6..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/saaj-impl-3.0.2.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/slf4j-api-2.0.16.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/slf4j-api-2.0.16.jar deleted file mode 100644 index cbb5448d..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/slf4j-api-2.0.16.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/spring-aop-6.1.3.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/spring-aop-6.1.3.jar deleted file mode 100644 index 88d140be..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/spring-aop-6.1.3.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/spring-expression-6.1.3.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/spring-expression-6.1.3.jar deleted file mode 100644 index 69e563b0..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/spring-expression-6.1.3.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/spring-jcl-6.1.3.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/spring-jcl-6.1.3.jar deleted file mode 100644 index 374c8dae..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/spring-jcl-6.1.3.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/stax-ex-2.1.0.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/stax-ex-2.1.0.jar deleted file mode 100644 index 293ac1e6..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/stax-ex-2.1.0.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/stax2-api-4.2.2.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/stax2-api-4.2.2.jar deleted file mode 100644 index cc5844fb..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/stax2-api-4.2.2.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/streambuffer-2.1.0.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/streambuffer-2.1.0.jar deleted file mode 100644 index 1d94d939..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/streambuffer-2.1.0.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/tomcat-juli-11.0.0.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/tomcat-juli-11.0.0.jar deleted file mode 100644 index 8d124b45..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/tomcat-juli-11.0.0.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/tomcat-tribes-11.0.0.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/tomcat-tribes-11.0.0.jar deleted file mode 100644 index f791bee7..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/tomcat-tribes-11.0.0.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/txw2-4.0.3.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/txw2-4.0.3.jar deleted file mode 100644 index 5a340a69..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/txw2-4.0.3.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/woden-core-1.0M10.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/woden-core-1.0M10.jar deleted file mode 100644 index 9777ad98..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/woden-core-1.0M10.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/woodstox-core-7.0.0.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/woodstox-core-7.0.0.jar deleted file mode 100644 index fe43392c..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/woodstox-core-7.0.0.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/wsdl4j-1.6.3.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/wsdl4j-1.6.3.jar deleted file mode 100644 index b9c10b97..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/wsdl4j-1.6.3.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/xml-resolver-1.2.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/xml-resolver-1.2.jar deleted file mode 100644 index e535bdc0..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/xml-resolver-1.2.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/xmlbeans-3.0.1.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/xmlbeans-3.0.1.jar deleted file mode 100644 index 1e61b5f9..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/xmlbeans-3.0.1.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/xmlschema-core-2.3.1.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/xmlschema-core-2.3.1.jar deleted file mode 100644 index 29701609..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/xmlschema-core-2.3.1.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/xpp3-1.1.3.4.O.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/xpp3-1.1.3.4.O.jar deleted file mode 100644 index 002ef69f..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/xpp3-1.1.3.4.O.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/xsom-4.0.3.jar b/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/xsom-4.0.3.jar deleted file mode 100644 index 42708430..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/lib/xsom-4.0.3.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/axis2-web/Error/AuthError.html b/edu.harvard.i2b2.server-common/lib/axis2.war/axis2-web/Error/AuthError.html deleted file mode 100644 index b61fef77..00000000 --- a/edu.harvard.i2b2.server-common/lib/axis2.war/axis2-web/Error/AuthError.html +++ /dev/null @@ -1,44 +0,0 @@ - - - - Error In Admin Application - - - - - - -
    Apache Software Founation LogoAXIS Logo
    - - - - - - -
    Failure in Authentication! Please check your username and password
    back
    - -
    - - - - -
    All rights reserved by Apache Software Foundation
    - - \ No newline at end of file diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/axis2-web/Error/GenError.html b/edu.harvard.i2b2.server-common/lib/axis2.war/axis2-web/Error/GenError.html deleted file mode 100644 index de5355d7..00000000 --- a/edu.harvard.i2b2.server-common/lib/axis2.war/axis2-web/Error/GenError.html +++ /dev/null @@ -1,44 +0,0 @@ - - - - Error In Admin Application - - - - - - -
    Apache Software Foundation LogoAXIS Logo
    - - - - - - -
    Server Encountered an Error!
    home
    - -
    - - - - -
    All rights reserved by Apache Software Foundation
    - - diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/axis2-web/Error/error404.jsp b/edu.harvard.i2b2.server-common/lib/axis2.war/axis2-web/Error/error404.jsp deleted file mode 100644 index c64576bc..00000000 --- a/edu.harvard.i2b2.server-common/lib/axis2.war/axis2-web/Error/error404.jsp +++ /dev/null @@ -1,63 +0,0 @@ -<%-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --%> - -<%@ page contentType="text/html;charset=iso-8859-1" language="java" %> - - - - - Axis2 :: Resource not found! - - - - - - - - - - -
    Apache Software Foundation LogoAXIS Logo
    - - - - - -
    -

    Requested resource not found!

    -
    -
    -
    -
    -
    home
    - - - - -
    - - - - - -

    Copyright © 1999-2021, The Apache Software Foundation
    Licensed under the Apache License, Version 2.0.
    -
     
    - - diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/axis2-web/Error/error500.jsp b/edu.harvard.i2b2.server-common/lib/axis2.war/axis2-web/Error/error500.jsp deleted file mode 100644 index 886f55dc..00000000 --- a/edu.harvard.i2b2.server-common/lib/axis2.war/axis2-web/Error/error500.jsp +++ /dev/null @@ -1,64 +0,0 @@ -<%-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --%> - -<%@ page contentType="text/html;charset=iso-8859-1" language="java" %> - - - - - Axis2 :: Internal server error - - - - - - - - - - -
    Apache Software Foundation LogoAXIS Logo
    - - - - - -
    -

    Internal server error

    -
    -
    -
    -
    -
    home
    -
    - - - - -
    - - - - - -

    Copyright © 1999-2021, The Apache Software Foundation
    Licensed under the Apache License, Version 2.0.
    -
     
    - - diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/axis2-web/HappyAxis.jsp b/edu.harvard.i2b2.server-common/lib/axis2.war/axis2-web/HappyAxis.jsp deleted file mode 100644 index 786bd9a4..00000000 --- a/edu.harvard.i2b2.server-common/lib/axis2.war/axis2-web/HappyAxis.jsp +++ /dev/null @@ -1,509 +0,0 @@ -<%-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --%> - - -<%@ page import="org.apache.axis2.AxisFault, - org.apache.axis2.Constants, - org.apache.axis2.addressing.EndpointReference, - org.apache.axis2.client.Options, - org.apache.axis2.client.ServiceClient, - org.apache.axis2.context.ConfigurationContext, - org.apache.axis2.context.ConfigurationContextFactory, - javax.xml.parsers.SAXParser, - javax.xml.parsers.SAXParserFactory, - java.io.IOException, - java.io.InputStream, - java.io.StringWriter, - org.apache.axiom.om.OMElement, - org.apache.axiom.om.OMFactory, - org.apache.axiom.om.OMNamespace, - org.apache.axiom.om.OMAbstractFactory, - javax.xml.stream.XMLOutputFactory, - javax.xml.stream.XMLStreamException" - session="false" %> - - - Axis2 Happiness Page - - - - - - -<%IP = request.getRequestURL().toString();%> -<%! - /* - * Happiness tests for axis2. These look at the classpath and warn if things - * are missing. Normally addng this much code in a JSP page is mad - * but here we want to validate JSP compilation too, and have a drop-in - * page for easy re-use - */ - String IP; - - /** - * Get a string providing install information. - * TODO: make this platform aware and give specific hints - */ - public String getInstallHints(HttpServletRequest request) { - - return "Note: On Tomcat 4.x and Java1.4, you may need to put libraries that contain " - + "java.* or javax.* packages into CATALINA_HOME/common/lib" - + "
    jaxrpc.jar and saaj.jar are two such libraries."; - } - - /** - * test for a class existing - * @param classname - * @return class iff present - */ - Class classExists(String classname) { - try { - return Class.forName(classname); - } catch (ClassNotFoundException e) { - return null; - } - } - - /** - * test for resource on the classpath - * @param resource - * @return true iff present - */ - boolean resourceExists(String resource) { - boolean found; - InputStream instream = this.getClass().getResourceAsStream(resource); - found = instream != null; - if (instream != null) { - try { - instream.close(); - } catch (IOException e) { - } - } - return found; - } - - /** - * probe for a class, print an error message is missing - * @param out stream to print stuff - * @param category text like "warning" or "error" - * @param classname class to look for - * @param jarFile where this class comes from - * @param errorText extra error text - * @param homePage where to d/l the library - * @return the number of missing classes - * @throws IOException - */ - int probeClass(JspWriter out, - String category, - String classname, - String jarFile, - String axisOperation, - String errorText, - String homePage) throws IOException { - try { - Class clazz = classExists(classname); - if (clazz == null) { - String url = ""; - if (homePage != null) { - url = "
    See " + homePage + ""; - } - out.write("

    " + category + ": could not find class " + classname - + " from file " + jarFile - + "
    " + errorText - + url - + "

    "); - return 1; - } else { - String location = getLocation(out, clazz); - if (location == null) { - out.write("Found " + axisOperation + " (" + classname + ")
    "); - } else { - out.write("Found " + axisOperation + " (" + classname + ")
      at " + location + "
    "); - } - return 0; - } - } catch (NoClassDefFoundError ncdfe) { - String url = ""; - if (homePage != null) { - url = "
    See " + homePage + ""; - } - out.write("

    " + category + ": could not find a dependency" - + " of class " + classname - + " from file " + jarFile - + "
    " + errorText - + url - + "
    The root cause was: " + ncdfe.getMessage() - + "
    This can happen e.g. if " + classname + " is in" - + " the 'common' classpath, but a dependency like " - + " activation.jar is only in the webapp classpath." - + "

    "); - return 1; - } - } - - /** - * get the location of a class - * @param out - * @param clazz - * @return the jar file or path where a class was found - */ - - String getLocation(JspWriter out, - Class clazz) { - try { - java.net.URL url = clazz.getProtectionDomain().getCodeSource().getLocation(); - String location = url.toString(); - if (location.startsWith("jar")) { - url = ((java.net.JarURLConnection) url.openConnection()).getJarFileURL(); - location = url.toString(); - } - - if (location.startsWith("file")) { - java.io.File file = new java.io.File(url.getFile()); - return file.getAbsolutePath(); - } else { - return url.toString(); - } - } catch (Throwable t) { - } - return "an unknown location"; - } - - /** - * a class we need if a class is missing - * @param out stream to print stuff - * @param classname class to look for - * @param jarFile where this class comes from - * @param errorText extra error text - * @param homePage where to d/l the library - * @throws IOException when needed - * @return the number of missing libraries (0 or 1) - */ - int needClass(JspWriter out, - String classname, - String jarFile, - String axisOperation, - String errorText, - String homePage) throws IOException { - return probeClass(out, - "Error", - classname, - jarFile, - axisOperation, - errorText, - homePage); - } - - /** - * print warning message if a class is missing - * @param out stream to print stuff - * @param classname class to look for - * @param jarFile where this class comes from - * @param errorText extra error text - * @param homePage where to d/l the library - * @throws IOException when needed - * @return the number of missing libraries (0 or 1) - */ - int wantClass(JspWriter out, - String classname, - String jarFile, - String axisOperation, - String errorText, - String homePage) throws IOException { - return probeClass(out, - "Warning", - classname, - jarFile, - axisOperation, - errorText, - homePage); - } - - /** - * probe for a resource existing, - * @param out - * @param resource - * @param errorText - * @throws Exception - */ - int wantResource(JspWriter out, - String resource, - String errorText) throws Exception { - if (!resourceExists(resource)) { - out.write("

    Warning: could not find resource " + resource - + "
    " - + errorText); - return 0; - } else { - out.write("found " + resource + "
    "); - return 1; - } - } - - - /** - * get servlet version string - * - */ - - public String getServletVersion() { - ServletContext context = getServletConfig().getServletContext(); - int major = context.getMajorVersion(); - int minor = context.getMinorVersion(); - return Integer.toString(major) + '.' + Integer.toString(minor); - } - - - /** - * what parser are we using. - * @return the classname of the parser - */ - private String getParserName() { - SAXParser saxParser = getSAXParser(); - if (saxParser == null) { - return "Could not create an XML Parser"; - } - - // check to what is in the classname - return saxParser.getClass().getName(); - } - - /** - * Create a JAXP SAXParser - * @return parser or null for trouble - */ - private SAXParser getSAXParser() { - SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); - if (saxParserFactory == null) { - return null; - } - SAXParser saxParser = null; - try { - saxParser = saxParserFactory.newSAXParser(); - } catch (Exception e) { - } - return saxParser; - } - - /** - * get the location of the parser - * @return path or null for trouble in tracking it down - */ - - private String getParserLocation(JspWriter out) { - SAXParser saxParser = getSAXParser(); - if (saxParser == null) { - return null; - } - return getLocation(out, saxParser.getClass()); - } - - private String value; - - private OMElement createEnvelope() { - OMFactory fac = OMAbstractFactory.getOMFactory(); - OMNamespace omNs = fac.createOMNamespace("http://axisversion.sample", "ns1"); - OMElement method = fac.createOMElement("getVersion", omNs); - OMElement value = fac.createOMElement("myValue", omNs); - method.addChild(value); - return method; - } - - public boolean invokeTheService() { - try { - // since this one is an internal request we do not use public frontendHostUrl - // for it - int lastindex = IP.lastIndexOf('/'); - IP = IP.substring(0, lastindex); - ///axis2/axis2-web/services/version - IP = IP.replaceAll("axis2-web", ""); - - OMElement payload = createEnvelope(); - ConfigurationContext configctx = - ConfigurationContextFactory.createConfigurationContextFromFileSystem(null, null); - ServiceClient client = new ServiceClient(configctx, null); - EndpointReference targetEPR = new EndpointReference(IP + configctx.getServicePath() + "/Version"); - Options options = new Options(); - client.setOptions(options); - options.setTo(targetEPR); - options.setTransportInProtocol(Constants.TRANSPORT_HTTP); - - OMElement result = client.sendReceive(payload); - StringWriter writer = new StringWriter(); - result.serialize(XMLOutputFactory.newInstance().createXMLStreamWriter(writer)); - writer.flush(); - value = writer.toString(); - value = value.replaceAll("<", "<"); - value = value.replaceAll(">", ">"); - return true; - } catch (AxisFault axisFault) { - System.out.println(value); - return false; - } catch (XMLStreamException e) { - value = e.getMessage(); - return false; - } - } - - public String getFormatedSystemProperty(String systemProperty){ - if (systemProperty == null) - return ""; - return systemProperty.replaceAll(":", ": "); - } -%> - -

    Axis2 Happiness Page

    - -

    Examining webapp configuration

    - - - -

    Essential Components

    - -<% - int needed = 0,wanted = 0; - - /** - * the essentials, without these Axis is not going to work - */ - needed = needClass(out, "org.apache.axis2.transport.http.AxisServlet", - "fatal error", - "Apache-Axis", - "Axis2 will not work", - "https://axis.apache.org/axis2"); - needed += needClass(out, "org.apache.commons.logging.Log", - "commons-logging.jar", - "Jakarta-Commons Logging", - "Axis2 will not work", - "http://jakarta.apache.org/commons/logging.html"); - needed += needClass(out, "javax.xml.stream.XMLStreamReader", - "stax-api-1.0.1.jar", - "Streaming API for XML", - "Axis2 will not work", - "http://dist.codehaus.org/stax/jars/"); - needed += needClass(out, "org.codehaus.stax2.XMLStreamWriter2", - "wstx-asl-3.0.1.jar", - "Streaming API for XML implementation", - "Axis2 will not work", - "http://dist.codehaus.org/stax/jars/"); - -%> -<% - /* - * resources on the classpath path - */ - /* broken; this is a file, not a resource - wantResource(out,"/server-config.wsdd", - "There is no server configuration file;" - +"run AdminClient to create one"); - */ - /* add more libraries here */ - - //is everything we need here - if (needed == 0) { - //yes, be happy - out.write("

    The core axis2 libraries are present.

    "); - } else { - //no, be very unhappy - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - out.write("

    " - + needed - + " core axis2 librar" - + (needed == 1 ? "y is" : "ies are") - + " missing

    "); - } - //now look at wanted stuff -%> -

    - Note: Even if everything this page probes for is present, - there is no guarantee your Axis Service will work, because there are many configuration options - that we do not check for. These tests are necessary but not sufficient -

    - -

    Examining Version Service

    -<% - boolean serviceStatus = invokeTheService(); - if (serviceStatus) { -%> -
    -

    - Found Axis2 default Version service and Axis2 is working - properly. -

    - -

    Now you can drop a service archive in axis2/WEB-INF/services. - Following output was produced while invoking Axis2 version service -

    -

    <%= value%>

    -
    - -<% -} else { -%> -

    - There was a problem in Axis2 version service , may be - the service not available or some thing has gone wrong. But this does - not mean system is not working ! - Try to upload some other service and check to see whether it is - working. -

    - -<% - } -%> -

    Examining Application Server

    -
    - - - - - -
    Servlet version<%=getServletVersion()%>
    Platform<%=getServletConfig().getServletContext().getServerInfo()%>
    -
    -

    Examining System Properties

    -<% - /** - * Dump the system properties - */ - java.util.Enumeration e = null; - try { - e = System.getProperties().propertyNames(); - } catch (SecurityException se) { - } - if (e != null) { - out.write(""); - for (; e.hasMoreElements();) { - out.write(""); - String key = (String) e.nextElement(); - out.write(""); - out.write(""); - out.write(""); - } - out.write("
    " + key + "" + getFormatedSystemProperty(System.getProperty(key)) + " 
    "); - out.write("

    "); - } else { - out.write("System properties are not accessible

    "); - } -%> - - - - - - diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/axis2-web/MainFrame.jsp b/edu.harvard.i2b2.server-common/lib/axis2.war/axis2-web/MainFrame.jsp deleted file mode 100644 index be78c528..00000000 --- a/edu.harvard.i2b2.server-common/lib/axis2.war/axis2-web/MainFrame.jsp +++ /dev/null @@ -1,29 +0,0 @@ -<%-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --%> - - - - - Axis2 Administration - - - - - diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/axis2-web/css/axis-style.css b/edu.harvard.i2b2.server-common/lib/axis2.war/axis2-web/css/axis-style.css deleted file mode 100644 index 2ebae6e5..00000000 --- a/edu.harvard.i2b2.server-common/lib/axis2.war/axis2-web/css/axis-style.css +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -BODY { - background-color : #FFFFFF; - margin-left:0; - margin-top:0; - font-family:Arial; - font-size:11pt; -} -h1 { font-family: Arial; font-size: 16pt; font-weight: bold } -h2 { font-family: Arial; font-size: 13pt; font-weight: bold; color: #5D0D7D } -ul { font-family: Arial; font-size: 11pt } -input { font-family: Arial; font-size: 8pt; font-weight: bold } -td { font-family: Arial; font-size: 10pt } -h3 { font-family: Arial; font-size: 12pt; font-weight:bold } -TABLE.FULL_BLANK { - width : 100%; - height : 100%; - border : 0; - padding : 0; -} - -TABLE.LOG_IN_FORM{ - height: 200px; - border:1px solid #000000; - width: 300px; - border-spacing:1px; - padding:1px; - background-color: #f7f7f7 ; -} - -UL.loginUL LI{ - padding: 10pt; -} \ No newline at end of file diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/axis2-web/error.jsp b/edu.harvard.i2b2.server-common/lib/axis2.war/axis2-web/error.jsp deleted file mode 100644 index 374a6d55..00000000 --- a/edu.harvard.i2b2.server-common/lib/axis2.war/axis2-web/error.jsp +++ /dev/null @@ -1,31 +0,0 @@ -<%-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --%> - -<%@ page contentType="text/html;charset=UTF-8" language="java" %> -<%@page isErrorPage="true" %> - - - - - - - - -
    An error has occured!. Please check the details below
    <%=exception.getMessage()%>
    - diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/axis2-web/images/asf-logo.gif b/edu.harvard.i2b2.server-common/lib/axis2.war/axis2-web/images/asf-logo.gif deleted file mode 100644 index b2403286..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/axis2-web/images/asf-logo.gif and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/axis2-web/images/axis.gif b/edu.harvard.i2b2.server-common/lib/axis2.war/axis2-web/images/axis.gif deleted file mode 100644 index e970c5b8..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/axis2-web/images/axis.gif and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/axis2-web/images/axis.jpg b/edu.harvard.i2b2.server-common/lib/axis2.war/axis2-web/images/axis.jpg deleted file mode 100644 index 47f97620..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/axis2-web/images/axis.jpg and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/axis2-web/images/axis_l.jpg b/edu.harvard.i2b2.server-common/lib/axis2.war/axis2-web/images/axis_l.jpg deleted file mode 100644 index 172a755f..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/axis2-web/images/axis_l.jpg and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/axis2-web/index.jsp b/edu.harvard.i2b2.server-common/lib/axis2.war/axis2-web/index.jsp deleted file mode 100644 index c6d138dc..00000000 --- a/edu.harvard.i2b2.server-common/lib/axis2.war/axis2-web/index.jsp +++ /dev/null @@ -1,59 +0,0 @@ -<%-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --%> - -<%@ page contentType="text/html;charset=UTF-8" language="java" session="false" %> - - - - - Axis 2 - Home - - - - - -
    - -

    Welcome!

    - Welcome to the new generation of Axis. If you can see this page you have - successfully deployed the Axis2 Web Application. However, to ensure that Axis2 - is properly working, we encourage you to click on the validate link. -
    -
      -
    • Services -
      - View the list of all the available services deployed in this server. -
    • -
    • Validate -
      - Check the system to see whether all the required libraries are in place - and view the system information. -
    • - <%--
    • Do an interop test -
      - You can run Interoperability tests here -
    • --%> -
    • Administration -
      - Console for administering this Axis2 installation. -
    • -
    - - - diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/org/apache/axis2/soapmonitor/applet/SOAPMonitorApplet$SOAPMonitorData.class b/edu.harvard.i2b2.server-common/lib/axis2.war/org/apache/axis2/soapmonitor/applet/SOAPMonitorApplet$SOAPMonitorData.class deleted file mode 100644 index 5dd12e07..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/org/apache/axis2/soapmonitor/applet/SOAPMonitorApplet$SOAPMonitorData.class and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/org/apache/axis2/soapmonitor/applet/SOAPMonitorApplet$SOAPMonitorFilter.class b/edu.harvard.i2b2.server-common/lib/axis2.war/org/apache/axis2/soapmonitor/applet/SOAPMonitorApplet$SOAPMonitorFilter.class deleted file mode 100644 index 4f90c31d..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/org/apache/axis2/soapmonitor/applet/SOAPMonitorApplet$SOAPMonitorFilter.class and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/org/apache/axis2/soapmonitor/applet/SOAPMonitorApplet$SOAPMonitorPage.class b/edu.harvard.i2b2.server-common/lib/axis2.war/org/apache/axis2/soapmonitor/applet/SOAPMonitorApplet$SOAPMonitorPage.class deleted file mode 100644 index e7ec03a3..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/org/apache/axis2/soapmonitor/applet/SOAPMonitorApplet$SOAPMonitorPage.class and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/org/apache/axis2/soapmonitor/applet/SOAPMonitorApplet$SOAPMonitorTableModel.class b/edu.harvard.i2b2.server-common/lib/axis2.war/org/apache/axis2/soapmonitor/applet/SOAPMonitorApplet$SOAPMonitorTableModel.class deleted file mode 100644 index eee4b3b3..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/org/apache/axis2/soapmonitor/applet/SOAPMonitorApplet$SOAPMonitorTableModel.class and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/org/apache/axis2/soapmonitor/applet/SOAPMonitorApplet$SOAPMonitorTextArea.class b/edu.harvard.i2b2.server-common/lib/axis2.war/org/apache/axis2/soapmonitor/applet/SOAPMonitorApplet$SOAPMonitorTextArea.class deleted file mode 100644 index 7d82a11e..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/org/apache/axis2/soapmonitor/applet/SOAPMonitorApplet$SOAPMonitorTextArea.class and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/org/apache/axis2/soapmonitor/applet/SOAPMonitorApplet$ServiceFilterPanel.class b/edu.harvard.i2b2.server-common/lib/axis2.war/org/apache/axis2/soapmonitor/applet/SOAPMonitorApplet$ServiceFilterPanel.class deleted file mode 100644 index a25984ad..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/org/apache/axis2/soapmonitor/applet/SOAPMonitorApplet$ServiceFilterPanel.class and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/org/apache/axis2/soapmonitor/applet/SOAPMonitorApplet.class b/edu.harvard.i2b2.server-common/lib/axis2.war/org/apache/axis2/soapmonitor/applet/SOAPMonitorApplet.class deleted file mode 100644 index 833488ee..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/axis2.war/org/apache/axis2/soapmonitor/applet/SOAPMonitorApplet.class and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/exec/commons-exec-1.4.0.jar b/edu.harvard.i2b2.server-common/lib/exec/commons-exec-1.4.0.jar deleted file mode 100644 index ac80d681..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/exec/commons-exec-1.4.0.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/jboss/ironjacamar-jdbc-1.3.2.Final.jar b/edu.harvard.i2b2.server-common/lib/jboss/ironjacamar-jdbc-1.3.2.Final.jar deleted file mode 100644 index 7b13ec2f..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/jboss/ironjacamar-jdbc-1.3.2.Final.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/jboss/jboss-cli-client.jar b/edu.harvard.i2b2.server-common/lib/jboss/jboss-cli-client.jar deleted file mode 100644 index f8290950..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/jboss/jboss-cli-client.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/jboss/wildfly-connector-10.0.0.Final.jar b/edu.harvard.i2b2.server-common/lib/jboss/wildfly-connector-10.0.0.Final.jar deleted file mode 100644 index 6941f6bd..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/jboss/wildfly-connector-10.0.0.Final.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/jdbc/mssql-jdbc-12.8.1.jre11.jar b/edu.harvard.i2b2.server-common/lib/jdbc/mssql-jdbc-12.8.1.jre11.jar deleted file mode 100644 index f609e86c..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/jdbc/mssql-jdbc-12.8.1.jre11.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/jdbc/ojdbc11.jar b/edu.harvard.i2b2.server-common/lib/jdbc/ojdbc11.jar deleted file mode 100644 index fb996022..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/jdbc/ojdbc11.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/jdbc/postgresql-42.7.4.jar b/edu.harvard.i2b2.server-common/lib/jdbc/postgresql-42.7.4.jar deleted file mode 100644 index 091b4d13..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/jdbc/postgresql-42.7.4.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/junit/hamcrest-core-1.3.jar b/edu.harvard.i2b2.server-common/lib/junit/hamcrest-core-1.3.jar deleted file mode 100644 index 9d5fe16e..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/junit/hamcrest-core-1.3.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/junit/junit-4.12.jar b/edu.harvard.i2b2.server-common/lib/junit/junit-4.12.jar deleted file mode 100644 index 3a7fc266..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/junit/junit-4.12.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/okta/okta-authn-sdk-api-3.0.0.jar b/edu.harvard.i2b2.server-common/lib/okta/okta-authn-sdk-api-3.0.0.jar deleted file mode 100644 index 7ad8fbcd..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/okta/okta-authn-sdk-api-3.0.0.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/okta/okta-sdk-api-19.0.1.jar b/edu.harvard.i2b2.server-common/lib/okta/okta-sdk-api-19.0.1.jar deleted file mode 100644 index 8abfd54d..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/okta/okta-sdk-api-19.0.1.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/quartz/quartz-2.3.0.jar b/edu.harvard.i2b2.server-common/lib/quartz/quartz-2.3.0.jar deleted file mode 100755 index b3002645..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/quartz/quartz-2.3.0.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/smbj/asn-one-0.6.0.jar b/edu.harvard.i2b2.server-common/lib/smbj/asn-one-0.6.0.jar deleted file mode 100644 index 5f65bc93..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/smbj/asn-one-0.6.0.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/smbj/bcprov-jdk18on-1.78.1.jar b/edu.harvard.i2b2.server-common/lib/smbj/bcprov-jdk18on-1.78.1.jar deleted file mode 100644 index 6726f833..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/smbj/bcprov-jdk18on-1.78.1.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/smbj/mbassador-1.3.0.jar b/edu.harvard.i2b2.server-common/lib/smbj/mbassador-1.3.0.jar deleted file mode 100644 index 1c919a03..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/smbj/mbassador-1.3.0.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/smbj/smbj-0.13.0.jar b/edu.harvard.i2b2.server-common/lib/smbj/smbj-0.13.0.jar deleted file mode 100644 index 64b90abb..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/smbj/smbj-0.13.0.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/spring/apachelicence-2.0.txt b/edu.harvard.i2b2.server-common/lib/spring/apachelicence-2.0.txt deleted file mode 100755 index ea2f013b..00000000 --- a/edu.harvard.i2b2.server-common/lib/spring/apachelicence-2.0.txt +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. \ No newline at end of file diff --git a/edu.harvard.i2b2.server-common/lib/spring/spring-beans-6.1.11.jar b/edu.harvard.i2b2.server-common/lib/spring/spring-beans-6.1.11.jar deleted file mode 100644 index c0655a8e..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/spring/spring-beans-6.1.11.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/spring/spring-context-6.1.11.jar b/edu.harvard.i2b2.server-common/lib/spring/spring-context-6.1.11.jar deleted file mode 100644 index e1756c9e..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/spring/spring-context-6.1.11.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/spring/spring-core-6.1.11.jar b/edu.harvard.i2b2.server-common/lib/spring/spring-core-6.1.11.jar deleted file mode 100644 index 1eb0e884..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/spring/spring-core-6.1.11.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/spring/spring-jdbc-6.1.11.jar b/edu.harvard.i2b2.server-common/lib/spring/spring-jdbc-6.1.11.jar deleted file mode 100644 index 8d2558c7..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/spring/spring-jdbc-6.1.11.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/spring/spring-tx-6.1.11.jar b/edu.harvard.i2b2.server-common/lib/spring/spring-tx-6.1.11.jar deleted file mode 100644 index 0f83151f..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/spring/spring-tx-6.1.11.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/lib/zip/zip4j-2.11.5.jar b/edu.harvard.i2b2.server-common/lib/zip/zip4j-2.11.5.jar deleted file mode 100644 index c08f0f3b..00000000 Binary files a/edu.harvard.i2b2.server-common/lib/zip/zip4j-2.11.5.jar and /dev/null differ diff --git a/edu.harvard.i2b2.server-common/pom.xml b/edu.harvard.i2b2.server-common/pom.xml new file mode 100644 index 00000000..94039ad2 --- /dev/null +++ b/edu.harvard.i2b2.server-common/pom.xml @@ -0,0 +1,133 @@ + + 4.0.0 + + edu.harvard.i2b2 + i2b2-parent + 2.0.0-SNAPSHOT + + edu.harvard.i2b2.server-common + jar + server-common + + + + org.springframework + spring-core + + + org.springframework + spring-beans + + + + org.springframework + spring-jdbc + + + + org.springframework + spring-context + + + + org.apache.axis2 + axis2-adb + + + + org.apache.axis2 + axis2-transport-http + + + + org.apache.axis2 + axis2-transport-local + + + + + org.apache.axis2 + axis2-jaxws + 2.0.0 + + + + jakarta.xml.bind + jakarta.xml.bind-api + 4.0.2 + + + org.glassfish.jaxb + jaxb-core + 4.0.5 + + + org.apache.commons + commons-lang3 + + + + org.postgresql + postgresql + 42.4.0 + + + com.oracle.database.jdbc + ojdbc8 + 21.5.0.0 + + + com.microsoft.sqlserver + mssql-jdbc + 10.2.1.jre8 + + + + com.google.code.gson + gson + 2.13.1 + + + + xalan + xalan + 2.7.3 + + + + org.apache.logging.log4j + log4j-core + + + commons-logging + commons-logging + + + + junit + junit + test + + + + + org.apache.httpcomponents.core5 + httpcore5 + 5.3.4 + + + + org.apache.httpcomponents.client5 + httpclient5 + 5.5 + + + + javax.annotation + javax.annotation-api + 1.3.2 + + + + \ No newline at end of file diff --git a/edu.harvard.i2b2.server-common/src/core/edu/harvard/i2b2/common/util/jaxb/XmlCharacterEscapeHandler.java b/edu.harvard.i2b2.server-common/src/core/edu/harvard/i2b2/common/util/jaxb/XmlCharacterEscapeHandler.java deleted file mode 100755 index 37e614e4..00000000 --- a/edu.harvard.i2b2.server-common/src/core/edu/harvard/i2b2/common/util/jaxb/XmlCharacterEscapeHandler.java +++ /dev/null @@ -1,85 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.common.util.jaxb; - -import java.io.IOException; -import java.io.Writer; - -import org.eclipse.tags.shaded.org.apache.xml.utils.XML11Char; -import org.glassfish.jaxb.core.marshaller.CharacterEscapeHandler; - - -public class XmlCharacterEscapeHandler implements CharacterEscapeHandler { - /** - * Escape characters inside the buffer and send the output to the writer. - * - * @exception IOException - * if something goes wrong, IOException can be thrown to stop the - * marshalling process. - */ - public void escape(char[] buf, int start, int len, boolean isAttValue, - Writer out) throws IOException { - for (int i = start; i < (start + len); i++) { - char ch = buf[i]; - -// you are supposed to do the standard XML character escapes - // like & ... & < ... < etc - if (ch == '&') { - out.write("&"); - - continue; - } - - if (ch == '<') { - out.write("<"); - continue; - } - - if (ch == '>') { - out.write(">"); - continue; - } - - - - if ((ch == '"') && isAttValue) { - // isAttValue is set to true when the marshaller is processing - // attribute values. Inside attribute values, there are more - // things you need to escape, usually. - out.write("""); - - continue; - } - - if ((ch == '\'') && isAttValue) { - out.write("'"); - - continue; - } - - - - // you should handle other characters like < or > - if (ch > 0x7F) { - // escape everything above ASCII to &#xXXXX; - out.write("&#x"); - out.write(Integer.toHexString(ch)); - out.write(";"); - - continue; - } - - - //use apache util to check for valid xml character - if (XML11Char.isXML11Valid(ch)) { - out.write(ch); - } - } - } -} diff --git a/edu.harvard.i2b2.server-common/src/core/edu/harvard/i2b2/common/exception/I2B2DAOException.java b/edu.harvard.i2b2.server-common/src/main/java/edu/harvard/i2b2/common/exception/I2B2DAOException.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.server-common/src/core/edu/harvard/i2b2/common/exception/I2B2DAOException.java rename to edu.harvard.i2b2.server-common/src/main/java/edu/harvard/i2b2/common/exception/I2B2DAOException.java diff --git a/edu.harvard.i2b2.server-common/src/core/edu/harvard/i2b2/common/exception/I2B2EJBException.java b/edu.harvard.i2b2.server-common/src/main/java/edu/harvard/i2b2/common/exception/I2B2EJBException.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.server-common/src/core/edu/harvard/i2b2/common/exception/I2B2EJBException.java rename to edu.harvard.i2b2.server-common/src/main/java/edu/harvard/i2b2/common/exception/I2B2EJBException.java diff --git a/edu.harvard.i2b2.server-common/src/core/edu/harvard/i2b2/common/exception/I2B2Exception.java b/edu.harvard.i2b2.server-common/src/main/java/edu/harvard/i2b2/common/exception/I2B2Exception.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.server-common/src/core/edu/harvard/i2b2/common/exception/I2B2Exception.java rename to edu.harvard.i2b2.server-common/src/main/java/edu/harvard/i2b2/common/exception/I2B2Exception.java diff --git a/edu.harvard.i2b2.server-common/src/core/edu/harvard/i2b2/common/exception/StackTraceUtil.java b/edu.harvard.i2b2.server-common/src/main/java/edu/harvard/i2b2/common/exception/StackTraceUtil.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.server-common/src/core/edu/harvard/i2b2/common/exception/StackTraceUtil.java rename to edu.harvard.i2b2.server-common/src/main/java/edu/harvard/i2b2/common/exception/StackTraceUtil.java diff --git a/edu.harvard.i2b2.server-common/src/core/edu/harvard/i2b2/common/util/PropertyUtil.java b/edu.harvard.i2b2.server-common/src/main/java/edu/harvard/i2b2/common/util/PropertyUtil.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.server-common/src/core/edu/harvard/i2b2/common/util/PropertyUtil.java rename to edu.harvard.i2b2.server-common/src/main/java/edu/harvard/i2b2/common/util/PropertyUtil.java diff --git a/edu.harvard.i2b2.server-common/src/core/edu/harvard/i2b2/common/util/ServiceLocator.java b/edu.harvard.i2b2.server-common/src/main/java/edu/harvard/i2b2/common/util/ServiceLocator.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.server-common/src/core/edu/harvard/i2b2/common/util/ServiceLocator.java rename to edu.harvard.i2b2.server-common/src/main/java/edu/harvard/i2b2/common/util/ServiceLocator.java diff --git a/edu.harvard.i2b2.server-common/src/core/edu/harvard/i2b2/common/util/ServiceLocatorException.java b/edu.harvard.i2b2.server-common/src/main/java/edu/harvard/i2b2/common/util/ServiceLocatorException.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.server-common/src/core/edu/harvard/i2b2/common/util/ServiceLocatorException.java rename to edu.harvard.i2b2.server-common/src/main/java/edu/harvard/i2b2/common/util/ServiceLocatorException.java diff --git a/edu.harvard.i2b2.server-common/src/core/edu/harvard/i2b2/common/util/XMLGregorianCalendarAdapterClass.java b/edu.harvard.i2b2.server-common/src/main/java/edu/harvard/i2b2/common/util/XMLGregorianCalendarAdapterClass.java similarity index 100% rename from edu.harvard.i2b2.server-common/src/core/edu/harvard/i2b2/common/util/XMLGregorianCalendarAdapterClass.java rename to edu.harvard.i2b2.server-common/src/main/java/edu/harvard/i2b2/common/util/XMLGregorianCalendarAdapterClass.java diff --git a/edu.harvard.i2b2.server-common/src/core/edu/harvard/i2b2/common/util/XMLGregorianCalendarDeserializer.java b/edu.harvard.i2b2.server-common/src/main/java/edu/harvard/i2b2/common/util/XMLGregorianCalendarDeserializer.java similarity index 100% rename from edu.harvard.i2b2.server-common/src/core/edu/harvard/i2b2/common/util/XMLGregorianCalendarDeserializer.java rename to edu.harvard.i2b2.server-common/src/main/java/edu/harvard/i2b2/common/util/XMLGregorianCalendarDeserializer.java diff --git a/edu.harvard.i2b2.server-common/src/core/edu/harvard/i2b2/common/util/axis2/ServiceClient.java b/edu.harvard.i2b2.server-common/src/main/java/edu/harvard/i2b2/common/util/axis2/ServiceClient.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.server-common/src/core/edu/harvard/i2b2/common/util/axis2/ServiceClient.java rename to edu.harvard.i2b2.server-common/src/main/java/edu/harvard/i2b2/common/util/axis2/ServiceClient.java index 02a13832..9642a6d8 --- a/edu.harvard.i2b2.server-common/src/core/edu/harvard/i2b2/common/util/axis2/ServiceClient.java +++ b/edu.harvard.i2b2.server-common/src/main/java/edu/harvard/i2b2/common/util/axis2/ServiceClient.java @@ -1,336 +1,336 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.common.util.axis2; - -/* - - * - * Contributors: - * Mike Mendis - */ - -import java.io.StringReader; -import java.lang.management.ManagementFactory; - -import javax.management.AttributeNotFoundException; -import javax.management.InstanceNotFoundException; -import javax.management.MBeanException; -import javax.management.MalformedObjectNameException; -import javax.management.ObjectName; -import javax.management.ReflectionException; -import javax.xml.stream.FactoryConfigurationError; -import javax.xml.stream.XMLInputFactory; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamReader; - -import org.apache.axiom.om.OMAbstractFactory; -import org.apache.axiom.om.OMElement; -import org.apache.axiom.om.OMNamespace; -import org.apache.axiom.om.OMXMLBuilderFactory; -import org.apache.axiom.soap.SOAP11Constants; -import org.apache.axiom.soap.SOAPEnvelope; -import org.apache.axiom.soap.SOAPFactory; -import org.apache.axis2.AxisFault; -import org.apache.axis2.Constants; -import org.apache.axis2.addressing.EndpointReference; -import org.apache.axis2.client.OperationClient; -import org.apache.axis2.client.Options; -import org.apache.axis2.context.ConfigurationContext; -import org.apache.axis2.context.MessageContext; -import org.apache.axis2.context.ServiceContext; -//import org.apache.axis2.transport.http.HTTPConstants; -import org.apache.axis2.wsdl.WSDLConstants; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -//import org.apache.xml.utils.QName; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.exception.StackTraceUtil; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; - -public class ServiceClient { - private static Log log = LogFactory.getLog(ServiceClient.class.getName()); - - //private static org.apache.axis2.client.ServiceClient serviceClient = null; - - - private static Object LOCK = new Object(); - - public static String sendREST(String restEPR, String requestString) throws Exception{ - - OMElement request = getPayLoad(requestString); - return sendREST(restEPR, request); - } - - - - public static String sendREST(String restEPR, OMElement request) throws Exception{ - - String response = null; - org.apache.axis2.client.ServiceClient serviceClient = null; - //org.apache.axis2.client.ServiceClient serviceClient_retry = null; - - int retry = 0; - boolean done = false; - String msg = null; - do { - try { - - serviceClient = new org.apache.axis2.client.ServiceClient(); - - - ServiceContext context = serviceClient.getServiceContext(); - /* - MultiThreadedHttpConnectionManager connManager = (MultiThreadedHttpConnectionManager)context.getProperty(HTTPConstants.MULTITHREAD_HTTP_CONNECTION_MANAGER); - - - if(connManager == null) { - connManager = new MultiThreadedHttpConnectionManager(); - context.setProperty(HTTPConstants.MULTITHREAD_HTTP_CONNECTION_MANAGER, connManager); - connManager.getParams().setMaxTotalConnections(100); - connManager.getParams().setDefaultMaxConnectionsPerHost(100); - connManager.getParams().setMaxConnectionsPerHost(HostConfiguration.ANY_HOST_CONFIGURATION, 100); - } - HttpClient httpClient = new HttpClient(connManager); - */ - Options options = new Options(); - options.setTo(new EndpointReference(restEPR)); - options.setTransportInProtocol(Constants.TRANSPORT_HTTP); - options.setProperty(Constants.Configuration.ENABLE_REST, Constants.VALUE_TRUE); -// options.setProperty(HTTPConstants.CACHED_HTTP_CLIENT, httpClient); - //MM axis2 2.0 options.setProperty(HTTPConstants.REUSE_HTTP_CLIENT, Constants.VALUE_TRUE); - serviceClient.setOptions(options); - - OMElement result = serviceClient.sendReceive(request); - if (result != null) { - response = result.toString(); - //logesapi.debug(response); - } - done = true; - } catch (Exception e) { - Thread.sleep(1000); - msg = e.getMessage(); - } finally { - if (serviceClient != null) { - try{ - serviceClient.cleanupTransport(); - serviceClient.cleanup(); - } catch (AxisFault e) { - log.debug("Error .", e); - } - } - } - if (retry == 5) - done = true; - retry ++; - } while (done == false); - - if (retry ==- 5) - throw new I2B2Exception(msg); - - return response; - } - - - - public static MessageContext getSOAPFile(String frUrl, OMElement requestElement, String frOperationName, String timeout) throws AxisFault - { - - org.apache.axis2.client.ServiceClient serviceClient = null; - serviceClient = new org.apache.axis2.client.ServiceClient(); - - // OMElement getRequestElmt = getRequestPayLoad(); - Options options = new Options(); - options.setTo(new EndpointReference(frUrl)); - options.setSoapVersionURI(SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI); - // options.setProperty(Constants.Configuration.ENABLE_REST, Constants.VALUE_TRUE); - options.setProperty(Constants.Configuration.ENABLE_SWA, Constants.VALUE_TRUE); - options.setProperty(Constants.Configuration.ENABLE_MTOM, Constants.VALUE_FALSE); - - // Increase the time out to receive large attachments - options.setTimeOutInMilliSeconds(Integer.parseInt(timeout)); - - options.setProperty(Constants.Configuration.CACHE_ATTACHMENTS, - Constants.VALUE_TRUE); - - //ServiceClient sender = new ServiceClient(); - - serviceClient.setOptions(options); - OperationClient mepClient = serviceClient.createClient(org.apache.axis2.client.ServiceClient.ANON_OUT_IN_OP); - - // SOAPFactory sfac = OMAbstractFactory.getSOAP11Factory(); - SOAPFactory sfac = OMAbstractFactory.getSOAP12Factory(); - SOAPEnvelope env = sfac.getDefaultEnvelope(); - env.getBody().addChild(requestElement); - MessageContext mc = new MessageContext(); - mc.setEnvelope(env); - mc.setDoingMTOM(false); - mc.setDoingSwA( true ); - - mepClient.addMessageContext(mc); - - mepClient.execute(true); - return mepClient - .getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE); - - - } - - public static OMElement getPayLoad(String requestPm) throws Exception { - OMElement lineItem = null; - try { - - StringReader strReader = new StringReader(requestPm); - XMLInputFactory xif = XMLInputFactory.newInstance(); - XMLStreamReader reader = xif.createXMLStreamReader(strReader); - - lineItem = OMXMLBuilderFactory.createStAXOMBuilder(reader).getDocumentElement(); - lineItem.build(); - - /* - // Create an XMLStreamReader without building the object model - StringReader strReader = new StringReader(requestPm); - XMLInputFactory xif = XMLInputFactory.newInstance(); - XMLStreamReader reader = xif.createXMLStreamReader(strReader); - while (reader.hasNext()) { - if (reader.getEventType() == XMLStreamReader.START_ELEMENT && - reader.getName().equals(new QName("tag"))) { - // A matching START_ELEMENT event was found. Build a corresponding OMElement. - lineItem = - OMXMLBuilderFactory.createStAXOMBuilder(reader).getDocumentElement(); - // Make sure that all events belonging to the element are consumed so - // that the XMLStreamReader points to a well defined location (namely the - // event immediately following the END_ELEMENT event). - lineItem.build(); - // Now process the element. - } else { - reader.next(); - } - } - */ - } catch (FactoryConfigurationError e) { - log.error(e.getMessage()); - throw new Exception(e); - } - return lineItem; - } - - /** - * Function constructs OMElement for the given String - * - * @param xmlString - * @return OMElement - * @throws XMLStreamException - */ - public static OMElement buildOMElementFromString(String xmlString) - throws XMLStreamException { - XMLInputFactory xif = XMLInputFactory.newInstance(); - StringReader strReader = new StringReader(xmlString); - XMLStreamReader reader = xif.createXMLStreamReader(strReader); - OMElement element = OMXMLBuilderFactory.createStAXOMBuilder(reader).getDocumentElement(); - - return element; - } - - public static String sendSOAP(String soapEPR, String requestString, String action, String operation) throws Exception{ - - org.apache.axis2.client.ServiceClient serviceClient = null; - serviceClient = new - org.apache.axis2.client.ServiceClient(); - OperationClient operationClient = serviceClient - .createClient(org.apache.axis2.client.ServiceClient.ANON_OUT_IN_OP); - - // creating message context - MessageContext outMsgCtx = new MessageContext(); - // assigning message context's option object into instance variable - Options opts = outMsgCtx.getOptions(); - // setting properties into option - // log.debug(soapEPR); - opts.setTo(new EndpointReference(soapEPR)); - opts.setAction(action); - opts.setTimeOutInMilliSeconds(180000); - - log.debug(requestString); - - SOAPEnvelope envelope = null; - - try { - SOAPFactory fac = OMAbstractFactory.getSOAP11Factory(); - envelope = fac.getDefaultEnvelope(); - OMNamespace omNs = fac.createOMNamespace( - "http://rpdr.partners.org/", - "rpdr"); - - - // creating the SOAP payload - OMElement method = fac.createOMElement(operation, omNs); - OMElement value = fac.createOMElement("RequestXmlString", omNs); - value.setText(requestString); - method.addChild(value); - envelope.getBody().addChild(method); - } - catch (FactoryConfigurationError e) { - log.error(e.getMessage()); - throw new Exception(e); - } - - outMsgCtx.setEnvelope(envelope); - - - operationClient.addMessageContext(outMsgCtx); - operationClient.execute(true); - - - MessageContext inMsgtCtx = operationClient.getMessageContext("In"); - SOAPEnvelope responseEnv = inMsgtCtx.getEnvelope(); - - OMElement soapResponse = responseEnv.getBody().getFirstElement(); - - OMElement soapResult = soapResponse.getFirstElement(); - - String i2b2Response = soapResult.getText(); - log.debug(i2b2Response); - - return i2b2Response; - } - public static String getContextRoot() throws InstanceNotFoundException, AttributeNotFoundException, MalformedObjectNameException, ReflectionException, MBeanException, AxisFault { - - org.apache.axis2.client.ServiceClient cl = ServiceClient.getServiceClient(); - Integer port = (Integer) ManagementFactory.getPlatformMBeanServer().getAttribute(new ObjectName("jboss.as:socket-binding-group=standard-sockets,socket-binding=http"), "port"); - - MessageContext mCtx = - MessageContext.getCurrentMessageContext(); - String url = null; - if (mCtx == null) - { - url = "http://localhost:" + port + "/i2b2"; - } else { - ConfigurationContext cCtx = - mCtx.getConfigurationContext(); - url= "http://localhost:" + port + cCtx.getContextRoot(); - } - return url; - - } - - public static org.apache.axis2.client.ServiceClient getServiceClient() throws AxisFault{ - org.apache.axis2.client.ServiceClient serviceClient = - null; - if (serviceClient == null) { - try { - serviceClient = new org.apache.axis2.client.ServiceClient(); - } catch (AxisFault e) { - log.error(e.getMessage()); - throw e; - } - } - return serviceClient; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.common.util.axis2; + +/* + + * + * Contributors: + * Mike Mendis + */ + +import java.io.StringReader; +import java.lang.management.ManagementFactory; + +import javax.management.AttributeNotFoundException; +import javax.management.InstanceNotFoundException; +import javax.management.MBeanException; +import javax.management.MalformedObjectNameException; +import javax.management.ObjectName; +import javax.management.ReflectionException; +import javax.xml.stream.FactoryConfigurationError; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import org.apache.axiom.om.OMAbstractFactory; +import org.apache.axiom.om.OMElement; +import org.apache.axiom.om.OMNamespace; +import org.apache.axiom.om.OMXMLBuilderFactory; +import org.apache.axiom.soap.SOAP11Constants; +import org.apache.axiom.soap.SOAPEnvelope; +import org.apache.axiom.soap.SOAPFactory; +import org.apache.axis2.AxisFault; +import org.apache.axis2.Constants; +import org.apache.axis2.addressing.EndpointReference; +import org.apache.axis2.client.OperationClient; +import org.apache.axis2.client.Options; +import org.apache.axis2.context.ConfigurationContext; +import org.apache.axis2.context.MessageContext; +import org.apache.axis2.context.ServiceContext; +//import org.apache.axis2.transport.http.HTTPConstants; +import org.apache.axis2.wsdl.WSDLConstants; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +//import org.apache.xml.utils.QName; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.exception.StackTraceUtil; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; + +public class ServiceClient { + private static Log log = LogFactory.getLog(ServiceClient.class.getName()); + + //private static org.apache.axis2.client.ServiceClient serviceClient = null; + + + private static Object LOCK = new Object(); + + public static String sendREST(String restEPR, String requestString) throws Exception{ + + OMElement request = getPayLoad(requestString); + return sendREST(restEPR, request); + } + + + + public static String sendREST(String restEPR, OMElement request) throws Exception{ + + String response = null; + org.apache.axis2.client.ServiceClient serviceClient = null; + //org.apache.axis2.client.ServiceClient serviceClient_retry = null; + + int retry = 0; + boolean done = false; + String msg = null; + do { + try { + + serviceClient = new org.apache.axis2.client.ServiceClient(); + + + ServiceContext context = serviceClient.getServiceContext(); + /* + MultiThreadedHttpConnectionManager connManager = (MultiThreadedHttpConnectionManager)context.getProperty(HTTPConstants.MULTITHREAD_HTTP_CONNECTION_MANAGER); + + + if(connManager == null) { + connManager = new MultiThreadedHttpConnectionManager(); + context.setProperty(HTTPConstants.MULTITHREAD_HTTP_CONNECTION_MANAGER, connManager); + connManager.getParams().setMaxTotalConnections(100); + connManager.getParams().setDefaultMaxConnectionsPerHost(100); + connManager.getParams().setMaxConnectionsPerHost(HostConfiguration.ANY_HOST_CONFIGURATION, 100); + } + HttpClient httpClient = new HttpClient(connManager); + */ + Options options = new Options(); + options.setTo(new EndpointReference(restEPR)); + options.setTransportInProtocol(Constants.TRANSPORT_HTTP); + options.setProperty(Constants.Configuration.ENABLE_REST, Constants.VALUE_TRUE); +// options.setProperty(HTTPConstants.CACHED_HTTP_CLIENT, httpClient); + //MM axis2 2.0 options.setProperty(HTTPConstants.REUSE_HTTP_CLIENT, Constants.VALUE_TRUE); + serviceClient.setOptions(options); + + OMElement result = serviceClient.sendReceive(request); + if (result != null) { + response = result.toString(); + //logesapi.debug(response); + } + done = true; + } catch (Exception e) { + Thread.sleep(1000); + msg = e.getMessage(); + } finally { + if (serviceClient != null) { + try{ + serviceClient.cleanupTransport(); + serviceClient.cleanup(); + } catch (AxisFault e) { + log.debug("Error .", e); + } + } + } + if (retry == 5) + done = true; + retry ++; + } while (done == false); + + if (retry ==- 5) + throw new I2B2Exception(msg); + + return response; + } + + + + public static MessageContext getSOAPFile(String frUrl, OMElement requestElement, String frOperationName, String timeout) throws AxisFault + { + + org.apache.axis2.client.ServiceClient serviceClient = null; + serviceClient = new org.apache.axis2.client.ServiceClient(); + + // OMElement getRequestElmt = getRequestPayLoad(); + Options options = new Options(); + options.setTo(new EndpointReference(frUrl)); + options.setSoapVersionURI(SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI); + // options.setProperty(Constants.Configuration.ENABLE_REST, Constants.VALUE_TRUE); + options.setProperty(Constants.Configuration.ENABLE_SWA, Constants.VALUE_TRUE); + options.setProperty(Constants.Configuration.ENABLE_MTOM, Constants.VALUE_FALSE); + + // Increase the time out to receive large attachments + options.setTimeOutInMilliSeconds(Integer.parseInt(timeout)); + + options.setProperty(Constants.Configuration.CACHE_ATTACHMENTS, + Constants.VALUE_TRUE); + + //ServiceClient sender = new ServiceClient(); + + serviceClient.setOptions(options); + OperationClient mepClient = serviceClient.createClient(org.apache.axis2.client.ServiceClient.ANON_OUT_IN_OP); + + // SOAPFactory sfac = OMAbstractFactory.getSOAP11Factory(); + SOAPFactory sfac = OMAbstractFactory.getSOAP12Factory(); + SOAPEnvelope env = sfac.getDefaultEnvelope(); + env.getBody().addChild(requestElement); + MessageContext mc = new MessageContext(); + mc.setEnvelope(env); + mc.setDoingMTOM(false); + mc.setDoingSwA( true ); + + mepClient.addMessageContext(mc); + + mepClient.execute(true); + return mepClient + .getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE); + + + } + + public static OMElement getPayLoad(String requestPm) throws Exception { + OMElement lineItem = null; + try { + + StringReader strReader = new StringReader(requestPm); + XMLInputFactory xif = XMLInputFactory.newInstance(); + XMLStreamReader reader = xif.createXMLStreamReader(strReader); + + lineItem = OMXMLBuilderFactory.createStAXOMBuilder(reader).getDocumentElement(); + lineItem.build(); + + /* + // Create an XMLStreamReader without building the object model + StringReader strReader = new StringReader(requestPm); + XMLInputFactory xif = XMLInputFactory.newInstance(); + XMLStreamReader reader = xif.createXMLStreamReader(strReader); + while (reader.hasNext()) { + if (reader.getEventType() == XMLStreamReader.START_ELEMENT && + reader.getName().equals(new QName("tag"))) { + // A matching START_ELEMENT event was found. Build a corresponding OMElement. + lineItem = + OMXMLBuilderFactory.createStAXOMBuilder(reader).getDocumentElement(); + // Make sure that all events belonging to the element are consumed so + // that the XMLStreamReader points to a well defined location (namely the + // event immediately following the END_ELEMENT event). + lineItem.build(); + // Now process the element. + } else { + reader.next(); + } + } + */ + } catch (FactoryConfigurationError e) { + log.error(e.getMessage()); + throw new Exception(e); + } + return lineItem; + } + + /** + * Function constructs OMElement for the given String + * + * @param xmlString + * @return OMElement + * @throws XMLStreamException + */ + public static OMElement buildOMElementFromString(String xmlString) + throws XMLStreamException { + XMLInputFactory xif = XMLInputFactory.newInstance(); + StringReader strReader = new StringReader(xmlString); + XMLStreamReader reader = xif.createXMLStreamReader(strReader); + OMElement element = OMXMLBuilderFactory.createStAXOMBuilder(reader).getDocumentElement(); + + return element; + } + + public static String sendSOAP(String soapEPR, String requestString, String action, String operation) throws Exception{ + + org.apache.axis2.client.ServiceClient serviceClient = null; + serviceClient = new + org.apache.axis2.client.ServiceClient(); + OperationClient operationClient = serviceClient + .createClient(org.apache.axis2.client.ServiceClient.ANON_OUT_IN_OP); + + // creating message context + MessageContext outMsgCtx = new MessageContext(); + // assigning message context's option object into instance variable + Options opts = outMsgCtx.getOptions(); + // setting properties into option + // log.debug(soapEPR); + opts.setTo(new EndpointReference(soapEPR)); + opts.setAction(action); + opts.setTimeOutInMilliSeconds(180000); + + log.debug(requestString); + + SOAPEnvelope envelope = null; + + try { + SOAPFactory fac = OMAbstractFactory.getSOAP11Factory(); + envelope = fac.getDefaultEnvelope(); + OMNamespace omNs = fac.createOMNamespace( + "http://rpdr.partners.org/", + "rpdr"); + + + // creating the SOAP payload + OMElement method = fac.createOMElement(operation, omNs); + OMElement value = fac.createOMElement("RequestXmlString", omNs); + value.setText(requestString); + method.addChild(value); + envelope.getBody().addChild(method); + } + catch (FactoryConfigurationError e) { + log.error(e.getMessage()); + throw new Exception(e); + } + + outMsgCtx.setEnvelope(envelope); + + + operationClient.addMessageContext(outMsgCtx); + operationClient.execute(true); + + + MessageContext inMsgtCtx = operationClient.getMessageContext("In"); + SOAPEnvelope responseEnv = inMsgtCtx.getEnvelope(); + + OMElement soapResponse = responseEnv.getBody().getFirstElement(); + + OMElement soapResult = soapResponse.getFirstElement(); + + String i2b2Response = soapResult.getText(); + log.debug(i2b2Response); + + return i2b2Response; + } + public static String getContextRoot() throws InstanceNotFoundException, AttributeNotFoundException, MalformedObjectNameException, ReflectionException, MBeanException, AxisFault { + + org.apache.axis2.client.ServiceClient cl = ServiceClient.getServiceClient(); + Integer port = (Integer) ManagementFactory.getPlatformMBeanServer().getAttribute(new ObjectName("jboss.as:socket-binding-group=standard-sockets,socket-binding=http"), "port"); + + MessageContext mCtx = + MessageContext.getCurrentMessageContext(); + String url = null; + if (mCtx == null) + { + url = "http://localhost:" + port + "/i2b2"; + } else { + ConfigurationContext cCtx = + mCtx.getConfigurationContext(); + url= "http://localhost:" + port + cCtx.getContextRoot(); + } + return url; + + } + + public static org.apache.axis2.client.ServiceClient getServiceClient() throws AxisFault{ + org.apache.axis2.client.ServiceClient serviceClient = + null; + if (serviceClient == null) { + try { + serviceClient = new org.apache.axis2.client.ServiceClient(); + } catch (AxisFault e) { + log.error(e.getMessage()); + throw e; + } + } + return serviceClient; + } + +} diff --git a/edu.harvard.i2b2.server-common/src/core/edu/harvard/i2b2/common/util/db/JDBCUtil.java b/edu.harvard.i2b2.server-common/src/main/java/edu/harvard/i2b2/common/util/db/JDBCUtil.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.server-common/src/core/edu/harvard/i2b2/common/util/db/JDBCUtil.java rename to edu.harvard.i2b2.server-common/src/main/java/edu/harvard/i2b2/common/util/db/JDBCUtil.java diff --git a/edu.harvard.i2b2.server-common/src/core/edu/harvard/i2b2/common/util/jaxb/DTOFactory.java b/edu.harvard.i2b2.server-common/src/main/java/edu/harvard/i2b2/common/util/jaxb/DTOFactory.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.server-common/src/core/edu/harvard/i2b2/common/util/jaxb/DTOFactory.java rename to edu.harvard.i2b2.server-common/src/main/java/edu/harvard/i2b2/common/util/jaxb/DTOFactory.java diff --git a/edu.harvard.i2b2.server-common/src/core/edu/harvard/i2b2/common/util/jaxb/JAXBUnWrapHelper.java b/edu.harvard.i2b2.server-common/src/main/java/edu/harvard/i2b2/common/util/jaxb/JAXBUnWrapHelper.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.server-common/src/core/edu/harvard/i2b2/common/util/jaxb/JAXBUnWrapHelper.java rename to edu.harvard.i2b2.server-common/src/main/java/edu/harvard/i2b2/common/util/jaxb/JAXBUnWrapHelper.java index 3aa2371f..90ff2650 --- a/edu.harvard.i2b2.server-common/src/core/edu/harvard/i2b2/common/util/jaxb/JAXBUnWrapHelper.java +++ b/edu.harvard.i2b2.server-common/src/main/java/edu/harvard/i2b2/common/util/jaxb/JAXBUnWrapHelper.java @@ -1,48 +1,48 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.common.util.jaxb; - -import java.util.List; - -import jakarta.xml.bind.JAXBElement; - -//import jakarta.xml.bind.JAXBElement; - - -public class JAXBUnWrapHelper { - public JAXBUnWrapHelper() { - } - - public Object getObjectByClass(List listType, Class requestClass) - throws JAXBUtilException { - Object returnObject = null; - - if (listType == null) { - throw new JAXBUtilException("Input list is null"); - } - - for (Object so : listType) { - Object object = null; - - if (so instanceof JAXBElement) { - object = ((JAXBElement) so).getValue(); - } else { - object = so; - } - - Class objClass = object.getClass(); - - if (objClass.equals(requestClass)) { - returnObject = object; - } - } - - return returnObject; - } -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.common.util.jaxb; + +import java.util.List; + +import jakarta.xml.bind.JAXBElement; + +//import jakarta.xml.bind.JAXBElement; + + +public class JAXBUnWrapHelper { + public JAXBUnWrapHelper() { + } + + public Object getObjectByClass(List listType, Class requestClass) + throws JAXBUtilException { + Object returnObject = null; + + if (listType == null) { + throw new JAXBUtilException("Input list is null"); + } + + for (Object so : listType) { + Object object = null; + + if (so instanceof JAXBElement) { + object = ((JAXBElement) so).getValue(); + } else { + object = so; + } + + Class objClass = object.getClass(); + + if (objClass.equals(requestClass)) { + returnObject = object; + } + } + + return returnObject; + } +} diff --git a/edu.harvard.i2b2.server-common/src/core/edu/harvard/i2b2/common/util/jaxb/JAXBUtil.java b/edu.harvard.i2b2.server-common/src/main/java/edu/harvard/i2b2/common/util/jaxb/JAXBUtil.java old mode 100755 new mode 100644 similarity index 96% rename from edu.harvard.i2b2.server-common/src/core/edu/harvard/i2b2/common/util/jaxb/JAXBUtil.java rename to edu.harvard.i2b2.server-common/src/main/java/edu/harvard/i2b2/common/util/jaxb/JAXBUtil.java index bd5c8bc9..121d9f4d --- a/edu.harvard.i2b2.server-common/src/core/edu/harvard/i2b2/common/util/jaxb/JAXBUtil.java +++ b/edu.harvard.i2b2.server-common/src/main/java/edu/harvard/i2b2/common/util/jaxb/JAXBUtil.java @@ -1,321 +1,321 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.common.util.jaxb; - -//import com.sun.org.apache.xml.internal.serialize.OutputFormat; -//import com.sun.org.apache.xml.internal.serialize.XMLSerializer; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.glassfish.jaxb.core.marshaller.NoEscapeHandler; -import org.w3c.dom.Document; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; -import org.xml.sax.SAXNotRecognizedException; -import org.xml.sax.SAXNotSupportedException; - -import jakarta.xml.bind.JAXBContext; -import jakarta.xml.bind.JAXBElement; -import jakarta.xml.bind.JAXBException; -import jakarta.xml.bind.Marshaller; -import jakarta.xml.bind.Unmarshaller; - -import java.io.File; -import java.io.InputStream; -import java.io.StringReader; -import java.io.Writer; -import java.util.ArrayList; - -//import jakarta.xml.bind.JAXBContext; -//import jakarta.xml.bind.JAXBElement; -//import jakarta.xml.bind.JAXBException; -//import jakarta.xml.bind.Marshaller; -//import jakarta.xml.bind.Unmarshaller; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.parsers.SAXParserFactory; -import javax.xml.transform.Source; -import javax.xml.transform.sax.SAXSource; - - -public class JAXBUtil { - private static Log log = LogFactory.getLog(JAXBUtil.class); - private String allPackageName = null; - private Class jaxbClass = null; - private JAXBContext jaxbContext = null; - - /** - * Default Constructor - * - */ - protected JAXBUtil() { - } - - /** - * Constructor to accept package name in String array - * - * @param packageName - */ - public JAXBUtil(String[] packageName) { - StringBuffer givenPackageName = new StringBuffer(); - - for (int i = 0; i < packageName.length; i++) { - givenPackageName.append(packageName[i]); - - if ((i + 1) < packageName.length) { - givenPackageName.append(":"); - } - } - - allPackageName = givenPackageName.toString(); - } - - public JAXBUtil(Class jaxbClass) { - this.jaxbClass = jaxbClass; - } - - private JAXBContext getJAXBContext() throws JAXBException { - - if (jaxbContext == null) { - if (jaxbClass != null) { - log.debug("JaxbClass is " + jaxbClass); - jaxbContext = JAXBContext.newInstance(jaxbClass); - } - else { - log.debug("AllPackageName is " + allPackageName); - jaxbContext = JAXBContext.newInstance(allPackageName,getClass().getClassLoader()); - } - } - - return jaxbContext; - } - - /** - * - * @param requestMessageType - * @param doc - * @throws JAXBUtilException - */ - public void marshaller(JAXBElement jaxbElement, Document doc) - throws JAXBUtilException { - try { - JAXBContext jaxbContext = getJAXBContext(); - Marshaller marshaller = jaxbContext.createMarshaller(); - /* MM - marshaller.setProperty("com.sun.xml.bind.xmlDeclaration",Boolean.TRUE); - marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, - Boolean.TRUE); - marshaller.setProperty( "jaxb.encoding", "UTF-8" ); - marshaller.setProperty( - "com.sun.xml.bind.characterEscapeHandler", - new XmlCharacterEscapeHandler() ); - */ - marshaller.marshal(jaxbElement, doc); - } catch (JAXBException jaxbEx) { - jaxbEx.printStackTrace(); - throw new JAXBUtilException("Error during marshalling ", jaxbEx); - } - } - - public void marshallerWithCDATA(Object element, Writer strWriter, String[] cdataElements) - throws JAXBUtilException { - marshallerWithCDATA( element, strWriter,cdataElements, false); - - } - - public void marshallerWithCDATA(Object element, Writer strWriter, String[] cdataElements, boolean useGlassFish) - throws JAXBUtilException { - try { - JAXBContext jaxbContext = getJAXBContext(); - Marshaller marshaller = jaxbContext.createMarshaller(); - marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, - Boolean.TRUE); - - if (useGlassFish) { - marshaller.setProperty("org.glassfish.jaxb.characterEscapeHandler", new NoEscapeHandler()); - } - //else { - // marshaller.setProperty("com.sun.xml.bind.xmlDeclaration",Boolean.TRUE); - //} - - marshaller.marshal(element, strWriter); - - } catch (Exception jaxbEx) { - jaxbEx.printStackTrace(); - throw new JAXBUtilException("Error during marshalling ", jaxbEx); - } - - } - - - /** - * - * @param requestMessageType - * @param strWriter - * @param splCharFilterFlag - * @throws JAXBUtilException - */ - public void marshaller(Object element, Writer strWriter, boolean splCharFilterFlag) - throws JAXBUtilException { - try { - - JAXBContext jaxbContext = getJAXBContext(); - Marshaller marshaller = jaxbContext.createMarshaller(); - //marshaller.setProperty("com.sun.xml.bind.xmlDeclaration",Boolean.TRUE); - marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, - Boolean.TRUE); - - - //character escape - if (splCharFilterFlag) { - marshaller.setProperty( "jaxb.encoding", "UTF-8" ); - // marshaller.setProperty( - // "com.sun.xml.bind.characterEscapeHandler", - // new XmlCharacterEscapeHandler() ); - } - - - - marshaller.marshal(element, strWriter); - } catch (Exception jaxbEx) { - jaxbEx.printStackTrace(); - throw new JAXBUtilException("Error during marshalling ", jaxbEx); - } - - } - - /** - * - * @param requestMessageType - * @param strWriter - * @throws JAXBUtilException - */ - public void marshaller(Object element, Writer strWriter) - throws JAXBUtilException { - marshaller(element, strWriter,false); - } - - - - public JAXBElement unMashallFromString(String xmlString) - throws JAXBUtilException { - if (xmlString == null) { - throw new JAXBUtilException("String value is Null"); - } - - JAXBElement jaxbElement = unmashalFromString(xmlString); - - return jaxbElement; - } - - public JAXBElement unMarshalFromInputStream(InputStream is) - throws JAXBUtilException { - if (is == null) { - throw new JAXBUtilException("Input Stream is Null"); - } - - JAXBElement jaxbElement = unmarshalFromInputStream(is); - - return jaxbElement; - } - - public JAXBElement unMashallFromDocument(Document doc) - throws JAXBUtilException { - if (doc == null) { - throw new JAXBUtilException("Document value is Null"); - } - - JAXBElement jaxbElement = unmashalFromDocument(doc); - - return jaxbElement; - } - - public JAXBElement unMashallerRequest(String fileName) - throws JAXBUtilException { - if (fileName == null) { - throw new JAXBUtilException("File name is Null"); - } - - JAXBElement jaxbElement = null; - - try { - JAXBContext jaxbContext = getJAXBContext(); - Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); - jaxbElement = (JAXBElement) unmarshaller.unmarshal(new File( - fileName)); - } catch (JAXBException jaxbEx) { - throw new JAXBUtilException("Error during unmarshall ", jaxbEx); - } - - return jaxbElement; - } - - private JAXBElement unmashalFromDocument(Document doc) - throws JAXBUtilException { - JAXBElement unMarshallObject = null; - - try { - JAXBContext jaxbContext = getJAXBContext(); - Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); - unMarshallObject = (JAXBElement) unmarshaller.unmarshal(doc); - } catch (JAXBException jaxbEx) { - throw new JAXBUtilException("Error during unmarshall ", jaxbEx); - } - - return unMarshallObject; - } - - private JAXBElement unmashalFromString(String xmlString) - throws JAXBUtilException { - JAXBElement unMarshallObject = null; - - try { - //Disable XXE - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setFeature("http://xml.org/sax/features/external-general-entities", false); - spf.setFeature("http://xml.org/sax/features/external-parameter-entities", false); - spf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); - - - //Do unmarshall operation - Source xmlSource = new SAXSource(spf.newSAXParser().getXMLReader(), - new InputSource(new StringReader(xmlString))); - - - JAXBContext jaxbContext = getJAXBContext(); - Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); - unMarshallObject = (JAXBElement) unmarshaller.unmarshal(new StringReader( - xmlString)); - log.debug("object.toString()" + - unMarshallObject.getDeclaredType().getCanonicalName()); - } catch (JAXBException | SAXException | ParserConfigurationException jaxbEx) { - throw new JAXBUtilException("Error during unmarshall ", jaxbEx); - } - - return unMarshallObject; - } - - private JAXBElement unmarshalFromInputStream(InputStream is) throws JAXBUtilException { - JAXBElement unMarshallObject = null; - - try { - JAXBContext jaxbContext = getJAXBContext(); - Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); - - unMarshallObject = (JAXBElement) unmarshaller.unmarshal(is); - log.debug("object.toString()" + - unMarshallObject.getDeclaredType().getCanonicalName()); - } catch (JAXBException jaxbEx) { - throw new JAXBUtilException("Error during unmarshall ", jaxbEx); - } - - return unMarshallObject; - } - - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.common.util.jaxb; + +//import com.sun.org.apache.xml.internal.serialize.OutputFormat; +//import com.sun.org.apache.xml.internal.serialize.XMLSerializer; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.glassfish.jaxb.core.marshaller.NoEscapeHandler; +import org.w3c.dom.Document; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; +import org.xml.sax.SAXNotRecognizedException; +import org.xml.sax.SAXNotSupportedException; + +import jakarta.xml.bind.JAXBContext; +import jakarta.xml.bind.JAXBElement; +import jakarta.xml.bind.JAXBException; +import jakarta.xml.bind.Marshaller; +import jakarta.xml.bind.Unmarshaller; + +import java.io.File; +import java.io.InputStream; +import java.io.StringReader; +import java.io.Writer; +import java.util.ArrayList; + +//import jakarta.xml.bind.JAXBContext; +//import jakarta.xml.bind.JAXBElement; +//import jakarta.xml.bind.JAXBException; +//import jakarta.xml.bind.Marshaller; +//import jakarta.xml.bind.Unmarshaller; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.parsers.SAXParserFactory; +import javax.xml.transform.Source; +import javax.xml.transform.sax.SAXSource; + + +public class JAXBUtil { + private static Log log = LogFactory.getLog(JAXBUtil.class); + private String allPackageName = null; + private Class jaxbClass = null; + private JAXBContext jaxbContext = null; + + /** + * Default Constructor + * + */ + protected JAXBUtil() { + } + + /** + * Constructor to accept package name in String array + * + * @param packageName + */ + public JAXBUtil(String[] packageName) { + StringBuffer givenPackageName = new StringBuffer(); + + for (int i = 0; i < packageName.length; i++) { + givenPackageName.append(packageName[i]); + + if ((i + 1) < packageName.length) { + givenPackageName.append(":"); + } + } + + allPackageName = givenPackageName.toString(); + } + + public JAXBUtil(Class jaxbClass) { + this.jaxbClass = jaxbClass; + } + + private JAXBContext getJAXBContext() throws JAXBException { + + if (jaxbContext == null) { + if (jaxbClass != null) { + log.debug("JaxbClass is " + jaxbClass); + jaxbContext = JAXBContext.newInstance(jaxbClass); + } + else { + log.debug("AllPackageName is " + allPackageName); + jaxbContext = JAXBContext.newInstance(allPackageName,getClass().getClassLoader()); + } + } + + return jaxbContext; + } + + /** + * + * @param requestMessageType + * @param doc + * @throws JAXBUtilException + */ + public void marshaller(JAXBElement jaxbElement, Document doc) + throws JAXBUtilException { + try { + JAXBContext jaxbContext = getJAXBContext(); + Marshaller marshaller = jaxbContext.createMarshaller(); + /* MM + marshaller.setProperty("com.sun.xml.bind.xmlDeclaration",Boolean.TRUE); + marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, + Boolean.TRUE); + marshaller.setProperty( "jaxb.encoding", "UTF-8" ); + marshaller.setProperty( + "com.sun.xml.bind.characterEscapeHandler", + new XmlCharacterEscapeHandler() ); + */ + marshaller.marshal(jaxbElement, doc); + } catch (JAXBException jaxbEx) { + jaxbEx.printStackTrace(); + throw new JAXBUtilException("Error during marshalling ", jaxbEx); + } + } + + public void marshallerWithCDATA(Object element, Writer strWriter, String[] cdataElements) + throws JAXBUtilException { + marshallerWithCDATA( element, strWriter,cdataElements, false); + + } + + public void marshallerWithCDATA(Object element, Writer strWriter, String[] cdataElements, boolean useGlassFish) + throws JAXBUtilException { + try { + JAXBContext jaxbContext = getJAXBContext(); + Marshaller marshaller = jaxbContext.createMarshaller(); + marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, + Boolean.TRUE); + + if (useGlassFish) { + marshaller.setProperty("org.glassfish.jaxb.characterEscapeHandler", new NoEscapeHandler()); + } + //else { + // marshaller.setProperty("com.sun.xml.bind.xmlDeclaration",Boolean.TRUE); + //} + + marshaller.marshal(element, strWriter); + + } catch (Exception jaxbEx) { + jaxbEx.printStackTrace(); + throw new JAXBUtilException("Error during marshalling ", jaxbEx); + } + + } + + + /** + * + * @param requestMessageType + * @param strWriter + * @param splCharFilterFlag + * @throws JAXBUtilException + */ + public void marshaller(Object element, Writer strWriter, boolean splCharFilterFlag) + throws JAXBUtilException { + try { + + JAXBContext jaxbContext = getJAXBContext(); + Marshaller marshaller = jaxbContext.createMarshaller(); + //marshaller.setProperty("com.sun.xml.bind.xmlDeclaration",Boolean.TRUE); + marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, + Boolean.TRUE); + + + //character escape + if (splCharFilterFlag) { + marshaller.setProperty( "jaxb.encoding", "UTF-8" ); + // marshaller.setProperty( + // "com.sun.xml.bind.characterEscapeHandler", + // new XmlCharacterEscapeHandler() ); + } + + + + marshaller.marshal(element, strWriter); + } catch (Exception jaxbEx) { + jaxbEx.printStackTrace(); + throw new JAXBUtilException("Error during marshalling ", jaxbEx); + } + + } + + /** + * + * @param requestMessageType + * @param strWriter + * @throws JAXBUtilException + */ + public void marshaller(Object element, Writer strWriter) + throws JAXBUtilException { + marshaller(element, strWriter,false); + } + + + + public JAXBElement unMashallFromString(String xmlString) + throws JAXBUtilException { + if (xmlString == null) { + throw new JAXBUtilException("String value is Null"); + } + + JAXBElement jaxbElement = unmashalFromString(xmlString); + + return jaxbElement; + } + + public JAXBElement unMarshalFromInputStream(InputStream is) + throws JAXBUtilException { + if (is == null) { + throw new JAXBUtilException("Input Stream is Null"); + } + + JAXBElement jaxbElement = unmarshalFromInputStream(is); + + return jaxbElement; + } + + public JAXBElement unMashallFromDocument(Document doc) + throws JAXBUtilException { + if (doc == null) { + throw new JAXBUtilException("Document value is Null"); + } + + JAXBElement jaxbElement = unmashalFromDocument(doc); + + return jaxbElement; + } + + public JAXBElement unMashallerRequest(String fileName) + throws JAXBUtilException { + if (fileName == null) { + throw new JAXBUtilException("File name is Null"); + } + + JAXBElement jaxbElement = null; + + try { + JAXBContext jaxbContext = getJAXBContext(); + Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); + jaxbElement = (JAXBElement) unmarshaller.unmarshal(new File( + fileName)); + } catch (JAXBException jaxbEx) { + throw new JAXBUtilException("Error during unmarshall ", jaxbEx); + } + + return jaxbElement; + } + + private JAXBElement unmashalFromDocument(Document doc) + throws JAXBUtilException { + JAXBElement unMarshallObject = null; + + try { + JAXBContext jaxbContext = getJAXBContext(); + Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); + unMarshallObject = (JAXBElement) unmarshaller.unmarshal(doc); + } catch (JAXBException jaxbEx) { + throw new JAXBUtilException("Error during unmarshall ", jaxbEx); + } + + return unMarshallObject; + } + + private JAXBElement unmashalFromString(String xmlString) + throws JAXBUtilException { + JAXBElement unMarshallObject = null; + + try { + //Disable XXE + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setFeature("http://xml.org/sax/features/external-general-entities", false); + spf.setFeature("http://xml.org/sax/features/external-parameter-entities", false); + spf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); + + + //Do unmarshall operation + Source xmlSource = new SAXSource(spf.newSAXParser().getXMLReader(), + new InputSource(new StringReader(xmlString))); + + + JAXBContext jaxbContext = getJAXBContext(); + Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); + unMarshallObject = (JAXBElement) unmarshaller.unmarshal(new StringReader( + xmlString)); + log.debug("object.toString()" + + unMarshallObject.getDeclaredType().getCanonicalName()); + } catch (JAXBException | SAXException | ParserConfigurationException jaxbEx) { + throw new JAXBUtilException("Error during unmarshall ", jaxbEx); + } + + return unMarshallObject; + } + + private JAXBElement unmarshalFromInputStream(InputStream is) throws JAXBUtilException { + JAXBElement unMarshallObject = null; + + try { + JAXBContext jaxbContext = getJAXBContext(); + Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); + + unMarshallObject = (JAXBElement) unmarshaller.unmarshal(is); + log.debug("object.toString()" + + unMarshallObject.getDeclaredType().getCanonicalName()); + } catch (JAXBException jaxbEx) { + throw new JAXBUtilException("Error during unmarshall ", jaxbEx); + } + + return unMarshallObject; + } + + +} diff --git a/edu.harvard.i2b2.server-common/src/core/edu/harvard/i2b2/common/util/jaxb/JAXBUtilException.java b/edu.harvard.i2b2.server-common/src/main/java/edu/harvard/i2b2/common/util/jaxb/JAXBUtilException.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.server-common/src/core/edu/harvard/i2b2/common/util/jaxb/JAXBUtilException.java rename to edu.harvard.i2b2.server-common/src/main/java/edu/harvard/i2b2/common/util/jaxb/JAXBUtilException.java diff --git a/edu.harvard.i2b2.server-common/src/main/java/edu/harvard/i2b2/common/util/jaxb/XmlCharacterEscapeHandler.java b/edu.harvard.i2b2.server-common/src/main/java/edu/harvard/i2b2/common/util/jaxb/XmlCharacterEscapeHandler.java new file mode 100644 index 00000000..aeb84e2b --- /dev/null +++ b/edu.harvard.i2b2.server-common/src/main/java/edu/harvard/i2b2/common/util/jaxb/XmlCharacterEscapeHandler.java @@ -0,0 +1,82 @@ +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.common.util.jaxb; + +import java.io.IOException; +import java.io.Writer; + +import org.apache.xml.utils.XML11Char; +//import org.eclipse.tags.shaded.org.apache.xml.utils.XML11Char; +import org.glassfish.jaxb.core.marshaller.CharacterEscapeHandler; + +public class XmlCharacterEscapeHandler implements CharacterEscapeHandler { + + /** + * Escape characters inside the buffer and send the output to the writer. + * + * @exception IOException + * if something goes wrong, IOException can be thrown to stop the + * marshalling process. + */ + @Override + public void escape(char[] buf, int start, int len, boolean isAttValue, + Writer out) throws IOException { + for (int i = start; i < (start + len); i++) { + char ch = buf[i]; + + // you are supposed to do the standard XML character escapes + // like & ... & < ... < etc + if (ch == '&') { + out.write("&"); + + continue; + } + + if (ch == '<') { + out.write("<"); + continue; + } + + if (ch == '>') { + out.write(">"); + continue; + } + + if ((ch == '"') && isAttValue) { + // isAttValue is set to true when the marshaller is processing + // attribute values. Inside attribute values, there are more + // things you need to escape, usually. + out.write("""); + + continue; + } + + if ((ch == '\'') && isAttValue) { + out.write("'"); + + continue; + } + + // you should handle other characters like < or > + if (ch > 0x7F) { + // escape everything above ASCII to &#xXXXX; + out.write("&#x"); + out.write(Integer.toHexString(ch)); + out.write(";"); + + continue; + } + + //use apache util to check for valid xml character + if (XML11Char.isXML11Valid(ch)) { + out.write(ch); + } + } + } +} diff --git a/edu.harvard.i2b2.server-common/src/core/edu/harvard/i2b2/common/util/xml/XMLOperatorLookup.java b/edu.harvard.i2b2.server-common/src/main/java/edu/harvard/i2b2/common/util/xml/XMLOperatorLookup.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.server-common/src/core/edu/harvard/i2b2/common/util/xml/XMLOperatorLookup.java rename to edu.harvard.i2b2.server-common/src/main/java/edu/harvard/i2b2/common/util/xml/XMLOperatorLookup.java diff --git a/edu.harvard.i2b2.server-common/src/core/edu/harvard/i2b2/common/util/xml/XMLUtil.java b/edu.harvard.i2b2.server-common/src/main/java/edu/harvard/i2b2/common/util/xml/XMLUtil.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.server-common/src/core/edu/harvard/i2b2/common/util/xml/XMLUtil.java rename to edu.harvard.i2b2.server-common/src/main/java/edu/harvard/i2b2/common/util/xml/XMLUtil.java diff --git a/edu.harvard.i2b2.server-common/src/test/.blank b/edu.harvard.i2b2.server-common/src/test/.blank deleted file mode 100755 index e69de29b..00000000 diff --git a/edu.harvard.i2b2.workplace/.classpath b/edu.harvard.i2b2.workplace/.classpath index cc709a3b..b9f6029d 100755 --- a/edu.harvard.i2b2.workplace/.classpath +++ b/edu.harvard.i2b2.workplace/.classpath @@ -1,153 +1,46 @@ - - - - - - - - - - - - - + - + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/edu.harvard.i2b2.workplace/.cvsignore b/edu.harvard.i2b2.workplace/.cvsignore deleted file mode 100755 index 009b250a..00000000 --- a/edu.harvard.i2b2.workplace/.cvsignore +++ /dev/null @@ -1,3 +0,0 @@ -gensrc -classes -genlib diff --git a/edu.harvard.i2b2.workplace/.gitignore b/edu.harvard.i2b2.workplace/.gitignore deleted file mode 100644 index ae3c1726..00000000 --- a/edu.harvard.i2b2.workplace/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/bin/ diff --git a/edu.harvard.i2b2.workplace/.project b/edu.harvard.i2b2.workplace/.project index 5b634944..824ca445 100755 --- a/edu.harvard.i2b2.workplace/.project +++ b/edu.harvard.i2b2.workplace/.project @@ -10,8 +10,14 @@ + + org.eclipse.m2e.core.maven2Builder + + + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature diff --git a/edu.harvard.i2b2.workplace/LICENSE.txt b/edu.harvard.i2b2.workplace/LICENSE.txt deleted file mode 100644 index e5a5569a..00000000 --- a/edu.harvard.i2b2.workplace/LICENSE.txt +++ /dev/null @@ -1,406 +0,0 @@ -#------------------------------------------------------------------------------- -# Copyright (c) 2006-2018 Massachusetts General Hospital -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Mozilla Public License, -# v. 2.0. If a copy of the MPL was not distributed with this file, You can -# obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under -# the terms of the Healthcare Disclaimer. -#------------------------------------------------------------------------------- -Mozilla Public License, version 2.0 - -1. Definitions - -1.1. "Contributor" - - means each individual or legal entity that creates, contributes to the - creation of, or owns Covered Software. - -1.2. "Contributor Version" - - means the combination of the Contributions of others (if any) used by a - Contributor and that particular Contributor's Contribution. - -1.3. "Contribution" - - means Covered Software of a particular Contributor. - -1.4. "Covered Software" - - means Source Code Form to which the initial Contributor has attached the - notice in Exhibit A, the Executable Form of such Source Code Form, and - Modifications of such Source Code Form, in each case including portions - thereof. - -1.5. "Incompatible With Secondary Licenses" - means - - a. that the initial Contributor has attached the notice described in - Exhibit B to the Covered Software; or - - b. that the Covered Software was made available under the terms of - version 1.1 or earlier of the License, but not also under the terms of - a Secondary License. - -1.6. "Executable Form" - - means any form of the work other than Source Code Form. - -1.7. "Larger Work" - - means a work that combines Covered Software with other material, in a - separate file or files, that is not Covered Software. - -1.8. "License" - - means this document. - -1.9. "Licensable" - - means having the right to grant, to the maximum extent possible, whether - at the time of the initial grant or subsequently, any and all of the - rights conveyed by this License. - -1.10. "Modifications" - - means any of the following: - - a. any file in Source Code Form that results from an addition to, - deletion from, or modification of the contents of Covered Software; or - - b. any new file in Source Code Form that contains any Covered Software. - -1.11. "Patent Claims" of a Contributor - - means any patent claim(s), including without limitation, method, - process, and apparatus claims, in any patent Licensable by such - Contributor that would be infringed, but for the grant of the License, - by the making, using, selling, offering for sale, having made, import, - or transfer of either its Contributions or its Contributor Version. - -1.12. "Secondary License" - - means either the GNU General Public License, Version 2.0, the GNU Lesser - General Public License, Version 2.1, the GNU Affero General Public - License, Version 3.0, or any later versions of those licenses. - -1.13. "Source Code Form" - - means the form of the work preferred for making modifications. - -1.14. "You" (or "Your") - - means an individual or a legal entity exercising rights under this - License. For legal entities, "You" includes any entity that controls, is - controlled by, or is under common control with You. For purposes of this - definition, "control" means (a) the power, direct or indirect, to cause - the direction or management of such entity, whether by contract or - otherwise, or (b) ownership of more than fifty percent (50%) of the - outstanding shares or beneficial ownership of such entity. - - -2. License Grants and Conditions - -2.1. Grants - - Each Contributor hereby grants You a world-wide, royalty-free, - non-exclusive license: - - a. under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or - as part of a Larger Work; and - - b. under Patent Claims of such Contributor to make, use, sell, offer for - sale, have made, import, and otherwise transfer either its - Contributions or its Contributor Version. - -2.2. Effective Date - - The licenses granted in Section 2.1 with respect to any Contribution - become effective for each Contribution on the date the Contributor first - distributes such Contribution. - -2.3. Limitations on Grant Scope - - The licenses granted in this Section 2 are the only rights granted under - this License. No additional rights or licenses will be implied from the - distribution or licensing of Covered Software under this License. - Notwithstanding Section 2.1(b) above, no patent license is granted by a - Contributor: - - a. for any code that a Contributor has removed from Covered Software; or - - b. for infringements caused by: (i) Your and any other third party's - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - - c. under Patent Claims infringed by Covered Software in the absence of - its Contributions. - - This License does not grant any rights in the trademarks, service marks, - or logos of any Contributor (except as may be necessary to comply with - the notice requirements in Section 3.4). - -2.4. Subsequent Licenses - - No Contributor makes additional grants as a result of Your choice to - distribute the Covered Software under a subsequent version of this - License (see Section 10.2) or under the terms of a Secondary License (if - permitted under the terms of Section 3.3). - -2.5. Representation - - Each Contributor represents that the Contributor believes its - Contributions are its original creation(s) or it has sufficient rights to - grant the rights to its Contributions conveyed by this License. - -2.6. Fair Use - - This License is not intended to limit any rights You have under - applicable copyright doctrines of fair use, fair dealing, or other - equivalents. - -2.7. Conditions - - Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in - Section 2.1. - - -3. Responsibilities - -3.1. Distribution of Source Form - - All distribution of Covered Software in Source Code Form, including any - Modifications that You create or to which You contribute, must be under - the terms of this License. You must inform recipients that the Source - Code Form of the Covered Software is governed by the terms of this - License, and how they can obtain a copy of this License. You may not - attempt to alter or restrict the recipients' rights in the Source Code - Form. - -3.2. Distribution of Executable Form - - If You distribute Covered Software in Executable Form then: - - a. such Covered Software must also be made available in Source Code Form, - as described in Section 3.1, and You must inform recipients of the - Executable Form how they can obtain a copy of such Source Code Form by - reasonable means in a timely manner, at a charge no more than the cost - of distribution to the recipient; and - - b. You may distribute such Executable Form under the terms of this - License, or sublicense it under different terms, provided that the - license for the Executable Form does not attempt to limit or alter the - recipients' rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - - You may create and distribute a Larger Work under terms of Your choice, - provided that You also comply with the requirements of this License for - the Covered Software. If the Larger Work is a combination of Covered - Software with a work governed by one or more Secondary Licenses, and the - Covered Software is not Incompatible With Secondary Licenses, this - License permits You to additionally distribute such Covered Software - under the terms of such Secondary License(s), so that the recipient of - the Larger Work may, at their option, further distribute the Covered - Software under the terms of either this License or such Secondary - License(s). - -3.4. Notices - - You may not remove or alter the substance of any license notices - (including copyright notices, patent notices, disclaimers of warranty, or - limitations of liability) contained within the Source Code Form of the - Covered Software, except that You may alter any license notices to the - extent required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - - You may choose to offer, and to charge a fee for, warranty, support, - indemnity or liability obligations to one or more recipients of Covered - Software. However, You may do so only on Your own behalf, and not on - behalf of any Contributor. You must make it absolutely clear that any - such warranty, support, indemnity, or liability obligation is offered by - You alone, and You hereby agree to indemnify every Contributor for any - liability incurred by such Contributor as a result of warranty, support, - indemnity or liability terms You offer. You may include additional - disclaimers of warranty and limitations of liability specific to any - jurisdiction. - -4. Inability to Comply Due to Statute or Regulation - - If it is impossible for You to comply with any of the terms of this License - with respect to some or all of the Covered Software due to statute, - judicial order, or regulation then You must: (a) comply with the terms of - this License to the maximum extent possible; and (b) describe the - limitations and the code they affect. Such description must be placed in a - text file included with all distributions of the Covered Software under - this License. Except to the extent prohibited by statute or regulation, - such description must be sufficiently detailed for a recipient of ordinary - skill to be able to understand it. - -5. Termination - -5.1. The rights granted under this License will terminate automatically if You - fail to comply with any of its terms. However, if You become compliant, - then the rights granted under this License from a particular Contributor - are reinstated (a) provisionally, unless and until such Contributor - explicitly and finally terminates Your grants, and (b) on an ongoing - basis, if such Contributor fails to notify You of the non-compliance by - some reasonable means prior to 60 days after You have come back into - compliance. Moreover, Your grants from a particular Contributor are - reinstated on an ongoing basis if such Contributor notifies You of the - non-compliance by some reasonable means, this is the first time You have - received notice of non-compliance with this License from such - Contributor, and You become compliant prior to 30 days after Your receipt - of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent - infringement claim (excluding declaratory judgment actions, - counter-claims, and cross-claims) alleging that a Contributor Version - directly or indirectly infringes any patent, then the rights granted to - You by any and all Contributors for the Covered Software under Section - 2.1 of this License shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user - license agreements (excluding distributors and resellers) which have been - validly granted by You or Your distributors under this License prior to - termination shall survive termination. - -6. Disclaimer of Warranty - - Covered Software is provided under this License on an "as is" basis, - without warranty of any kind, either expressed, implied, or statutory, - including, without limitation, warranties that the Covered Software is free - of defects, merchantable, fit for a particular purpose or non-infringing. - The entire risk as to the quality and performance of the Covered Software - is with You. Should any Covered Software prove defective in any respect, - You (not any Contributor) assume the cost of any necessary servicing, - repair, or correction. This disclaimer of warranty constitutes an essential - part of this License. No use of any Covered Software is authorized under - this License except under this disclaimer. - -7. Limitation of Liability - - Under no circumstances and under no legal theory, whether tort (including - negligence), contract, or otherwise, shall any Contributor, or anyone who - distributes Covered Software as permitted above, be liable to You for any - direct, indirect, special, incidental, or consequential damages of any - character including, without limitation, damages for lost profits, loss of - goodwill, work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses, even if such party shall have been - informed of the possibility of such damages. This limitation of liability - shall not apply to liability for death or personal injury resulting from - such party's negligence to the extent applicable law prohibits such - limitation. Some jurisdictions do not allow the exclusion or limitation of - incidental or consequential damages, so this exclusion and limitation may - not apply to You. - -8. Litigation - - Any litigation relating to this License may be brought only in the courts - of a jurisdiction where the defendant maintains its principal place of - business and such litigation shall be governed by laws of that - jurisdiction, without reference to its conflict-of-law provisions. Nothing - in this Section shall prevent a party's ability to bring cross-claims or - counter-claims. - -9. Miscellaneous - - This License represents the complete agreement concerning the subject - matter hereof. If any provision of this License is held to be - unenforceable, such provision shall be reformed only to the extent - necessary to make it enforceable. Any law or regulation which provides that - the language of a contract shall be construed against the drafter shall not - be used to construe this License against a Contributor. - - -10. Versions of the License - -10.1. New Versions - - Mozilla Foundation is the license steward. Except as provided in Section - 10.3, no one other than the license steward has the right to modify or - publish new versions of this License. Each version will be given a - distinguishing version number. - -10.2. Effect of New Versions - - You may distribute the Covered Software under the terms of the version - of the License under which You originally received the Covered Software, - or under the terms of any subsequent version published by the license - steward. - -10.3. Modified Versions - - If you create software not governed by this License, and you want to - create a new license for such software, you may create and use a - modified version of this License if you rename the license and remove - any references to the name of the license steward (except to note that - such modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary - Licenses If You choose to distribute Source Code Form that is - Incompatible With Secondary Licenses under the terms of this version of - the License, the notice described in Exhibit B of this License must be - attached. - -Exhibit A - Source Code Form License Notice - - This Source Code Form is subject to the - terms of the Mozilla Public License, v. - 2.0. If a copy of the MPL was not - distributed with this file, You can - obtain one at - http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular file, -then You may include the notice in a location (such as a LICENSE file in a -relevant directory) where a recipient would be likely to look for such a -notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - "Incompatible With Secondary Licenses" Notice - - This Source Code Form is "Incompatible - With Secondary Licenses", as defined by - the Mozilla Public License, v. 2.0. - ---------------------- - -Healthcare Disclaimer - -In the United States, or any other jurisdictions where they may apply, the -following additional disclaimer of warranty and limitation of liability are -hereby incorporated into the terms and conditions of MPL 2.0: - -1. No warranties of any kind whatsoever are made as to the results that - You will obtain from relying upon the covered code (or any information - or content obtained by way of the covered code), including but not - limited to compliance with privacy laws or regulations or clinical - care industry standards and protocols. Use of the covered code is not - a substitute for a health care provider’s standard practice or - professional judgment. Any decision with regard to the appropriateness - of treatment, or the validity or reliability of information or content - made available by the covered code, is the sole responsibility of the - health care provider. Consequently, it is incumbent upon each health - care provider to verify all medical history and treatment plans with - each patient. - -2. Under no circumstances and under no legal theory, whether tort - (including negligence), contract, or otherwise, shall any Contributor, - or anyone who distributes Covered Software as permitted by the - license, be liable to You for any indirect, special, incidental, - consequential damages of any character including, without limitation, - damages for loss of goodwill, work stoppage, computer failure or - malfunction, or any and all other damages or losses, of any nature - whatsoever (direct or otherwise) on account of or associated with the - use or inability to use the covered content (including, without - limitation, the use of information or content made available by the - covered code, all documentation associated therewith, and the failure - of the covered code to comply with privacy laws and regulations or - clinical care industry standards and protocols), even if such party - shall have been informed of the possibility of such damages. diff --git a/edu.harvard.i2b2.workplace/build.properties b/edu.harvard.i2b2.workplace/build.properties deleted file mode 100755 index f48d1b6f..00000000 --- a/edu.harvard.i2b2.workplace/build.properties +++ /dev/null @@ -1,10 +0,0 @@ -#Ant build property file - -## JBOSS HOME -jboss.home=/opt/wildfly-17.0.1.Final -axis2.war.name=i2b2.war - -report=test-reports -testfiledir=testfiles -testhost=http://127.0.0.1:9090/i2b2/services - diff --git a/edu.harvard.i2b2.workplace/build.xml b/edu.harvard.i2b2.workplace/build.xml deleted file mode 100755 index 2a4ad38f..00000000 --- a/edu.harvard.i2b2.workplace/build.xml +++ /dev/null @@ -1,244 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/edu.harvard.i2b2.workplace/data_build.xml b/edu.harvard.i2b2.workplace/data_build.xml deleted file mode 100755 index b646cda9..00000000 --- a/edu.harvard.i2b2.workplace/data_build.xml +++ /dev/null @@ -1,46 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - CREATE USER i2b2demodata IDENTIFIED BY i2b2demodata; - CREATE USER i2b2metadata IDENTIFIED BY i2b2metadata; - - - - - - - - - - - - - - - - - - diff --git a/edu.harvard.i2b2.workplace/master_build.xml b/edu.harvard.i2b2.workplace/master_build.xml deleted file mode 100755 index bb391c43..00000000 --- a/edu.harvard.i2b2.workplace/master_build.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/edu.harvard.i2b2.workplace/pom.xml b/edu.harvard.i2b2.workplace/pom.xml new file mode 100644 index 00000000..e9cea541 --- /dev/null +++ b/edu.harvard.i2b2.workplace/pom.xml @@ -0,0 +1,43 @@ + + 4.0.0 + + edu.harvard.i2b2 + i2b2-parent + 2.0.0-SNAPSHOT + + edu.harvard.i2b2.workplace + jar + workplace Module + + + + + org.codehaus.mojo + build-helper-maven-plugin + 3.0.0 + + + generate-sources + + add-source + + + + gensrc + + + + + + + + + + + edu.harvard.i2b2 + edu.harvard.i2b2.server-common + + + + \ No newline at end of file diff --git a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/dao/DataSourceLookupHelper.java b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/dao/DataSourceLookupHelper.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/dao/DataSourceLookupHelper.java rename to edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/dao/DataSourceLookupHelper.java diff --git a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/dao/DblookupDao.java b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/dao/DblookupDao.java similarity index 100% rename from edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/dao/DblookupDao.java rename to edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/dao/DblookupDao.java diff --git a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/dao/FolderDao.java b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/dao/FolderDao.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/dao/FolderDao.java rename to edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/dao/FolderDao.java index 89d3017b..d06a8931 --- a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/dao/FolderDao.java +++ b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/dao/FolderDao.java @@ -1,1944 +1,1944 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Lori Phillips - */ -package edu.harvard.i2b2.workplace.dao; - -import java.io.IOException; -import java.sql.Clob; -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Date; -import javax.sql.DataSource; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.dao.DataAccessException; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.RowMapper; -import org.springframework.jdbc.core.support.JdbcDaoSupport; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.db.JDBCUtil; -import edu.harvard.i2b2.common.util.jaxb.DTOFactory; -import edu.harvard.i2b2.common.util.xml.XMLUtil; -import edu.harvard.i2b2.workplace.dao.GetFolderMapper; -import edu.harvard.i2b2.workplace.datavo.i2b2message.SecurityType; -import edu.harvard.i2b2.workplace.datavo.pm.ProjectType; -import edu.harvard.i2b2.workplace.datavo.wdo.AnnotateChildType; -import edu.harvard.i2b2.workplace.datavo.wdo.ChildType; -import edu.harvard.i2b2.workplace.datavo.wdo.DblookupType; -import edu.harvard.i2b2.workplace.datavo.wdo.DeleteChildType; -import edu.harvard.i2b2.workplace.datavo.wdo.ExportChildType; -import edu.harvard.i2b2.workplace.datavo.wdo.FolderType; -import edu.harvard.i2b2.workplace.datavo.wdo.GetChildrenType; -import edu.harvard.i2b2.workplace.datavo.wdo.GetReturnType; -import edu.harvard.i2b2.workplace.datavo.wdo.ProtectedType; -import edu.harvard.i2b2.workplace.datavo.wdo.RenameChildType; -import edu.harvard.i2b2.workplace.datavo.wdo.FindByChildType; -import edu.harvard.i2b2.workplace.datavo.wdo.XmlValueType; -import edu.harvard.i2b2.workplace.delegate.crc.CallCRCUtil; -import edu.harvard.i2b2.workplace.ejb.DBInfoType; -import edu.harvard.i2b2.workplace.util.StringUtil; -import edu.harvard.i2b2.workplace.util.WorkplaceUtil; - - -public class FolderDao extends JdbcDaoSupport { - - private static Log log = LogFactory.getLog(FolderDao.class); - protected static Log logesapi = LogFactory.getLog(FolderDao.class); - - // final static String CORE = " c_hierarchy, c_hlevel, c_name, c_user_id, c_group_id, c_share_id, c_index, c_parent_index, c_visualattributes, c_tooltip"; - // final static String DEFAULT = " c_name, c_hierarchy"; - final static String CORE = " c_name, c_user_id, c_group_id, c_protected_access, c_share_id, c_index, c_parent_index, c_visualattributes, c_tooltip"; - final static String DEFAULT = " c_name, c_index, c_protected_access "; - final static String ALL = CORE + ", c_entry_date, c_change_date, c_status_cd"; - final static String BLOB = ", c_work_xml, c_work_xml_schema, c_work_xml_i2b2_type "; - - private JdbcTemplate jt; - private String metadataSchema; - - private void setDataSource(String dataSource) { - DataSource ds = null; - try { - ds = WorkplaceUtil.getInstance().getDataSource(dataSource); - // metadataSchema = ds.getConnection().getSchema() + "."; - Connection conn = ds.getConnection(); - - metadataSchema = conn.getSchema() + "."; - conn.close(); - } catch (I2B2Exception e2) { - log.error(e2.getMessage());; - } catch (SQLException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - this.jt = new JdbcTemplate(ds); - } - - private String getMetadataSchema() throws I2B2Exception{ - - return metadataSchema; //WorkplaceUtil.getInstance().getMetaDataSchemaName(); - } - - - public List findRootFoldersByProject(final GetReturnType returnType, final String userId, final ProjectType projectInfo, final DBInfoType dbInfo) throws DataAccessException, I2B2Exception{ - - // find return parameters - String parameters = CORE; - if (returnType.getType().equals("core")){ - parameters = CORE; - } - /* else if (returnType.getType().equals("all")){ - parameters = ALL; - } - */ - - String metadataSchema = dbInfo.getDb_fullSchema(); - setDataSource(dbInfo.getDb_dataSource()); - - // 1. check if user already has a folder - // if not create one. - check_addRootNode(metadataSchema, userId, projectInfo, dbInfo); - - - // First step is to call PM to see what roles user belongs to. - - if (projectInfo.getRole().size() == 0) - { - log.error("no role found for this user in project: " + projectInfo.getName()); - I2B2Exception e = new I2B2Exception("No role found for user"); - throw e; - } - - boolean protectedAccess = false; - Iterator it = projectInfo.getRole().iterator(); - while (it.hasNext()){ - String role = (String) it.next(); - if(role.toLowerCase().equalsIgnoreCase("DATA_PROT")) { - protectedAccess = true; - break; - } - } - - //ParameterizedRowMapper mapper = getMapper(returnType.getType(), false, null, dbInfo.getDb_serverType()); - - GetFolderMapper mapper = GetTableMapper(returnType.getType(), false, null, dbInfo.getDb_serverType()); - - - List queryResult = null; - if (!protectedAccess){ - String tablesSql = "select distinct(c_table_cd), " + parameters + " from " + metadataSchema + "workplace_access where c_protected_access = ? and LOWER(c_group_id) = ? order by c_name"; //c_hierarchy"; - - try { - queryResult = jt.query(tablesSql, mapper, "N", projectInfo.getId().toLowerCase()); - } catch (DataAccessException e) { - log.error(e.getMessage()); - throw new I2B2DAOException("Database error"); - } - } - else{ - String tablesSql = "select distinct(c_table_cd), " + parameters + " from " + metadataSchema + "workplace_access where LOWER(c_group_id) = ? order by c_name"; //c_hierarchy"; - - try { - queryResult = jt.query(tablesSql, mapper, projectInfo.getId().toLowerCase()); - } catch (DataAccessException e) { - log.error(e.getMessage()); - throw new I2B2DAOException("Database Error"); - } - } - - log.debug("result size = " + queryResult.size()); - - return queryResult; - } - - public List findRootFoldersByUser(final GetReturnType returnType, final String userId, final ProjectType projectInfo, final DBInfoType dbInfo) throws DataAccessException, I2B2Exception{ - - // find return parameters - String parameters = CORE; - if (returnType.getType().equals("core")){ - parameters = CORE; - } - /* else if (returnType.getType().equals("all")){ - parameters = ALL; - } - */ - - String metadataSchema = dbInfo.getDb_fullSchema(); - setDataSource(dbInfo.getDb_dataSource()); - - - // 1. check if user already has a folder - // if not create one. - check_addRootNode(metadataSchema, userId, projectInfo, dbInfo); - - - if (projectInfo.getRole().size() == 0) - { - log.error("no role found for this user in project: " + projectInfo.getName()); - I2B2Exception e = new I2B2Exception("No role found for user"); - throw e; - } - - boolean protectedAccess = false; - Iterator it = projectInfo.getRole().iterator(); - while (it.hasNext()){ - String role = (String) it.next(); - if(role.toLowerCase().equalsIgnoreCase("DATA_PROT")) { - protectedAccess = true; - break; - } - } - - - GetFolderMapper mapper = GetTableMapper(returnType.getType(), false, null, dbInfo.getDb_serverType()); - - List queryResult = null; - if (!protectedAccess){ - String tablesSql = "select distinct(c_table_cd), " + parameters + " from " + metadataSchema + "workplace_access where (c_share_id = 'Y' and LOWER(c_group_id) = ?) or (c_protected_access = ? and LOWER(c_user_id) = ? and LOWER(c_group_id) = ?) order by c_name"; //c_hierarchy"; - - // log.info(tablesSql); - try { - queryResult = jt.query(tablesSql, mapper, projectInfo.getId().toLowerCase(), "N",userId.toLowerCase(), projectInfo.getId().toLowerCase()); - } catch (DataAccessException e) { - log.error(e.getMessage()); - throw new I2B2DAOException("Database error findRootFoldersByUser"); - } - } - else{ - String tablesSql = "select distinct(c_table_cd), " + parameters + " from " + metadataSchema + "workplace_access where (c_share_id = 'Y' and LOWER(c_group_id) = ?) or (LOWER(c_user_id) = ? and LOWER(c_group_id) = ?) order by c_name"; //c_hierarchy"; - try { - queryResult = jt.query(tablesSql, - GetTableMapper(returnType.getType(), false, null, dbInfo.getDb_serverType()) - , projectInfo.getId().toLowerCase(), userId.toLowerCase(), projectInfo.getId().toLowerCase()); - } catch (DataAccessException e) { - log.error(e.getMessage()); - throw new I2B2DAOException("Database Error findRootFoldersByUser 2"); - } - } - /* - ParameterizedRowMapper map = new ParameterizedRowMapper() { - public String mapRow(ResultSet rs, int rowNum) throws SQLException { - String name = "\\\\" + rs.getString("c_table_cd") + "\\" + rs.getString("c_table_name"); - return name; - } - }; - if(queryResult.size() == 0){ - // this means that user is accessing for first time - // grab tableCd tableName pair - // and then insert an entry for the user - String tablesSql = "select distinct(c_table_cd), c_table_name from " + metadataSchema + "workplace_access"; - - try { - queryResult = jt.query(tablesSql, map); - } catch (DataAccessException e) { - log.error(e.getMessage()); - throw new I2B2DAOException("Database Error"); - } - if(queryResult.size() == 0) - throw new I2B2DAOException("Database Error"); - else{ - queryResult= addRootNode((String)queryResult.get(0), userId, projectInfo, dbInfo); - } - }*/ - log.debug("result size = " + queryResult.size()); - - return queryResult; - } - - public void check_addRootNode(String metadataSchema, String userId, ProjectType projectInfo, DBInfoType dbInfo) throws I2B2DAOException, I2B2Exception{ - - String entriesSql = "select c_name from " + metadataSchema + "workplace_access where LOWER(c_user_id) = ? and LOWER(c_group_id) = ?"; - - /* - ParameterizedRowMapper map = new ParameterizedRowMapper() { - @Override - public String mapRow(ResultSet rs, int rowNum) throws SQLException { - String name = rs.getString("c_name") ; - return name; - } - }; - - String map = jt.queryForObject(entriesSql,String.class); - */ - List queryResult = null; - try { - //queryResult = jt.query(entriesSql, map, userId.toLowerCase(), projectInfo.getId().toLowerCase()); - queryResult = jt.queryForList(entriesSql, String.class, userId.toLowerCase(), projectInfo.getId().toLowerCase()); - - } catch (DataAccessException e1) { - // TODO Auto-generated catch block - log.error(e1.getMessage()); - throw new I2B2DAOException("Database Error check_addRootNode"); - } - // log.info("check for root node size = " + queryResult.size()); - if(queryResult.size() > 0) - return; - - // else queryResult is empty - // need to create a new entry for user - - //1. get ProtectedAccess status for user - if (projectInfo.getRole().size() == 0) - { - log.error("no role found for this user in project: " + projectInfo.getName()); - I2B2Exception e = new I2B2Exception("No role found for user"); - throw e; - } - - String protectedAccess = "N"; - Iterator it = projectInfo.getRole().iterator(); - while (it.hasNext()){ - String role = (String) it.next(); - if(role.toLowerCase().equals("protected_access")) { - protectedAccess = "Y"; - break; - } - } - // 2. Get tableCd tableName info - String tableSql = "select distinct(c_table_cd), c_table_name from " + metadataSchema + "workplace_access"; - - /* - ParameterizedRowMapper map2 = new ParameterizedRowMapper() { - @Override - public String mapRow(ResultSet rs, int rowNum) throws SQLException { - String name = "\\\\" + rs.getString("c_table_cd") + "\\" + rs.getString("c_table_name"); - return name; - } - }; - */ - String tableInfo = jt.queryForObject(tableSql, new getFolderTableMapper()); - //String tableInfo = (String)queryResult.get(0); - - //extract table code and table name - String tableCd = StringUtil.getTableCd(tableInfo); - String tableName = StringUtil.getIndex(tableInfo); - - String addSql = "insert into " + metadataSchema+ "workplace_access " + - "(c_table_cd, c_table_name, c_hlevel, c_protected_access, c_name, c_user_id, c_index, c_visualattributes, c_share_id, c_group_id, c_entry_date) values (?,?,?,?,?,?,?,?,?,?,?)"; - - int numRootsAdded = -1; - String index = StringUtil.generateMessageId(); - try { - numRootsAdded = jt.update(addSql, tableCd, tableName, 0, protectedAccess, - userId, userId,index, "CA", "N", projectInfo.getId(), Calendar.getInstance().getTime()); - - } catch (DataAccessException e) { - log.error("Dao addChild failed"); - log.error(e.getMessage()); - throw new I2B2DAOException("Data access error check_addRootNode" , e); - } - - // log.info(addSql + " " + numRowsAdded); - log.debug("Number of roots added: " + numRootsAdded); - - return; - - } - - public String exportNode(final ExportChildType childrenType, ProjectType projectInfo, SecurityType securityType) throws I2B2DAOException, I2B2Exception{ - - // find return parameters - String type = "core"; - String parameters = CORE; - - - - if (projectInfo.getRole().size() == 0) - { - log.error("no role found for this user in project: " + projectInfo.getName()); - I2B2Exception e = new I2B2Exception("No role found for user"); - throw e; - } - - boolean protectedAccess = false; - Iterator it = projectInfo.getRole().iterator(); - while (it.hasNext()){ - String role = (String) it.next(); - if(role.toLowerCase().equalsIgnoreCase("DATA_PROT")) { - protectedAccess = true; - break; - } - } - String queryResult = null; - - // Get the query master for the actual query run - if (childrenType.getType().equalsIgnoreCase("QM")) { - try { - log.debug("Start to get QM results from CRC"); - //CallCRCUtil callCRC = new CallCRCUtil(securityType, projectInfo.getId()); - log.debug("getting Response"); - queryResult = CallCRCUtil.callCRCQueryRequestXML(childrenType.getNode(), securityType, projectInfo.getId()); - logesapi.debug("got response: " + queryResult); - //if (masterInstanceResultResponseType != null && masterInstanceResultResponseType.getQueryMaster().size() > 0) - // queryResult =XMLUtil.convertDOMElementToString((Element) masterInstanceResultResponseType.getQueryMaster().get(0).getRequestXml().getContent().get(0)); ; //respoonseType.getQueryResultInstance(); - } catch (Exception e) { - log.error(e.getMessage()); - throw new I2B2DAOException("Database Error exportNode"); - } - //log.debug("result size = " + queryResult.size()); - // Get the analysis breakdowns - } else if (childrenType.getType().equalsIgnoreCase("QR")) { - try { - log.debug("Start to get QR results from CRC"); - //CallCRCUtil callCRC = new CallCRCUtil(securityType, projectInfo.getId()); - log.debug("getting Response"); - queryResult = CallCRCUtil.callCRCResultInstanceXML(childrenType.getNode(), securityType, projectInfo.getId()); - logesapi.debug("got response: " + queryResult); - //if (masterInstanceResultResponseType != null) - // queryResult = (String) masterInstanceResultResponseType.getCrcXmlResult().getXmlValue().getContent().get(0); - //XMLUtil.convertDOMElementToString((Element) masterInstanceResultResponseType.getCrcXmlResult().getXmlValue().getContent().get(0)); //respoonseType.getQueryResultInstance(); - //queryResult = jt.query(sql, mapper, parentIndex ); - } catch (Exception e) { - log.error(e.getMessage()); - throw new I2B2DAOException("Database Error exportNode2"); - } - //log.debug("result size = " + queryResult.size()); - } - logesapi.debug("result is: " + queryResult); - return queryResult; - - } - - public List findChildrenByParent(final GetChildrenType childrenType, ProjectType projectInfo, DBInfoType dbInfo) throws I2B2DAOException, I2B2Exception{ - - // find return parameters - String type = "core"; - String parameters = CORE; - if (childrenType.getType().equals("all")){ - parameters = ALL; - type = "all"; - } - if(childrenType.isBlob() == true) - parameters = parameters + BLOB; - - String metadataSchema = dbInfo.getDb_fullSchema(); - setDataSource(dbInfo.getDb_dataSource()); - - if (projectInfo.getRole().size() == 0) - { - log.error("no role found for this user in project: " + projectInfo.getName()); - I2B2Exception e = new I2B2Exception("No role found for user"); - throw e; - } - - boolean protectedAccess = false; - Iterator it = projectInfo.getRole().iterator(); - while (it.hasNext()){ - String role = (String) it.next(); - if(role.toLowerCase().equalsIgnoreCase("DATA_PROT")) { - protectedAccess = true; - break; - } - } - - /* - ParameterizedRowMapper map = new ParameterizedRowMapper() { - @Override - public String mapRow(ResultSet rs, int rowNum) throws SQLException { - String name = (rs.getString("c_table_name")); - return name; - } - }; - */ - - //extract table code - String tableCd = StringUtil.getTableCd(childrenType.getParent()); - // log.debug(tableCd); - String tableName=null; - if (!protectedAccess){ - String tableSql = "select distinct(c_table_name) from " + metadataSchema + "workplace_access where c_table_cd = ? and c_protected_access = ? "; - //log.info("getChildren " + tableSql + tableCd); - try { - //tableName = jt.queryForObject(tableSql, map, tableCd, "N"); - tableName = jt.queryForObject(tableSql,String.class, tableCd, "N"); - } catch (DataAccessException e) { - log.error(e.getMessage()); - throw new I2B2DAOException("Database Error findChildrenByParent" ); - } - }else { - String tableSql = "select distinct(c_table_name) from " + metadataSchema + "workplace_access where c_table_cd = ?"; - try { - //tableName = jt.queryForObject(tableSql, map, tableCd); - tableName = jt.queryForObject(tableSql,String.class, tableCd); - - } catch (DataAccessException e) { - log.error(e.getMessage()); - throw new I2B2DAOException("Database Error findChildrenByParent 2"); - } - } - - String hidden = ""; - if(childrenType.isHiddens() == false) - hidden = " and c_visualattributes not like '_H%'"; - - String sql = "select " + parameters +" from " + metadataSchema+tableName + " where c_parent_index = ? and (c_status_cd != 'D' or c_status_cd is null)"; - sql = sql + hidden + " order by c_name "; - - String parentIndex = StringUtil.getIndex(childrenType.getParent()); - - log.debug(sql + " " + parentIndex); - // log.info(type + " " + tableCd ); - - GetFolderMapper mapper = GetTableMapper(type, childrenType.isBlob(), tableCd, dbInfo.getDb_serverType()); - - List queryResult = null; - try { - queryResult = jt.query(sql, mapper, parentIndex ); - } catch (DataAccessException e) { - log.error(e.getMessage()); - throw new I2B2DAOException("Database Error findChildrenByParent 3"); - } - log.debug("result size = " + queryResult.size()); - - - return queryResult; - // tested statement with aqua data studio verified output from above against this. - // select c_fullname, c_name, c_synonym_cd, c_visualattributes from metadata.testrpdr - // where c_fullname like '\RPDR\Diagnoses\Circulatory system (390-459)\Arterial vascular disease (440-447)\(446) Polyarteritis nodosa and al%' - // and c_hlevel = 5 and c_visualattributes not like '_H%' and c_synonym_cd = 'N' - - // verified both with and without hiddens and synonyms. - - // clob test level = 4 - // \\testrpdr\RPDR\HealthHistory\PHY\Health Maintenance\Mammogram\Mammogram - Deferred - } - - /** - * This method finds the workplace with a given keyword. It first searches the WORKPLACE ACCESS table - * to find the table where the workplace contents are stored. And then it searches the resulting table - * for any content with given name and other parameters - * - * @param returnType - * @param userId - * @param projectInfo - * @param dbInfo - * @return - * @throws DataAccessException - * @throws I2B2Exception - * - * @author Neha Patel - */ - public List findWorkplaceByKeyword(final FindByChildType returnType, String userId, final ProjectType projectInfo, final DBInfoType dbInfo) throws DataAccessException, I2B2Exception{ - - // find return parameters - String type = "core"; // Default Type is core - String parameters = CORE; // parameters to be used in select statement - String category = ""; - String hiddenStr = ""; - String maxString = ""; - String searchWord = ""; - - if (returnType!=null){ - - // determines which columns should be used in select statement - if(returnType.getType().equals("all")){ - parameters = ALL; - type = "all"; - } - - // if request parameter blob is set to true then include - // columns with xml info in select statement :- - // c_work_xml, c_work_xml_schema, c_work_xml_i2b2_type - if(returnType.isBlob() == true) - parameters = parameters + BLOB; - - // category is the directory where user is looking for the content - category= returnType.getCategory(); - - // request parameter hidden indicates to display hidden files or not - if(returnType.isHiddens() == false) - hiddenStr = " and c_visualattributes not like '_H%'"; - - // get strategy if content name starts with given word - // or it contains given word or it ends with given word - if(returnType.getMatchStr().getStrategy().equals("exact")) { - searchWord = returnType.getMatchStr().getValue().toLowerCase(); - } - - else if(returnType.getMatchStr().getStrategy().equals("left")){ - searchWord = returnType.getMatchStr().getValue().toLowerCase()+ "%"; - } - - else if(returnType.getMatchStr().getStrategy().equals("right")) { - searchWord ="%"+ returnType.getMatchStr().getValue().toLowerCase(); - } - - else if(returnType.getMatchStr().getStrategy().equals("contains")) { - searchWord = "%" + returnType.getMatchStr().getValue().toLowerCase() + "%"; - } - - try { - // setting max number of rows to be returned - if(returnType.getMax() !=null && returnType.getMax()>0 && dbInfo!=null){ - int fetchSize = returnType.getMax() +1 ; - - // if server is oracle then use rownum to return max number of rows - if(dbInfo.getDb_serverType().toUpperCase().equals("ORACLE")) - maxString = " and rownum>0 and rownum <=" + fetchSize; - - // if server is SQL SERVER then use 'TOP' clause to return max number of rows - else if(dbInfo.getDb_serverType().toUpperCase().equals("SQLSERVER")){ - maxString = "TOP " + fetchSize + " "; - parameters = maxString + parameters; // appended maxstring infront of parameters - maxString = ""; - } - //else if(dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL")) - // maxString = " limit " + fetchSize; - - } - } - catch( Exception e){ - log.error(e); - } - } - - if (projectInfo.getRole().size() == 0) - { - log.error("no role found for this user in project: " + projectInfo.getName()); - I2B2Exception e = new I2B2Exception("No role found for user"); - throw e; - } - - boolean protectedAccess = false; - Iterator it = projectInfo.getRole().iterator(); - while (it.hasNext()){ - String role = (String) it.next(); - if(role.toLowerCase().equalsIgnoreCase("DATA_PROT")) { - protectedAccess = true; - break; - } - } - - if(returnType.getCategory().trim().equalsIgnoreCase("@")){ - return findInAll(returnType, projectInfo, type, parameters, hiddenStr, maxString, searchWord, protectedAccess, dbInfo, userId ); - } - else { - return findInCategory(returnType, projectInfo, type, parameters, category, hiddenStr, maxString, searchWord, dbInfo, protectedAccess); - } - - } - - /** - * This method finds the search word in the given category. - * - * @param returnType - * @param projectInfo - * @param type - parameters to be used in the select statement. Can have two values core or all - * @param parameters - * @param category - * @param hiddenStr - string to be used in where clause - * @param maxString - string to be used in select or where clause - * @param searchWord - * @param dbInfo - * @param protectedAccess - * @return - * @throws I2B2DAOException - * - * @author Neha Patel - */ - private List findInCategory(final FindByChildType returnType, final ProjectType projectInfo, String type, String parameters, String category, String hiddenStr, String maxString, - String searchWord, final DBInfoType dbInfo, boolean protectedAccess) throws I2B2DAOException { - - String metadataSchema = dbInfo.getDb_fullSchema(); - setDataSource(dbInfo.getDb_dataSource()); - - /* - ParameterizedRowMapper map = new ParameterizedRowMapper() { - @Override - public String mapRow(ResultSet rs, int rowNum) throws SQLException { - String name = "\\\\" + rs.getString("c_table_cd") + "\\" + rs.getString("c_table_name"); - return name; - } - }; - - */ - // Getting tablename where the content is saved from table 'WORKPLACE' - List queryResult = null; - - String resultStr=null; - StringBuilder sqlToRetreiveTableNm = new StringBuilder( "select distinct c_table_cd, c_table_name from " + metadataSchema + "workplace_access where LOWER(c_user_id) = ? and LOWER(c_group_id) = ?"); - if (!protectedAccess){ - - sqlToRetreiveTableNm.append(" and c_protected_access = ? "); - try { - queryResult = jt.query(sqlToRetreiveTableNm.toString(), new getFolderTableMapper(), category.toLowerCase(), projectInfo.getId().toLowerCase(), "N"); - resultStr = (String)queryResult.get(0); - } catch (DataAccessException e) { - log.error(e.getMessage()); - throw new I2B2DAOException("findWorkplaceByKeyword(): Database Error while accessing workplace_access table with protected access"); - } - }else { - try { - queryResult = jt.query(sqlToRetreiveTableNm.toString(), new getFolderTableMapper(), category.toLowerCase(), projectInfo.getId().toLowerCase()); - resultStr = (String)queryResult.get(0); - } catch (DataAccessException e) { - log.error(e.getMessage()); - throw new I2B2DAOException("findWorkplaceByKeyword(): Database Error while accessing workplace_access table"); - } - } - - String tableCd = StringUtil.getTableCd(resultStr); - String tableName = StringUtil.getIndex(resultStr); - - StringBuilder sql = new StringBuilder ("select " + parameters +" from " + metadataSchema+tableName + " where LOWER(c_user_id) = ? and LOWER(c_group_id) = ? and LOWER(c_name) like ? and (c_status_cd != 'D' or c_status_cd is null) "); - sql.append( hiddenStr + maxString ); - - GetFolderMapper mapper = GetTableMapper(type, returnType.isBlob(), tableCd, dbInfo.getDb_serverType()); - - - /* - * commenting out protectedAcess code from workplace table for now - * - if (!protectedAccess){ - sql.append(" and (c_protected_access != 'Y' or c_protected_access is null) "); - } - */ - - sql.append( " order by c_name "); - - // Executing the query to find the workplace content with the given name - List queryResult2; - - try { - queryResult2 = jt.query(sql.toString(), mapper, category.toLowerCase(), projectInfo.getId().toLowerCase(), searchWord ); - } catch (DataAccessException e) { - log.error(e.getMessage()); - log.error("findWorkplaceByKeyword(): Database Error while accessing workplace table"); - throw new I2B2DAOException("findWorkplaceByKeyword(): Database Error while accessing workplace table"); - } - - log.debug("result size = " + queryResult2.size()); - - return queryResult2; - } - - /** - * This method searches for the word in the whole project. If the user has a manager role then it searches in the whole project - * if the user doesn't have manager role then it searches with the condition of userid or share = Y - * - * @param returnType - * @param projectInfo - * @param type - * @param parameters - * @param hiddenStr - * @param maxString - * @param searchWord - * @param protectedAccess - * @param dbInfo - * @param userId - * @return - * @throws DataAccessException - * @throws I2B2Exception - * - * @author Neha Patel - */ - private List findInAll(final FindByChildType returnType, final ProjectType projectInfo, String type, String parameters, String hiddenStr, String maxString, - String searchWord, boolean protectedAccess, final DBInfoType dbInfo, final String userId) throws DataAccessException, I2B2Exception{ - - - // Check if user is a manager - boolean managerRole = false; - for(String param :projectInfo.getRole()) { - if(param.equalsIgnoreCase("manager")) { - managerRole = true; - break; - } - } - - String metadataSchema = dbInfo.getDb_fullSchema(); - setDataSource(dbInfo.getDb_dataSource()); - - /* - ParameterizedRowMapper map = new ParameterizedRowMapper() { - @Override - public String mapRow(ResultSet rs, int rowNum) throws SQLException { - String name = "\\\\" + rs.getString("c_table_cd") + "\\" + rs.getString("c_table_name"); - return name; - } - }; - */ - - // Getting tablename where the content is saved from table 'WORKPLACE' - List queryResult = null; - - String resultStr=null; - StringBuilder sqlToRetreiveTableNm = new StringBuilder( "select distinct c_table_cd, c_table_name from " + metadataSchema + "workplace_access where "); - - // if user is a manager then search in the whole project - if(managerRole){ - sqlToRetreiveTableNm.append("LOWER(c_group_id) = ? "); - } - else { - // if user is not a manager then user should be able to search only in his folder or shared folder of the project - sqlToRetreiveTableNm.append("(LOWER(c_user_id) = ? and LOWER(c_group_id) = ?) or (LOWER(c_group_id) = ? and c_share_id = 'Y') "); - } - - if (!protectedAccess){ - sqlToRetreiveTableNm.append(" and (c_protected_access = 'N' or c_protected_access is null) "); - } - - try { - if(managerRole){ - queryResult = jt.queryForList(sqlToRetreiveTableNm.toString(), new getFolderTableMapper(), projectInfo.getId().toLowerCase()); - } - else { - queryResult = jt.queryForList(sqlToRetreiveTableNm.toString(), new getFolderTableMapper(), userId.toLowerCase(), projectInfo.getId().toLowerCase(), projectInfo.getId().toLowerCase()); - } - resultStr = (String)queryResult.get(0); - } catch (DataAccessException e) { - log.error(e.getMessage()); - throw new I2B2DAOException("findWorkplaceByKeyword(): Database Error while accessing workplace_access table with protected access"); - } - - String tableCd = ""; - String tableName = ""; - List returnResult = null; - - // Run the query for each tablename. There could be more than one table where workplace content is stored - if(queryResult != null && !queryResult.isEmpty()){ - Iterator itr = queryResult.iterator(); - while(itr.hasNext()){ - resultStr = (String)itr.next(); - tableCd = StringUtil.getTableCd(resultStr); - tableName = StringUtil.getIndex(resultStr); - - StringBuilder sql = new StringBuilder ("select from where LOWER(c_name) like ? and (c_status_cd != 'D' or c_status_cd is null) "); - - if(managerRole){ - sql.append("and LOWER(c_group_id) = ? "); - } - else { - sql.append("and ((LOWER(c_user_id) = ? and LOWER(c_group_id) = ?) or (LOWER(c_group_id) = ? and c_share_id = 'Y')) "); - } - - sql.append( hiddenStr + maxString ); - - GetFolderMapper mapper = GetTableMapper(type, returnType.isBlob(), tableCd, dbInfo.getDb_serverType()); - - /* - * commenting out protectedAcess code from workplace table for now - * - if (!protectedAccess){ - sql.append(" and (c_protected_access != 'Y' or c_protected_access is null) "); - } - */ - - sql.append( " order by c_name "); - - // Executing the query to find the workplace content with the given name - List workplaceResult=null; - - try { - - String sqlFinal = sql.toString().replace("", metadataSchema + tableName); - sqlFinal = sqlFinal.toString().replace("", parameters); - - - if(managerRole){ - workplaceResult = jt.query(sqlFinal, mapper, searchWord, projectInfo.getId().toLowerCase() ); - } - else { - workplaceResult = jt.query(sqlFinal, mapper, searchWord, userId.toLowerCase(), projectInfo.getId().toLowerCase(), projectInfo.getId().toLowerCase() ); - } - } catch (DataAccessException e) { - log.error(e.getMessage()); - log.error("findWorkplaceByKeyword(): Database Error while accessing workplace table"); - throw new I2B2DAOException("findWorkplaceByKeyword(): Database Error while accessing workplace table"); - } - - if(returnResult==null){ - returnResult=workplaceResult; - } - else { - returnResult.addAll(workplaceResult); - } - } // end while (itr.hasNext()) - - } - log.debug("result size = " + returnResult.size()); - - return returnResult; - } - - /** - * This method determines if the given category(workplace root folder name) is shared or not by - * checking c_share_id parameter in workplace_access table - * - * @param category - the root folder name which is in question if its shared or not - * @param projectInfo - * @param dbInfo - * @return - * @throws DataAccessException - * @throws I2B2Exception - * - * @author Neha Patel - */ - public boolean isShared(String category, final ProjectType projectInfo, final DBInfoType dbInfo) throws DataAccessException, I2B2Exception{ - - boolean isSharedBool= false; - String metadataSchema = dbInfo.getDb_fullSchema(); - setDataSource(dbInfo.getDb_dataSource()); - - /* - ParameterizedRowMapper map = new ParameterizedRowMapper() { - @Override - public String mapRow(ResultSet rs, int rowNum) throws SQLException { - String name = rs.getString("c_share_id") ; - return name; - } - }; - */ - - // Getting column 'c_share_id' to check if the given category/folder is shared - List queryResult = null; - String resultStr=""; - - String sqlForCheckingShared = "select c_share_id from " + metadataSchema + "workplace_access where LOWER(c_user_id) = ? and LOWER(c_group_id) = ? and (c_status_cd != 'D' or c_status_cd is null)"; - - try { - //queryResult = jt.query(sqlForCheckingShared.toString(), map, category.toLowerCase(), projectInfo.getId().toLowerCase()); - queryResult = jt.queryForList(sqlForCheckingShared.toString(), String.class, category.toLowerCase(), projectInfo.getId().toLowerCase()); - - if(queryResult !=null && !queryResult.isEmpty()){ - resultStr = (String)queryResult.get(0); - } - } catch (DataAccessException e) { - log.error(e.getMessage()); - throw new I2B2DAOException("isShared(): Database Error while accessing workplace_access table"); - } - - if(resultStr!=null && resultStr.toUpperCase().trim().equals("Y")){ - isSharedBool = true; - } - else - isSharedBool = false; - - return isSharedBool; - } - - public int renameNode(final RenameChildType renameChildType, ProjectType projectInfo, DBInfoType dbInfo) throws I2B2DAOException, I2B2Exception{ - - String metadataSchema = dbInfo.getDb_fullSchema(); - setDataSource(dbInfo.getDb_dataSource()); - - if (projectInfo.getRole().size() == 0) - { - log.error("no role found for this user in project: " + projectInfo.getName()); - I2B2Exception e = new I2B2Exception("No role found for user"); - throw e; - } - - boolean protectedAccess = false; - Iterator it = projectInfo.getRole().iterator(); - while (it.hasNext()){ - String role = (String) it.next(); - if(role.toLowerCase().equalsIgnoreCase("DATA_PROT")) { - protectedAccess = true; - break; - } - } - - /* - ParameterizedRowMapper map = new ParameterizedRowMapper() { - @Override - public String mapRow(ResultSet rs, int rowNum) throws SQLException { - String name = (rs.getString("c_table_name")); - return name; - } - }; - */ - - //extract table code - String tableCd = StringUtil.getTableCd(renameChildType.getNode()); - // table code to table name conversion - String tableName=null; - if (!protectedAccess){ - String tableSql = "select distinct(c_table_name) from " + metadataSchema + "workplace_access where c_table_cd = ? and c_protected_access = ? "; - try { - tableName = jt.queryForObject(tableSql, String.class, tableCd, "N"); - } catch (DataAccessException e) { - log.error(e.getMessage()); - throw new I2B2DAOException("Database Error"); - } - }else { - String tableSql = "select distinct(c_table_name) from " + metadataSchema + "workplace_access where c_table_cd = ?"; - try { - tableName = jt.queryForObject(tableSql, String.class, tableCd); - } catch (DataAccessException e) { - log.error(e.getMessage()); - throw new I2B2DAOException("Database Error"); - } - } - - String index = StringUtil.getIndex(renameChildType.getNode()); - - // get original name and work xml - String sql = "select c_name, c_work_xml, c_work_xml_i2b2_type from " + metadataSchema + tableName + " where c_index = ? "; - /* - ParameterizedRowMapper map2 = new ParameterizedRowMapper() { - @Override - public FolderType mapRow(ResultSet rs, int rowNum) throws SQLException { - FolderType child = new FolderType(); - child.setName(rs.getString("c_name")); - // child.setTooltip(rs.getString("c_tooltip")); - child.setWorkXmlI2B2Type(rs.getString("c_work_xml_i2b2_type")); - - return child; - } - }; - */ - List queryResult = null; - try { - queryResult = jt.query(sql, new mapToFolderXML(), index); - } catch (DataAccessException e) { - log.error("Dao queryResult failed"); - log.error(e.getMessage()); - throw new I2B2DAOException("Data access error " , e); - } - FolderType node = (FolderType)queryResult.get(0); - - // String newTooltip = StringUtil.replaceEnd(node.getTooltip(),node.getName(), renameChildType.getName()); - // log.info(newTooltip); - int numRowsRenamed = -1; - if(node.getWorkXmlI2B2Type().equals("FOLDER")){ - String updateSql = "update " + metadataSchema+tableName + " set c_name = ? where c_index = ? "; - try { - numRowsRenamed = jt.update(updateSql, renameChildType.getName(),index); - } catch (DataAccessException e) { - log.error("Dao renameChild failed"); - log.error(e.getMessage()); - throw new I2B2DAOException("Data access error " , e); - } - } - else { - String updateSql = "update " + metadataSchema+tableName + " set c_name = ? where c_index = ? "; - - /* - String newXml = null; - // Element newXmlElement = node.getWorkXml().getAny().get(0); - Element newXmlElement = renameChildType.getWorkXml().getAny().get(0); - if(newXmlElement != null){ - newXml = XMLUtil.convertDOMElementToString(newXmlElement); - // log.debug(newXml); - } - */ - try { - numRowsRenamed = jt.update(updateSql, renameChildType.getName(), index); - } catch (DataAccessException e) { - log.error("Dao renameChild failed"); - log.error(e.getMessage()); - throw new I2B2DAOException("Data access error " , e); - } - } - log.debug("Number of rows renamed: " + numRowsRenamed); - return numRowsRenamed; - - } - - public int moveNode(final ChildType childType, ProjectType projectInfo, DBInfoType dbInfo) throws I2B2DAOException, I2B2Exception{ - - String metadataSchema = dbInfo.getDb_fullSchema(); - setDataSource(dbInfo.getDb_dataSource()); - - if (projectInfo.getRole().size() == 0) - { - log.error("no role found for this user in project: " + projectInfo.getName()); - I2B2Exception e = new I2B2Exception("No role found for user"); - throw e; - } - - boolean protectedAccess = false; - Iterator it = projectInfo.getRole().iterator(); - while (it.hasNext()){ - String role = (String) it.next(); - if(role.toLowerCase().equalsIgnoreCase("DATA_PROT")) { - protectedAccess = true; - break; - } - } - - /* - ParameterizedRowMapper map = new ParameterizedRowMapper() { - @Override - public String mapRow(ResultSet rs, int rowNum) throws SQLException { - String name = (rs.getString("c_table_name")); - return name; - } - }; - */ - - //extract table code - String tableCd = StringUtil.getTableCd(childType.getNode()); - // table code to table name conversion - String tableName=null; - if (!protectedAccess){ - String tableSql = "select distinct(c_table_name) from " + metadataSchema + "workplace_access where c_table_cd = ? and c_protected_access = ? "; - try { - tableName = jt.queryForObject(tableSql, String.class, tableCd, "N"); - } catch (DataAccessException e) { - log.error(e.getMessage()); - throw new I2B2DAOException("Database Error"); - } - }else { - String tableSql = "select distinct(c_table_name) from " + metadataSchema + "workplace_access where c_table_cd = ?"; - try { - tableName = jt.queryForObject(tableSql, String.class, tableCd); - } catch (DataAccessException e) { - log.error(e.getMessage()); - throw new I2B2DAOException("Database Error"); - } - } - - String index = StringUtil.getIndex(childType.getNode()); - String updateSql = "update " + metadataSchema+tableName + " set c_parent_index = ? where c_index = ? "; - - int numRowsMoved = -1; - try { - numRowsMoved = jt.update(updateSql, childType.getParent(), index); - } catch (DataAccessException e) { - log.error("Dao moveChild failed"); - log.error(e.getMessage()); - throw new I2B2DAOException("Data access error " , e); - } - // log.info(updateSql + " " + path + " " + numRowsAnnotated); - log.debug("Number of rows moved: " + numRowsMoved); - return numRowsMoved; - - } - - public int annotateNode(final AnnotateChildType annotateChildType, ProjectType projectInfo, DBInfoType dbInfo) throws I2B2DAOException, I2B2Exception{ - - String metadataSchema = dbInfo.getDb_fullSchema(); - setDataSource(dbInfo.getDb_dataSource()); - - if (projectInfo.getRole().size() == 0) - { - log.error("no role found for this user in project: " + projectInfo.getName()); - I2B2Exception e = new I2B2Exception("No role found for user"); - throw e; - } - - boolean protectedAccess = false; - Iterator it = projectInfo.getRole().iterator(); - while (it.hasNext()){ - String role = (String) it.next(); - if(role.toLowerCase().equalsIgnoreCase("DATA_PROT")) { - protectedAccess = true; - break; - } - } - - /* - ParameterizedRowMapper map = new ParameterizedRowMapper() { - @Override - public String mapRow(ResultSet rs, int rowNum) throws SQLException { - String name = (rs.getString("c_table_name")); - return name; - } - }; - */ - - //extract table code - String tableCd = StringUtil.getTableCd(annotateChildType.getNode()); - // table code to table name conversion - String tableName=null; - if (!protectedAccess){ - String tableSql = "select distinct(c_table_name) from " + metadataSchema + "workplace_access where c_table_cd = ? and c_protected_access = ? "; - try { - tableName = jt.queryForObject(tableSql, String.class, tableCd, "N"); - } catch (DataAccessException e) { - log.error(e.getMessage()); - throw new I2B2DAOException("Database Error"); - } - }else { - String tableSql = "select distinct(c_table_name) from " + metadataSchema + "workplace_access where c_table_cd = ?"; - try { - tableName = jt.queryForObject(tableSql, String.class, tableCd); - } catch (DataAccessException e) { - log.error(e.getMessage()); - throw new I2B2DAOException("Database Error"); - } - } - - String index = StringUtil.getIndex(annotateChildType.getNode()); - String updateSql = "update " + metadataSchema+tableName + " set c_tooltip = ? where c_index = ? "; - - int numRowsAnnotated = -1; - try { - numRowsAnnotated = jt.update(updateSql, annotateChildType.getTooltip(), index); - } catch (DataAccessException e) { - log.error("Dao annotateChild failed"); - log.error(e.getMessage()); - throw new I2B2DAOException("Data access error " , e); - } - // log.info(updateSql + " " + path + " " + numRowsAnnotated); - log.debug("Number of rows annotated: " + numRowsAnnotated); - return numRowsAnnotated; - - } - - - public int addNode(final FolderType addChildType, ProjectType projectInfo, DBInfoType dbInfo) throws I2B2DAOException, I2B2Exception{ - - String metadataSchema = dbInfo.getDb_fullSchema(); - setDataSource(dbInfo.getDb_dataSource()); - - if (projectInfo.getRole().size() == 0) - { - log.error("no role found for this user in project: " + projectInfo.getName()); - I2B2Exception e = new I2B2Exception("No role found for user"); - throw e; - } - - boolean protectedAccess = false; - Iterator it = projectInfo.getRole().iterator(); - while (it.hasNext()){ - String role = (String) it.next(); - if(role.toLowerCase().equalsIgnoreCase("DATA_PROT")) { - protectedAccess = true; - break; - } - } - - /* - ParameterizedRowMapper map = new ParameterizedRowMapper() { - @Override - public String mapRow(ResultSet rs, int rowNum) throws SQLException { - String name = (rs.getString("c_table_name")); - return name; - } - }; - */ - - //extract table code - String tableCd = StringUtil.getTableCd(addChildType.getParentIndex()); - // table code to table name conversion - String tableName=null; - if (!protectedAccess){ - String tableSql = "select distinct(c_table_name) from " + metadataSchema + "workplace_access where c_table_cd = ? and c_protected_access = ? "; - try { - tableName = jt.queryForObject(tableSql, String.class, tableCd, "N"); - } catch (DataAccessException e) { - log.error(tableSql + tableCd); - log.error(e.getMessage()); - throw new I2B2DAOException("Database Error"); - } - }else { - String tableSql = "select distinct(c_table_name) from " + metadataSchema + "workplace_access where c_table_cd = ?"; - try { - tableName = jt.queryForObject(tableSql, String.class, tableCd); - } catch (DataAccessException e) { - log.error(e.getMessage()); - throw new I2B2DAOException("Database Error"); - } - } - - int numRowsAdded = -1; - try { - String xml = null; - XmlValueType workXml=addChildType.getWorkXml(); - if (workXml != null) { - String addSql = "insert into " + metadataSchema+tableName + - "(c_name, c_user_id, c_index, c_parent_index, c_visualattributes, c_group_id, c_share_id, c_tooltip, c_entry_date, c_work_xml, c_work_xml_i2b2_type) values (?,?,?,?,?,?,?,?,?,?,?)"; - Element element = workXml.getAny().get(0); - if(element != null) - xml = XMLUtil.convertDOMElementToString(element); - numRowsAdded = jt.update(addSql, - addChildType.getName(), addChildType.getUserId(),addChildType.getIndex(), StringUtil.getIndex(addChildType.getParentIndex()), - addChildType.getVisualAttributes(), addChildType.getGroupId(), addChildType.getShareId(), addChildType.getTooltip(), Calendar.getInstance().getTime(), - xml, addChildType.getWorkXmlI2B2Type()); - } - else { - String addSql = "insert into " + metadataSchema+tableName + - "(c_name, c_user_id, c_index, c_parent_index, c_visualattributes, c_group_id, c_share_id, c_tooltip, c_entry_date, c_work_xml_i2b2_type) values (?,?,?,?,?,?,?,?,?,?)"; - numRowsAdded = jt.update(addSql, - addChildType.getName(), addChildType.getUserId(),addChildType.getIndex(), StringUtil.getIndex(addChildType.getParentIndex()), - addChildType.getVisualAttributes(), addChildType.getGroupId(), addChildType.getShareId(), addChildType.getTooltip(), Calendar.getInstance().getTime(), - addChildType.getWorkXmlI2B2Type()); - } - } catch (DataAccessException e) { - log.error("Dao addChild failed"); - log.error(e.getMessage()); - throw new I2B2DAOException("Data access error " , e); - } - - // log.info(addSql + " " + numRowsAdded); - log.debug("Number of rows added: " + numRowsAdded); - - return numRowsAdded; - - } - - - public int deleteNode(final DeleteChildType deleteChildType, ProjectType projectInfo, DBInfoType dbInfo) throws DataAccessException, I2B2Exception{ - String metadataSchema = dbInfo.getDb_fullSchema(); - String serverType = dbInfo.getDb_serverType(); - setDataSource(dbInfo.getDb_dataSource()); - - if (projectInfo.getRole().size() == 0) - { - log.error("no role found for this user in project: " + projectInfo.getName()); - I2B2Exception e = new I2B2Exception("No role found for user"); - throw e; - } - - boolean protectedAccess = false; - Iterator it = projectInfo.getRole().iterator(); - while (it.hasNext()){ - String role = (String) it.next(); - if(role.toLowerCase().equalsIgnoreCase("DATA_PROT")) { - protectedAccess = true; - break; - } - } - - /* - ParameterizedRowMapper map = new ParameterizedRowMapper() { - @Override - public String mapRow(ResultSet rs, int rowNum) throws SQLException { - String name = (rs.getString("c_table_name")); - return name; - } - }; - */ - //extract table code - String tableCd = StringUtil.getTableCd(deleteChildType.getNode()); - // table code to table name conversion - String tableName=null; - if (!protectedAccess){ - String tableSql = "select distinct(c_table_name) from " + metadataSchema + "workplace_access where c_table_cd = ? and c_protected_access = ? "; - try { - tableName = jt.queryForObject(tableSql, String.class, tableCd, "N"); - } catch (DataAccessException e) { - log.error(e.getMessage()); - throw new I2B2DAOException("Database Error"); - } - }else { - String tableSql = "select distinct(c_table_name) from " + metadataSchema + "workplace_access where c_table_cd = ?"; - try { - tableName = jt.queryForObject(tableSql, String.class, tableCd); - } catch (DataAccessException e) { - log.error(e.getMessage()); - throw new I2B2DAOException("Database Error"); - } - } - String index = StringUtil.getIndex(deleteChildType.getNode()); - checkForChildrenDeletion(index, tableName, metadataSchema); - //Mark node for deletion - - String updateSql = " update " + metadataSchema+tableName + " set c_change_date = ?, c_status_cd = 'D' where c_index = ? "; - log.debug(serverType + "updateSql " + index); - int numRowsDeleted = -1; - try { - // log.info(sql + " " + w_index); - numRowsDeleted = jt.update(updateSql, Calendar.getInstance().getTime(),index); - } catch (DataAccessException e) { - log.error("Dao deleteChild failed"); - log.error(e.getMessage()); - throw e; - } - log.debug("Number of rows deleted " + numRowsDeleted); - return numRowsDeleted; - - } - - /** - * This method is to set protected access on a file/folder in workplace - * It first checks if user has correct privileges to the file, that is - * either he she is manager or the file is shared or the file belongs - * to him/her. The it searches for all the folders under the given - * index. if folders are found then it runs the update query atleast - * 3 times to update the root folder in workplace_access table, all the - * child folders in workplace table and all the child content in workplace - * table. - * - * @param requestType - * @param projectInfo - * @param dbInfo - * @param userId - * @return - * @throws I2B2DAOException - * @throws I2B2Exception - * - * @author Neha Patel - */ - public int setProtectedAccess(final ProtectedType requestType, final ProjectType projectInfo, final DBInfoType dbInfo, String userId) throws I2B2DAOException, I2B2Exception{ - - boolean settingRoot = false; - int numRowsSet = -1; - int numParentUpdated = -1; - int numWorkAccUpdated =-1; - String sharedStr =""; - String contentUserId = ""; - String tableName = ""; - boolean managerRole = false; - boolean isFolder = true; - - String metadataSchema = dbInfo.getDb_fullSchema(); - setDataSource(dbInfo.getDb_dataSource()); - - if (projectInfo.getRole().size() == 0) - { - log.error("no role found for this user in project: " + projectInfo.getName()); - I2B2Exception e = new I2B2Exception("No role found for user"); - throw e; - } - - // Check if user is a manager - for(String param :projectInfo.getRole()) { - if(param.equalsIgnoreCase("manager")) { - managerRole = true; - break; - } - } - - /* - ParameterizedRowMapper map = new ParameterizedRowMapper() { - @Override - public String mapRow(ResultSet rs, int rowNum) throws SQLException { - - String resultRow = "\\tablename=" + rs.getString("c_table_name") + "\\share_id=" + rs.getString("c_share_id") + "\\user_id=" + rs.getString("c_user_id") ; - - return resultRow; - } - }; - */ - - //extract table code and index - String tableCd = StringUtil.getTableCd(requestType.getIndex()); - String index = StringUtil.getIndex(requestType.getIndex()); - - List resultString = null; - StringBuilder sqlToRetrieveTableName = new StringBuilder("select distinct c_table_name, c_share_id, c_user_id from " + metadataSchema - + "workplace_access where LOWER(c_group_id) = ?"); - - // Check if the user is setting access for root directory - // by looking for index in the current table - try { - sqlToRetrieveTableName.append(" and c_index = ? "); - resultString = jt.query(sqlToRetrieveTableName.toString(), new mapToShareAccess(),projectInfo.getId().toLowerCase(), index); - } catch (DataAccessException e) { - log.error(e.getMessage()); - throw new I2B2DAOException("Database Error"); - } - - String resultToSplit= ""; - // if the above query returned any result - // that means user was setting access for root directory - if(resultString!=null && !resultString.isEmpty()){ - - settingRoot = true; - isFolder = true; - - // getting tablename, share_id, user_id from the result string - resultToSplit = (String) resultString.get(0); - int indexofShared = resultToSplit.indexOf("\\share_id="); - int indexofUser = resultToSplit.indexOf("\\user_id="); - tableName = resultToSplit.substring(11, indexofShared); - - // if its not manager check if the file/folder is shared - // if not shared either, then verify that user is setting - // privilege for his/her file/folder - if(managerRole == false){ - sharedStr = resultToSplit.substring(indexofShared+10, indexofUser); - contentUserId = resultToSplit.substring(indexofUser+9); - - if ((!sharedStr.equalsIgnoreCase("Y")) && (!contentUserId.equalsIgnoreCase(userId))){ - log.debug( "User does not have privileges to set protected access for this content"); - return -11111; - } // if (sharedStr==null || !sharedStr.equalsIgnoreCase("Y")) - } // if managerRole == false - } //if(resultString!=null && !resultString.isEmpty()) - // query result is null that means item doesn't exist in workplace_access table - // or user is not setting access for root directory - // Get tablename using the tablecd given as part of indexString in the request - else if(resultString == null || resultString.isEmpty()){ - - // replace the last condition of 'and c_index=?' with 'and c_table_cd' - sqlToRetrieveTableName.replace(sqlToRetrieveTableName.lastIndexOf("and"), sqlToRetrieveTableName.length()-1, " and LOWER(c_table_cd) = ? "); - - try { - resultString = jt.query(sqlToRetrieveTableName.toString(), new mapToShareAccess(), projectInfo.getId().toLowerCase(), tableCd.toLowerCase()); - } catch (DataAccessException e) { - log.error(e.getMessage()); - throw new I2B2DAOException("Database Error"); - } - - resultToSplit = (String) resultString.get(0); - - // getting tablename from the query result - tableName = resultToSplit.substring(11, resultToSplit.indexOf("\\share_id=")); - - List result; - /* - ParameterizedRowMapper mapTocheckAccess = new ParameterizedRowMapper() { - @Override - public String mapRow(ResultSet rs, int rowNum) throws SQLException { - - String resultRow = "\\share_id=" + rs.getString("c_share_id") + "\\user_id=" + rs.getString("c_user_id") + "\\type=" + rs.getString("c_work_xml_i2b2_type") ; - - return resultRow; - } - }; - */ - - // Run query in table workplace to find out if the content is shared or does it belong to user - // Also find the type of the file - String sql = "select c_share_id, c_user_id, c_work_xml_i2b2_type from " + metadataSchema + tableName + " where c_index = ? and LOWER(c_group_id) = ?"; - try{ - result = jt.query(sql, new mapTocheckAccess(), index, projectInfo.getId().toLowerCase()); - } catch (DataAccessException e) { - log.error(e.getMessage()); - throw new I2B2DAOException("Database Error"); - } - - // get the user id and share_id from result string - resultToSplit = (String) result.get(0); - String type = resultToSplit.substring(resultToSplit.lastIndexOf("\\")+6); - - if(!type.equalsIgnoreCase("FOLDER")){ - isFolder= false; - } - else - isFolder=true; - - // if user is not a manager - // then check if file/folder is shared - // if not shared then verify file/folder belongs to user - if(managerRole == false){ - - sharedStr = resultToSplit.substring(10, resultToSplit.indexOf("\\user_id=")); - contentUserId = resultToSplit.substring(resultToSplit.indexOf("\\user_id=")+9, resultToSplit.lastIndexOf("\\")); - - if ((sharedStr!=null && !sharedStr.equalsIgnoreCase("Y")) && (!contentUserId.equalsIgnoreCase(userId))){ - log.debug( "User does not have privileges to set protected access for this content"); - return -11111; - } // if (sharedStr==null || !sharedStr.equalsIgnoreCase("Y")) - } // if managerRole == false - } - - StringBuilder indexStr = new StringBuilder(); - String protectedAccVal= ""; - - if(requestType.getProtectedAccess().trim().equalsIgnoreCase("true")) - protectedAccVal = "Y"; - else - protectedAccVal = "N"; - - ArrayList parentIdxList = new ArrayList(); - parentIdxList.add(index); - indexStr.append("'" + index + "'"); - - // if initial request was for a folder only - // then run this part - if(isFolder){ - - List resultingIndx; - /* - ParameterizedRowMapper mapForIndexes = new ParameterizedRowMapper() { - @Override - public String mapRow(ResultSet rs, int rowNum) throws SQLException { - String name = (rs.getString("c_index")); - return name; - } - }; - */ - - // Get all the parent indexes (folder indexes under the top level directory) - // and store it in an arraylist - String parentIdx = ""; - for (int i = 0; i < parentIdxList.size(); i ++){ - try { - parentIdx = parentIdxList.get(i); - if(i>0){ - indexStr.append(", '" + parentIdx + "'"); - } - String sqlToCollectIndex = "select c_index from " + metadataSchema + tableName + " where c_parent_index = ? and LOWER(c_group_id) = ? and c_work_xml_i2b2_type = 'FOLDER'"; - resultingIndx = jt.queryForList(sqlToCollectIndex, String.class, parentIdx, projectInfo.getId().toLowerCase()); - } catch (DataAccessException e) { - log.error(e.getMessage()); - throw new I2B2DAOException("Database Error"); - } - if(resultingIndx != null) - parentIdxList.addAll(resultingIndx); - } - - // set the protected access for all the content found under the - // parent indexes stored in the arraylist - numParentUpdated = updateProtectedAccess(metadataSchema,tableName, "c_parent_index" , indexStr.toString(), protectedAccVal); - } - - if(settingRoot){ - // set the protected access for root directory which is in workplace_access table - numWorkAccUpdated = updateProtectedAccess(metadataSchema,"workplace_access", "c_index",indexStr.toString(), protectedAccVal); - } - - // If setting root folder, then set all the folders to protected access - // if setting one item then still use the same query to set that item to protected_access - numRowsSet = updateProtectedAccess(metadataSchema,tableName, "c_index",indexStr.toString(), protectedAccVal); - - // Return the correct number of updated rows - if(isFolder) - numRowsSet += numParentUpdated; - - if(settingRoot) - numRowsSet += numWorkAccUpdated; - - return numRowsSet; - } - - /** - * @param numRowsSet - * @param metadataSchema - * @param tableName - * @param indexStr - * @param protectedAccVal - * @return - * @throws I2B2DAOException - * - * @author Neha Patel - */ - private int updateProtectedAccess(String metadataSchema,String tableName, String columnName, String indexStr, String protectedAccVal) - throws I2B2DAOException { - - String updateSql = "update set c_protected_access = ? where in ( )"; - int numRowsSet=-1; - - try { - String sqlFinal = updateSql.replace("", metadataSchema+tableName); - sqlFinal = sqlFinal.replace("", columnName); - sqlFinal = sqlFinal.replace("", indexStr); - - String protectedAccValFinal = protectedAccVal.replace("", indexStr); - - numRowsSet = jt.update(sqlFinal, protectedAccValFinal); - } catch (DataAccessException e) { - log.error("Dao updateProtectedAccess failed"); - log.error(e.getMessage()); - throw new I2B2DAOException("Data access error " , e); - } - return numRowsSet; - } - - - private void checkForChildrenDeletion(String nodeIndex, String tableName, String metadataSchema) throws DataAccessException { - - // mark children for deletion - String updateSql = " update " + metadataSchema+tableName + " set c_change_date = ?, c_status_cd = 'D' where c_parent_index = ? "; - int numChildrenDeleted = -1; - try { - // log.info(sql + " " + w_index); - numChildrenDeleted = jt.update(updateSql, Calendar.getInstance().getTime(),nodeIndex); - } catch (DataAccessException e) { - log.error("Dao deleteChild failed"); - log.error(e.getMessage()); - throw e; - } - log.debug("Number of children deleted: "+ numChildrenDeleted); - // look for children that are folders - String folderSql = "select c_index from " + metadataSchema+tableName + " where c_parent_index = ? and c_visualattributes like 'F%' "; - - /* - ParameterizedRowMapper map = new ParameterizedRowMapper() { - @Override - public String mapRow(ResultSet rs, int rowNum) throws SQLException { - String index = (rs.getString("c_index")); - return index; - } - }; - */ - - List folders = null; - try{ - folders = jt.queryForList(folderSql, String.class, nodeIndex); - } catch (DataAccessException e) { - log.error(e.getMessage()); - throw e; - } - // recursively check folders for children to delete - if (folders != null){ - Iterator it = folders.iterator(); - while(it.hasNext()){ - String folderIndex = (String) it.next(); - checkForChildrenDeletion(folderIndex, tableName, metadataSchema); - } - } - - } - - private GetFolderMapper GetTableMapper(final String type, final boolean isBlob, final String tableCd, final String dbType) { - - - GetFolderMapper folderMapper = new GetFolderMapper(); - - folderMapper.setType(type); - folderMapper.setBlob(isBlob); - folderMapper.setTableCd(tableCd); - folderMapper.setDbType(dbType); - return folderMapper; - } - -} - - -class mapToShareAccess implements RowMapper { - //ParameterizedRowMapper map = new ParameterizedRowMapper() { - @Override - public String mapRow(ResultSet rs, int rowNum) throws SQLException { - - String resultRow = "\\tablename=" + rs.getString("c_table_name") + "\\share_id=" + rs.getString("c_share_id") + "\\user_id=" + rs.getString("c_user_id") ; - - return resultRow; - } -}; - -class mapTocheckAccess implements RowMapper { - @Override - //ParameterizedRowMapper mapTocheckAccess = new ParameterizedRowMapper() { - // @Override - public String mapRow(ResultSet rs, int rowNum) throws SQLException { - - String resultRow = "\\share_id=" + rs.getString("c_share_id") + "\\user_id=" + rs.getString("c_user_id") + "\\type=" + rs.getString("c_work_xml_i2b2_type") ; - - return resultRow; - } -}; - -class mapToFolderXML implements RowMapper { - //ParameterizedRowMapper map2 = new ParameterizedRowMapper() { - @Override - public FolderType mapRow(ResultSet rs, int rowNum) throws SQLException { - FolderType child = new FolderType(); - child.setName(rs.getString("c_name")); - // child.setTooltip(rs.getString("c_tooltip")); - child.setWorkXmlI2B2Type(rs.getString("c_work_xml_i2b2_type")); - - return child; - } -}; - - -class getFolderTableMapper implements RowMapper { - @Override - public String mapRow(ResultSet rs, int rowNum) throws SQLException { - String str = "\\\\" + rs.getString("c_table_cd") + "\\" + rs.getString("c_table_name"); - return str; - } - -} - -class getTableMapper implements RowMapper { - @Override - public DblookupType mapRow(ResultSet rs, int rowNum) throws SQLException { - DblookupType dblu = new DblookupType(); - dblu.setDomainId(rs.getString("c_domain_id")); - dblu.setProjectPath(rs.getString("c_project_path")); - dblu.setOwnerId(rs.getString("c_owner_id")); - dblu.setDbFullschema(rs.getString("c_db_fullschema")); - dblu.setDbDatasource(rs.getString("c_db_datasource")); - dblu.setDbServertype(rs.getString("c_db_servertype")); - dblu.setDbNicename(rs.getString("c_db_nicename")); - dblu.setDbTooltip(rs.getString("c_db_tooltip")); - dblu.setComment(rs.getString("c_comment")); - dblu.setEntryDate(rs.getString("c_entry_date")); - dblu.setChangeDate(rs.getString("c_change_date")); - dblu.setStatusCd(rs.getString("c_status_cd")); - return dblu; - } -} - - -class GetFolderMapper implements RowMapper { - - public void setDbType(String dbType) { - this.dbType = dbType; - } - public void setType(String type) { - this.type = type; - } - public void setBlob(boolean isBlob) { - this.isBlob = isBlob; - } - public void setTableCd(String tableCd) { - this.tableCd = tableCd; - } - String type; - boolean isBlob; - String tableCd; - String dbType; - @Override - public FolderType mapRow(ResultSet rs, int rowNum) throws SQLException { - - - - //private ParameterizedRowMapper getMapper(final String type, final boolean isBlob, final String tableCd, final String dbType){ - - FolderType child = new FolderType(); - //TODO fix this for all/+blob - if (tableCd == null){ - // child.setHierarchy("\\\\" + rs.getString("c_table_cd")+ rs.getString("c_hierarchy")); - child.setIndex("\\\\" + rs.getString("c_table_cd")+ "\\" + rs.getString("c_index")); - } - else{ - // child.setHierarchy("\\\\" + tableCd + rs.getString("c_hierarchy")); - child.setIndex("\\\\" + tableCd + "\\" + rs.getString("c_index")); - } - // log.debug("getMapper: " + child.getIndex()); - child.setName(rs.getString("c_name")); - - child.setProtectedAccess(rs.getString("c_protected_access")); - - if(!(type.equals("default"))) { - child.setUserId(rs.getString("c_user_id")); - // child.setHlevel(rs.getInt("c_hlevel")); - child.setGroupId(rs.getString("c_group_id")); - child.setVisualAttributes(rs.getString("c_visualattributes")); - // child.setIndex(rs.getString("c_index")); - child.setParentIndex(rs.getString("c_parent_index")); - child.setShareId(rs.getString("c_share_id" )); - - // Building tooltip for the response - // eg. project name - cname \n tooltip from db - String toolTip = rs.getString("c_group_id") + " - " + rs.getString("c_name") ; - if(rs.getString("c_tooltip")!=null && !rs.getString("c_tooltip").isEmpty()){ - toolTip = toolTip + "\n" + rs.getString("c_tooltip"); - } - - //child.setTooltip(rs.getString("c_tooltip")); - child.setTooltip(toolTip); - - }if(isBlob == true){ - child.setWorkXmlI2B2Type(rs.getString("c_work_xml_i2b2_type")); - - String c_xml = null; - try { - if (dbType.equals("POSTGRESQL")) - { - c_xml = rs.getString("c_work_xml"); - } else - { - c_xml = rs.getString("c_work_xml"); //JDBCUtil.getClobString(rs.getClob("c_work_xml")); - } - if (c_xml != null){ - //c_xml = JDBCUtil.getClobString(xml_clob); - if ((c_xml!=null)&&(c_xml.trim().length()>0)&&(!c_xml.equals("(null)"))) - { - //SAXBuilder parser = new SAXBuilder(); - //java.io.StringReader xmlStringReader = new java.io.StringReader(c_xml); - Element rootElement = null; - try { - //org.jdom.Document metadataDoc = parser.build(xmlStringReader); - Document doc = XMLUtil.loadXMLFrom(new java.io.ByteArrayInputStream(c_xml.getBytes())); - //org.jdom.output.DOMOutputter out = new DOMOutputter(); - //Document doc = out.output(metadataDoc); - rootElement = doc.getDocumentElement(); - } catch (IOException e1) { - child.setWorkXml(null); - } - if (rootElement != null) { - XmlValueType xml = new XmlValueType(); - xml.getAny().add(rootElement); - child.setWorkXml(xml); - } - else { - // log.debug("rootElement is null"); - child.setWorkXml(null); - } - }else { - // log.debug("work xml is null"); - child.setWorkXml(null); - } - } - else { - // log.debug("work xml is null"); - child.setWorkXml(null); - } - } catch (Exception e) { - child.setWorkXml(null); - } - - try { - Clob xml_schema_clob = rs.getClob("c_work_xml_schema"); - if (xml_schema_clob != null){ - c_xml = JDBCUtil.getClobString(xml_schema_clob); - if ((c_xml!=null)&&(c_xml.trim().length()>0)&&(!c_xml.equals("(null)"))) - { - Element rootElement = null; - try { - //org.jdom.Document metadataDoc = parser.build(xmlStringReader); - Document doc = XMLUtil.loadXMLFrom(new java.io.ByteArrayInputStream(c_xml.getBytes())); - //org.jdom.output.DOMOutputter out = new DOMOutputter(); - //Document doc = out.output(metadataDoc); - rootElement = doc.getDocumentElement(); - - } catch (IOException e1) { - child.setWorkXmlSchema(null); - } - if (rootElement != null) { - XmlValueType xml = new XmlValueType(); - xml.getAny().add(rootElement); - child.setWorkXmlSchema(xml); - } - else { - // log.debug("rootElement is null"); - child.setWorkXmlSchema(null); - } - }else { - // log.debug("work xml schema is null"); - child.setWorkXmlSchema(null); - } - } - else { - // log.debug("work xml schema is null"); - child.setWorkXmlSchema(null); - } - } catch (Exception e) { - child.setWorkXmlSchema(null); - } - } - if((type.equals("all"))){ - DTOFactory factory = new DTOFactory(); - // make sure date isnt null before converting to XMLGregorianCalendar - Date date = rs.getDate("c_entry_date"); - if (date == null) - child.setEntryDate(null); - else - child.setEntryDate(factory.getXMLGregorianCalendar(date.getTime())); - - date = rs.getDate("c_change_date"); - if (date == null) - child.setChangeDate(null); - else - child.setChangeDate(factory.getXMLGregorianCalendar(date.getTime())); - - child.setStatusCd(rs.getString("c_status_cd")); - - } - return child; - } - - -} - +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Lori Phillips + */ +package edu.harvard.i2b2.workplace.dao; + +import java.io.IOException; +import java.sql.Clob; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Date; +import javax.sql.DataSource; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.dao.DataAccessException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.RowMapper; +import org.springframework.jdbc.core.support.JdbcDaoSupport; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.db.JDBCUtil; +import edu.harvard.i2b2.common.util.jaxb.DTOFactory; +import edu.harvard.i2b2.common.util.xml.XMLUtil; +import edu.harvard.i2b2.workplace.dao.GetFolderMapper; +import edu.harvard.i2b2.workplace.datavo.i2b2message.SecurityType; +import edu.harvard.i2b2.workplace.datavo.pm.ProjectType; +import edu.harvard.i2b2.workplace.datavo.wdo.AnnotateChildType; +import edu.harvard.i2b2.workplace.datavo.wdo.ChildType; +import edu.harvard.i2b2.workplace.datavo.wdo.DblookupType; +import edu.harvard.i2b2.workplace.datavo.wdo.DeleteChildType; +import edu.harvard.i2b2.workplace.datavo.wdo.ExportChildType; +import edu.harvard.i2b2.workplace.datavo.wdo.FolderType; +import edu.harvard.i2b2.workplace.datavo.wdo.GetChildrenType; +import edu.harvard.i2b2.workplace.datavo.wdo.GetReturnType; +import edu.harvard.i2b2.workplace.datavo.wdo.ProtectedType; +import edu.harvard.i2b2.workplace.datavo.wdo.RenameChildType; +import edu.harvard.i2b2.workplace.datavo.wdo.FindByChildType; +import edu.harvard.i2b2.workplace.datavo.wdo.XmlValueType; +import edu.harvard.i2b2.workplace.delegate.crc.CallCRCUtil; +import edu.harvard.i2b2.workplace.ejb.DBInfoType; +import edu.harvard.i2b2.workplace.util.StringUtil; +import edu.harvard.i2b2.workplace.util.WorkplaceUtil; + + +public class FolderDao extends JdbcDaoSupport { + + private static Log log = LogFactory.getLog(FolderDao.class); + protected static Log logesapi = LogFactory.getLog(FolderDao.class); + + // final static String CORE = " c_hierarchy, c_hlevel, c_name, c_user_id, c_group_id, c_share_id, c_index, c_parent_index, c_visualattributes, c_tooltip"; + // final static String DEFAULT = " c_name, c_hierarchy"; + final static String CORE = " c_name, c_user_id, c_group_id, c_protected_access, c_share_id, c_index, c_parent_index, c_visualattributes, c_tooltip"; + final static String DEFAULT = " c_name, c_index, c_protected_access "; + final static String ALL = CORE + ", c_entry_date, c_change_date, c_status_cd"; + final static String BLOB = ", c_work_xml, c_work_xml_schema, c_work_xml_i2b2_type "; + + private JdbcTemplate jt; + private String metadataSchema; + + private void setDataSource(String dataSource) { + DataSource ds = null; + try { + ds = WorkplaceUtil.getInstance().getDataSource(dataSource); + // metadataSchema = ds.getConnection().getSchema() + "."; + Connection conn = ds.getConnection(); + + metadataSchema = conn.getSchema() + "."; + conn.close(); + } catch (I2B2Exception e2) { + log.error(e2.getMessage());; + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + this.jt = new JdbcTemplate(ds); + } + + private String getMetadataSchema() throws I2B2Exception{ + + return metadataSchema; //WorkplaceUtil.getInstance().getMetaDataSchemaName(); + } + + + public List findRootFoldersByProject(final GetReturnType returnType, final String userId, final ProjectType projectInfo, final DBInfoType dbInfo) throws DataAccessException, I2B2Exception{ + + // find return parameters + String parameters = CORE; + if (returnType.getType().equals("core")){ + parameters = CORE; + } + /* else if (returnType.getType().equals("all")){ + parameters = ALL; + } + */ + + String metadataSchema = dbInfo.getDb_fullSchema(); + setDataSource(dbInfo.getDb_dataSource()); + + // 1. check if user already has a folder + // if not create one. + check_addRootNode(metadataSchema, userId, projectInfo, dbInfo); + + + // First step is to call PM to see what roles user belongs to. + + if (projectInfo.getRole().size() == 0) + { + log.error("no role found for this user in project: " + projectInfo.getName()); + I2B2Exception e = new I2B2Exception("No role found for user"); + throw e; + } + + boolean protectedAccess = false; + Iterator it = projectInfo.getRole().iterator(); + while (it.hasNext()){ + String role = (String) it.next(); + if(role.toLowerCase().equalsIgnoreCase("DATA_PROT")) { + protectedAccess = true; + break; + } + } + + //ParameterizedRowMapper mapper = getMapper(returnType.getType(), false, null, dbInfo.getDb_serverType()); + + GetFolderMapper mapper = GetTableMapper(returnType.getType(), false, null, dbInfo.getDb_serverType()); + + + List queryResult = null; + if (!protectedAccess){ + String tablesSql = "select distinct(c_table_cd), " + parameters + " from " + metadataSchema + "workplace_access where c_protected_access = ? and LOWER(c_group_id) = ? order by c_name"; //c_hierarchy"; + + try { + queryResult = jt.query(tablesSql, mapper, "N", projectInfo.getId().toLowerCase()); + } catch (DataAccessException e) { + log.error(e.getMessage()); + throw new I2B2DAOException("Database error"); + } + } + else{ + String tablesSql = "select distinct(c_table_cd), " + parameters + " from " + metadataSchema + "workplace_access where LOWER(c_group_id) = ? order by c_name"; //c_hierarchy"; + + try { + queryResult = jt.query(tablesSql, mapper, projectInfo.getId().toLowerCase()); + } catch (DataAccessException e) { + log.error(e.getMessage()); + throw new I2B2DAOException("Database Error"); + } + } + + log.debug("result size = " + queryResult.size()); + + return queryResult; + } + + public List findRootFoldersByUser(final GetReturnType returnType, final String userId, final ProjectType projectInfo, final DBInfoType dbInfo) throws DataAccessException, I2B2Exception{ + + // find return parameters + String parameters = CORE; + if (returnType.getType().equals("core")){ + parameters = CORE; + } + /* else if (returnType.getType().equals("all")){ + parameters = ALL; + } + */ + + String metadataSchema = dbInfo.getDb_fullSchema(); + setDataSource(dbInfo.getDb_dataSource()); + + + // 1. check if user already has a folder + // if not create one. + check_addRootNode(metadataSchema, userId, projectInfo, dbInfo); + + + if (projectInfo.getRole().size() == 0) + { + log.error("no role found for this user in project: " + projectInfo.getName()); + I2B2Exception e = new I2B2Exception("No role found for user"); + throw e; + } + + boolean protectedAccess = false; + Iterator it = projectInfo.getRole().iterator(); + while (it.hasNext()){ + String role = (String) it.next(); + if(role.toLowerCase().equalsIgnoreCase("DATA_PROT")) { + protectedAccess = true; + break; + } + } + + + GetFolderMapper mapper = GetTableMapper(returnType.getType(), false, null, dbInfo.getDb_serverType()); + + List queryResult = null; + if (!protectedAccess){ + String tablesSql = "select distinct(c_table_cd), " + parameters + " from " + metadataSchema + "workplace_access where (c_share_id = 'Y' and LOWER(c_group_id) = ?) or (c_protected_access = ? and LOWER(c_user_id) = ? and LOWER(c_group_id) = ?) order by c_name"; //c_hierarchy"; + + // log.info(tablesSql); + try { + queryResult = jt.query(tablesSql, mapper, projectInfo.getId().toLowerCase(), "N",userId.toLowerCase(), projectInfo.getId().toLowerCase()); + } catch (DataAccessException e) { + log.error(e.getMessage()); + throw new I2B2DAOException("Database error findRootFoldersByUser"); + } + } + else{ + String tablesSql = "select distinct(c_table_cd), " + parameters + " from " + metadataSchema + "workplace_access where (c_share_id = 'Y' and LOWER(c_group_id) = ?) or (LOWER(c_user_id) = ? and LOWER(c_group_id) = ?) order by c_name"; //c_hierarchy"; + try { + queryResult = jt.query(tablesSql, + GetTableMapper(returnType.getType(), false, null, dbInfo.getDb_serverType()) + , projectInfo.getId().toLowerCase(), userId.toLowerCase(), projectInfo.getId().toLowerCase()); + } catch (DataAccessException e) { + log.error(e.getMessage()); + throw new I2B2DAOException("Database Error findRootFoldersByUser 2"); + } + } + /* + ParameterizedRowMapper map = new ParameterizedRowMapper() { + public String mapRow(ResultSet rs, int rowNum) throws SQLException { + String name = "\\\\" + rs.getString("c_table_cd") + "\\" + rs.getString("c_table_name"); + return name; + } + }; + if(queryResult.size() == 0){ + // this means that user is accessing for first time + // grab tableCd tableName pair + // and then insert an entry for the user + String tablesSql = "select distinct(c_table_cd), c_table_name from " + metadataSchema + "workplace_access"; + + try { + queryResult = jt.query(tablesSql, map); + } catch (DataAccessException e) { + log.error(e.getMessage()); + throw new I2B2DAOException("Database Error"); + } + if(queryResult.size() == 0) + throw new I2B2DAOException("Database Error"); + else{ + queryResult= addRootNode((String)queryResult.get(0), userId, projectInfo, dbInfo); + } + }*/ + log.debug("result size = " + queryResult.size()); + + return queryResult; + } + + public void check_addRootNode(String metadataSchema, String userId, ProjectType projectInfo, DBInfoType dbInfo) throws I2B2DAOException, I2B2Exception{ + + String entriesSql = "select c_name from " + metadataSchema + "workplace_access where LOWER(c_user_id) = ? and LOWER(c_group_id) = ?"; + + /* + ParameterizedRowMapper map = new ParameterizedRowMapper() { + @Override + public String mapRow(ResultSet rs, int rowNum) throws SQLException { + String name = rs.getString("c_name") ; + return name; + } + }; + + String map = jt.queryForObject(entriesSql,String.class); + */ + List queryResult = null; + try { + //queryResult = jt.query(entriesSql, map, userId.toLowerCase(), projectInfo.getId().toLowerCase()); + queryResult = jt.queryForList(entriesSql, String.class, userId.toLowerCase(), projectInfo.getId().toLowerCase()); + + } catch (DataAccessException e1) { + // TODO Auto-generated catch block + log.error(e1.getMessage()); + throw new I2B2DAOException("Database Error check_addRootNode"); + } + // log.info("check for root node size = " + queryResult.size()); + if(queryResult.size() > 0) + return; + + // else queryResult is empty + // need to create a new entry for user + + //1. get ProtectedAccess status for user + if (projectInfo.getRole().size() == 0) + { + log.error("no role found for this user in project: " + projectInfo.getName()); + I2B2Exception e = new I2B2Exception("No role found for user"); + throw e; + } + + String protectedAccess = "N"; + Iterator it = projectInfo.getRole().iterator(); + while (it.hasNext()){ + String role = (String) it.next(); + if(role.toLowerCase().equals("protected_access")) { + protectedAccess = "Y"; + break; + } + } + // 2. Get tableCd tableName info + String tableSql = "select distinct(c_table_cd), c_table_name from " + metadataSchema + "workplace_access"; + + /* + ParameterizedRowMapper map2 = new ParameterizedRowMapper() { + @Override + public String mapRow(ResultSet rs, int rowNum) throws SQLException { + String name = "\\\\" + rs.getString("c_table_cd") + "\\" + rs.getString("c_table_name"); + return name; + } + }; + */ + String tableInfo = jt.queryForObject(tableSql, new getFolderTableMapper()); + //String tableInfo = (String)queryResult.get(0); + + //extract table code and table name + String tableCd = StringUtil.getTableCd(tableInfo); + String tableName = StringUtil.getIndex(tableInfo); + + String addSql = "insert into " + metadataSchema+ "workplace_access " + + "(c_table_cd, c_table_name, c_hlevel, c_protected_access, c_name, c_user_id, c_index, c_visualattributes, c_share_id, c_group_id, c_entry_date) values (?,?,?,?,?,?,?,?,?,?,?)"; + + int numRootsAdded = -1; + String index = StringUtil.generateMessageId(); + try { + numRootsAdded = jt.update(addSql, tableCd, tableName, 0, protectedAccess, + userId, userId,index, "CA", "N", projectInfo.getId(), Calendar.getInstance().getTime()); + + } catch (DataAccessException e) { + log.error("Dao addChild failed"); + log.error(e.getMessage()); + throw new I2B2DAOException("Data access error check_addRootNode" , e); + } + + // log.info(addSql + " " + numRowsAdded); + log.debug("Number of roots added: " + numRootsAdded); + + return; + + } + + public String exportNode(final ExportChildType childrenType, ProjectType projectInfo, SecurityType securityType) throws I2B2DAOException, I2B2Exception{ + + // find return parameters + String type = "core"; + String parameters = CORE; + + + + if (projectInfo.getRole().size() == 0) + { + log.error("no role found for this user in project: " + projectInfo.getName()); + I2B2Exception e = new I2B2Exception("No role found for user"); + throw e; + } + + boolean protectedAccess = false; + Iterator it = projectInfo.getRole().iterator(); + while (it.hasNext()){ + String role = (String) it.next(); + if(role.toLowerCase().equalsIgnoreCase("DATA_PROT")) { + protectedAccess = true; + break; + } + } + String queryResult = null; + + // Get the query master for the actual query run + if (childrenType.getType().equalsIgnoreCase("QM")) { + try { + log.debug("Start to get QM results from CRC"); + //CallCRCUtil callCRC = new CallCRCUtil(securityType, projectInfo.getId()); + log.debug("getting Response"); + queryResult = CallCRCUtil.callCRCQueryRequestXML(childrenType.getNode(), securityType, projectInfo.getId()); + logesapi.debug("got response: " + queryResult); + //if (masterInstanceResultResponseType != null && masterInstanceResultResponseType.getQueryMaster().size() > 0) + // queryResult =XMLUtil.convertDOMElementToString((Element) masterInstanceResultResponseType.getQueryMaster().get(0).getRequestXml().getContent().get(0)); ; //respoonseType.getQueryResultInstance(); + } catch (Exception e) { + log.error(e.getMessage()); + throw new I2B2DAOException("Database Error exportNode"); + } + //log.debug("result size = " + queryResult.size()); + // Get the analysis breakdowns + } else if (childrenType.getType().equalsIgnoreCase("QR")) { + try { + log.debug("Start to get QR results from CRC"); + //CallCRCUtil callCRC = new CallCRCUtil(securityType, projectInfo.getId()); + log.debug("getting Response"); + queryResult = CallCRCUtil.callCRCResultInstanceXML(childrenType.getNode(), securityType, projectInfo.getId()); + logesapi.debug("got response: " + queryResult); + //if (masterInstanceResultResponseType != null) + // queryResult = (String) masterInstanceResultResponseType.getCrcXmlResult().getXmlValue().getContent().get(0); + //XMLUtil.convertDOMElementToString((Element) masterInstanceResultResponseType.getCrcXmlResult().getXmlValue().getContent().get(0)); //respoonseType.getQueryResultInstance(); + //queryResult = jt.query(sql, mapper, parentIndex ); + } catch (Exception e) { + log.error(e.getMessage()); + throw new I2B2DAOException("Database Error exportNode2"); + } + //log.debug("result size = " + queryResult.size()); + } + logesapi.debug("result is: " + queryResult); + return queryResult; + + } + + public List findChildrenByParent(final GetChildrenType childrenType, ProjectType projectInfo, DBInfoType dbInfo) throws I2B2DAOException, I2B2Exception{ + + // find return parameters + String type = "core"; + String parameters = CORE; + if (childrenType.getType().equals("all")){ + parameters = ALL; + type = "all"; + } + if(childrenType.isBlob() == true) + parameters = parameters + BLOB; + + String metadataSchema = dbInfo.getDb_fullSchema(); + setDataSource(dbInfo.getDb_dataSource()); + + if (projectInfo.getRole().size() == 0) + { + log.error("no role found for this user in project: " + projectInfo.getName()); + I2B2Exception e = new I2B2Exception("No role found for user"); + throw e; + } + + boolean protectedAccess = false; + Iterator it = projectInfo.getRole().iterator(); + while (it.hasNext()){ + String role = (String) it.next(); + if(role.toLowerCase().equalsIgnoreCase("DATA_PROT")) { + protectedAccess = true; + break; + } + } + + /* + ParameterizedRowMapper map = new ParameterizedRowMapper() { + @Override + public String mapRow(ResultSet rs, int rowNum) throws SQLException { + String name = (rs.getString("c_table_name")); + return name; + } + }; + */ + + //extract table code + String tableCd = StringUtil.getTableCd(childrenType.getParent()); + // log.debug(tableCd); + String tableName=null; + if (!protectedAccess){ + String tableSql = "select distinct(c_table_name) from " + metadataSchema + "workplace_access where c_table_cd = ? and c_protected_access = ? "; + //log.info("getChildren " + tableSql + tableCd); + try { + //tableName = jt.queryForObject(tableSql, map, tableCd, "N"); + tableName = jt.queryForObject(tableSql,String.class, tableCd, "N"); + } catch (DataAccessException e) { + log.error(e.getMessage()); + throw new I2B2DAOException("Database Error findChildrenByParent" ); + } + }else { + String tableSql = "select distinct(c_table_name) from " + metadataSchema + "workplace_access where c_table_cd = ?"; + try { + //tableName = jt.queryForObject(tableSql, map, tableCd); + tableName = jt.queryForObject(tableSql,String.class, tableCd); + + } catch (DataAccessException e) { + log.error(e.getMessage()); + throw new I2B2DAOException("Database Error findChildrenByParent 2"); + } + } + + String hidden = ""; + if(childrenType.isHiddens() == false) + hidden = " and c_visualattributes not like '_H%'"; + + String sql = "select " + parameters +" from " + metadataSchema+tableName + " where c_parent_index = ? and (c_status_cd != 'D' or c_status_cd is null)"; + sql = sql + hidden + " order by c_name "; + + String parentIndex = StringUtil.getIndex(childrenType.getParent()); + + log.debug(sql + " " + parentIndex); + // log.info(type + " " + tableCd ); + + GetFolderMapper mapper = GetTableMapper(type, childrenType.isBlob(), tableCd, dbInfo.getDb_serverType()); + + List queryResult = null; + try { + queryResult = jt.query(sql, mapper, parentIndex ); + } catch (DataAccessException e) { + log.error(e.getMessage()); + throw new I2B2DAOException("Database Error findChildrenByParent 3"); + } + log.debug("result size = " + queryResult.size()); + + + return queryResult; + // tested statement with aqua data studio verified output from above against this. + // select c_fullname, c_name, c_synonym_cd, c_visualattributes from metadata.testrpdr + // where c_fullname like '\RPDR\Diagnoses\Circulatory system (390-459)\Arterial vascular disease (440-447)\(446) Polyarteritis nodosa and al%' + // and c_hlevel = 5 and c_visualattributes not like '_H%' and c_synonym_cd = 'N' + + // verified both with and without hiddens and synonyms. + + // clob test level = 4 + // \\testrpdr\RPDR\HealthHistory\PHY\Health Maintenance\Mammogram\Mammogram - Deferred + } + + /** + * This method finds the workplace with a given keyword. It first searches the WORKPLACE ACCESS table + * to find the table where the workplace contents are stored. And then it searches the resulting table + * for any content with given name and other parameters + * + * @param returnType + * @param userId + * @param projectInfo + * @param dbInfo + * @return + * @throws DataAccessException + * @throws I2B2Exception + * + * @author Neha Patel + */ + public List findWorkplaceByKeyword(final FindByChildType returnType, String userId, final ProjectType projectInfo, final DBInfoType dbInfo) throws DataAccessException, I2B2Exception{ + + // find return parameters + String type = "core"; // Default Type is core + String parameters = CORE; // parameters to be used in select statement + String category = ""; + String hiddenStr = ""; + String maxString = ""; + String searchWord = ""; + + if (returnType!=null){ + + // determines which columns should be used in select statement + if(returnType.getType().equals("all")){ + parameters = ALL; + type = "all"; + } + + // if request parameter blob is set to true then include + // columns with xml info in select statement :- + // c_work_xml, c_work_xml_schema, c_work_xml_i2b2_type + if(returnType.isBlob() == true) + parameters = parameters + BLOB; + + // category is the directory where user is looking for the content + category= returnType.getCategory(); + + // request parameter hidden indicates to display hidden files or not + if(returnType.isHiddens() == false) + hiddenStr = " and c_visualattributes not like '_H%'"; + + // get strategy if content name starts with given word + // or it contains given word or it ends with given word + if(returnType.getMatchStr().getStrategy().equals("exact")) { + searchWord = returnType.getMatchStr().getValue().toLowerCase(); + } + + else if(returnType.getMatchStr().getStrategy().equals("left")){ + searchWord = returnType.getMatchStr().getValue().toLowerCase()+ "%"; + } + + else if(returnType.getMatchStr().getStrategy().equals("right")) { + searchWord ="%"+ returnType.getMatchStr().getValue().toLowerCase(); + } + + else if(returnType.getMatchStr().getStrategy().equals("contains")) { + searchWord = "%" + returnType.getMatchStr().getValue().toLowerCase() + "%"; + } + + try { + // setting max number of rows to be returned + if(returnType.getMax() !=null && returnType.getMax()>0 && dbInfo!=null){ + int fetchSize = returnType.getMax() +1 ; + + // if server is oracle then use rownum to return max number of rows + if(dbInfo.getDb_serverType().toUpperCase().equals("ORACLE")) + maxString = " and rownum>0 and rownum <=" + fetchSize; + + // if server is SQL SERVER then use 'TOP' clause to return max number of rows + else if(dbInfo.getDb_serverType().toUpperCase().equals("SQLSERVER")){ + maxString = "TOP " + fetchSize + " "; + parameters = maxString + parameters; // appended maxstring infront of parameters + maxString = ""; + } + //else if(dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL")) + // maxString = " limit " + fetchSize; + + } + } + catch( Exception e){ + log.error(e); + } + } + + if (projectInfo.getRole().size() == 0) + { + log.error("no role found for this user in project: " + projectInfo.getName()); + I2B2Exception e = new I2B2Exception("No role found for user"); + throw e; + } + + boolean protectedAccess = false; + Iterator it = projectInfo.getRole().iterator(); + while (it.hasNext()){ + String role = (String) it.next(); + if(role.toLowerCase().equalsIgnoreCase("DATA_PROT")) { + protectedAccess = true; + break; + } + } + + if(returnType.getCategory().trim().equalsIgnoreCase("@")){ + return findInAll(returnType, projectInfo, type, parameters, hiddenStr, maxString, searchWord, protectedAccess, dbInfo, userId ); + } + else { + return findInCategory(returnType, projectInfo, type, parameters, category, hiddenStr, maxString, searchWord, dbInfo, protectedAccess); + } + + } + + /** + * This method finds the search word in the given category. + * + * @param returnType + * @param projectInfo + * @param type - parameters to be used in the select statement. Can have two values core or all + * @param parameters + * @param category + * @param hiddenStr - string to be used in where clause + * @param maxString - string to be used in select or where clause + * @param searchWord + * @param dbInfo + * @param protectedAccess + * @return + * @throws I2B2DAOException + * + * @author Neha Patel + */ + private List findInCategory(final FindByChildType returnType, final ProjectType projectInfo, String type, String parameters, String category, String hiddenStr, String maxString, + String searchWord, final DBInfoType dbInfo, boolean protectedAccess) throws I2B2DAOException { + + String metadataSchema = dbInfo.getDb_fullSchema(); + setDataSource(dbInfo.getDb_dataSource()); + + /* + ParameterizedRowMapper map = new ParameterizedRowMapper() { + @Override + public String mapRow(ResultSet rs, int rowNum) throws SQLException { + String name = "\\\\" + rs.getString("c_table_cd") + "\\" + rs.getString("c_table_name"); + return name; + } + }; + + */ + // Getting tablename where the content is saved from table 'WORKPLACE' + List queryResult = null; + + String resultStr=null; + StringBuilder sqlToRetreiveTableNm = new StringBuilder( "select distinct c_table_cd, c_table_name from " + metadataSchema + "workplace_access where LOWER(c_user_id) = ? and LOWER(c_group_id) = ?"); + if (!protectedAccess){ + + sqlToRetreiveTableNm.append(" and c_protected_access = ? "); + try { + queryResult = jt.query(sqlToRetreiveTableNm.toString(), new getFolderTableMapper(), category.toLowerCase(), projectInfo.getId().toLowerCase(), "N"); + resultStr = (String)queryResult.get(0); + } catch (DataAccessException e) { + log.error(e.getMessage()); + throw new I2B2DAOException("findWorkplaceByKeyword(): Database Error while accessing workplace_access table with protected access"); + } + }else { + try { + queryResult = jt.query(sqlToRetreiveTableNm.toString(), new getFolderTableMapper(), category.toLowerCase(), projectInfo.getId().toLowerCase()); + resultStr = (String)queryResult.get(0); + } catch (DataAccessException e) { + log.error(e.getMessage()); + throw new I2B2DAOException("findWorkplaceByKeyword(): Database Error while accessing workplace_access table"); + } + } + + String tableCd = StringUtil.getTableCd(resultStr); + String tableName = StringUtil.getIndex(resultStr); + + StringBuilder sql = new StringBuilder ("select " + parameters +" from " + metadataSchema+tableName + " where LOWER(c_user_id) = ? and LOWER(c_group_id) = ? and LOWER(c_name) like ? and (c_status_cd != 'D' or c_status_cd is null) "); + sql.append( hiddenStr + maxString ); + + GetFolderMapper mapper = GetTableMapper(type, returnType.isBlob(), tableCd, dbInfo.getDb_serverType()); + + + /* + * commenting out protectedAcess code from workplace table for now + * + if (!protectedAccess){ + sql.append(" and (c_protected_access != 'Y' or c_protected_access is null) "); + } + */ + + sql.append( " order by c_name "); + + // Executing the query to find the workplace content with the given name + List queryResult2; + + try { + queryResult2 = jt.query(sql.toString(), mapper, category.toLowerCase(), projectInfo.getId().toLowerCase(), searchWord ); + } catch (DataAccessException e) { + log.error(e.getMessage()); + log.error("findWorkplaceByKeyword(): Database Error while accessing workplace table"); + throw new I2B2DAOException("findWorkplaceByKeyword(): Database Error while accessing workplace table"); + } + + log.debug("result size = " + queryResult2.size()); + + return queryResult2; + } + + /** + * This method searches for the word in the whole project. If the user has a manager role then it searches in the whole project + * if the user doesn't have manager role then it searches with the condition of userid or share = Y + * + * @param returnType + * @param projectInfo + * @param type + * @param parameters + * @param hiddenStr + * @param maxString + * @param searchWord + * @param protectedAccess + * @param dbInfo + * @param userId + * @return + * @throws DataAccessException + * @throws I2B2Exception + * + * @author Neha Patel + */ + private List findInAll(final FindByChildType returnType, final ProjectType projectInfo, String type, String parameters, String hiddenStr, String maxString, + String searchWord, boolean protectedAccess, final DBInfoType dbInfo, final String userId) throws DataAccessException, I2B2Exception{ + + + // Check if user is a manager + boolean managerRole = false; + for(String param :projectInfo.getRole()) { + if(param.equalsIgnoreCase("manager")) { + managerRole = true; + break; + } + } + + String metadataSchema = dbInfo.getDb_fullSchema(); + setDataSource(dbInfo.getDb_dataSource()); + + /* + ParameterizedRowMapper map = new ParameterizedRowMapper() { + @Override + public String mapRow(ResultSet rs, int rowNum) throws SQLException { + String name = "\\\\" + rs.getString("c_table_cd") + "\\" + rs.getString("c_table_name"); + return name; + } + }; + */ + + // Getting tablename where the content is saved from table 'WORKPLACE' + List queryResult = null; + + String resultStr=null; + StringBuilder sqlToRetreiveTableNm = new StringBuilder( "select distinct c_table_cd, c_table_name from " + metadataSchema + "workplace_access where "); + + // if user is a manager then search in the whole project + if(managerRole){ + sqlToRetreiveTableNm.append("LOWER(c_group_id) = ? "); + } + else { + // if user is not a manager then user should be able to search only in his folder or shared folder of the project + sqlToRetreiveTableNm.append("(LOWER(c_user_id) = ? and LOWER(c_group_id) = ?) or (LOWER(c_group_id) = ? and c_share_id = 'Y') "); + } + + if (!protectedAccess){ + sqlToRetreiveTableNm.append(" and (c_protected_access = 'N' or c_protected_access is null) "); + } + + try { + if(managerRole){ + queryResult = jt.queryForList(sqlToRetreiveTableNm.toString(), new getFolderTableMapper(), projectInfo.getId().toLowerCase()); + } + else { + queryResult = jt.queryForList(sqlToRetreiveTableNm.toString(), new getFolderTableMapper(), userId.toLowerCase(), projectInfo.getId().toLowerCase(), projectInfo.getId().toLowerCase()); + } + resultStr = (String)queryResult.get(0); + } catch (DataAccessException e) { + log.error(e.getMessage()); + throw new I2B2DAOException("findWorkplaceByKeyword(): Database Error while accessing workplace_access table with protected access"); + } + + String tableCd = ""; + String tableName = ""; + List returnResult = null; + + // Run the query for each tablename. There could be more than one table where workplace content is stored + if(queryResult != null && !queryResult.isEmpty()){ + Iterator itr = queryResult.iterator(); + while(itr.hasNext()){ + resultStr = (String)itr.next(); + tableCd = StringUtil.getTableCd(resultStr); + tableName = StringUtil.getIndex(resultStr); + + StringBuilder sql = new StringBuilder ("select from where LOWER(c_name) like ? and (c_status_cd != 'D' or c_status_cd is null) "); + + if(managerRole){ + sql.append("and LOWER(c_group_id) = ? "); + } + else { + sql.append("and ((LOWER(c_user_id) = ? and LOWER(c_group_id) = ?) or (LOWER(c_group_id) = ? and c_share_id = 'Y')) "); + } + + sql.append( hiddenStr + maxString ); + + GetFolderMapper mapper = GetTableMapper(type, returnType.isBlob(), tableCd, dbInfo.getDb_serverType()); + + /* + * commenting out protectedAcess code from workplace table for now + * + if (!protectedAccess){ + sql.append(" and (c_protected_access != 'Y' or c_protected_access is null) "); + } + */ + + sql.append( " order by c_name "); + + // Executing the query to find the workplace content with the given name + List workplaceResult=null; + + try { + + String sqlFinal = sql.toString().replace("", metadataSchema + tableName); + sqlFinal = sqlFinal.toString().replace("", parameters); + + + if(managerRole){ + workplaceResult = jt.query(sqlFinal, mapper, searchWord, projectInfo.getId().toLowerCase() ); + } + else { + workplaceResult = jt.query(sqlFinal, mapper, searchWord, userId.toLowerCase(), projectInfo.getId().toLowerCase(), projectInfo.getId().toLowerCase() ); + } + } catch (DataAccessException e) { + log.error(e.getMessage()); + log.error("findWorkplaceByKeyword(): Database Error while accessing workplace table"); + throw new I2B2DAOException("findWorkplaceByKeyword(): Database Error while accessing workplace table"); + } + + if(returnResult==null){ + returnResult=workplaceResult; + } + else { + returnResult.addAll(workplaceResult); + } + } // end while (itr.hasNext()) + + } + log.debug("result size = " + returnResult.size()); + + return returnResult; + } + + /** + * This method determines if the given category(workplace root folder name) is shared or not by + * checking c_share_id parameter in workplace_access table + * + * @param category - the root folder name which is in question if its shared or not + * @param projectInfo + * @param dbInfo + * @return + * @throws DataAccessException + * @throws I2B2Exception + * + * @author Neha Patel + */ + public boolean isShared(String category, final ProjectType projectInfo, final DBInfoType dbInfo) throws DataAccessException, I2B2Exception{ + + boolean isSharedBool= false; + String metadataSchema = dbInfo.getDb_fullSchema(); + setDataSource(dbInfo.getDb_dataSource()); + + /* + ParameterizedRowMapper map = new ParameterizedRowMapper() { + @Override + public String mapRow(ResultSet rs, int rowNum) throws SQLException { + String name = rs.getString("c_share_id") ; + return name; + } + }; + */ + + // Getting column 'c_share_id' to check if the given category/folder is shared + List queryResult = null; + String resultStr=""; + + String sqlForCheckingShared = "select c_share_id from " + metadataSchema + "workplace_access where LOWER(c_user_id) = ? and LOWER(c_group_id) = ? and (c_status_cd != 'D' or c_status_cd is null)"; + + try { + //queryResult = jt.query(sqlForCheckingShared.toString(), map, category.toLowerCase(), projectInfo.getId().toLowerCase()); + queryResult = jt.queryForList(sqlForCheckingShared.toString(), String.class, category.toLowerCase(), projectInfo.getId().toLowerCase()); + + if(queryResult !=null && !queryResult.isEmpty()){ + resultStr = (String)queryResult.get(0); + } + } catch (DataAccessException e) { + log.error(e.getMessage()); + throw new I2B2DAOException("isShared(): Database Error while accessing workplace_access table"); + } + + if(resultStr!=null && resultStr.toUpperCase().trim().equals("Y")){ + isSharedBool = true; + } + else + isSharedBool = false; + + return isSharedBool; + } + + public int renameNode(final RenameChildType renameChildType, ProjectType projectInfo, DBInfoType dbInfo) throws I2B2DAOException, I2B2Exception{ + + String metadataSchema = dbInfo.getDb_fullSchema(); + setDataSource(dbInfo.getDb_dataSource()); + + if (projectInfo.getRole().size() == 0) + { + log.error("no role found for this user in project: " + projectInfo.getName()); + I2B2Exception e = new I2B2Exception("No role found for user"); + throw e; + } + + boolean protectedAccess = false; + Iterator it = projectInfo.getRole().iterator(); + while (it.hasNext()){ + String role = (String) it.next(); + if(role.toLowerCase().equalsIgnoreCase("DATA_PROT")) { + protectedAccess = true; + break; + } + } + + /* + ParameterizedRowMapper map = new ParameterizedRowMapper() { + @Override + public String mapRow(ResultSet rs, int rowNum) throws SQLException { + String name = (rs.getString("c_table_name")); + return name; + } + }; + */ + + //extract table code + String tableCd = StringUtil.getTableCd(renameChildType.getNode()); + // table code to table name conversion + String tableName=null; + if (!protectedAccess){ + String tableSql = "select distinct(c_table_name) from " + metadataSchema + "workplace_access where c_table_cd = ? and c_protected_access = ? "; + try { + tableName = jt.queryForObject(tableSql, String.class, tableCd, "N"); + } catch (DataAccessException e) { + log.error(e.getMessage()); + throw new I2B2DAOException("Database Error"); + } + }else { + String tableSql = "select distinct(c_table_name) from " + metadataSchema + "workplace_access where c_table_cd = ?"; + try { + tableName = jt.queryForObject(tableSql, String.class, tableCd); + } catch (DataAccessException e) { + log.error(e.getMessage()); + throw new I2B2DAOException("Database Error"); + } + } + + String index = StringUtil.getIndex(renameChildType.getNode()); + + // get original name and work xml + String sql = "select c_name, c_work_xml, c_work_xml_i2b2_type from " + metadataSchema + tableName + " where c_index = ? "; + /* + ParameterizedRowMapper map2 = new ParameterizedRowMapper() { + @Override + public FolderType mapRow(ResultSet rs, int rowNum) throws SQLException { + FolderType child = new FolderType(); + child.setName(rs.getString("c_name")); + // child.setTooltip(rs.getString("c_tooltip")); + child.setWorkXmlI2B2Type(rs.getString("c_work_xml_i2b2_type")); + + return child; + } + }; + */ + List queryResult = null; + try { + queryResult = jt.query(sql, new mapToFolderXML(), index); + } catch (DataAccessException e) { + log.error("Dao queryResult failed"); + log.error(e.getMessage()); + throw new I2B2DAOException("Data access error " , e); + } + FolderType node = (FolderType)queryResult.get(0); + + // String newTooltip = StringUtil.replaceEnd(node.getTooltip(),node.getName(), renameChildType.getName()); + // log.info(newTooltip); + int numRowsRenamed = -1; + if(node.getWorkXmlI2B2Type().equals("FOLDER")){ + String updateSql = "update " + metadataSchema+tableName + " set c_name = ? where c_index = ? "; + try { + numRowsRenamed = jt.update(updateSql, renameChildType.getName(),index); + } catch (DataAccessException e) { + log.error("Dao renameChild failed"); + log.error(e.getMessage()); + throw new I2B2DAOException("Data access error " , e); + } + } + else { + String updateSql = "update " + metadataSchema+tableName + " set c_name = ? where c_index = ? "; + + /* + String newXml = null; + // Element newXmlElement = node.getWorkXml().getAny().get(0); + Element newXmlElement = renameChildType.getWorkXml().getAny().get(0); + if(newXmlElement != null){ + newXml = XMLUtil.convertDOMElementToString(newXmlElement); + // log.debug(newXml); + } + */ + try { + numRowsRenamed = jt.update(updateSql, renameChildType.getName(), index); + } catch (DataAccessException e) { + log.error("Dao renameChild failed"); + log.error(e.getMessage()); + throw new I2B2DAOException("Data access error " , e); + } + } + log.debug("Number of rows renamed: " + numRowsRenamed); + return numRowsRenamed; + + } + + public int moveNode(final ChildType childType, ProjectType projectInfo, DBInfoType dbInfo) throws I2B2DAOException, I2B2Exception{ + + String metadataSchema = dbInfo.getDb_fullSchema(); + setDataSource(dbInfo.getDb_dataSource()); + + if (projectInfo.getRole().size() == 0) + { + log.error("no role found for this user in project: " + projectInfo.getName()); + I2B2Exception e = new I2B2Exception("No role found for user"); + throw e; + } + + boolean protectedAccess = false; + Iterator it = projectInfo.getRole().iterator(); + while (it.hasNext()){ + String role = (String) it.next(); + if(role.toLowerCase().equalsIgnoreCase("DATA_PROT")) { + protectedAccess = true; + break; + } + } + + /* + ParameterizedRowMapper map = new ParameterizedRowMapper() { + @Override + public String mapRow(ResultSet rs, int rowNum) throws SQLException { + String name = (rs.getString("c_table_name")); + return name; + } + }; + */ + + //extract table code + String tableCd = StringUtil.getTableCd(childType.getNode()); + // table code to table name conversion + String tableName=null; + if (!protectedAccess){ + String tableSql = "select distinct(c_table_name) from " + metadataSchema + "workplace_access where c_table_cd = ? and c_protected_access = ? "; + try { + tableName = jt.queryForObject(tableSql, String.class, tableCd, "N"); + } catch (DataAccessException e) { + log.error(e.getMessage()); + throw new I2B2DAOException("Database Error"); + } + }else { + String tableSql = "select distinct(c_table_name) from " + metadataSchema + "workplace_access where c_table_cd = ?"; + try { + tableName = jt.queryForObject(tableSql, String.class, tableCd); + } catch (DataAccessException e) { + log.error(e.getMessage()); + throw new I2B2DAOException("Database Error"); + } + } + + String index = StringUtil.getIndex(childType.getNode()); + String updateSql = "update " + metadataSchema+tableName + " set c_parent_index = ? where c_index = ? "; + + int numRowsMoved = -1; + try { + numRowsMoved = jt.update(updateSql, childType.getParent(), index); + } catch (DataAccessException e) { + log.error("Dao moveChild failed"); + log.error(e.getMessage()); + throw new I2B2DAOException("Data access error " , e); + } + // log.info(updateSql + " " + path + " " + numRowsAnnotated); + log.debug("Number of rows moved: " + numRowsMoved); + return numRowsMoved; + + } + + public int annotateNode(final AnnotateChildType annotateChildType, ProjectType projectInfo, DBInfoType dbInfo) throws I2B2DAOException, I2B2Exception{ + + String metadataSchema = dbInfo.getDb_fullSchema(); + setDataSource(dbInfo.getDb_dataSource()); + + if (projectInfo.getRole().size() == 0) + { + log.error("no role found for this user in project: " + projectInfo.getName()); + I2B2Exception e = new I2B2Exception("No role found for user"); + throw e; + } + + boolean protectedAccess = false; + Iterator it = projectInfo.getRole().iterator(); + while (it.hasNext()){ + String role = (String) it.next(); + if(role.toLowerCase().equalsIgnoreCase("DATA_PROT")) { + protectedAccess = true; + break; + } + } + + /* + ParameterizedRowMapper map = new ParameterizedRowMapper() { + @Override + public String mapRow(ResultSet rs, int rowNum) throws SQLException { + String name = (rs.getString("c_table_name")); + return name; + } + }; + */ + + //extract table code + String tableCd = StringUtil.getTableCd(annotateChildType.getNode()); + // table code to table name conversion + String tableName=null; + if (!protectedAccess){ + String tableSql = "select distinct(c_table_name) from " + metadataSchema + "workplace_access where c_table_cd = ? and c_protected_access = ? "; + try { + tableName = jt.queryForObject(tableSql, String.class, tableCd, "N"); + } catch (DataAccessException e) { + log.error(e.getMessage()); + throw new I2B2DAOException("Database Error"); + } + }else { + String tableSql = "select distinct(c_table_name) from " + metadataSchema + "workplace_access where c_table_cd = ?"; + try { + tableName = jt.queryForObject(tableSql, String.class, tableCd); + } catch (DataAccessException e) { + log.error(e.getMessage()); + throw new I2B2DAOException("Database Error"); + } + } + + String index = StringUtil.getIndex(annotateChildType.getNode()); + String updateSql = "update " + metadataSchema+tableName + " set c_tooltip = ? where c_index = ? "; + + int numRowsAnnotated = -1; + try { + numRowsAnnotated = jt.update(updateSql, annotateChildType.getTooltip(), index); + } catch (DataAccessException e) { + log.error("Dao annotateChild failed"); + log.error(e.getMessage()); + throw new I2B2DAOException("Data access error " , e); + } + // log.info(updateSql + " " + path + " " + numRowsAnnotated); + log.debug("Number of rows annotated: " + numRowsAnnotated); + return numRowsAnnotated; + + } + + + public int addNode(final FolderType addChildType, ProjectType projectInfo, DBInfoType dbInfo) throws I2B2DAOException, I2B2Exception{ + + String metadataSchema = dbInfo.getDb_fullSchema(); + setDataSource(dbInfo.getDb_dataSource()); + + if (projectInfo.getRole().size() == 0) + { + log.error("no role found for this user in project: " + projectInfo.getName()); + I2B2Exception e = new I2B2Exception("No role found for user"); + throw e; + } + + boolean protectedAccess = false; + Iterator it = projectInfo.getRole().iterator(); + while (it.hasNext()){ + String role = (String) it.next(); + if(role.toLowerCase().equalsIgnoreCase("DATA_PROT")) { + protectedAccess = true; + break; + } + } + + /* + ParameterizedRowMapper map = new ParameterizedRowMapper() { + @Override + public String mapRow(ResultSet rs, int rowNum) throws SQLException { + String name = (rs.getString("c_table_name")); + return name; + } + }; + */ + + //extract table code + String tableCd = StringUtil.getTableCd(addChildType.getParentIndex()); + // table code to table name conversion + String tableName=null; + if (!protectedAccess){ + String tableSql = "select distinct(c_table_name) from " + metadataSchema + "workplace_access where c_table_cd = ? and c_protected_access = ? "; + try { + tableName = jt.queryForObject(tableSql, String.class, tableCd, "N"); + } catch (DataAccessException e) { + log.error(tableSql + tableCd); + log.error(e.getMessage()); + throw new I2B2DAOException("Database Error"); + } + }else { + String tableSql = "select distinct(c_table_name) from " + metadataSchema + "workplace_access where c_table_cd = ?"; + try { + tableName = jt.queryForObject(tableSql, String.class, tableCd); + } catch (DataAccessException e) { + log.error(e.getMessage()); + throw new I2B2DAOException("Database Error"); + } + } + + int numRowsAdded = -1; + try { + String xml = null; + XmlValueType workXml=addChildType.getWorkXml(); + if (workXml != null) { + String addSql = "insert into " + metadataSchema+tableName + + "(c_name, c_user_id, c_index, c_parent_index, c_visualattributes, c_group_id, c_share_id, c_tooltip, c_entry_date, c_work_xml, c_work_xml_i2b2_type) values (?,?,?,?,?,?,?,?,?,?,?)"; + Element element = workXml.getAny().get(0); + if(element != null) + xml = XMLUtil.convertDOMElementToString(element); + numRowsAdded = jt.update(addSql, + addChildType.getName(), addChildType.getUserId(),addChildType.getIndex(), StringUtil.getIndex(addChildType.getParentIndex()), + addChildType.getVisualAttributes(), addChildType.getGroupId(), addChildType.getShareId(), addChildType.getTooltip(), Calendar.getInstance().getTime(), + xml, addChildType.getWorkXmlI2B2Type()); + } + else { + String addSql = "insert into " + metadataSchema+tableName + + "(c_name, c_user_id, c_index, c_parent_index, c_visualattributes, c_group_id, c_share_id, c_tooltip, c_entry_date, c_work_xml_i2b2_type) values (?,?,?,?,?,?,?,?,?,?)"; + numRowsAdded = jt.update(addSql, + addChildType.getName(), addChildType.getUserId(),addChildType.getIndex(), StringUtil.getIndex(addChildType.getParentIndex()), + addChildType.getVisualAttributes(), addChildType.getGroupId(), addChildType.getShareId(), addChildType.getTooltip(), Calendar.getInstance().getTime(), + addChildType.getWorkXmlI2B2Type()); + } + } catch (DataAccessException e) { + log.error("Dao addChild failed"); + log.error(e.getMessage()); + throw new I2B2DAOException("Data access error " , e); + } + + // log.info(addSql + " " + numRowsAdded); + log.debug("Number of rows added: " + numRowsAdded); + + return numRowsAdded; + + } + + + public int deleteNode(final DeleteChildType deleteChildType, ProjectType projectInfo, DBInfoType dbInfo) throws DataAccessException, I2B2Exception{ + String metadataSchema = dbInfo.getDb_fullSchema(); + String serverType = dbInfo.getDb_serverType(); + setDataSource(dbInfo.getDb_dataSource()); + + if (projectInfo.getRole().size() == 0) + { + log.error("no role found for this user in project: " + projectInfo.getName()); + I2B2Exception e = new I2B2Exception("No role found for user"); + throw e; + } + + boolean protectedAccess = false; + Iterator it = projectInfo.getRole().iterator(); + while (it.hasNext()){ + String role = (String) it.next(); + if(role.toLowerCase().equalsIgnoreCase("DATA_PROT")) { + protectedAccess = true; + break; + } + } + + /* + ParameterizedRowMapper map = new ParameterizedRowMapper() { + @Override + public String mapRow(ResultSet rs, int rowNum) throws SQLException { + String name = (rs.getString("c_table_name")); + return name; + } + }; + */ + //extract table code + String tableCd = StringUtil.getTableCd(deleteChildType.getNode()); + // table code to table name conversion + String tableName=null; + if (!protectedAccess){ + String tableSql = "select distinct(c_table_name) from " + metadataSchema + "workplace_access where c_table_cd = ? and c_protected_access = ? "; + try { + tableName = jt.queryForObject(tableSql, String.class, tableCd, "N"); + } catch (DataAccessException e) { + log.error(e.getMessage()); + throw new I2B2DAOException("Database Error"); + } + }else { + String tableSql = "select distinct(c_table_name) from " + metadataSchema + "workplace_access where c_table_cd = ?"; + try { + tableName = jt.queryForObject(tableSql, String.class, tableCd); + } catch (DataAccessException e) { + log.error(e.getMessage()); + throw new I2B2DAOException("Database Error"); + } + } + String index = StringUtil.getIndex(deleteChildType.getNode()); + checkForChildrenDeletion(index, tableName, metadataSchema); + //Mark node for deletion + + String updateSql = " update " + metadataSchema+tableName + " set c_change_date = ?, c_status_cd = 'D' where c_index = ? "; + log.debug(serverType + "updateSql " + index); + int numRowsDeleted = -1; + try { + // log.info(sql + " " + w_index); + numRowsDeleted = jt.update(updateSql, Calendar.getInstance().getTime(),index); + } catch (DataAccessException e) { + log.error("Dao deleteChild failed"); + log.error(e.getMessage()); + throw e; + } + log.debug("Number of rows deleted " + numRowsDeleted); + return numRowsDeleted; + + } + + /** + * This method is to set protected access on a file/folder in workplace + * It first checks if user has correct privileges to the file, that is + * either he she is manager or the file is shared or the file belongs + * to him/her. The it searches for all the folders under the given + * index. if folders are found then it runs the update query atleast + * 3 times to update the root folder in workplace_access table, all the + * child folders in workplace table and all the child content in workplace + * table. + * + * @param requestType + * @param projectInfo + * @param dbInfo + * @param userId + * @return + * @throws I2B2DAOException + * @throws I2B2Exception + * + * @author Neha Patel + */ + public int setProtectedAccess(final ProtectedType requestType, final ProjectType projectInfo, final DBInfoType dbInfo, String userId) throws I2B2DAOException, I2B2Exception{ + + boolean settingRoot = false; + int numRowsSet = -1; + int numParentUpdated = -1; + int numWorkAccUpdated =-1; + String sharedStr =""; + String contentUserId = ""; + String tableName = ""; + boolean managerRole = false; + boolean isFolder = true; + + String metadataSchema = dbInfo.getDb_fullSchema(); + setDataSource(dbInfo.getDb_dataSource()); + + if (projectInfo.getRole().size() == 0) + { + log.error("no role found for this user in project: " + projectInfo.getName()); + I2B2Exception e = new I2B2Exception("No role found for user"); + throw e; + } + + // Check if user is a manager + for(String param :projectInfo.getRole()) { + if(param.equalsIgnoreCase("manager")) { + managerRole = true; + break; + } + } + + /* + ParameterizedRowMapper map = new ParameterizedRowMapper() { + @Override + public String mapRow(ResultSet rs, int rowNum) throws SQLException { + + String resultRow = "\\tablename=" + rs.getString("c_table_name") + "\\share_id=" + rs.getString("c_share_id") + "\\user_id=" + rs.getString("c_user_id") ; + + return resultRow; + } + }; + */ + + //extract table code and index + String tableCd = StringUtil.getTableCd(requestType.getIndex()); + String index = StringUtil.getIndex(requestType.getIndex()); + + List resultString = null; + StringBuilder sqlToRetrieveTableName = new StringBuilder("select distinct c_table_name, c_share_id, c_user_id from " + metadataSchema + + "workplace_access where LOWER(c_group_id) = ?"); + + // Check if the user is setting access for root directory + // by looking for index in the current table + try { + sqlToRetrieveTableName.append(" and c_index = ? "); + resultString = jt.query(sqlToRetrieveTableName.toString(), new mapToShareAccess(),projectInfo.getId().toLowerCase(), index); + } catch (DataAccessException e) { + log.error(e.getMessage()); + throw new I2B2DAOException("Database Error"); + } + + String resultToSplit= ""; + // if the above query returned any result + // that means user was setting access for root directory + if(resultString!=null && !resultString.isEmpty()){ + + settingRoot = true; + isFolder = true; + + // getting tablename, share_id, user_id from the result string + resultToSplit = (String) resultString.get(0); + int indexofShared = resultToSplit.indexOf("\\share_id="); + int indexofUser = resultToSplit.indexOf("\\user_id="); + tableName = resultToSplit.substring(11, indexofShared); + + // if its not manager check if the file/folder is shared + // if not shared either, then verify that user is setting + // privilege for his/her file/folder + if(managerRole == false){ + sharedStr = resultToSplit.substring(indexofShared+10, indexofUser); + contentUserId = resultToSplit.substring(indexofUser+9); + + if ((!sharedStr.equalsIgnoreCase("Y")) && (!contentUserId.equalsIgnoreCase(userId))){ + log.debug( "User does not have privileges to set protected access for this content"); + return -11111; + } // if (sharedStr==null || !sharedStr.equalsIgnoreCase("Y")) + } // if managerRole == false + } //if(resultString!=null && !resultString.isEmpty()) + // query result is null that means item doesn't exist in workplace_access table + // or user is not setting access for root directory + // Get tablename using the tablecd given as part of indexString in the request + else if(resultString == null || resultString.isEmpty()){ + + // replace the last condition of 'and c_index=?' with 'and c_table_cd' + sqlToRetrieveTableName.replace(sqlToRetrieveTableName.lastIndexOf("and"), sqlToRetrieveTableName.length()-1, " and LOWER(c_table_cd) = ? "); + + try { + resultString = jt.query(sqlToRetrieveTableName.toString(), new mapToShareAccess(), projectInfo.getId().toLowerCase(), tableCd.toLowerCase()); + } catch (DataAccessException e) { + log.error(e.getMessage()); + throw new I2B2DAOException("Database Error"); + } + + resultToSplit = (String) resultString.get(0); + + // getting tablename from the query result + tableName = resultToSplit.substring(11, resultToSplit.indexOf("\\share_id=")); + + List result; + /* + ParameterizedRowMapper mapTocheckAccess = new ParameterizedRowMapper() { + @Override + public String mapRow(ResultSet rs, int rowNum) throws SQLException { + + String resultRow = "\\share_id=" + rs.getString("c_share_id") + "\\user_id=" + rs.getString("c_user_id") + "\\type=" + rs.getString("c_work_xml_i2b2_type") ; + + return resultRow; + } + }; + */ + + // Run query in table workplace to find out if the content is shared or does it belong to user + // Also find the type of the file + String sql = "select c_share_id, c_user_id, c_work_xml_i2b2_type from " + metadataSchema + tableName + " where c_index = ? and LOWER(c_group_id) = ?"; + try{ + result = jt.query(sql, new mapTocheckAccess(), index, projectInfo.getId().toLowerCase()); + } catch (DataAccessException e) { + log.error(e.getMessage()); + throw new I2B2DAOException("Database Error"); + } + + // get the user id and share_id from result string + resultToSplit = (String) result.get(0); + String type = resultToSplit.substring(resultToSplit.lastIndexOf("\\")+6); + + if(!type.equalsIgnoreCase("FOLDER")){ + isFolder= false; + } + else + isFolder=true; + + // if user is not a manager + // then check if file/folder is shared + // if not shared then verify file/folder belongs to user + if(managerRole == false){ + + sharedStr = resultToSplit.substring(10, resultToSplit.indexOf("\\user_id=")); + contentUserId = resultToSplit.substring(resultToSplit.indexOf("\\user_id=")+9, resultToSplit.lastIndexOf("\\")); + + if ((sharedStr!=null && !sharedStr.equalsIgnoreCase("Y")) && (!contentUserId.equalsIgnoreCase(userId))){ + log.debug( "User does not have privileges to set protected access for this content"); + return -11111; + } // if (sharedStr==null || !sharedStr.equalsIgnoreCase("Y")) + } // if managerRole == false + } + + StringBuilder indexStr = new StringBuilder(); + String protectedAccVal= ""; + + if(requestType.getProtectedAccess().trim().equalsIgnoreCase("true")) + protectedAccVal = "Y"; + else + protectedAccVal = "N"; + + ArrayList parentIdxList = new ArrayList(); + parentIdxList.add(index); + indexStr.append("'" + index + "'"); + + // if initial request was for a folder only + // then run this part + if(isFolder){ + + List resultingIndx; + /* + ParameterizedRowMapper mapForIndexes = new ParameterizedRowMapper() { + @Override + public String mapRow(ResultSet rs, int rowNum) throws SQLException { + String name = (rs.getString("c_index")); + return name; + } + }; + */ + + // Get all the parent indexes (folder indexes under the top level directory) + // and store it in an arraylist + String parentIdx = ""; + for (int i = 0; i < parentIdxList.size(); i ++){ + try { + parentIdx = parentIdxList.get(i); + if(i>0){ + indexStr.append(", '" + parentIdx + "'"); + } + String sqlToCollectIndex = "select c_index from " + metadataSchema + tableName + " where c_parent_index = ? and LOWER(c_group_id) = ? and c_work_xml_i2b2_type = 'FOLDER'"; + resultingIndx = jt.queryForList(sqlToCollectIndex, String.class, parentIdx, projectInfo.getId().toLowerCase()); + } catch (DataAccessException e) { + log.error(e.getMessage()); + throw new I2B2DAOException("Database Error"); + } + if(resultingIndx != null) + parentIdxList.addAll(resultingIndx); + } + + // set the protected access for all the content found under the + // parent indexes stored in the arraylist + numParentUpdated = updateProtectedAccess(metadataSchema,tableName, "c_parent_index" , indexStr.toString(), protectedAccVal); + } + + if(settingRoot){ + // set the protected access for root directory which is in workplace_access table + numWorkAccUpdated = updateProtectedAccess(metadataSchema,"workplace_access", "c_index",indexStr.toString(), protectedAccVal); + } + + // If setting root folder, then set all the folders to protected access + // if setting one item then still use the same query to set that item to protected_access + numRowsSet = updateProtectedAccess(metadataSchema,tableName, "c_index",indexStr.toString(), protectedAccVal); + + // Return the correct number of updated rows + if(isFolder) + numRowsSet += numParentUpdated; + + if(settingRoot) + numRowsSet += numWorkAccUpdated; + + return numRowsSet; + } + + /** + * @param numRowsSet + * @param metadataSchema + * @param tableName + * @param indexStr + * @param protectedAccVal + * @return + * @throws I2B2DAOException + * + * @author Neha Patel + */ + private int updateProtectedAccess(String metadataSchema,String tableName, String columnName, String indexStr, String protectedAccVal) + throws I2B2DAOException { + + String updateSql = "update set c_protected_access = ? where in ( )"; + int numRowsSet=-1; + + try { + String sqlFinal = updateSql.replace("", metadataSchema+tableName); + sqlFinal = sqlFinal.replace("", columnName); + sqlFinal = sqlFinal.replace("", indexStr); + + String protectedAccValFinal = protectedAccVal.replace("", indexStr); + + numRowsSet = jt.update(sqlFinal, protectedAccValFinal); + } catch (DataAccessException e) { + log.error("Dao updateProtectedAccess failed"); + log.error(e.getMessage()); + throw new I2B2DAOException("Data access error " , e); + } + return numRowsSet; + } + + + private void checkForChildrenDeletion(String nodeIndex, String tableName, String metadataSchema) throws DataAccessException { + + // mark children for deletion + String updateSql = " update " + metadataSchema+tableName + " set c_change_date = ?, c_status_cd = 'D' where c_parent_index = ? "; + int numChildrenDeleted = -1; + try { + // log.info(sql + " " + w_index); + numChildrenDeleted = jt.update(updateSql, Calendar.getInstance().getTime(),nodeIndex); + } catch (DataAccessException e) { + log.error("Dao deleteChild failed"); + log.error(e.getMessage()); + throw e; + } + log.debug("Number of children deleted: "+ numChildrenDeleted); + // look for children that are folders + String folderSql = "select c_index from " + metadataSchema+tableName + " where c_parent_index = ? and c_visualattributes like 'F%' "; + + /* + ParameterizedRowMapper map = new ParameterizedRowMapper() { + @Override + public String mapRow(ResultSet rs, int rowNum) throws SQLException { + String index = (rs.getString("c_index")); + return index; + } + }; + */ + + List folders = null; + try{ + folders = jt.queryForList(folderSql, String.class, nodeIndex); + } catch (DataAccessException e) { + log.error(e.getMessage()); + throw e; + } + // recursively check folders for children to delete + if (folders != null){ + Iterator it = folders.iterator(); + while(it.hasNext()){ + String folderIndex = (String) it.next(); + checkForChildrenDeletion(folderIndex, tableName, metadataSchema); + } + } + + } + + private GetFolderMapper GetTableMapper(final String type, final boolean isBlob, final String tableCd, final String dbType) { + + + GetFolderMapper folderMapper = new GetFolderMapper(); + + folderMapper.setType(type); + folderMapper.setBlob(isBlob); + folderMapper.setTableCd(tableCd); + folderMapper.setDbType(dbType); + return folderMapper; + } + +} + + +class mapToShareAccess implements RowMapper { + //ParameterizedRowMapper map = new ParameterizedRowMapper() { + @Override + public String mapRow(ResultSet rs, int rowNum) throws SQLException { + + String resultRow = "\\tablename=" + rs.getString("c_table_name") + "\\share_id=" + rs.getString("c_share_id") + "\\user_id=" + rs.getString("c_user_id") ; + + return resultRow; + } +}; + +class mapTocheckAccess implements RowMapper { + @Override + //ParameterizedRowMapper mapTocheckAccess = new ParameterizedRowMapper() { + // @Override + public String mapRow(ResultSet rs, int rowNum) throws SQLException { + + String resultRow = "\\share_id=" + rs.getString("c_share_id") + "\\user_id=" + rs.getString("c_user_id") + "\\type=" + rs.getString("c_work_xml_i2b2_type") ; + + return resultRow; + } +}; + +class mapToFolderXML implements RowMapper { + //ParameterizedRowMapper map2 = new ParameterizedRowMapper() { + @Override + public FolderType mapRow(ResultSet rs, int rowNum) throws SQLException { + FolderType child = new FolderType(); + child.setName(rs.getString("c_name")); + // child.setTooltip(rs.getString("c_tooltip")); + child.setWorkXmlI2B2Type(rs.getString("c_work_xml_i2b2_type")); + + return child; + } +}; + + +class getFolderTableMapper implements RowMapper { + @Override + public String mapRow(ResultSet rs, int rowNum) throws SQLException { + String str = "\\\\" + rs.getString("c_table_cd") + "\\" + rs.getString("c_table_name"); + return str; + } + +} + +class getTableMapper implements RowMapper { + @Override + public DblookupType mapRow(ResultSet rs, int rowNum) throws SQLException { + DblookupType dblu = new DblookupType(); + dblu.setDomainId(rs.getString("c_domain_id")); + dblu.setProjectPath(rs.getString("c_project_path")); + dblu.setOwnerId(rs.getString("c_owner_id")); + dblu.setDbFullschema(rs.getString("c_db_fullschema")); + dblu.setDbDatasource(rs.getString("c_db_datasource")); + dblu.setDbServertype(rs.getString("c_db_servertype")); + dblu.setDbNicename(rs.getString("c_db_nicename")); + dblu.setDbTooltip(rs.getString("c_db_tooltip")); + dblu.setComment(rs.getString("c_comment")); + dblu.setEntryDate(rs.getString("c_entry_date")); + dblu.setChangeDate(rs.getString("c_change_date")); + dblu.setStatusCd(rs.getString("c_status_cd")); + return dblu; + } +} + + +class GetFolderMapper implements RowMapper { + + public void setDbType(String dbType) { + this.dbType = dbType; + } + public void setType(String type) { + this.type = type; + } + public void setBlob(boolean isBlob) { + this.isBlob = isBlob; + } + public void setTableCd(String tableCd) { + this.tableCd = tableCd; + } + String type; + boolean isBlob; + String tableCd; + String dbType; + @Override + public FolderType mapRow(ResultSet rs, int rowNum) throws SQLException { + + + + //private ParameterizedRowMapper getMapper(final String type, final boolean isBlob, final String tableCd, final String dbType){ + + FolderType child = new FolderType(); + //TODO fix this for all/+blob + if (tableCd == null){ + // child.setHierarchy("\\\\" + rs.getString("c_table_cd")+ rs.getString("c_hierarchy")); + child.setIndex("\\\\" + rs.getString("c_table_cd")+ "\\" + rs.getString("c_index")); + } + else{ + // child.setHierarchy("\\\\" + tableCd + rs.getString("c_hierarchy")); + child.setIndex("\\\\" + tableCd + "\\" + rs.getString("c_index")); + } + // log.debug("getMapper: " + child.getIndex()); + child.setName(rs.getString("c_name")); + + child.setProtectedAccess(rs.getString("c_protected_access")); + + if(!(type.equals("default"))) { + child.setUserId(rs.getString("c_user_id")); + // child.setHlevel(rs.getInt("c_hlevel")); + child.setGroupId(rs.getString("c_group_id")); + child.setVisualAttributes(rs.getString("c_visualattributes")); + // child.setIndex(rs.getString("c_index")); + child.setParentIndex(rs.getString("c_parent_index")); + child.setShareId(rs.getString("c_share_id" )); + + // Building tooltip for the response + // eg. project name - cname \n tooltip from db + String toolTip = rs.getString("c_group_id") + " - " + rs.getString("c_name") ; + if(rs.getString("c_tooltip")!=null && !rs.getString("c_tooltip").isEmpty()){ + toolTip = toolTip + "\n" + rs.getString("c_tooltip"); + } + + //child.setTooltip(rs.getString("c_tooltip")); + child.setTooltip(toolTip); + + }if(isBlob == true){ + child.setWorkXmlI2B2Type(rs.getString("c_work_xml_i2b2_type")); + + String c_xml = null; + try { + if (dbType.equals("POSTGRESQL")) + { + c_xml = rs.getString("c_work_xml"); + } else + { + c_xml = rs.getString("c_work_xml"); //JDBCUtil.getClobString(rs.getClob("c_work_xml")); + } + if (c_xml != null){ + //c_xml = JDBCUtil.getClobString(xml_clob); + if ((c_xml!=null)&&(c_xml.trim().length()>0)&&(!c_xml.equals("(null)"))) + { + //SAXBuilder parser = new SAXBuilder(); + //java.io.StringReader xmlStringReader = new java.io.StringReader(c_xml); + Element rootElement = null; + try { + //org.jdom.Document metadataDoc = parser.build(xmlStringReader); + Document doc = XMLUtil.loadXMLFrom(new java.io.ByteArrayInputStream(c_xml.getBytes())); + //org.jdom.output.DOMOutputter out = new DOMOutputter(); + //Document doc = out.output(metadataDoc); + rootElement = doc.getDocumentElement(); + } catch (IOException e1) { + child.setWorkXml(null); + } + if (rootElement != null) { + XmlValueType xml = new XmlValueType(); + xml.getAny().add(rootElement); + child.setWorkXml(xml); + } + else { + // log.debug("rootElement is null"); + child.setWorkXml(null); + } + }else { + // log.debug("work xml is null"); + child.setWorkXml(null); + } + } + else { + // log.debug("work xml is null"); + child.setWorkXml(null); + } + } catch (Exception e) { + child.setWorkXml(null); + } + + try { + Clob xml_schema_clob = rs.getClob("c_work_xml_schema"); + if (xml_schema_clob != null){ + c_xml = JDBCUtil.getClobString(xml_schema_clob); + if ((c_xml!=null)&&(c_xml.trim().length()>0)&&(!c_xml.equals("(null)"))) + { + Element rootElement = null; + try { + //org.jdom.Document metadataDoc = parser.build(xmlStringReader); + Document doc = XMLUtil.loadXMLFrom(new java.io.ByteArrayInputStream(c_xml.getBytes())); + //org.jdom.output.DOMOutputter out = new DOMOutputter(); + //Document doc = out.output(metadataDoc); + rootElement = doc.getDocumentElement(); + + } catch (IOException e1) { + child.setWorkXmlSchema(null); + } + if (rootElement != null) { + XmlValueType xml = new XmlValueType(); + xml.getAny().add(rootElement); + child.setWorkXmlSchema(xml); + } + else { + // log.debug("rootElement is null"); + child.setWorkXmlSchema(null); + } + }else { + // log.debug("work xml schema is null"); + child.setWorkXmlSchema(null); + } + } + else { + // log.debug("work xml schema is null"); + child.setWorkXmlSchema(null); + } + } catch (Exception e) { + child.setWorkXmlSchema(null); + } + } + if((type.equals("all"))){ + DTOFactory factory = new DTOFactory(); + // make sure date isnt null before converting to XMLGregorianCalendar + Date date = rs.getDate("c_entry_date"); + if (date == null) + child.setEntryDate(null); + else + child.setEntryDate(factory.getXMLGregorianCalendar(date.getTime())); + + date = rs.getDate("c_change_date"); + if (date == null) + child.setChangeDate(null); + else + child.setChangeDate(factory.getXMLGregorianCalendar(date.getTime())); + + child.setStatusCd(rs.getString("c_status_cd")); + + } + return child; + } + + +} + diff --git a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/dao/WorkplaceDbDao.java b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/dao/WorkplaceDbDao.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/dao/WorkplaceDbDao.java rename to edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/dao/WorkplaceDbDao.java diff --git a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/delegate/AddChildHandler.java b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/delegate/AddChildHandler.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/delegate/AddChildHandler.java rename to edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/delegate/AddChildHandler.java diff --git a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/delegate/AnnotateChildHandler.java b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/delegate/AnnotateChildHandler.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/delegate/AnnotateChildHandler.java rename to edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/delegate/AnnotateChildHandler.java index 4e39e257..acf2d52c --- a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/delegate/AnnotateChildHandler.java +++ b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/delegate/AnnotateChildHandler.java @@ -1,95 +1,95 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Lori Phillips - */ -package edu.harvard.i2b2.workplace.delegate; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.workplace.datavo.i2b2message.MessageHeaderType; -import edu.harvard.i2b2.workplace.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.workplace.datavo.wdo.AnnotateChildType; -import edu.harvard.i2b2.workplace.datavo.pm.ProjectType; -import edu.harvard.i2b2.workplace.dao.FolderDao; -import edu.harvard.i2b2.workplace.ws.AnnotateChildDataMessage; -import edu.harvard.i2b2.workplace.ws.MessageFactory; - - -public class AnnotateChildHandler extends RequestHandler { - private AnnotateChildDataMessage annotateChildMsg = null; - private AnnotateChildType annotateChildType = null; - private ProjectType projectInfo = null; - - public AnnotateChildHandler(AnnotateChildDataMessage requestMsg) throws I2B2Exception { - annotateChildMsg = requestMsg; - annotateChildType = requestMsg.getAnnotateChildType(); - annotateChildType.setNode(annotateChildType.getNode().replaceAll("\\<[^>]*>","")); - annotateChildType.setTooltip(annotateChildType.getTooltip().replaceAll("\\<[^>]*>","")); - - // test bad username -- good 2/1/08 - // annotateChildMsg.getMessageHeaderType().getSecurity().setUsername("bad"); - projectInfo = getRoleInfo(requestMsg.getMessageHeaderType()); - setDbInfo(requestMsg.getMessageHeaderType()); - } - - @Override - public String execute() throws I2B2Exception { - // call ejb and pass input object - FolderDao annotateChildDao = new FolderDao(); - ResponseMessageType responseMessageType = null; - int numAnnotated = -1; - - // check to see if we have projectInfo (if not indicates PM service problem) - if(projectInfo == null) { - String response = null; - responseMessageType = MessageFactory.doBuildErrorResponse(annotateChildMsg.getMessageHeaderType(), "User was not validated"); - response = MessageFactory.convertToXMLString(responseMessageType); - log.debug("USER_INVALID or PM_SERVICE_PROBLEM"); - return response; - } - - else { - try { - numAnnotated = annotateChildDao.annotateNode(annotateChildType, projectInfo, this.getDbInfo()); - } catch (I2B2DAOException e) { - log.error("AnnotateChildHandler received I2B2DAO exception from DAO"); - responseMessageType = MessageFactory.doBuildErrorResponse(annotateChildMsg.getMessageHeaderType(), "Database error"); - } catch (I2B2Exception e) { - log.error("AnnotateChildHandler received I2B2 exception from DAO"); - responseMessageType = MessageFactory.doBuildErrorResponse(annotateChildMsg.getMessageHeaderType(), "Database error"); - } - } - - // no errors found - if(responseMessageType == null) { - // no db error but response is empty - if (numAnnotated == 0) { - log.error("annotate object not found"); - responseMessageType = MessageFactory.doBuildErrorResponse(annotateChildMsg.getMessageHeaderType(), "Node not found"); - } - else if (numAnnotated == -1) { - log.error("database error"); - responseMessageType = MessageFactory.doBuildErrorResponse(annotateChildMsg.getMessageHeaderType(), "Database error"); - } - else { - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(annotateChildMsg.getMessageHeaderType()); -// responseMessageType = MessageFactory.createBuildResponse(messageHeader, null); - responseMessageType = MessageFactory.createBuildResponse(messageHeader); - } - } - String responseWdo = null; - responseWdo = MessageFactory.convertToXMLString(responseMessageType); - return responseWdo; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Lori Phillips + */ +package edu.harvard.i2b2.workplace.delegate; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.workplace.datavo.i2b2message.MessageHeaderType; +import edu.harvard.i2b2.workplace.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.workplace.datavo.wdo.AnnotateChildType; +import edu.harvard.i2b2.workplace.datavo.pm.ProjectType; +import edu.harvard.i2b2.workplace.dao.FolderDao; +import edu.harvard.i2b2.workplace.ws.AnnotateChildDataMessage; +import edu.harvard.i2b2.workplace.ws.MessageFactory; + + +public class AnnotateChildHandler extends RequestHandler { + private AnnotateChildDataMessage annotateChildMsg = null; + private AnnotateChildType annotateChildType = null; + private ProjectType projectInfo = null; + + public AnnotateChildHandler(AnnotateChildDataMessage requestMsg) throws I2B2Exception { + annotateChildMsg = requestMsg; + annotateChildType = requestMsg.getAnnotateChildType(); + annotateChildType.setNode(annotateChildType.getNode().replaceAll("\\<[^>]*>","")); + annotateChildType.setTooltip(annotateChildType.getTooltip().replaceAll("\\<[^>]*>","")); + + // test bad username -- good 2/1/08 + // annotateChildMsg.getMessageHeaderType().getSecurity().setUsername("bad"); + projectInfo = getRoleInfo(requestMsg.getMessageHeaderType()); + setDbInfo(requestMsg.getMessageHeaderType()); + } + + @Override + public String execute() throws I2B2Exception { + // call ejb and pass input object + FolderDao annotateChildDao = new FolderDao(); + ResponseMessageType responseMessageType = null; + int numAnnotated = -1; + + // check to see if we have projectInfo (if not indicates PM service problem) + if(projectInfo == null) { + String response = null; + responseMessageType = MessageFactory.doBuildErrorResponse(annotateChildMsg.getMessageHeaderType(), "User was not validated"); + response = MessageFactory.convertToXMLString(responseMessageType); + log.debug("USER_INVALID or PM_SERVICE_PROBLEM"); + return response; + } + + else { + try { + numAnnotated = annotateChildDao.annotateNode(annotateChildType, projectInfo, this.getDbInfo()); + } catch (I2B2DAOException e) { + log.error("AnnotateChildHandler received I2B2DAO exception from DAO"); + responseMessageType = MessageFactory.doBuildErrorResponse(annotateChildMsg.getMessageHeaderType(), "Database error"); + } catch (I2B2Exception e) { + log.error("AnnotateChildHandler received I2B2 exception from DAO"); + responseMessageType = MessageFactory.doBuildErrorResponse(annotateChildMsg.getMessageHeaderType(), "Database error"); + } + } + + // no errors found + if(responseMessageType == null) { + // no db error but response is empty + if (numAnnotated == 0) { + log.error("annotate object not found"); + responseMessageType = MessageFactory.doBuildErrorResponse(annotateChildMsg.getMessageHeaderType(), "Node not found"); + } + else if (numAnnotated == -1) { + log.error("database error"); + responseMessageType = MessageFactory.doBuildErrorResponse(annotateChildMsg.getMessageHeaderType(), "Database error"); + } + else { + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(annotateChildMsg.getMessageHeaderType()); +// responseMessageType = MessageFactory.createBuildResponse(messageHeader, null); + responseMessageType = MessageFactory.createBuildResponse(messageHeader); + } + } + String responseWdo = null; + responseWdo = MessageFactory.convertToXMLString(responseMessageType); + return responseWdo; + } + +} diff --git a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/delegate/DeleteChildHandler.java b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/delegate/DeleteChildHandler.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/delegate/DeleteChildHandler.java rename to edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/delegate/DeleteChildHandler.java diff --git a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/delegate/DeleteDblookupHandler.java b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/delegate/DeleteDblookupHandler.java similarity index 100% rename from edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/delegate/DeleteDblookupHandler.java rename to edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/delegate/DeleteDblookupHandler.java diff --git a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/delegate/ExportChildHandler.java b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/delegate/ExportChildHandler.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/delegate/ExportChildHandler.java rename to edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/delegate/ExportChildHandler.java diff --git a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/delegate/GetAllDblookupsHandler.java b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/delegate/GetAllDblookupsHandler.java similarity index 100% rename from edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/delegate/GetAllDblookupsHandler.java rename to edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/delegate/GetAllDblookupsHandler.java diff --git a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/delegate/GetChildrenHandler.java b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/delegate/GetChildrenHandler.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/delegate/GetChildrenHandler.java rename to edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/delegate/GetChildrenHandler.java diff --git a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/delegate/GetDblookupHandler.java b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/delegate/GetDblookupHandler.java similarity index 100% rename from edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/delegate/GetDblookupHandler.java rename to edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/delegate/GetDblookupHandler.java diff --git a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/delegate/GetFoldersByProjectHandler.java b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/delegate/GetFoldersByProjectHandler.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/delegate/GetFoldersByProjectHandler.java rename to edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/delegate/GetFoldersByProjectHandler.java diff --git a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/delegate/GetFoldersByUserIdHandler.java b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/delegate/GetFoldersByUserIdHandler.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/delegate/GetFoldersByUserIdHandler.java rename to edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/delegate/GetFoldersByUserIdHandler.java diff --git a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/delegate/GetNameInfoHandler.java b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/delegate/GetNameInfoHandler.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/delegate/GetNameInfoHandler.java rename to edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/delegate/GetNameInfoHandler.java diff --git a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/delegate/MoveChildHandler.java b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/delegate/MoveChildHandler.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/delegate/MoveChildHandler.java rename to edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/delegate/MoveChildHandler.java diff --git a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/delegate/RenameChildHandler.java b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/delegate/RenameChildHandler.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/delegate/RenameChildHandler.java rename to edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/delegate/RenameChildHandler.java index 75fd134e..5f15fb9e --- a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/delegate/RenameChildHandler.java +++ b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/delegate/RenameChildHandler.java @@ -1,94 +1,94 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Lori Phillips - */ -package edu.harvard.i2b2.workplace.delegate; - -import edu.harvard.i2b2.common.exception.I2B2DAOException; -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.workplace.datavo.i2b2message.MessageHeaderType; -import edu.harvard.i2b2.workplace.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.workplace.datavo.wdo.RenameChildType; -import edu.harvard.i2b2.workplace.datavo.pm.ProjectType; -import edu.harvard.i2b2.workplace.dao.FolderDao; -import edu.harvard.i2b2.workplace.ws.RenameChildDataMessage; -import edu.harvard.i2b2.workplace.ws.MessageFactory; - - -public class RenameChildHandler extends RequestHandler { - private RenameChildDataMessage renameChildMsg = null; - private RenameChildType renameChildType = null; - private ProjectType projectInfo = null; - - public RenameChildHandler(RenameChildDataMessage requestMsg) throws I2B2Exception { - renameChildMsg = requestMsg; - renameChildType = requestMsg.getRenameChildType(); - - renameChildType.setName(renameChildType.getName().replaceAll("\\<[^>]*>","")); - // test bad username -- good 2/1/08 - // renameChildMsg.getMessageHeaderType().getSecurity().setUsername("bad"); - projectInfo = getRoleInfo(requestMsg.getMessageHeaderType()); - setDbInfo(requestMsg.getMessageHeaderType()); - } - - @Override - public String execute() throws I2B2Exception { - // call ejb and pass input object - FolderDao renameChildDao = new FolderDao(); - ResponseMessageType responseMessageType = null; - int numRenamed = -1; - - // check to see if we have projectInfo (if not indicates PM service problem) - if(projectInfo == null) { - String response = null; - responseMessageType = MessageFactory.doBuildErrorResponse(renameChildMsg.getMessageHeaderType(), "User was not validated"); - response = MessageFactory.convertToXMLString(responseMessageType); - log.debug("USER_INVALID or PM_SERVICE_PROBLEM"); - return response; - } - - else { - try { - numRenamed = renameChildDao.renameNode(renameChildType, projectInfo, this.getDbInfo()); - } catch (I2B2DAOException e) { - log.error("RenameChildHandler received I2B2DAO exception from DAO"); - responseMessageType = MessageFactory.doBuildErrorResponse(renameChildMsg.getMessageHeaderType(), "Database error"); - } catch (I2B2Exception e) { - log.error("RenameChildHandler received I2B2 exception from DAO"); - responseMessageType = MessageFactory.doBuildErrorResponse(renameChildMsg.getMessageHeaderType(), "Database error"); - } - } - - // no errors found - if(responseMessageType == null) { - // no db error but response is empty - if (numRenamed == 0) { - log.error("rename object not found"); - responseMessageType = MessageFactory.doBuildErrorResponse(renameChildMsg.getMessageHeaderType(), "Node not found"); - } - else if (numRenamed == -1) { - log.error("database error"); - responseMessageType = MessageFactory.doBuildErrorResponse(renameChildMsg.getMessageHeaderType(), "Database error"); - } - else { - MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(renameChildMsg.getMessageHeaderType()); -// responseMessageType = MessageFactory.createBuildResponse(messageHeader, null); - responseMessageType = MessageFactory.createBuildResponse(messageHeader); - } - } - String responseWdo = null; - responseWdo = MessageFactory.convertToXMLString(responseMessageType); - return responseWdo; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Lori Phillips + */ +package edu.harvard.i2b2.workplace.delegate; + +import edu.harvard.i2b2.common.exception.I2B2DAOException; +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.workplace.datavo.i2b2message.MessageHeaderType; +import edu.harvard.i2b2.workplace.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.workplace.datavo.wdo.RenameChildType; +import edu.harvard.i2b2.workplace.datavo.pm.ProjectType; +import edu.harvard.i2b2.workplace.dao.FolderDao; +import edu.harvard.i2b2.workplace.ws.RenameChildDataMessage; +import edu.harvard.i2b2.workplace.ws.MessageFactory; + + +public class RenameChildHandler extends RequestHandler { + private RenameChildDataMessage renameChildMsg = null; + private RenameChildType renameChildType = null; + private ProjectType projectInfo = null; + + public RenameChildHandler(RenameChildDataMessage requestMsg) throws I2B2Exception { + renameChildMsg = requestMsg; + renameChildType = requestMsg.getRenameChildType(); + + renameChildType.setName(renameChildType.getName().replaceAll("\\<[^>]*>","")); + // test bad username -- good 2/1/08 + // renameChildMsg.getMessageHeaderType().getSecurity().setUsername("bad"); + projectInfo = getRoleInfo(requestMsg.getMessageHeaderType()); + setDbInfo(requestMsg.getMessageHeaderType()); + } + + @Override + public String execute() throws I2B2Exception { + // call ejb and pass input object + FolderDao renameChildDao = new FolderDao(); + ResponseMessageType responseMessageType = null; + int numRenamed = -1; + + // check to see if we have projectInfo (if not indicates PM service problem) + if(projectInfo == null) { + String response = null; + responseMessageType = MessageFactory.doBuildErrorResponse(renameChildMsg.getMessageHeaderType(), "User was not validated"); + response = MessageFactory.convertToXMLString(responseMessageType); + log.debug("USER_INVALID or PM_SERVICE_PROBLEM"); + return response; + } + + else { + try { + numRenamed = renameChildDao.renameNode(renameChildType, projectInfo, this.getDbInfo()); + } catch (I2B2DAOException e) { + log.error("RenameChildHandler received I2B2DAO exception from DAO"); + responseMessageType = MessageFactory.doBuildErrorResponse(renameChildMsg.getMessageHeaderType(), "Database error"); + } catch (I2B2Exception e) { + log.error("RenameChildHandler received I2B2 exception from DAO"); + responseMessageType = MessageFactory.doBuildErrorResponse(renameChildMsg.getMessageHeaderType(), "Database error"); + } + } + + // no errors found + if(responseMessageType == null) { + // no db error but response is empty + if (numRenamed == 0) { + log.error("rename object not found"); + responseMessageType = MessageFactory.doBuildErrorResponse(renameChildMsg.getMessageHeaderType(), "Node not found"); + } + else if (numRenamed == -1) { + log.error("database error"); + responseMessageType = MessageFactory.doBuildErrorResponse(renameChildMsg.getMessageHeaderType(), "Database error"); + } + else { + MessageHeaderType messageHeader = MessageFactory.createResponseMessageHeader(renameChildMsg.getMessageHeaderType()); +// responseMessageType = MessageFactory.createBuildResponse(messageHeader, null); + responseMessageType = MessageFactory.createBuildResponse(messageHeader); + } + } + String responseWdo = null; + responseWdo = MessageFactory.convertToXMLString(responseMessageType); + return responseWdo; + } + +} diff --git a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/delegate/RequestHandler.java b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/delegate/RequestHandler.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/delegate/RequestHandler.java rename to edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/delegate/RequestHandler.java index 51587a8c..9f70e7a4 --- a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/delegate/RequestHandler.java +++ b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/delegate/RequestHandler.java @@ -30,10 +30,10 @@ import edu.harvard.i2b2.workplace.datavo.pm.GetUserConfigurationType; import edu.harvard.i2b2.workplace.datavo.pm.ProjectType; import edu.harvard.i2b2.workplace.dao.DataSourceLookupHelper; -import edu.harvard.i2b2.pm.ws.PMResponseMessage; -import edu.harvard.i2b2.pm.ws.PMServiceDriver; import edu.harvard.i2b2.workplace.ejb.DBInfoType; import edu.harvard.i2b2.workplace.util.WorkplaceUtil; +import edu.harvard.i2b2.workplacepm.ws.PMResponseMessage; +import edu.harvard.i2b2.workplacepm.ws.PMServiceDriver; public abstract class RequestHandler { protected final Log log = LogFactory.getLog(getClass()); diff --git a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/delegate/SetDblookupHandler.java b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/delegate/SetDblookupHandler.java similarity index 100% rename from edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/delegate/SetDblookupHandler.java rename to edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/delegate/SetDblookupHandler.java diff --git a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/delegate/SetProtectedAcessHandler.java b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/delegate/SetProtectedAcessHandler.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/delegate/SetProtectedAcessHandler.java rename to edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/delegate/SetProtectedAcessHandler.java diff --git a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/delegate/crc/CRCServiceClient.java b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/delegate/crc/CRCServiceClient.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/delegate/crc/CRCServiceClient.java rename to edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/delegate/crc/CRCServiceClient.java diff --git a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/delegate/crc/CallCRCUtil.java b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/delegate/crc/CallCRCUtil.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/delegate/crc/CallCRCUtil.java rename to edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/delegate/crc/CallCRCUtil.java index 4a02eacc..a66967c3 --- a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/delegate/crc/CallCRCUtil.java +++ b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/delegate/crc/CallCRCUtil.java @@ -1,322 +1,322 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -package edu.harvard.i2b2.workplace.delegate.crc; - -import java.io.StringReader; -import java.io.StringWriter; - -import jakarta.xml.bind.JAXBElement; -import javax.xml.stream.XMLInputFactory; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamReader; - -import org.apache.axiom.om.OMAbstractFactory; -import org.apache.axiom.om.OMElement; -import org.apache.axiom.om.OMFactory; -import org.apache.axiom.om.OMXMLBuilderFactory; -import org.apache.axis2.AxisFault; -import org.apache.axis2.Constants; -import org.apache.axis2.addressing.EndpointReference; -import org.apache.axis2.client.Options; -import edu.harvard.i2b2.common.util.axis2.ServiceClient; -import org.apache.axis2.context.ServiceContext; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.workplace.datavo.crc.setfinder.query.CrcXmlResultResponseType; -import edu.harvard.i2b2.workplace.datavo.crc.setfinder.query.MasterRequestType; -import edu.harvard.i2b2.workplace.datavo.crc.setfinder.query.MasterResponseType; -import edu.harvard.i2b2.workplace.datavo.crc.setfinder.query.PsmQryHeaderType; -import edu.harvard.i2b2.workplace.datavo.crc.setfinder.query.PsmRequestTypeType; -import edu.harvard.i2b2.workplace.datavo.crc.setfinder.query.ResultRequestType; -import edu.harvard.i2b2.workplace.datavo.i2b2message.ApplicationType; -import edu.harvard.i2b2.workplace.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.workplace.datavo.i2b2message.FacilityType; -import edu.harvard.i2b2.workplace.datavo.i2b2message.MessageHeaderType; -import edu.harvard.i2b2.workplace.datavo.i2b2message.RequestHeaderType; -import edu.harvard.i2b2.workplace.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.workplace.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.workplace.datavo.i2b2message.ResultStatusType; -import edu.harvard.i2b2.workplace.datavo.i2b2message.SecurityType; -import edu.harvard.i2b2.workplace.util.WorkplaceJAXBUtil; -import edu.harvard.i2b2.workplace.util.WorkplaceUtil; - -public class CallCRCUtil { - - // private SecurityType securityType = null; - // private String projectId = null; - //private String crcUrl = null; - static WorkplaceUtil workplaceUtil = WorkplaceUtil.getInstance(); - static ServiceClient serviceClient = null; - private static Log log = LogFactory.getLog(CallCRCUtil.class); - protected static Log logesapi = LogFactory.getLog(CallCRCUtil.class); - - /* - public CallCRCUtil(SecurityType securityType, String projectId) - throws I2B2Exception { - this.securityType = securityType; - this.projectId = projectId; - this.crcUrl = workplaceUtil.getCRCUrl(); - log.debug("CRC Workplace call url: " + crcUrl); - } - - public CallCRCUtil(String crcUrl, SecurityType securityType, - String projectId) throws I2B2Exception { - this.securityType = securityType; - this.projectId = projectId; - this.crcUrl = crcUrl; - } - */ - - public static String callCRCResultInstanceXML(String resultInstanceID, SecurityType securityType, String projectId) - throws I2B2Exception { - // ResultResponseType resultResponseType = null; - String response = null; - try { - log.debug("begin build element"); - RequestMessageType requestMessageType = buildResultInstanceRequestXMLRequestMessage(resultInstanceID, securityType, projectId); - OMElement requestElement = buildOMElement(requestMessageType); - logesapi.debug("callCRCQueryRequestXML - CRC setfinder query request XML call's request xml " - + requestElement); - response = ServiceClient.sendREST(workplaceUtil.getCRCUrl() + "/request", requestElement).toString(); - logesapi.debug("callCRCQueryRequestXML - CRC setfinder query request XML call's response xml " + response.toString()); - //resultResponseType = getResultResponseMessage(response.toString()); - //masterInstanceResultResponseType = getResponseMessage(response - // .toString()); - - } catch (JAXBUtilException jaxbEx) { - log.error(jaxbEx.getLocalizedMessage()); - throw new I2B2Exception("Error in CRC upload ", jaxbEx); - } catch (XMLStreamException e) { - log.error(e.getLocalizedMessage()); - throw new I2B2Exception("Error in CRC upload ", e); - - } catch (Exception e) { - log.error(e.getLocalizedMessage()); - throw new I2B2Exception("Error in CRC upload ", e); - } finally { - - } - - return response; - } - - public static String callCRCQueryRequestXML(String queryMasterId, SecurityType securityType, String projectId) - throws I2B2Exception { - // ResultResponseType resultResponseType = null; - //MasterResponseType masterInstanceResultResponseType = null; - String response = null; - try { - log.debug("begin build element"); - RequestMessageType requestMessageType = buildSetfinderRequestXMLRequestMessage(queryMasterId, securityType, projectId); - OMElement requestElement = buildOMElement(requestMessageType); - log.debug("callCRCQueryRequestXML - CRC setfinder query request XML call's request xml " - + requestElement); - response = ServiceClient.sendREST(workplaceUtil.getCRCUrl() + "/request", requestElement); - - //log.debug("callCRCQueryRequestXML - CRC setfinder query request XML call's response xml " + response.toString()); - //resultResponseType = getResultResponseMessage(response.toString()); - //masterInstanceResultResponseType = getMasterInstanceResultResponseMessage(response - // .toString()); - - } catch (JAXBUtilException jaxbEx) { - log.error(jaxbEx.getLocalizedMessage()); - throw new I2B2Exception("Error in CRC upload ", jaxbEx); - } catch (XMLStreamException e) { - log.error(e.getLocalizedMessage()); - throw new I2B2Exception("Error in CRC upload ", e); - - } catch (Exception e) { - log.error(e.getLocalizedMessage()); - throw new I2B2Exception("Error in CRC upload ", e); - } finally { - - } - return response; - } - - - // public RequestMessageType buildSetfinderStatusRequestMessage(String queryInstanceId) { - public static RequestMessageType buildResultInstanceRequestXMLRequestMessage(String resultInstanceId, SecurityType securityType, String projectId) { - ResultRequestType masterRequestType = new ResultRequestType(); - masterRequestType.setQueryResultInstanceId(resultInstanceId); - - MessageHeaderType messageHeaderType = new MessageHeaderType(); - ApplicationType appType = new ApplicationType(); - appType.setApplicationName("Workplace Cell"); - appType.setApplicationVersion("1.701"); - messageHeaderType.setSendingApplication(appType); - - messageHeaderType.setSecurity(securityType); - messageHeaderType.setProjectId(projectId); - - messageHeaderType.setReceivingApplication(messageHeaderType - .getSendingApplication()); - FacilityType facilityType = new FacilityType(); - facilityType.setFacilityName("sample"); - messageHeaderType.setSendingFacility(facilityType); - messageHeaderType.setReceivingFacility(facilityType); - - RequestMessageType requestMessageType = new RequestMessageType(); - - edu.harvard.i2b2.workplace.datavo.crc.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.workplace.datavo.crc.setfinder.query.ObjectFactory(); - BodyType bodyType = new BodyType(); - PsmQryHeaderType psm = new PsmQryHeaderType(); - psm.setRequestType(PsmRequestTypeType.CRC_QRY_GET_RESULT_DOCUMENT_FROM_RESULT_INSTANCE_ID); //.CRC_QRY_GET_QUERY_RESULT_INSTANCE_LIST_FROM_QUERY_INSTANCE_ID); - bodyType.getAny().add(of.createPsmheader(psm)); - - bodyType.getAny().add(of.createRequest(masterRequestType)); - requestMessageType.setMessageBody(bodyType); - - requestMessageType.setMessageHeader(messageHeaderType); - - RequestHeaderType requestHeader = new RequestHeaderType(); - requestHeader.setResultWaittimeMs(3000); - requestMessageType.setRequestHeader(requestHeader); - return requestMessageType; - } - - public static RequestMessageType buildSetfinderRequestXMLRequestMessage(String queryMasterId, SecurityType securityType, String projectId) { - MasterRequestType masterRequestType = new MasterRequestType(); - masterRequestType.setQueryMasterId(queryMasterId); - - MessageHeaderType messageHeaderType = new MessageHeaderType(); - ApplicationType appType = new ApplicationType(); - appType.setApplicationName("Workplace Cell"); - appType.setApplicationVersion("1.701"); - messageHeaderType.setSendingApplication(appType); - - messageHeaderType.setSecurity(securityType); - messageHeaderType.setProjectId(projectId); - - messageHeaderType.setReceivingApplication(messageHeaderType - .getSendingApplication()); - FacilityType facilityType = new FacilityType(); - facilityType.setFacilityName("sample"); - messageHeaderType.setSendingFacility(facilityType); - messageHeaderType.setReceivingFacility(facilityType); - - RequestMessageType requestMessageType = new RequestMessageType(); - - edu.harvard.i2b2.workplace.datavo.crc.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.workplace.datavo.crc.setfinder.query.ObjectFactory(); - BodyType bodyType = new BodyType(); - PsmQryHeaderType psm = new PsmQryHeaderType(); - psm.setRequestType(PsmRequestTypeType.CRC_QRY_GET_REQUEST_XML_FROM_QUERY_MASTER_ID); //.CRC_QRY_GET_QUERY_RESULT_INSTANCE_LIST_FROM_QUERY_INSTANCE_ID); - bodyType.getAny().add(of.createPsmheader(psm)); - - bodyType.getAny().add(of.createRequest(masterRequestType)); - requestMessageType.setMessageBody(bodyType); - - requestMessageType.setMessageHeader(messageHeaderType); - - RequestHeaderType requestHeader = new RequestHeaderType(); - requestHeader.setResultWaittimeMs(3000); - requestMessageType.setRequestHeader(requestHeader); - return requestMessageType; - } - - private static CrcXmlResultResponseType getResponseMessage( - String responseXml) throws JAXBUtilException, I2B2Exception { - JAXBElement responseJaxb = WorkplaceJAXBUtil.getJAXBUtil() - .unMashallFromString(responseXml); - ResponseMessageType r = (ResponseMessageType) responseJaxb.getValue(); - log.debug("CRC's workplace call response xml" + responseXml); - - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - ResultStatusType rt = r.getResponseHeader().getResultStatus(); - if (rt.getStatus().getType().equals("ERROR")) { - throw new I2B2Exception(rt.getStatus().getValue()); - } - CrcXmlResultResponseType masterInstanceResultResponseType = (CrcXmlResultResponseType) helper - .getObjectByClass(r.getMessageBody().getAny(), - CrcXmlResultResponseType.class); - log.debug("got CrcXmlResultResponseType: " + masterInstanceResultResponseType); - return masterInstanceResultResponseType; - } - - private static MasterResponseType getMasterInstanceResultResponseMessage( - String responseXml) throws JAXBUtilException, I2B2Exception { - JAXBElement responseJaxb = WorkplaceJAXBUtil.getJAXBUtil() - .unMashallFromString(responseXml); - ResponseMessageType r = (ResponseMessageType) responseJaxb.getValue(); - log.debug("CRC's workplace call response xml" + responseXml); - - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - ResultStatusType rt = r.getResponseHeader().getResultStatus(); - if (rt.getStatus().getType().equals("ERROR")) { - throw new I2B2Exception(rt.getStatus().getValue()); - } - MasterResponseType masterInstanceResultResponseType = (MasterResponseType) helper - .getObjectByClass(r.getMessageBody().getAny(), - MasterResponseType.class); - log.debug("got MasterInstanceResultResponseType"); - return masterInstanceResultResponseType; - } - - - - private static OMElement buildOMElement(RequestMessageType requestMessageType) - throws XMLStreamException, JAXBUtilException { - StringWriter strWriter = new StringWriter(); - edu.harvard.i2b2.workplace.datavo.i2b2message.ObjectFactory hiveof = new edu.harvard.i2b2.workplace.datavo.i2b2message.ObjectFactory(); - WorkplaceJAXBUtil.getJAXBUtil().marshaller( - hiveof.createRequest(requestMessageType), strWriter); - // getOMElement from message - OMFactory fac = OMAbstractFactory.getOMFactory(); - - StringReader strReader = new StringReader(strWriter.toString()); - XMLInputFactory xif = XMLInputFactory.newInstance(); - XMLStreamReader reader = xif.createXMLStreamReader(strReader); - OMElement request = OMXMLBuilderFactory.createStAXOMBuilder(reader).getDocumentElement(); - - return request; - } - - /* - private static OMElement getServiceClient(String operationName, OMElement request) throws AxisFault, I2B2Exception { - // call - OMElement response = null; - - serviceClient = CRCServiceClient.getServiceClient(); - - ServiceContext context = serviceClient.getServiceContext(); - MultiThreadedHttpConnectionManager connManager = (MultiThreadedHttpConnectionManager)context.getProperty(HTTPConstants.MULTITHREAD_HTTP_CONNECTION_MANAGER); - - if(connManager == null) { - connManager = new MultiThreadedHttpConnectionManager(); - context.setProperty(HTTPConstants.MULTITHREAD_HTTP_CONNECTION_MANAGER, connManager); - connManager.getParams().setMaxTotalConnections(100); - connManager.getParams().setMaxConnectionsPerHost(HostConfiguration.ANY_HOST_CONFIGURATION, 100); - } - HttpClient httpClient = new HttpClient(connManager); - - - Options options = new Options(); - options.setTo(new EndpointReference(workplaceUtil.getCRCUrl() + operationName)); - options.setTransportInProtocol(Constants.TRANSPORT_HTTP); - options.setProperty(Constants.Configuration.ENABLE_REST, - Constants.VALUE_TRUE); - options.setProperty(HTTPConstants.CACHED_HTTP_CLIENT, - httpClient); - options.setProperty(HTTPConstants.REUSE_HTTP_CLIENT, Constants.VALUE_TRUE); - // options.setProperty(HTTPConstants.AUTO_RELEASE_CONNECTION, true); - serviceClient.setOptions(options); - response = serviceClient.sendReceive(request); - - - return response; - - } - */ -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +package edu.harvard.i2b2.workplace.delegate.crc; + +import java.io.StringReader; +import java.io.StringWriter; + +import jakarta.xml.bind.JAXBElement; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import org.apache.axiom.om.OMAbstractFactory; +import org.apache.axiom.om.OMElement; +import org.apache.axiom.om.OMFactory; +import org.apache.axiom.om.OMXMLBuilderFactory; +import org.apache.axis2.AxisFault; +import org.apache.axis2.Constants; +import org.apache.axis2.addressing.EndpointReference; +import org.apache.axis2.client.Options; +import edu.harvard.i2b2.common.util.axis2.ServiceClient; +import org.apache.axis2.context.ServiceContext; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.workplace.datavo.crc.setfinder.query.CrcXmlResultResponseType; +import edu.harvard.i2b2.workplace.datavo.crc.setfinder.query.MasterRequestType; +import edu.harvard.i2b2.workplace.datavo.crc.setfinder.query.MasterResponseType; +import edu.harvard.i2b2.workplace.datavo.crc.setfinder.query.PsmQryHeaderType; +import edu.harvard.i2b2.workplace.datavo.crc.setfinder.query.PsmRequestTypeType; +import edu.harvard.i2b2.workplace.datavo.crc.setfinder.query.ResultRequestType; +import edu.harvard.i2b2.workplace.datavo.i2b2message.ApplicationType; +import edu.harvard.i2b2.workplace.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.workplace.datavo.i2b2message.FacilityType; +import edu.harvard.i2b2.workplace.datavo.i2b2message.MessageHeaderType; +import edu.harvard.i2b2.workplace.datavo.i2b2message.RequestHeaderType; +import edu.harvard.i2b2.workplace.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.workplace.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.workplace.datavo.i2b2message.ResultStatusType; +import edu.harvard.i2b2.workplace.datavo.i2b2message.SecurityType; +import edu.harvard.i2b2.workplace.util.WorkplaceJAXBUtil; +import edu.harvard.i2b2.workplace.util.WorkplaceUtil; + +public class CallCRCUtil { + + // private SecurityType securityType = null; + // private String projectId = null; + //private String crcUrl = null; + static WorkplaceUtil workplaceUtil = WorkplaceUtil.getInstance(); + static ServiceClient serviceClient = null; + private static Log log = LogFactory.getLog(CallCRCUtil.class); + protected static Log logesapi = LogFactory.getLog(CallCRCUtil.class); + + /* + public CallCRCUtil(SecurityType securityType, String projectId) + throws I2B2Exception { + this.securityType = securityType; + this.projectId = projectId; + this.crcUrl = workplaceUtil.getCRCUrl(); + log.debug("CRC Workplace call url: " + crcUrl); + } + + public CallCRCUtil(String crcUrl, SecurityType securityType, + String projectId) throws I2B2Exception { + this.securityType = securityType; + this.projectId = projectId; + this.crcUrl = crcUrl; + } + */ + + public static String callCRCResultInstanceXML(String resultInstanceID, SecurityType securityType, String projectId) + throws I2B2Exception { + // ResultResponseType resultResponseType = null; + String response = null; + try { + log.debug("begin build element"); + RequestMessageType requestMessageType = buildResultInstanceRequestXMLRequestMessage(resultInstanceID, securityType, projectId); + OMElement requestElement = buildOMElement(requestMessageType); + logesapi.debug("callCRCQueryRequestXML - CRC setfinder query request XML call's request xml " + + requestElement); + response = ServiceClient.sendREST(workplaceUtil.getCRCUrl() + "/request", requestElement).toString(); + logesapi.debug("callCRCQueryRequestXML - CRC setfinder query request XML call's response xml " + response.toString()); + //resultResponseType = getResultResponseMessage(response.toString()); + //masterInstanceResultResponseType = getResponseMessage(response + // .toString()); + + } catch (JAXBUtilException jaxbEx) { + log.error(jaxbEx.getLocalizedMessage()); + throw new I2B2Exception("Error in CRC upload ", jaxbEx); + } catch (XMLStreamException e) { + log.error(e.getLocalizedMessage()); + throw new I2B2Exception("Error in CRC upload ", e); + + } catch (Exception e) { + log.error(e.getLocalizedMessage()); + throw new I2B2Exception("Error in CRC upload ", e); + } finally { + + } + + return response; + } + + public static String callCRCQueryRequestXML(String queryMasterId, SecurityType securityType, String projectId) + throws I2B2Exception { + // ResultResponseType resultResponseType = null; + //MasterResponseType masterInstanceResultResponseType = null; + String response = null; + try { + log.debug("begin build element"); + RequestMessageType requestMessageType = buildSetfinderRequestXMLRequestMessage(queryMasterId, securityType, projectId); + OMElement requestElement = buildOMElement(requestMessageType); + log.debug("callCRCQueryRequestXML - CRC setfinder query request XML call's request xml " + + requestElement); + response = ServiceClient.sendREST(workplaceUtil.getCRCUrl() + "/request", requestElement); + + //log.debug("callCRCQueryRequestXML - CRC setfinder query request XML call's response xml " + response.toString()); + //resultResponseType = getResultResponseMessage(response.toString()); + //masterInstanceResultResponseType = getMasterInstanceResultResponseMessage(response + // .toString()); + + } catch (JAXBUtilException jaxbEx) { + log.error(jaxbEx.getLocalizedMessage()); + throw new I2B2Exception("Error in CRC upload ", jaxbEx); + } catch (XMLStreamException e) { + log.error(e.getLocalizedMessage()); + throw new I2B2Exception("Error in CRC upload ", e); + + } catch (Exception e) { + log.error(e.getLocalizedMessage()); + throw new I2B2Exception("Error in CRC upload ", e); + } finally { + + } + return response; + } + + + // public RequestMessageType buildSetfinderStatusRequestMessage(String queryInstanceId) { + public static RequestMessageType buildResultInstanceRequestXMLRequestMessage(String resultInstanceId, SecurityType securityType, String projectId) { + ResultRequestType masterRequestType = new ResultRequestType(); + masterRequestType.setQueryResultInstanceId(resultInstanceId); + + MessageHeaderType messageHeaderType = new MessageHeaderType(); + ApplicationType appType = new ApplicationType(); + appType.setApplicationName("Workplace Cell"); + appType.setApplicationVersion("1.701"); + messageHeaderType.setSendingApplication(appType); + + messageHeaderType.setSecurity(securityType); + messageHeaderType.setProjectId(projectId); + + messageHeaderType.setReceivingApplication(messageHeaderType + .getSendingApplication()); + FacilityType facilityType = new FacilityType(); + facilityType.setFacilityName("sample"); + messageHeaderType.setSendingFacility(facilityType); + messageHeaderType.setReceivingFacility(facilityType); + + RequestMessageType requestMessageType = new RequestMessageType(); + + edu.harvard.i2b2.workplace.datavo.crc.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.workplace.datavo.crc.setfinder.query.ObjectFactory(); + BodyType bodyType = new BodyType(); + PsmQryHeaderType psm = new PsmQryHeaderType(); + psm.setRequestType(PsmRequestTypeType.CRC_QRY_GET_RESULT_DOCUMENT_FROM_RESULT_INSTANCE_ID); //.CRC_QRY_GET_QUERY_RESULT_INSTANCE_LIST_FROM_QUERY_INSTANCE_ID); + bodyType.getAny().add(of.createPsmheader(psm)); + + bodyType.getAny().add(of.createRequest(masterRequestType)); + requestMessageType.setMessageBody(bodyType); + + requestMessageType.setMessageHeader(messageHeaderType); + + RequestHeaderType requestHeader = new RequestHeaderType(); + requestHeader.setResultWaittimeMs(3000); + requestMessageType.setRequestHeader(requestHeader); + return requestMessageType; + } + + public static RequestMessageType buildSetfinderRequestXMLRequestMessage(String queryMasterId, SecurityType securityType, String projectId) { + MasterRequestType masterRequestType = new MasterRequestType(); + masterRequestType.setQueryMasterId(queryMasterId); + + MessageHeaderType messageHeaderType = new MessageHeaderType(); + ApplicationType appType = new ApplicationType(); + appType.setApplicationName("Workplace Cell"); + appType.setApplicationVersion("1.701"); + messageHeaderType.setSendingApplication(appType); + + messageHeaderType.setSecurity(securityType); + messageHeaderType.setProjectId(projectId); + + messageHeaderType.setReceivingApplication(messageHeaderType + .getSendingApplication()); + FacilityType facilityType = new FacilityType(); + facilityType.setFacilityName("sample"); + messageHeaderType.setSendingFacility(facilityType); + messageHeaderType.setReceivingFacility(facilityType); + + RequestMessageType requestMessageType = new RequestMessageType(); + + edu.harvard.i2b2.workplace.datavo.crc.setfinder.query.ObjectFactory of = new edu.harvard.i2b2.workplace.datavo.crc.setfinder.query.ObjectFactory(); + BodyType bodyType = new BodyType(); + PsmQryHeaderType psm = new PsmQryHeaderType(); + psm.setRequestType(PsmRequestTypeType.CRC_QRY_GET_REQUEST_XML_FROM_QUERY_MASTER_ID); //.CRC_QRY_GET_QUERY_RESULT_INSTANCE_LIST_FROM_QUERY_INSTANCE_ID); + bodyType.getAny().add(of.createPsmheader(psm)); + + bodyType.getAny().add(of.createRequest(masterRequestType)); + requestMessageType.setMessageBody(bodyType); + + requestMessageType.setMessageHeader(messageHeaderType); + + RequestHeaderType requestHeader = new RequestHeaderType(); + requestHeader.setResultWaittimeMs(3000); + requestMessageType.setRequestHeader(requestHeader); + return requestMessageType; + } + + private static CrcXmlResultResponseType getResponseMessage( + String responseXml) throws JAXBUtilException, I2B2Exception { + JAXBElement responseJaxb = WorkplaceJAXBUtil.getJAXBUtil() + .unMashallFromString(responseXml); + ResponseMessageType r = (ResponseMessageType) responseJaxb.getValue(); + log.debug("CRC's workplace call response xml" + responseXml); + + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + ResultStatusType rt = r.getResponseHeader().getResultStatus(); + if (rt.getStatus().getType().equals("ERROR")) { + throw new I2B2Exception(rt.getStatus().getValue()); + } + CrcXmlResultResponseType masterInstanceResultResponseType = (CrcXmlResultResponseType) helper + .getObjectByClass(r.getMessageBody().getAny(), + CrcXmlResultResponseType.class); + log.debug("got CrcXmlResultResponseType: " + masterInstanceResultResponseType); + return masterInstanceResultResponseType; + } + + private static MasterResponseType getMasterInstanceResultResponseMessage( + String responseXml) throws JAXBUtilException, I2B2Exception { + JAXBElement responseJaxb = WorkplaceJAXBUtil.getJAXBUtil() + .unMashallFromString(responseXml); + ResponseMessageType r = (ResponseMessageType) responseJaxb.getValue(); + log.debug("CRC's workplace call response xml" + responseXml); + + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + ResultStatusType rt = r.getResponseHeader().getResultStatus(); + if (rt.getStatus().getType().equals("ERROR")) { + throw new I2B2Exception(rt.getStatus().getValue()); + } + MasterResponseType masterInstanceResultResponseType = (MasterResponseType) helper + .getObjectByClass(r.getMessageBody().getAny(), + MasterResponseType.class); + log.debug("got MasterInstanceResultResponseType"); + return masterInstanceResultResponseType; + } + + + + private static OMElement buildOMElement(RequestMessageType requestMessageType) + throws XMLStreamException, JAXBUtilException { + StringWriter strWriter = new StringWriter(); + edu.harvard.i2b2.workplace.datavo.i2b2message.ObjectFactory hiveof = new edu.harvard.i2b2.workplace.datavo.i2b2message.ObjectFactory(); + WorkplaceJAXBUtil.getJAXBUtil().marshaller( + hiveof.createRequest(requestMessageType), strWriter); + // getOMElement from message + OMFactory fac = OMAbstractFactory.getOMFactory(); + + StringReader strReader = new StringReader(strWriter.toString()); + XMLInputFactory xif = XMLInputFactory.newInstance(); + XMLStreamReader reader = xif.createXMLStreamReader(strReader); + OMElement request = OMXMLBuilderFactory.createStAXOMBuilder(reader).getDocumentElement(); + + return request; + } + + /* + private static OMElement getServiceClient(String operationName, OMElement request) throws AxisFault, I2B2Exception { + // call + OMElement response = null; + + serviceClient = CRCServiceClient.getServiceClient(); + + ServiceContext context = serviceClient.getServiceContext(); + MultiThreadedHttpConnectionManager connManager = (MultiThreadedHttpConnectionManager)context.getProperty(HTTPConstants.MULTITHREAD_HTTP_CONNECTION_MANAGER); + + if(connManager == null) { + connManager = new MultiThreadedHttpConnectionManager(); + context.setProperty(HTTPConstants.MULTITHREAD_HTTP_CONNECTION_MANAGER, connManager); + connManager.getParams().setMaxTotalConnections(100); + connManager.getParams().setMaxConnectionsPerHost(HostConfiguration.ANY_HOST_CONFIGURATION, 100); + } + HttpClient httpClient = new HttpClient(connManager); + + + Options options = new Options(); + options.setTo(new EndpointReference(workplaceUtil.getCRCUrl() + operationName)); + options.setTransportInProtocol(Constants.TRANSPORT_HTTP); + options.setProperty(Constants.Configuration.ENABLE_REST, + Constants.VALUE_TRUE); + options.setProperty(HTTPConstants.CACHED_HTTP_CLIENT, + httpClient); + options.setProperty(HTTPConstants.REUSE_HTTP_CLIENT, Constants.VALUE_TRUE); + // options.setProperty(HTTPConstants.AUTO_RELEASE_CONNECTION, true); + serviceClient.setOptions(options); + response = serviceClient.sendReceive(request); + + + return response; + + } + */ +} diff --git a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/ejb/DBInfoType.java b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/ejb/DBInfoType.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/ejb/DBInfoType.java rename to edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/ejb/DBInfoType.java diff --git a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/ejb/DataSourceLookup.java b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/ejb/DataSourceLookup.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/ejb/DataSourceLookup.java rename to edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/ejb/DataSourceLookup.java diff --git a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/ejb/NodeType.java b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/ejb/NodeType.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/ejb/NodeType.java rename to edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/ejb/NodeType.java diff --git a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/util/DateUtil.java b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/util/DateUtil.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/util/DateUtil.java rename to edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/util/DateUtil.java diff --git a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/util/JAXBConstant.java b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/util/JAXBConstant.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/util/JAXBConstant.java rename to edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/util/JAXBConstant.java diff --git a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/util/StringUtil.java b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/util/StringUtil.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/util/StringUtil.java rename to edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/util/StringUtil.java diff --git a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/util/WorkplaceJAXBUtil.java b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/util/WorkplaceJAXBUtil.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/util/WorkplaceJAXBUtil.java rename to edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/util/WorkplaceJAXBUtil.java diff --git a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/util/WorkplaceUtil.java b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/util/WorkplaceUtil.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/util/WorkplaceUtil.java rename to edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/util/WorkplaceUtil.java diff --git a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/ws/AddChildDataMessage.java b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/ws/AddChildDataMessage.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/ws/AddChildDataMessage.java rename to edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/ws/AddChildDataMessage.java diff --git a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/ws/AnnotateChildDataMessage.java b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/ws/AnnotateChildDataMessage.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/ws/AnnotateChildDataMessage.java rename to edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/ws/AnnotateChildDataMessage.java diff --git a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/ws/DeleteChildDataMessage.java b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/ws/DeleteChildDataMessage.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/ws/DeleteChildDataMessage.java rename to edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/ws/DeleteChildDataMessage.java diff --git a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/ws/DeleteDblookupDataMessage.java b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/ws/DeleteDblookupDataMessage.java similarity index 100% rename from edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/ws/DeleteDblookupDataMessage.java rename to edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/ws/DeleteDblookupDataMessage.java diff --git a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/ws/ExecutorRunnable.java b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/ws/ExecutorRunnable.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/ws/ExecutorRunnable.java rename to edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/ws/ExecutorRunnable.java diff --git a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/ws/ExportChildDataMessage.java b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/ws/ExportChildDataMessage.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/ws/ExportChildDataMessage.java rename to edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/ws/ExportChildDataMessage.java diff --git a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/ws/GetAllDblookupsDataMessage.java b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/ws/GetAllDblookupsDataMessage.java similarity index 100% rename from edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/ws/GetAllDblookupsDataMessage.java rename to edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/ws/GetAllDblookupsDataMessage.java diff --git a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/ws/GetChildrenDataMessage.java b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/ws/GetChildrenDataMessage.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/ws/GetChildrenDataMessage.java rename to edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/ws/GetChildrenDataMessage.java diff --git a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/ws/GetDblookupDataMessage.java b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/ws/GetDblookupDataMessage.java similarity index 100% rename from edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/ws/GetDblookupDataMessage.java rename to edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/ws/GetDblookupDataMessage.java diff --git a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/ws/GetFoldersDataMessage.java b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/ws/GetFoldersDataMessage.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/ws/GetFoldersDataMessage.java rename to edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/ws/GetFoldersDataMessage.java diff --git a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/ws/GetNameInfoDataMessage.java b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/ws/GetNameInfoDataMessage.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/ws/GetNameInfoDataMessage.java rename to edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/ws/GetNameInfoDataMessage.java diff --git a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/ws/MessageFactory.java b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/ws/MessageFactory.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/ws/MessageFactory.java rename to edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/ws/MessageFactory.java diff --git a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/ws/MoveChildDataMessage.java b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/ws/MoveChildDataMessage.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/ws/MoveChildDataMessage.java rename to edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/ws/MoveChildDataMessage.java diff --git a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/ws/ProtectedDataMessage.java b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/ws/ProtectedDataMessage.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/ws/ProtectedDataMessage.java rename to edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/ws/ProtectedDataMessage.java diff --git a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/ws/RenameChildDataMessage.java b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/ws/RenameChildDataMessage.java old mode 100755 new mode 100644 similarity index 100% rename from edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/ws/RenameChildDataMessage.java rename to edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/ws/RenameChildDataMessage.java diff --git a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/ws/RequestDataMessage.java b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/ws/RequestDataMessage.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/ws/RequestDataMessage.java rename to edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/ws/RequestDataMessage.java index e830c107..07d416a7 --- a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/ws/RequestDataMessage.java +++ b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/ws/RequestDataMessage.java @@ -1,59 +1,59 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Raj Kuttan - * Lori Phillips - */ -package edu.harvard.i2b2.workplace.ws; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.workplace.datavo.i2b2message.MessageHeaderType; -import edu.harvard.i2b2.workplace.datavo.i2b2message.RequestMessageType; -import edu.harvard.i2b2.workplace.util.WorkplaceJAXBUtil; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import jakarta.xml.bind.JAXBElement; - - -/** - * The RequestDataMessage class is a helper class to build Workplace messages in the - * i2b2 format - */ -public abstract class RequestDataMessage{ - protected final Log log = LogFactory.getLog(getClass()); - - public RequestMessageType reqMessageType = null; - - public void setRequestMessageType(String requestWdo) throws I2B2Exception { - try { - JAXBElement jaxbElement = WorkplaceJAXBUtil.getJAXBUtil().unMashallFromString(requestWdo); - this.reqMessageType = (RequestMessageType) jaxbElement.getValue(); - - } catch (JAXBUtilException e) { - throw new I2B2Exception("Umarshaller error: " + e.getMessage() + - requestWdo, e); - } - } - - - - public RequestMessageType getRequestMessageType() { - return reqMessageType; - } - - public MessageHeaderType getMessageHeaderType() { - return reqMessageType.getMessageHeader(); - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Raj Kuttan + * Lori Phillips + */ +package edu.harvard.i2b2.workplace.ws; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.workplace.datavo.i2b2message.MessageHeaderType; +import edu.harvard.i2b2.workplace.datavo.i2b2message.RequestMessageType; +import edu.harvard.i2b2.workplace.util.WorkplaceJAXBUtil; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import jakarta.xml.bind.JAXBElement; + + +/** + * The RequestDataMessage class is a helper class to build Workplace messages in the + * i2b2 format + */ +public abstract class RequestDataMessage{ + protected final Log log = LogFactory.getLog(getClass()); + + public RequestMessageType reqMessageType = null; + + public void setRequestMessageType(String requestWdo) throws I2B2Exception { + try { + JAXBElement jaxbElement = WorkplaceJAXBUtil.getJAXBUtil().unMashallFromString(requestWdo); + this.reqMessageType = (RequestMessageType) jaxbElement.getValue(); + + } catch (JAXBUtilException e) { + throw new I2B2Exception("Umarshaller error: " + e.getMessage() + + requestWdo, e); + } + } + + + + public RequestMessageType getRequestMessageType() { + return reqMessageType; + } + + public MessageHeaderType getMessageHeaderType() { + return reqMessageType.getMessageHeader(); + } + +} diff --git a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/ws/SetDblookupDataMessage.java b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/ws/SetDblookupDataMessage.java similarity index 100% rename from edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/ws/SetDblookupDataMessage.java rename to edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/ws/SetDblookupDataMessage.java diff --git a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/ws/WorkplaceService.java b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/ws/WorkplaceService.java old mode 100755 new mode 100644 similarity index 97% rename from edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/ws/WorkplaceService.java rename to edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/ws/WorkplaceService.java index 3a2d6a6a..43696620 --- a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/workplace/ws/WorkplaceService.java +++ b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplace/ws/WorkplaceService.java @@ -1,704 +1,704 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Raj Kuttan - * Lori Phillips - */ -package edu.harvard.i2b2.workplace.ws; - -import edu.harvard.i2b2.common.exception.I2B2Exception; -import edu.harvard.i2b2.workplace.delegate.DeleteDblookupHandler; -import edu.harvard.i2b2.workplace.delegate.GetAllDblookupsHandler; -import edu.harvard.i2b2.workplace.delegate.GetDblookupHandler; -import edu.harvard.i2b2.workplace.delegate.SetDblookupHandler; -import edu.harvard.i2b2.workplace.ws.DeleteDblookupDataMessage; -import edu.harvard.i2b2.workplace.ws.GetAllDblookupsDataMessage; -import edu.harvard.i2b2.workplace.ws.GetDblookupDataMessage; -import edu.harvard.i2b2.workplace.ws.SetDblookupDataMessage; -import edu.harvard.i2b2.workplace.delegate.RequestHandler; -import edu.harvard.i2b2.workplace.ws.ExecutorRunnable; -import edu.harvard.i2b2.workplace.ws.MessageFactory; -import edu.harvard.i2b2.workplace.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.workplace.delegate.AddChildHandler; -import edu.harvard.i2b2.workplace.delegate.AnnotateChildHandler; -import edu.harvard.i2b2.workplace.delegate.DeleteChildHandler; -import edu.harvard.i2b2.workplace.delegate.ExportChildHandler; -import edu.harvard.i2b2.workplace.delegate.GetFoldersByProjectHandler; -import edu.harvard.i2b2.workplace.delegate.GetFoldersByUserIdHandler; -import edu.harvard.i2b2.workplace.delegate.GetChildrenHandler; -import edu.harvard.i2b2.workplace.delegate.RenameChildHandler; -import edu.harvard.i2b2.workplace.delegate.MoveChildHandler; -import edu.harvard.i2b2.workplace.delegate.GetNameInfoHandler; -import edu.harvard.i2b2.workplace.delegate.SetProtectedAcessHandler; - -import org.apache.axiom.om.OMElement; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -//import javax.xml.stream.XMLStreamException; - - -/** - * This is webservice skeleton class. It parses incoming Workplace service requests - * and generates responses in the Work Data Object XML format. - * - */ -public class WorkplaceService { - private static Log log = LogFactory.getLog(WorkplaceService.class); - protected final Log logesapi = LogFactory.getLog(getClass()); - - /** - * This function is main webservice interface to get vocab data - * for a query. It uses AXIOM elements(OMElement) to conveniently parse - * xml messages. - * - * It excepts incoming request in i2b2 message format, which wraps a Workplace - * query inside a vocab query request object. The response is also will be in i2b2 - * message format, which will wrap work data object. Work data object will - * have all the results returned by the query. - * - * - * @param getChildren - * @return OMElement in i2b2message format - * @throws Exception - */ - public OMElement getChildren(OMElement getChildrenElement) - throws I2B2Exception { - - - // OMElement returnElement = null; - String workplaceDataResponse = null; - String unknownErrorMessage = "Error message delivered from the remote server \n" + - "You may wish to retry your last action"; - - if (getChildrenElement == null) { - log.error("Incoming Workplace request is null"); - - ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, - unknownErrorMessage); - workplaceDataResponse = MessageFactory.convertToXMLString(responseMsgType); - return MessageFactory.createResponseOMElementFromString(workplaceDataResponse); - } - - GetChildrenDataMessage childrenDataMsg = new GetChildrenDataMessage(); - String requestElementString = getChildrenElement.toString(); - childrenDataMsg.setRequestMessageType(requestElementString); - - long waitTime = 0; - if ((childrenDataMsg.getRequestMessageType() != null) && (childrenDataMsg.getRequestMessageType().getRequestHeader() != null)) { - waitTime = childrenDataMsg.getRequestMessageType() - .getRequestHeader() - .getResultWaittimeMs(); - } - - //do Workplace query processing inside thread, so that - // service could send back message with timeout error. - // ExecutorRunnable er = new ExecutorRunnable(); - return execute(new GetChildrenHandler(childrenDataMsg), waitTime); - - } - - /** - * This function is main webservice interface to get vocab data - * for a query. It uses AXIOM elements(OMElement) to conveniently parse - * xml messages. - * - * It excepts incoming request in i2b2 message format, which wraps an Workplace - * query inside a work query request object. The response is also will be in i2b2 - * message format, which will wrap work data object. Work data object will - * have all the results returned by the query. - * - * - * @param OMElement getFoldersElement - * @return OMElement in i2b2message format - * @throws Exception - */ - public OMElement getFoldersByProject(OMElement getFoldersElement) - throws Exception { - - // OMElement returnElement = null; - String workplaceDataResponse = null; - String unknownErrorMessage = "Error message delivered from the remote server \n" + - "You may wish to retry your last action"; - - if (getFoldersElement == null) { - log.error("Incoming Workplace request is null"); - - ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, - unknownErrorMessage); - workplaceDataResponse = MessageFactory.convertToXMLString(responseMsgType); - return MessageFactory.createResponseOMElementFromString(workplaceDataResponse); - } - - GetFoldersDataMessage foldersDataMsg = new GetFoldersDataMessage(); - String requestElementString = getFoldersElement.toString(); - // log.info(requestElementString); - foldersDataMsg.setRequestMessageType(requestElementString); - - long waitTime = 0; - if ((foldersDataMsg.getRequestMessageType() != null) && (foldersDataMsg.getRequestMessageType().getRequestHeader() != null)) { - waitTime = foldersDataMsg.getRequestMessageType() - .getRequestHeader() - .getResultWaittimeMs(); - } - - //do Workplace query processing inside thread, so that - // service could sends back message with timeout error. - - // ExecutorRunnable er = new ExecutorRunnable(); - return execute(new GetFoldersByProjectHandler(foldersDataMsg), waitTime); - - } - - - public OMElement getFoldersByUserId(OMElement getFoldersElement) - throws Exception { - - // OMElement returnElement = null; - String workplaceDataResponse = null; - String unknownErrorMessage = "Error message delivered from the remote server \n" + - "You may wish to retry your last action"; - - if (getFoldersElement == null) { - log.error("Incoming Workplace request is null"); - - ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, - unknownErrorMessage); - workplaceDataResponse = MessageFactory.convertToXMLString(responseMsgType); - return MessageFactory.createResponseOMElementFromString(workplaceDataResponse); - } - - GetFoldersDataMessage foldersDataMsg = new GetFoldersDataMessage(); - String requestElementString = getFoldersElement.toString(); - // log.info(requestElementString); - foldersDataMsg.setRequestMessageType(requestElementString); - - long waitTime = 0; - if ((foldersDataMsg.getRequestMessageType() != null) && (foldersDataMsg.getRequestMessageType().getRequestHeader() != null)) { - waitTime = foldersDataMsg.getRequestMessageType() - .getRequestHeader() - .getResultWaittimeMs(); - } - - //do Workplace query processing inside thread, so that - // service could send back message with timeout error. - // ExecutorRunnable er = new ExecutorRunnable(); - return execute(new GetFoldersByUserIdHandler(foldersDataMsg), waitTime); - - } - - /** - * - * This method is for finding the workplace item with the given keyword - * It uses AXIOM elements(OMElement) to conveniently parse - * xml messages. - * - * It excepts incoming request in i2b2 message format, which wraps an Workplace - * query inside a work query request object. The response is also will be in i2b2 - * message format, which will wrap work data object. Work data object will - * have all the results returned by the query. - * - - * @param requestElement - * @return - * @throws Exception - * - * @author Neha Patel - */ - public OMElement getNameInfo(OMElement requestElement) - throws Exception { - - //OMElement requestElement = null; - String workplaceDataResponse = null; - String unknownErrorMessage = "Error message delivered from the remote server \n" + - "You may wish to retry your last action"; - - if (requestElement == null) { - log.error("Incoming Find Workplace request is null"); - - ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, - unknownErrorMessage); - workplaceDataResponse = MessageFactory.convertToXMLString(responseMsgType); - return MessageFactory.createResponseOMElementFromString(workplaceDataResponse); - } - - GetNameInfoDataMessage foldersDataMsg = new GetNameInfoDataMessage(); - String requestElementString = requestElement.toString(); - logesapi.debug(requestElementString); - foldersDataMsg.setRequestMessageType(requestElementString); - - long waitTime = 0; - if ((foldersDataMsg.getRequestMessageType() != null) && (foldersDataMsg.getRequestMessageType().getRequestHeader() != null)) { - - waitTime = foldersDataMsg.getRequestMessageType() - .getRequestHeader() - .getResultWaittimeMs(); - } - - return execute(new GetNameInfoHandler(foldersDataMsg), waitTime); - } - - - public OMElement deleteChild(OMElement deleteNodeElement)throws Exception { - // OMElement returnElement = null; - String workplaceDataResponse = null; - String unknownErrorMessage = "Error message delivered from the remote server \n" + - "You may wish to retry your last action"; - - if (deleteNodeElement == null) { - log.error("Incoming Workplace request is null"); - - ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, - unknownErrorMessage); - workplaceDataResponse = MessageFactory.convertToXMLString(responseMsgType); - return MessageFactory.createResponseOMElementFromString(workplaceDataResponse); - } - - DeleteChildDataMessage deleteDataMsg = new DeleteChildDataMessage(); - String requestElementString = deleteNodeElement.toString(); - // log.info(requestElementString); - deleteDataMsg.setRequestMessageType(requestElementString); - - long waitTime = 0; - if ((deleteDataMsg.getRequestMessageType() != null) && (deleteDataMsg.getRequestMessageType().getRequestHeader() != null)) { - waitTime = deleteDataMsg.getRequestMessageType() - .getRequestHeader() - .getResultWaittimeMs(); - } - - //do Workplace query processing inside thread, so that - // service could send back message with timeout error. - // ExecutorRunnable er = new ExecutorRunnable(); - return execute(new DeleteChildHandler(deleteDataMsg), waitTime); - - } - - - public OMElement moveChild(OMElement nodeElement)throws Exception { - // OMElement returnElement = null; - String workplaceDataResponse = null; - String unknownErrorMessage = "Error message delivered from the remote server \n" + - "You may wish to retry your last action"; - - if (nodeElement == null) { - log.error("Incoming Workplace request is null"); - - ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, - unknownErrorMessage); - workplaceDataResponse = MessageFactory.convertToXMLString(responseMsgType); - return MessageFactory.createResponseOMElementFromString(workplaceDataResponse); - } - - MoveChildDataMessage moveDataMsg = new MoveChildDataMessage(); - String requestElementString = nodeElement.toString(); - // log.info(requestElementString); - moveDataMsg.setRequestMessageType(requestElementString); - - long waitTime = 0; - if ((moveDataMsg.getRequestMessageType() != null) && (moveDataMsg.getRequestMessageType().getRequestHeader() != null)) { - waitTime = moveDataMsg.getRequestMessageType() - .getRequestHeader() - .getResultWaittimeMs(); - } - - //do Workplace query processing inside thread, so that - // service could send back message with timeout error. - // ExecutorRunnable er = new ExecutorRunnable(); - return execute(new MoveChildHandler(moveDataMsg), waitTime); - } - - - public OMElement renameChild(OMElement renameNodeElement) throws Exception { - // OMElement returnElement = null; - String workplaceDataResponse = null; - String unknownErrorMessage = "Error message delivered from the remote server \n" + - "You may wish to retry your last action"; - - if (renameNodeElement == null) { - log.error("Incoming Workplace request is null"); - - ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, - unknownErrorMessage); - workplaceDataResponse = MessageFactory.convertToXMLString(responseMsgType); - return MessageFactory.createResponseOMElementFromString(workplaceDataResponse); - } - - RenameChildDataMessage renameDataMsg = new RenameChildDataMessage(); - String requestElementString = renameNodeElement.toString(); - // log.info(requestElementString); - renameDataMsg.setRequestMessageType(requestElementString); - - long waitTime = 0; - if ((renameDataMsg.getRequestMessageType() != null) && (renameDataMsg.getRequestMessageType().getRequestHeader() != null)) { - waitTime = renameDataMsg.getRequestMessageType() - .getRequestHeader() - .getResultWaittimeMs(); - } - - //do Workplace query processing inside thread, so that - // service could send back message with timeout error. - // ExecutorRunnable er = new ExecutorRunnable(); - return execute(new RenameChildHandler(renameDataMsg), waitTime); - - } - - public OMElement annotateChild(OMElement annotateNodeElement) throws Exception { - // OMElement returnElement = null; - String workplaceDataResponse = null; - String unknownErrorMessage = "Error message delivered from the remote server \n" + - "You may wish to retry your last action"; - - if (annotateNodeElement == null) { - log.error("Incoming Workplace request is null"); - - ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, - unknownErrorMessage); - workplaceDataResponse = MessageFactory.convertToXMLString(responseMsgType); - return MessageFactory.createResponseOMElementFromString(workplaceDataResponse); - } - - AnnotateChildDataMessage annotateDataMsg = new AnnotateChildDataMessage(); - String requestElementString = annotateNodeElement.toString(); - // log.info(requestElementString); - annotateDataMsg.setRequestMessageType(requestElementString); - - long waitTime = 0; - if ((annotateDataMsg.getRequestMessageType() != null) && (annotateDataMsg.getRequestMessageType().getRequestHeader() != null)) { - waitTime = annotateDataMsg.getRequestMessageType() - .getRequestHeader() - .getResultWaittimeMs(); - } - - //do Workplace query processing inside thread, so that - // service could send back message with timeout error. - // ExecutorRunnable er = new ExecutorRunnable(); - return execute(new AnnotateChildHandler(annotateDataMsg), waitTime); - - } - - public OMElement exportChild(OMElement aexportNodeElement) throws Exception { - log.debug("In export Child"); - // OMElement returnElement = null; - String workplaceDataResponse = null; - String unknownErrorMessage = "Error message delivered from the remote server \n" + - "You may wish to retry your last action"; - - if (aexportNodeElement == null) { - log.error("Incoming Workplace request is null"); - - ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, - unknownErrorMessage); - workplaceDataResponse = MessageFactory.convertToXMLString(responseMsgType); - return MessageFactory.createResponseOMElementFromString(workplaceDataResponse); - } - - log.debug("Start of request string"); - ExportChildDataMessage exportDataMsg = new ExportChildDataMessage(); - String requestElementString = aexportNodeElement.toString(); - log.debug("created new string"); - exportDataMsg.setRequestMessageType(requestElementString); - log.debug("set request messagetype"); - long waitTime = 0; - if ((exportDataMsg.getRequestMessageType() != null) && (exportDataMsg.getRequestMessageType().getRequestHeader() != null)) { - waitTime = exportDataMsg.getRequestMessageType() - .getRequestHeader() - .getResultWaittimeMs(); - } - - //do Workplace query processing inside thread, so that - // service could send back message with timeout error. - // ExecutorRunnable er = new ExecutorRunnable(); - return execute(new ExportChildHandler(exportDataMsg), waitTime); - - } - - - public OMElement addChild(OMElement addNodeElement) throws Exception { - // OMElement returnElement = null; - String workplaceDataResponse = null; - String unknownErrorMessage = "Error message delivered from the remote server \n" + - "You may wish to retry your last action"; - - if (addNodeElement == null) { - log.error("Incoming Workplace request is null"); - - ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, - unknownErrorMessage); - workplaceDataResponse = MessageFactory.convertToXMLString(responseMsgType); - return MessageFactory.createResponseOMElementFromString(workplaceDataResponse); - } - - AddChildDataMessage addDataMsg = new AddChildDataMessage(); - String requestElementString = addNodeElement.toString(); - // log.info(requestElementString); - addDataMsg.setRequestMessageType(requestElementString); - - long waitTime = 0; - if ((addDataMsg.getRequestMessageType() != null) && (addDataMsg.getRequestMessageType().getRequestHeader() != null)) { - waitTime = addDataMsg.getRequestMessageType() - .getRequestHeader() - .getResultWaittimeMs(); - } - - //do Workplace query processing inside thread, so that - // service could send back message with timeout error. - // ExecutorRunnable er = new ExecutorRunnable(); - return execute(new AddChildHandler(addDataMsg), waitTime); - - } - - public OMElement setProtectedAccess(OMElement requestElement) throws Exception { - - // OMElement returnElement = null; - String workplaceDataResponse = null; - String unknownErrorMessage = "Error message delivered from the remote server \n" + - "You may wish to retry your last action"; - - if (requestElement == null) { - log.error("Incoming Workplace request is null"); - - ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, - unknownErrorMessage); - workplaceDataResponse = MessageFactory.convertToXMLString(responseMsgType); - return MessageFactory.createResponseOMElementFromString(workplaceDataResponse); - } - - ProtectedDataMessage protectedDataMsg = new ProtectedDataMessage(); - String requestElementString = requestElement.toString(); - - protectedDataMsg.setRequestMessageType(requestElementString); - - long waitTime = 0; - if ((protectedDataMsg.getRequestMessageType() != null) && (protectedDataMsg.getRequestMessageType().getRequestHeader() != null)) { - waitTime = protectedDataMsg.getRequestMessageType() - .getRequestHeader() - .getResultWaittimeMs(); - } - - return execute(new SetProtectedAcessHandler(protectedDataMsg), waitTime); - } - - private OMElement execute(RequestHandler handler, long waitTime)throws I2B2Exception{ - //do workplace processing inside thread, so that - // service could send back message with timeout error. - log.debug("In execute"); - - OMElement returnElement = null; - - String unknownErrorMessage = "Error message delivered from the remote server \n" + - "You may wish to retry your last action"; - - - ExecutorRunnable er = new ExecutorRunnable(); - - er.setRequestHandler(handler); - - Thread t = new Thread(er); - String workplaceDataResponse = null; - - synchronized (t) { - t.start(); - - // try { - // if (waitTime > 0) { - // t.wait(waitTime); - // } else { - // t.wait(); - // } - - try { - long startTime = System.currentTimeMillis(); - long deltaTime = -1; - while((er.isJobCompleteFlag() == false)&& (deltaTime < waitTime)){ - if (waitTime > 0) { - t.wait(waitTime - deltaTime); - deltaTime = System.currentTimeMillis() - startTime; - } else { - t.wait(); - } - } - - workplaceDataResponse = er.getOutputString(); - - if (workplaceDataResponse == null) { - if (er.getJobException() != null) { - log.error("er.jobException is " + er.getJobException().getMessage()); - - log.info("waitTime is " + waitTime); - ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, - unknownErrorMessage); - workplaceDataResponse = MessageFactory.convertToXMLString(responseMsgType); - - } else if (er.isJobCompleteFlag() == false) { - //5000 - String timeOuterror = "Remote server timed out \n" + - "Result waittime = " + - waitTime + - " ms elapsed,\nPlease try again"; - log.error(timeOuterror); - log.debug("workplace waited " + deltaTime + "ms for " + er.getRequestHandler().getClass().getName()); - ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, - timeOuterror); - workplaceDataResponse = MessageFactory.convertToXMLString(responseMsgType); - - } else { - log.error("workplace data response is null"); - log.info("waitTime is " + waitTime); - log.debug("workplace waited " + deltaTime + "ms for " + er.getRequestHandler().getClass().getName()); - ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, - unknownErrorMessage); - workplaceDataResponse = MessageFactory.convertToXMLString(responseMsgType); - } - } - } catch (InterruptedException e) { - log.error(e.getMessage()); - throw new I2B2Exception("Thread error while running Workplace job "); - } finally { - t.interrupt(); - er = null; - t = null; - } - } - returnElement = MessageFactory.createResponseOMElementFromString(workplaceDataResponse); - - return returnElement; - } - - /** swc20160519 - * This function is main webservice interface to get the I2B2HIVE.WORK_DB_LOOKUP data. - * It uses AXIOM elements(OMElement) to conveniently parse xml messages. - * - * It accepts incoming request, and returns a response, both in i2b2 message format. - * - * @param OMElement - * getAllDblookupsElement - * @return OMElement in i2b2message format - * @throws Exception - */ - public OMElement getAllDblookups(OMElement getAllDblookupsElement) throws I2B2Exception { - log.info("getAllDblookups"); - String wpDataResponse = null; - String unknownErrMsg = null; - if (null == getAllDblookupsElement) { - log.error("Incoming Workplace request is null"); - unknownErrMsg = "Error message delivered from the remote server.\nYou may wish to retry your last action"; - ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, unknownErrMsg); - wpDataResponse = MessageFactory.convertToXMLString(responseMsgType); - return MessageFactory.createResponseOMElementFromString(wpDataResponse); - } - String requestElementString = getAllDblookupsElement.toString(); - GetAllDblookupsDataMessage dblookupsDataMsg = new GetAllDblookupsDataMessage(requestElementString); - long waitTime = 0; - if ((null != dblookupsDataMsg.getRequestMessageType()) && (null != dblookupsDataMsg.getRequestMessageType().getRequestHeader())) { - waitTime = dblookupsDataMsg.getRequestMessageType().getRequestHeader().getResultWaittimeMs(); - } - // do processing inside thread, so that service could send back message with timeout error. - return execute(new GetAllDblookupsHandler(dblookupsDataMsg), waitTime); - } - - /** swc20160519 - * This function is main webservice interface to get specific I2B2HIVE.WORK_DB_LOOKUP data. - * It uses AXIOM elements(OMElement) to conveniently parse xml messages. - * - * It accepts incoming request, and returns a response, both in i2b2 message format. - * - * @param OMElement - * getDblookupElement - * @return OMElement in i2b2message format - * @throws Exception - */ - public OMElement getDblookup(OMElement getDblookupElement) throws I2B2Exception { - String wpDataResponse = null; - String unknownErrMsg = null; - if (null == getDblookupElement) { - log.error("Incoming Workplace request is null"); - unknownErrMsg = "Error message delivered from the remote server.\nYou may wish to retry your last action"; - ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, unknownErrMsg); - wpDataResponse = MessageFactory.convertToXMLString(responseMsgType); - return MessageFactory.createResponseOMElementFromString(wpDataResponse); - } - String requestElementString = getDblookupElement.toString(); - GetDblookupDataMessage dblookupDataMsg = new GetDblookupDataMessage(requestElementString); - long waitTime = 0; - if ((null != dblookupDataMsg.getRequestMessageType()) && (null != dblookupDataMsg.getRequestMessageType().getRequestHeader())) { - waitTime = dblookupDataMsg.getRequestMessageType().getRequestHeader().getResultWaittimeMs(); - } - // do processing inside thread, so that service could send back message with timeout error. - return execute(new GetDblookupHandler(dblookupDataMsg), waitTime); - } - - /** swc20160519 - * This function is main webservice interface to add a new entry to the I2B2HIVE.WORK_DB_LOOKUP data. - * It uses AXIOM elements(OMElement) to conveniently parse xml messages. - * - * It accepts incoming request, and returns a response, both in i2b2 message format. - * - * @param OMElement - * getAllDblookupsElement - * @return OMElement in i2b2message format - * @throws Exception - */ - public OMElement setDblookup(OMElement setDblookupElement) throws I2B2Exception { - String wpDataResponse = null; - String unknownErrMsg = null; - if (null == setDblookupElement) { - log.error("Incoming Workplace request is null"); - unknownErrMsg = "Error message delivered from the remote server.\nYou may wish to retry your last action"; - ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, unknownErrMsg); - wpDataResponse = MessageFactory.convertToXMLString(responseMsgType); - return MessageFactory.createResponseOMElementFromString(wpDataResponse); - } - String requestElementString = setDblookupElement.toString(); - SetDblookupDataMessage dblookupDataMsg = new SetDblookupDataMessage(requestElementString); - long waitTime = 0; - if ((null != dblookupDataMsg.getRequestMessageType()) && (null != dblookupDataMsg.getRequestMessageType().getRequestHeader())) { - waitTime = dblookupDataMsg.getRequestMessageType().getRequestHeader().getResultWaittimeMs(); - } - // do processing inside thread, so that service could send back message with timeout error. - return execute(new SetDblookupHandler(dblookupDataMsg), waitTime); - } - - /** swc20160519 - * This function is main webservice interface to delete specific I2B2HIVE.WORK_DB_LOOKUP data. - * It uses AXIOM elements(OMElement) to conveniently parse xml messages. - * - * It accepts incoming request, and returns a response, both in i2b2 message format. - * - * @param OMElement - * deleteDblookupElement - * @return OMElement in i2b2message format - * @throws Exception - */ - public OMElement deleteDblookup(OMElement deleteDblookupElement) throws I2B2Exception { - String wpDataResponse = null; - String unknownErrMsg = null; - if (null == deleteDblookupElement) { - log.error("Incoming Workplace request is null"); - unknownErrMsg = "Error message delivered from the remote server.\nYou may wish to retry your last action"; - ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, unknownErrMsg); - wpDataResponse = MessageFactory.convertToXMLString(responseMsgType); - return MessageFactory.createResponseOMElementFromString(wpDataResponse); - } - String requestElementString = deleteDblookupElement.toString(); - DeleteDblookupDataMessage dblookupDataMsg = new DeleteDblookupDataMessage(requestElementString); - long waitTime = 0; - if ((null != dblookupDataMsg.getRequestMessageType()) && (null != dblookupDataMsg.getRequestMessageType().getRequestHeader())) { - waitTime = dblookupDataMsg.getRequestMessageType().getRequestHeader().getResultWaittimeMs(); - } - // do processing inside thread, so that service could send back message with timeout error. - return execute(new DeleteDblookupHandler(dblookupDataMsg), waitTime); - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Raj Kuttan + * Lori Phillips + */ +package edu.harvard.i2b2.workplace.ws; + +import edu.harvard.i2b2.common.exception.I2B2Exception; +import edu.harvard.i2b2.workplace.delegate.DeleteDblookupHandler; +import edu.harvard.i2b2.workplace.delegate.GetAllDblookupsHandler; +import edu.harvard.i2b2.workplace.delegate.GetDblookupHandler; +import edu.harvard.i2b2.workplace.delegate.SetDblookupHandler; +import edu.harvard.i2b2.workplace.ws.DeleteDblookupDataMessage; +import edu.harvard.i2b2.workplace.ws.GetAllDblookupsDataMessage; +import edu.harvard.i2b2.workplace.ws.GetDblookupDataMessage; +import edu.harvard.i2b2.workplace.ws.SetDblookupDataMessage; +import edu.harvard.i2b2.workplace.delegate.RequestHandler; +import edu.harvard.i2b2.workplace.ws.ExecutorRunnable; +import edu.harvard.i2b2.workplace.ws.MessageFactory; +import edu.harvard.i2b2.workplace.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.workplace.delegate.AddChildHandler; +import edu.harvard.i2b2.workplace.delegate.AnnotateChildHandler; +import edu.harvard.i2b2.workplace.delegate.DeleteChildHandler; +import edu.harvard.i2b2.workplace.delegate.ExportChildHandler; +import edu.harvard.i2b2.workplace.delegate.GetFoldersByProjectHandler; +import edu.harvard.i2b2.workplace.delegate.GetFoldersByUserIdHandler; +import edu.harvard.i2b2.workplace.delegate.GetChildrenHandler; +import edu.harvard.i2b2.workplace.delegate.RenameChildHandler; +import edu.harvard.i2b2.workplace.delegate.MoveChildHandler; +import edu.harvard.i2b2.workplace.delegate.GetNameInfoHandler; +import edu.harvard.i2b2.workplace.delegate.SetProtectedAcessHandler; + +import org.apache.axiom.om.OMElement; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +//import javax.xml.stream.XMLStreamException; + + +/** + * This is webservice skeleton class. It parses incoming Workplace service requests + * and generates responses in the Work Data Object XML format. + * + */ +public class WorkplaceService { + private static Log log = LogFactory.getLog(WorkplaceService.class); + protected final Log logesapi = LogFactory.getLog(getClass()); + + /** + * This function is main webservice interface to get vocab data + * for a query. It uses AXIOM elements(OMElement) to conveniently parse + * xml messages. + * + * It excepts incoming request in i2b2 message format, which wraps a Workplace + * query inside a vocab query request object. The response is also will be in i2b2 + * message format, which will wrap work data object. Work data object will + * have all the results returned by the query. + * + * + * @param getChildren + * @return OMElement in i2b2message format + * @throws Exception + */ + public OMElement getChildren(OMElement getChildrenElement) + throws I2B2Exception { + + + // OMElement returnElement = null; + String workplaceDataResponse = null; + String unknownErrorMessage = "Error message delivered from the remote server \n" + + "You may wish to retry your last action"; + + if (getChildrenElement == null) { + log.error("Incoming Workplace request is null"); + + ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, + unknownErrorMessage); + workplaceDataResponse = MessageFactory.convertToXMLString(responseMsgType); + return MessageFactory.createResponseOMElementFromString(workplaceDataResponse); + } + + GetChildrenDataMessage childrenDataMsg = new GetChildrenDataMessage(); + String requestElementString = getChildrenElement.toString(); + childrenDataMsg.setRequestMessageType(requestElementString); + + long waitTime = 0; + if ((childrenDataMsg.getRequestMessageType() != null) && (childrenDataMsg.getRequestMessageType().getRequestHeader() != null)) { + waitTime = childrenDataMsg.getRequestMessageType() + .getRequestHeader() + .getResultWaittimeMs(); + } + + //do Workplace query processing inside thread, so that + // service could send back message with timeout error. + // ExecutorRunnable er = new ExecutorRunnable(); + return execute(new GetChildrenHandler(childrenDataMsg), waitTime); + + } + + /** + * This function is main webservice interface to get vocab data + * for a query. It uses AXIOM elements(OMElement) to conveniently parse + * xml messages. + * + * It excepts incoming request in i2b2 message format, which wraps an Workplace + * query inside a work query request object. The response is also will be in i2b2 + * message format, which will wrap work data object. Work data object will + * have all the results returned by the query. + * + * + * @param OMElement getFoldersElement + * @return OMElement in i2b2message format + * @throws Exception + */ + public OMElement getFoldersByProject(OMElement getFoldersElement) + throws Exception { + + // OMElement returnElement = null; + String workplaceDataResponse = null; + String unknownErrorMessage = "Error message delivered from the remote server \n" + + "You may wish to retry your last action"; + + if (getFoldersElement == null) { + log.error("Incoming Workplace request is null"); + + ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, + unknownErrorMessage); + workplaceDataResponse = MessageFactory.convertToXMLString(responseMsgType); + return MessageFactory.createResponseOMElementFromString(workplaceDataResponse); + } + + GetFoldersDataMessage foldersDataMsg = new GetFoldersDataMessage(); + String requestElementString = getFoldersElement.toString(); + // log.info(requestElementString); + foldersDataMsg.setRequestMessageType(requestElementString); + + long waitTime = 0; + if ((foldersDataMsg.getRequestMessageType() != null) && (foldersDataMsg.getRequestMessageType().getRequestHeader() != null)) { + waitTime = foldersDataMsg.getRequestMessageType() + .getRequestHeader() + .getResultWaittimeMs(); + } + + //do Workplace query processing inside thread, so that + // service could sends back message with timeout error. + + // ExecutorRunnable er = new ExecutorRunnable(); + return execute(new GetFoldersByProjectHandler(foldersDataMsg), waitTime); + + } + + + public OMElement getFoldersByUserId(OMElement getFoldersElement) + throws Exception { + + // OMElement returnElement = null; + String workplaceDataResponse = null; + String unknownErrorMessage = "Error message delivered from the remote server \n" + + "You may wish to retry your last action"; + + if (getFoldersElement == null) { + log.error("Incoming Workplace request is null"); + + ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, + unknownErrorMessage); + workplaceDataResponse = MessageFactory.convertToXMLString(responseMsgType); + return MessageFactory.createResponseOMElementFromString(workplaceDataResponse); + } + + GetFoldersDataMessage foldersDataMsg = new GetFoldersDataMessage(); + String requestElementString = getFoldersElement.toString(); + // log.info(requestElementString); + foldersDataMsg.setRequestMessageType(requestElementString); + + long waitTime = 0; + if ((foldersDataMsg.getRequestMessageType() != null) && (foldersDataMsg.getRequestMessageType().getRequestHeader() != null)) { + waitTime = foldersDataMsg.getRequestMessageType() + .getRequestHeader() + .getResultWaittimeMs(); + } + + //do Workplace query processing inside thread, so that + // service could send back message with timeout error. + // ExecutorRunnable er = new ExecutorRunnable(); + return execute(new GetFoldersByUserIdHandler(foldersDataMsg), waitTime); + + } + + /** + * + * This method is for finding the workplace item with the given keyword + * It uses AXIOM elements(OMElement) to conveniently parse + * xml messages. + * + * It excepts incoming request in i2b2 message format, which wraps an Workplace + * query inside a work query request object. The response is also will be in i2b2 + * message format, which will wrap work data object. Work data object will + * have all the results returned by the query. + * + + * @param requestElement + * @return + * @throws Exception + * + * @author Neha Patel + */ + public OMElement getNameInfo(OMElement requestElement) + throws Exception { + + //OMElement requestElement = null; + String workplaceDataResponse = null; + String unknownErrorMessage = "Error message delivered from the remote server \n" + + "You may wish to retry your last action"; + + if (requestElement == null) { + log.error("Incoming Find Workplace request is null"); + + ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, + unknownErrorMessage); + workplaceDataResponse = MessageFactory.convertToXMLString(responseMsgType); + return MessageFactory.createResponseOMElementFromString(workplaceDataResponse); + } + + GetNameInfoDataMessage foldersDataMsg = new GetNameInfoDataMessage(); + String requestElementString = requestElement.toString(); + logesapi.debug(requestElementString); + foldersDataMsg.setRequestMessageType(requestElementString); + + long waitTime = 0; + if ((foldersDataMsg.getRequestMessageType() != null) && (foldersDataMsg.getRequestMessageType().getRequestHeader() != null)) { + + waitTime = foldersDataMsg.getRequestMessageType() + .getRequestHeader() + .getResultWaittimeMs(); + } + + return execute(new GetNameInfoHandler(foldersDataMsg), waitTime); + } + + + public OMElement deleteChild(OMElement deleteNodeElement)throws Exception { + // OMElement returnElement = null; + String workplaceDataResponse = null; + String unknownErrorMessage = "Error message delivered from the remote server \n" + + "You may wish to retry your last action"; + + if (deleteNodeElement == null) { + log.error("Incoming Workplace request is null"); + + ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, + unknownErrorMessage); + workplaceDataResponse = MessageFactory.convertToXMLString(responseMsgType); + return MessageFactory.createResponseOMElementFromString(workplaceDataResponse); + } + + DeleteChildDataMessage deleteDataMsg = new DeleteChildDataMessage(); + String requestElementString = deleteNodeElement.toString(); + // log.info(requestElementString); + deleteDataMsg.setRequestMessageType(requestElementString); + + long waitTime = 0; + if ((deleteDataMsg.getRequestMessageType() != null) && (deleteDataMsg.getRequestMessageType().getRequestHeader() != null)) { + waitTime = deleteDataMsg.getRequestMessageType() + .getRequestHeader() + .getResultWaittimeMs(); + } + + //do Workplace query processing inside thread, so that + // service could send back message with timeout error. + // ExecutorRunnable er = new ExecutorRunnable(); + return execute(new DeleteChildHandler(deleteDataMsg), waitTime); + + } + + + public OMElement moveChild(OMElement nodeElement)throws Exception { + // OMElement returnElement = null; + String workplaceDataResponse = null; + String unknownErrorMessage = "Error message delivered from the remote server \n" + + "You may wish to retry your last action"; + + if (nodeElement == null) { + log.error("Incoming Workplace request is null"); + + ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, + unknownErrorMessage); + workplaceDataResponse = MessageFactory.convertToXMLString(responseMsgType); + return MessageFactory.createResponseOMElementFromString(workplaceDataResponse); + } + + MoveChildDataMessage moveDataMsg = new MoveChildDataMessage(); + String requestElementString = nodeElement.toString(); + // log.info(requestElementString); + moveDataMsg.setRequestMessageType(requestElementString); + + long waitTime = 0; + if ((moveDataMsg.getRequestMessageType() != null) && (moveDataMsg.getRequestMessageType().getRequestHeader() != null)) { + waitTime = moveDataMsg.getRequestMessageType() + .getRequestHeader() + .getResultWaittimeMs(); + } + + //do Workplace query processing inside thread, so that + // service could send back message with timeout error. + // ExecutorRunnable er = new ExecutorRunnable(); + return execute(new MoveChildHandler(moveDataMsg), waitTime); + } + + + public OMElement renameChild(OMElement renameNodeElement) throws Exception { + // OMElement returnElement = null; + String workplaceDataResponse = null; + String unknownErrorMessage = "Error message delivered from the remote server \n" + + "You may wish to retry your last action"; + + if (renameNodeElement == null) { + log.error("Incoming Workplace request is null"); + + ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, + unknownErrorMessage); + workplaceDataResponse = MessageFactory.convertToXMLString(responseMsgType); + return MessageFactory.createResponseOMElementFromString(workplaceDataResponse); + } + + RenameChildDataMessage renameDataMsg = new RenameChildDataMessage(); + String requestElementString = renameNodeElement.toString(); + // log.info(requestElementString); + renameDataMsg.setRequestMessageType(requestElementString); + + long waitTime = 0; + if ((renameDataMsg.getRequestMessageType() != null) && (renameDataMsg.getRequestMessageType().getRequestHeader() != null)) { + waitTime = renameDataMsg.getRequestMessageType() + .getRequestHeader() + .getResultWaittimeMs(); + } + + //do Workplace query processing inside thread, so that + // service could send back message with timeout error. + // ExecutorRunnable er = new ExecutorRunnable(); + return execute(new RenameChildHandler(renameDataMsg), waitTime); + + } + + public OMElement annotateChild(OMElement annotateNodeElement) throws Exception { + // OMElement returnElement = null; + String workplaceDataResponse = null; + String unknownErrorMessage = "Error message delivered from the remote server \n" + + "You may wish to retry your last action"; + + if (annotateNodeElement == null) { + log.error("Incoming Workplace request is null"); + + ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, + unknownErrorMessage); + workplaceDataResponse = MessageFactory.convertToXMLString(responseMsgType); + return MessageFactory.createResponseOMElementFromString(workplaceDataResponse); + } + + AnnotateChildDataMessage annotateDataMsg = new AnnotateChildDataMessage(); + String requestElementString = annotateNodeElement.toString(); + // log.info(requestElementString); + annotateDataMsg.setRequestMessageType(requestElementString); + + long waitTime = 0; + if ((annotateDataMsg.getRequestMessageType() != null) && (annotateDataMsg.getRequestMessageType().getRequestHeader() != null)) { + waitTime = annotateDataMsg.getRequestMessageType() + .getRequestHeader() + .getResultWaittimeMs(); + } + + //do Workplace query processing inside thread, so that + // service could send back message with timeout error. + // ExecutorRunnable er = new ExecutorRunnable(); + return execute(new AnnotateChildHandler(annotateDataMsg), waitTime); + + } + + public OMElement exportChild(OMElement aexportNodeElement) throws Exception { + log.debug("In export Child"); + // OMElement returnElement = null; + String workplaceDataResponse = null; + String unknownErrorMessage = "Error message delivered from the remote server \n" + + "You may wish to retry your last action"; + + if (aexportNodeElement == null) { + log.error("Incoming Workplace request is null"); + + ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, + unknownErrorMessage); + workplaceDataResponse = MessageFactory.convertToXMLString(responseMsgType); + return MessageFactory.createResponseOMElementFromString(workplaceDataResponse); + } + + log.debug("Start of request string"); + ExportChildDataMessage exportDataMsg = new ExportChildDataMessage(); + String requestElementString = aexportNodeElement.toString(); + log.debug("created new string"); + exportDataMsg.setRequestMessageType(requestElementString); + log.debug("set request messagetype"); + long waitTime = 0; + if ((exportDataMsg.getRequestMessageType() != null) && (exportDataMsg.getRequestMessageType().getRequestHeader() != null)) { + waitTime = exportDataMsg.getRequestMessageType() + .getRequestHeader() + .getResultWaittimeMs(); + } + + //do Workplace query processing inside thread, so that + // service could send back message with timeout error. + // ExecutorRunnable er = new ExecutorRunnable(); + return execute(new ExportChildHandler(exportDataMsg), waitTime); + + } + + + public OMElement addChild(OMElement addNodeElement) throws Exception { + // OMElement returnElement = null; + String workplaceDataResponse = null; + String unknownErrorMessage = "Error message delivered from the remote server \n" + + "You may wish to retry your last action"; + + if (addNodeElement == null) { + log.error("Incoming Workplace request is null"); + + ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, + unknownErrorMessage); + workplaceDataResponse = MessageFactory.convertToXMLString(responseMsgType); + return MessageFactory.createResponseOMElementFromString(workplaceDataResponse); + } + + AddChildDataMessage addDataMsg = new AddChildDataMessage(); + String requestElementString = addNodeElement.toString(); + // log.info(requestElementString); + addDataMsg.setRequestMessageType(requestElementString); + + long waitTime = 0; + if ((addDataMsg.getRequestMessageType() != null) && (addDataMsg.getRequestMessageType().getRequestHeader() != null)) { + waitTime = addDataMsg.getRequestMessageType() + .getRequestHeader() + .getResultWaittimeMs(); + } + + //do Workplace query processing inside thread, so that + // service could send back message with timeout error. + // ExecutorRunnable er = new ExecutorRunnable(); + return execute(new AddChildHandler(addDataMsg), waitTime); + + } + + public OMElement setProtectedAccess(OMElement requestElement) throws Exception { + + // OMElement returnElement = null; + String workplaceDataResponse = null; + String unknownErrorMessage = "Error message delivered from the remote server \n" + + "You may wish to retry your last action"; + + if (requestElement == null) { + log.error("Incoming Workplace request is null"); + + ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, + unknownErrorMessage); + workplaceDataResponse = MessageFactory.convertToXMLString(responseMsgType); + return MessageFactory.createResponseOMElementFromString(workplaceDataResponse); + } + + ProtectedDataMessage protectedDataMsg = new ProtectedDataMessage(); + String requestElementString = requestElement.toString(); + + protectedDataMsg.setRequestMessageType(requestElementString); + + long waitTime = 0; + if ((protectedDataMsg.getRequestMessageType() != null) && (protectedDataMsg.getRequestMessageType().getRequestHeader() != null)) { + waitTime = protectedDataMsg.getRequestMessageType() + .getRequestHeader() + .getResultWaittimeMs(); + } + + return execute(new SetProtectedAcessHandler(protectedDataMsg), waitTime); + } + + private OMElement execute(RequestHandler handler, long waitTime)throws I2B2Exception{ + //do workplace processing inside thread, so that + // service could send back message with timeout error. + log.debug("In execute"); + + OMElement returnElement = null; + + String unknownErrorMessage = "Error message delivered from the remote server \n" + + "You may wish to retry your last action"; + + + ExecutorRunnable er = new ExecutorRunnable(); + + er.setRequestHandler(handler); + + Thread t = new Thread(er); + String workplaceDataResponse = null; + + synchronized (t) { + t.start(); + + // try { + // if (waitTime > 0) { + // t.wait(waitTime); + // } else { + // t.wait(); + // } + + try { + long startTime = System.currentTimeMillis(); + long deltaTime = -1; + while((er.isJobCompleteFlag() == false)&& (deltaTime < waitTime)){ + if (waitTime > 0) { + t.wait(waitTime - deltaTime); + deltaTime = System.currentTimeMillis() - startTime; + } else { + t.wait(); + } + } + + workplaceDataResponse = er.getOutputString(); + + if (workplaceDataResponse == null) { + if (er.getJobException() != null) { + log.error("er.jobException is " + er.getJobException().getMessage()); + + log.info("waitTime is " + waitTime); + ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, + unknownErrorMessage); + workplaceDataResponse = MessageFactory.convertToXMLString(responseMsgType); + + } else if (er.isJobCompleteFlag() == false) { + //5000 + String timeOuterror = "Remote server timed out \n" + + "Result waittime = " + + waitTime + + " ms elapsed,\nPlease try again"; + log.error(timeOuterror); + log.debug("workplace waited " + deltaTime + "ms for " + er.getRequestHandler().getClass().getName()); + ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, + timeOuterror); + workplaceDataResponse = MessageFactory.convertToXMLString(responseMsgType); + + } else { + log.error("workplace data response is null"); + log.info("waitTime is " + waitTime); + log.debug("workplace waited " + deltaTime + "ms for " + er.getRequestHandler().getClass().getName()); + ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, + unknownErrorMessage); + workplaceDataResponse = MessageFactory.convertToXMLString(responseMsgType); + } + } + } catch (InterruptedException e) { + log.error(e.getMessage()); + throw new I2B2Exception("Thread error while running Workplace job "); + } finally { + t.interrupt(); + er = null; + t = null; + } + } + returnElement = MessageFactory.createResponseOMElementFromString(workplaceDataResponse); + + return returnElement; + } + + /** swc20160519 + * This function is main webservice interface to get the I2B2HIVE.WORK_DB_LOOKUP data. + * It uses AXIOM elements(OMElement) to conveniently parse xml messages. + * + * It accepts incoming request, and returns a response, both in i2b2 message format. + * + * @param OMElement + * getAllDblookupsElement + * @return OMElement in i2b2message format + * @throws Exception + */ + public OMElement getAllDblookups(OMElement getAllDblookupsElement) throws I2B2Exception { + log.info("getAllDblookups"); + String wpDataResponse = null; + String unknownErrMsg = null; + if (null == getAllDblookupsElement) { + log.error("Incoming Workplace request is null"); + unknownErrMsg = "Error message delivered from the remote server.\nYou may wish to retry your last action"; + ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, unknownErrMsg); + wpDataResponse = MessageFactory.convertToXMLString(responseMsgType); + return MessageFactory.createResponseOMElementFromString(wpDataResponse); + } + String requestElementString = getAllDblookupsElement.toString(); + GetAllDblookupsDataMessage dblookupsDataMsg = new GetAllDblookupsDataMessage(requestElementString); + long waitTime = 0; + if ((null != dblookupsDataMsg.getRequestMessageType()) && (null != dblookupsDataMsg.getRequestMessageType().getRequestHeader())) { + waitTime = dblookupsDataMsg.getRequestMessageType().getRequestHeader().getResultWaittimeMs(); + } + // do processing inside thread, so that service could send back message with timeout error. + return execute(new GetAllDblookupsHandler(dblookupsDataMsg), waitTime); + } + + /** swc20160519 + * This function is main webservice interface to get specific I2B2HIVE.WORK_DB_LOOKUP data. + * It uses AXIOM elements(OMElement) to conveniently parse xml messages. + * + * It accepts incoming request, and returns a response, both in i2b2 message format. + * + * @param OMElement + * getDblookupElement + * @return OMElement in i2b2message format + * @throws Exception + */ + public OMElement getDblookup(OMElement getDblookupElement) throws I2B2Exception { + String wpDataResponse = null; + String unknownErrMsg = null; + if (null == getDblookupElement) { + log.error("Incoming Workplace request is null"); + unknownErrMsg = "Error message delivered from the remote server.\nYou may wish to retry your last action"; + ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, unknownErrMsg); + wpDataResponse = MessageFactory.convertToXMLString(responseMsgType); + return MessageFactory.createResponseOMElementFromString(wpDataResponse); + } + String requestElementString = getDblookupElement.toString(); + GetDblookupDataMessage dblookupDataMsg = new GetDblookupDataMessage(requestElementString); + long waitTime = 0; + if ((null != dblookupDataMsg.getRequestMessageType()) && (null != dblookupDataMsg.getRequestMessageType().getRequestHeader())) { + waitTime = dblookupDataMsg.getRequestMessageType().getRequestHeader().getResultWaittimeMs(); + } + // do processing inside thread, so that service could send back message with timeout error. + return execute(new GetDblookupHandler(dblookupDataMsg), waitTime); + } + + /** swc20160519 + * This function is main webservice interface to add a new entry to the I2B2HIVE.WORK_DB_LOOKUP data. + * It uses AXIOM elements(OMElement) to conveniently parse xml messages. + * + * It accepts incoming request, and returns a response, both in i2b2 message format. + * + * @param OMElement + * getAllDblookupsElement + * @return OMElement in i2b2message format + * @throws Exception + */ + public OMElement setDblookup(OMElement setDblookupElement) throws I2B2Exception { + String wpDataResponse = null; + String unknownErrMsg = null; + if (null == setDblookupElement) { + log.error("Incoming Workplace request is null"); + unknownErrMsg = "Error message delivered from the remote server.\nYou may wish to retry your last action"; + ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, unknownErrMsg); + wpDataResponse = MessageFactory.convertToXMLString(responseMsgType); + return MessageFactory.createResponseOMElementFromString(wpDataResponse); + } + String requestElementString = setDblookupElement.toString(); + SetDblookupDataMessage dblookupDataMsg = new SetDblookupDataMessage(requestElementString); + long waitTime = 0; + if ((null != dblookupDataMsg.getRequestMessageType()) && (null != dblookupDataMsg.getRequestMessageType().getRequestHeader())) { + waitTime = dblookupDataMsg.getRequestMessageType().getRequestHeader().getResultWaittimeMs(); + } + // do processing inside thread, so that service could send back message with timeout error. + return execute(new SetDblookupHandler(dblookupDataMsg), waitTime); + } + + /** swc20160519 + * This function is main webservice interface to delete specific I2B2HIVE.WORK_DB_LOOKUP data. + * It uses AXIOM elements(OMElement) to conveniently parse xml messages. + * + * It accepts incoming request, and returns a response, both in i2b2 message format. + * + * @param OMElement + * deleteDblookupElement + * @return OMElement in i2b2message format + * @throws Exception + */ + public OMElement deleteDblookup(OMElement deleteDblookupElement) throws I2B2Exception { + String wpDataResponse = null; + String unknownErrMsg = null; + if (null == deleteDblookupElement) { + log.error("Incoming Workplace request is null"); + unknownErrMsg = "Error message delivered from the remote server.\nYou may wish to retry your last action"; + ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, unknownErrMsg); + wpDataResponse = MessageFactory.convertToXMLString(responseMsgType); + return MessageFactory.createResponseOMElementFromString(wpDataResponse); + } + String requestElementString = deleteDblookupElement.toString(); + DeleteDblookupDataMessage dblookupDataMsg = new DeleteDblookupDataMessage(requestElementString); + long waitTime = 0; + if ((null != dblookupDataMsg.getRequestMessageType()) && (null != dblookupDataMsg.getRequestMessageType().getRequestHeader())) { + waitTime = dblookupDataMsg.getRequestMessageType().getRequestHeader().getResultWaittimeMs(); + } + // do processing inside thread, so that service could send back message with timeout error. + return execute(new DeleteDblookupHandler(dblookupDataMsg), waitTime); + } + +} diff --git a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/pm/ws/GetUserConfigurationRequestMessage.java b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplacepm/ws/GetUserConfigurationRequestMessage.java old mode 100755 new mode 100644 similarity index 98% rename from edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/pm/ws/GetUserConfigurationRequestMessage.java rename to edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplacepm/ws/GetUserConfigurationRequestMessage.java index fd1ab3e9..67f7aa4b --- a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/pm/ws/GetUserConfigurationRequestMessage.java +++ b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplacepm/ws/GetUserConfigurationRequestMessage.java @@ -13,7 +13,7 @@ * Mike Mendis * Raj Kuttan */ -package edu.harvard.i2b2.pm.ws; +package edu.harvard.i2b2.workplacepm.ws; import java.io.StringWriter; diff --git a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/pm/ws/PMResponseMessage.java b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplacepm/ws/PMResponseMessage.java old mode 100755 new mode 100644 similarity index 95% rename from edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/pm/ws/PMResponseMessage.java rename to edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplacepm/ws/PMResponseMessage.java index b14c7e58..b9b4d2d1 --- a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/pm/ws/PMResponseMessage.java +++ b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplacepm/ws/PMResponseMessage.java @@ -1,71 +1,71 @@ -/******************************************************************************* - * Copyright (c) 2006-2018 Massachusetts General Hospital - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Mozilla Public License, - * v. 2.0. If a copy of the MPL was not distributed with this file, You can - * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under - * the terms of the Healthcare Disclaimer. - ******************************************************************************/ -/* - - * - * Contributors: - * Mike Mendis - * Raj Kuttan - */ -package edu.harvard.i2b2.pm.ws; - -import jakarta.xml.bind.JAXBElement; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; -import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; -import edu.harvard.i2b2.workplace.datavo.i2b2message.BodyType; -import edu.harvard.i2b2.workplace.datavo.i2b2message.ResponseHeaderType; -import edu.harvard.i2b2.workplace.datavo.i2b2message.ResponseMessageType; -import edu.harvard.i2b2.workplace.datavo.i2b2message.StatusType; -import edu.harvard.i2b2.workplace.datavo.pm.ConfigureType; -import edu.harvard.i2b2.workplace.util.WorkplaceJAXBUtil; - - -public class PMResponseMessage { - - public static final String THIS_CLASS_NAME = PMResponseMessage.class.getName(); - private Log log = LogFactory.getLog(THIS_CLASS_NAME); - private ResponseMessageType pmRespMessageType = null; - - public PMResponseMessage() {} - - public StatusType processResult(String response) { - StatusType status = null; - - JAXBElement jaxbElement; - try { - jaxbElement = WorkplaceJAXBUtil.getJAXBUtil().unMashallFromString(response); - } catch (JAXBUtilException e) { - return status; - } - - pmRespMessageType = (ResponseMessageType) jaxbElement.getValue(); - - // Get response message status - ResponseHeaderType responseHeader = pmRespMessageType.getResponseHeader(); - status = responseHeader.getResultStatus().getStatus(); - - return status; - } - - - public ConfigureType readUserInfo() throws Exception { - ConfigureType pmResponse = null; - - BodyType bodyType = pmRespMessageType.getMessageBody(); - JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); - pmResponse = (ConfigureType)helper.getObjectByClass(bodyType.getAny(), ConfigureType.class); - - return pmResponse; - } - -} +/******************************************************************************* + * Copyright (c) 2006-2018 Massachusetts General Hospital + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. I2b2 is also distributed under + * the terms of the Healthcare Disclaimer. + ******************************************************************************/ +/* + + * + * Contributors: + * Mike Mendis + * Raj Kuttan + */ +package edu.harvard.i2b2.workplacepm.ws; + +import jakarta.xml.bind.JAXBElement; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.harvard.i2b2.common.util.jaxb.JAXBUnWrapHelper; +import edu.harvard.i2b2.common.util.jaxb.JAXBUtilException; +import edu.harvard.i2b2.workplace.datavo.i2b2message.BodyType; +import edu.harvard.i2b2.workplace.datavo.i2b2message.ResponseHeaderType; +import edu.harvard.i2b2.workplace.datavo.i2b2message.ResponseMessageType; +import edu.harvard.i2b2.workplace.datavo.i2b2message.StatusType; +import edu.harvard.i2b2.workplace.datavo.pm.ConfigureType; +import edu.harvard.i2b2.workplace.util.WorkplaceJAXBUtil; + + +public class PMResponseMessage { + + public static final String THIS_CLASS_NAME = PMResponseMessage.class.getName(); + private Log log = LogFactory.getLog(THIS_CLASS_NAME); + private ResponseMessageType pmRespMessageType = null; + + public PMResponseMessage() {} + + public StatusType processResult(String response) { + StatusType status = null; + + JAXBElement jaxbElement; + try { + jaxbElement = WorkplaceJAXBUtil.getJAXBUtil().unMashallFromString(response); + } catch (JAXBUtilException e) { + return status; + } + + pmRespMessageType = (ResponseMessageType) jaxbElement.getValue(); + + // Get response message status + ResponseHeaderType responseHeader = pmRespMessageType.getResponseHeader(); + status = responseHeader.getResultStatus().getStatus(); + + return status; + } + + + public ConfigureType readUserInfo() throws Exception { + ConfigureType pmResponse = null; + + BodyType bodyType = pmRespMessageType.getMessageBody(); + JAXBUnWrapHelper helper = new JAXBUnWrapHelper(); + pmResponse = (ConfigureType)helper.getObjectByClass(bodyType.getAny(), ConfigureType.class); + + return pmResponse; + } + +} diff --git a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/pm/ws/PMServiceDriver.java b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplacepm/ws/PMServiceDriver.java old mode 100755 new mode 100644 similarity index 98% rename from edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/pm/ws/PMServiceDriver.java rename to edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplacepm/ws/PMServiceDriver.java index 2b7219a0..b3663501 --- a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/pm/ws/PMServiceDriver.java +++ b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplacepm/ws/PMServiceDriver.java @@ -14,7 +14,7 @@ * Raj Kuttan * Lori Phillips */ -package edu.harvard.i2b2.pm.ws; +package edu.harvard.i2b2.workplacepm.ws; import java.io.StringReader; diff --git a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/pm/ws/ProjectManagementRequestData.java b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplacepm/ws/ProjectManagementRequestData.java old mode 100755 new mode 100644 similarity index 99% rename from edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/pm/ws/ProjectManagementRequestData.java rename to edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplacepm/ws/ProjectManagementRequestData.java index 79d24b99..5ee89b73 --- a/edu.harvard.i2b2.workplace/src/edu/harvard/i2b2/pm/ws/ProjectManagementRequestData.java +++ b/edu.harvard.i2b2.workplace/src/main/java/edu/harvard/i2b2/workplacepm/ws/ProjectManagementRequestData.java @@ -13,7 +13,7 @@ * Mike Mendis * Raj Kuttan */ -package edu.harvard.i2b2.pm.ws; +package edu.harvard.i2b2.workplacepm.ws; import java.io.StringWriter; import java.math.BigDecimal; diff --git a/edu.harvard.i2b2.xml/.project b/edu.harvard.i2b2.xml/.project deleted file mode 100755 index b1a55734..00000000 --- a/edu.harvard.i2b2.xml/.project +++ /dev/null @@ -1,11 +0,0 @@ - - - edu.harvard.i2b2.xml - - - - - - - - diff --git a/edu.harvard.i2b2.xml/.settings/.cvsignore b/edu.harvard.i2b2.xml/.settings/.cvsignore deleted file mode 100755 index 13af95c3..00000000 --- a/edu.harvard.i2b2.xml/.settings/.cvsignore +++ /dev/null @@ -1 +0,0 @@ -org.eclipse.core.resources.prefs diff --git a/edu.harvard.i2b2.xml/LICENSE.txt b/edu.harvard.i2b2.xml/LICENSE.txt deleted file mode 100755 index 41df1d24..00000000 --- a/edu.harvard.i2b2.xml/LICENSE.txt +++ /dev/null @@ -1,398 +0,0 @@ -Mozilla Public License, version 2.0 - -1. Definitions - -1.1. "Contributor" - - means each individual or legal entity that creates, contributes to the - creation of, or owns Covered Software. - -1.2. "Contributor Version" - - means the combination of the Contributions of others (if any) used by a - Contributor and that particular Contributor's Contribution. - -1.3. "Contribution" - - means Covered Software of a particular Contributor. - -1.4. "Covered Software" - - means Source Code Form to which the initial Contributor has attached the - notice in Exhibit A, the Executable Form of such Source Code Form, and - Modifications of such Source Code Form, in each case including portions - thereof. - -1.5. "Incompatible With Secondary Licenses" - means - - a. that the initial Contributor has attached the notice described in - Exhibit B to the Covered Software; or - - b. that the Covered Software was made available under the terms of - version 1.1 or earlier of the License, but not also under the terms of - a Secondary License. - -1.6. "Executable Form" - - means any form of the work other than Source Code Form. - -1.7. "Larger Work" - - means a work that combines Covered Software with other material, in a - separate file or files, that is not Covered Software. - -1.8. "License" - - means this document. - -1.9. "Licensable" - - means having the right to grant, to the maximum extent possible, whether - at the time of the initial grant or subsequently, any and all of the - rights conveyed by this License. - -1.10. "Modifications" - - means any of the following: - - a. any file in Source Code Form that results from an addition to, - deletion from, or modification of the contents of Covered Software; or - - b. any new file in Source Code Form that contains any Covered Software. - -1.11. "Patent Claims" of a Contributor - - means any patent claim(s), including without limitation, method, - process, and apparatus claims, in any patent Licensable by such - Contributor that would be infringed, but for the grant of the License, - by the making, using, selling, offering for sale, having made, import, - or transfer of either its Contributions or its Contributor Version. - -1.12. "Secondary License" - - means either the GNU General Public License, Version 2.0, the GNU Lesser - General Public License, Version 2.1, the GNU Affero General Public - License, Version 3.0, or any later versions of those licenses. - -1.13. "Source Code Form" - - means the form of the work preferred for making modifications. - -1.14. "You" (or "Your") - - means an individual or a legal entity exercising rights under this - License. For legal entities, "You" includes any entity that controls, is - controlled by, or is under common control with You. For purposes of this - definition, "control" means (a) the power, direct or indirect, to cause - the direction or management of such entity, whether by contract or - otherwise, or (b) ownership of more than fifty percent (50%) of the - outstanding shares or beneficial ownership of such entity. - - -2. License Grants and Conditions - -2.1. Grants - - Each Contributor hereby grants You a world-wide, royalty-free, - non-exclusive license: - - a. under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or - as part of a Larger Work; and - - b. under Patent Claims of such Contributor to make, use, sell, offer for - sale, have made, import, and otherwise transfer either its - Contributions or its Contributor Version. - -2.2. Effective Date - - The licenses granted in Section 2.1 with respect to any Contribution - become effective for each Contribution on the date the Contributor first - distributes such Contribution. - -2.3. Limitations on Grant Scope - - The licenses granted in this Section 2 are the only rights granted under - this License. No additional rights or licenses will be implied from the - distribution or licensing of Covered Software under this License. - Notwithstanding Section 2.1(b) above, no patent license is granted by a - Contributor: - - a. for any code that a Contributor has removed from Covered Software; or - - b. for infringements caused by: (i) Your and any other third party's - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - - c. under Patent Claims infringed by Covered Software in the absence of - its Contributions. - - This License does not grant any rights in the trademarks, service marks, - or logos of any Contributor (except as may be necessary to comply with - the notice requirements in Section 3.4). - -2.4. Subsequent Licenses - - No Contributor makes additional grants as a result of Your choice to - distribute the Covered Software under a subsequent version of this - License (see Section 10.2) or under the terms of a Secondary License (if - permitted under the terms of Section 3.3). - -2.5. Representation - - Each Contributor represents that the Contributor believes its - Contributions are its original creation(s) or it has sufficient rights to - grant the rights to its Contributions conveyed by this License. - -2.6. Fair Use - - This License is not intended to limit any rights You have under - applicable copyright doctrines of fair use, fair dealing, or other - equivalents. - -2.7. Conditions - - Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in - Section 2.1. - - -3. Responsibilities - -3.1. Distribution of Source Form - - All distribution of Covered Software in Source Code Form, including any - Modifications that You create or to which You contribute, must be under - the terms of this License. You must inform recipients that the Source - Code Form of the Covered Software is governed by the terms of this - License, and how they can obtain a copy of this License. You may not - attempt to alter or restrict the recipients' rights in the Source Code - Form. - -3.2. Distribution of Executable Form - - If You distribute Covered Software in Executable Form then: - - a. such Covered Software must also be made available in Source Code Form, - as described in Section 3.1, and You must inform recipients of the - Executable Form how they can obtain a copy of such Source Code Form by - reasonable means in a timely manner, at a charge no more than the cost - of distribution to the recipient; and - - b. You may distribute such Executable Form under the terms of this - License, or sublicense it under different terms, provided that the - license for the Executable Form does not attempt to limit or alter the - recipients' rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - - You may create and distribute a Larger Work under terms of Your choice, - provided that You also comply with the requirements of this License for - the Covered Software. If the Larger Work is a combination of Covered - Software with a work governed by one or more Secondary Licenses, and the - Covered Software is not Incompatible With Secondary Licenses, this - License permits You to additionally distribute such Covered Software - under the terms of such Secondary License(s), so that the recipient of - the Larger Work may, at their option, further distribute the Covered - Software under the terms of either this License or such Secondary - License(s). - -3.4. Notices - - You may not remove or alter the substance of any license notices - (including copyright notices, patent notices, disclaimers of warranty, or - limitations of liability) contained within the Source Code Form of the - Covered Software, except that You may alter any license notices to the - extent required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - - You may choose to offer, and to charge a fee for, warranty, support, - indemnity or liability obligations to one or more recipients of Covered - Software. However, You may do so only on Your own behalf, and not on - behalf of any Contributor. You must make it absolutely clear that any - such warranty, support, indemnity, or liability obligation is offered by - You alone, and You hereby agree to indemnify every Contributor for any - liability incurred by such Contributor as a result of warranty, support, - indemnity or liability terms You offer. You may include additional - disclaimers of warranty and limitations of liability specific to any - jurisdiction. - -4. Inability to Comply Due to Statute or Regulation - - If it is impossible for You to comply with any of the terms of this License - with respect to some or all of the Covered Software due to statute, - judicial order, or regulation then You must: (a) comply with the terms of - this License to the maximum extent possible; and (b) describe the - limitations and the code they affect. Such description must be placed in a - text file included with all distributions of the Covered Software under - this License. Except to the extent prohibited by statute or regulation, - such description must be sufficiently detailed for a recipient of ordinary - skill to be able to understand it. - -5. Termination - -5.1. The rights granted under this License will terminate automatically if You - fail to comply with any of its terms. However, if You become compliant, - then the rights granted under this License from a particular Contributor - are reinstated (a) provisionally, unless and until such Contributor - explicitly and finally terminates Your grants, and (b) on an ongoing - basis, if such Contributor fails to notify You of the non-compliance by - some reasonable means prior to 60 days after You have come back into - compliance. Moreover, Your grants from a particular Contributor are - reinstated on an ongoing basis if such Contributor notifies You of the - non-compliance by some reasonable means, this is the first time You have - received notice of non-compliance with this License from such - Contributor, and You become compliant prior to 30 days after Your receipt - of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent - infringement claim (excluding declaratory judgment actions, - counter-claims, and cross-claims) alleging that a Contributor Version - directly or indirectly infringes any patent, then the rights granted to - You by any and all Contributors for the Covered Software under Section - 2.1 of this License shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user - license agreements (excluding distributors and resellers) which have been - validly granted by You or Your distributors under this License prior to - termination shall survive termination. - -6. Disclaimer of Warranty - - Covered Software is provided under this License on an "as is" basis, - without warranty of any kind, either expressed, implied, or statutory, - including, without limitation, warranties that the Covered Software is free - of defects, merchantable, fit for a particular purpose or non-infringing. - The entire risk as to the quality and performance of the Covered Software - is with You. Should any Covered Software prove defective in any respect, - You (not any Contributor) assume the cost of any necessary servicing, - repair, or correction. This disclaimer of warranty constitutes an essential - part of this License. No use of any Covered Software is authorized under - this License except under this disclaimer. - -7. Limitation of Liability - - Under no circumstances and under no legal theory, whether tort (including - negligence), contract, or otherwise, shall any Contributor, or anyone who - distributes Covered Software as permitted above, be liable to You for any - direct, indirect, special, incidental, or consequential damages of any - character including, without limitation, damages for lost profits, loss of - goodwill, work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses, even if such party shall have been - informed of the possibility of such damages. This limitation of liability - shall not apply to liability for death or personal injury resulting from - such party's negligence to the extent applicable law prohibits such - limitation. Some jurisdictions do not allow the exclusion or limitation of - incidental or consequential damages, so this exclusion and limitation may - not apply to You. - -8. Litigation - - Any litigation relating to this License may be brought only in the courts - of a jurisdiction where the defendant maintains its principal place of - business and such litigation shall be governed by laws of that - jurisdiction, without reference to its conflict-of-law provisions. Nothing - in this Section shall prevent a party's ability to bring cross-claims or - counter-claims. - -9. Miscellaneous - - This License represents the complete agreement concerning the subject - matter hereof. If any provision of this License is held to be - unenforceable, such provision shall be reformed only to the extent - necessary to make it enforceable. Any law or regulation which provides that - the language of a contract shall be construed against the drafter shall not - be used to construe this License against a Contributor. - - -10. Versions of the License - -10.1. New Versions - - Mozilla Foundation is the license steward. Except as provided in Section - 10.3, no one other than the license steward has the right to modify or - publish new versions of this License. Each version will be given a - distinguishing version number. - -10.2. Effect of New Versions - - You may distribute the Covered Software under the terms of the version - of the License under which You originally received the Covered Software, - or under the terms of any subsequent version published by the license - steward. - -10.3. Modified Versions - - If you create software not governed by this License, and you want to - create a new license for such software, you may create and use a - modified version of this License if you rename the license and remove - any references to the name of the license steward (except to note that - such modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary - Licenses If You choose to distribute Source Code Form that is - Incompatible With Secondary Licenses under the terms of this version of - the License, the notice described in Exhibit B of this License must be - attached. - -Exhibit A - Source Code Form License Notice - - This Source Code Form is subject to the - terms of the Mozilla Public License, v. - 2.0. If a copy of the MPL was not - distributed with this file, You can - obtain one at - http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular file, -then You may include the notice in a location (such as a LICENSE file in a -relevant directory) where a recipient would be likely to look for such a -notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - "Incompatible With Secondary Licenses" Notice - - This Source Code Form is "Incompatible - With Secondary Licenses", as defined by - the Mozilla Public License, v. 2.0. - ---------------------- - -Healthcare Disclaimer - -In the United States, or any other jurisdictions where they may apply, the -following additional disclaimer of warranty and limitation of liability are -hereby incorporated into the terms and conditions of MPL 2.0: - -1. No warranties of any kind whatsoever are made as to the results that - You will obtain from relying upon the covered code (or any information - or content obtained by way of the covered code), including but not - limited to compliance with privacy laws or regulations or clinical - care industry standards and protocols. Use of the covered code is not - a substitute for a health care provider’s standard practice or - professional judgment. Any decision with regard to the appropriateness - of treatment, or the validity or reliability of information or content - made available by the covered code, is the sole responsibility of the - health care provider. Consequently, it is incumbent upon each health - care provider to verify all medical history and treatment plans with - each patient. - -2. Under no circumstances and under no legal theory, whether tort - (including negligence), contract, or otherwise, shall any Contributor, - or anyone who distributes Covered Software as permitted by the - license, be liable to You for any indirect, special, incidental, - consequential damages of any character including, without limitation, - damages for loss of goodwill, work stoppage, computer failure or - malfunction, or any and all other damages or losses, of any nature - whatsoever (direct or otherwise) on account of or associated with the - use or inability to use the covered content (including, without - limitation, the use of information or content made available by the - covered code, all documentation associated therewith, and the failure - of the covered code to comply with privacy laws and regulations or - clinical care industry standards and protocols), even if such party - shall have been informed of the possibility of such damages. diff --git a/i2b2/pom.xml b/i2b2/pom.xml new file mode 100644 index 00000000..898f1339 --- /dev/null +++ b/i2b2/pom.xml @@ -0,0 +1,95 @@ + + 4.0.0 + + edu.harvard.i2b2 + i2b2-parent + 2.0.0-SNAPSHOT + + i2b2 + war + i2b2 + + + + + i2b2 + + + org.apache.maven.plugins + maven-war-plugin + + + i2b2 + + + + + + + + + edu.harvard.i2b2 + edu.harvard.i2b2.server-common + + + + edu.harvard.i2b2 + edu.harvard.i2b2.crc + + + + edu.harvard.i2b2 + edu.harvard.i2b2.ontology + + + + edu.harvard.i2b2 + edu.harvard.i2b2.workplace + + + + edu.harvard.i2b2 + edu.harvard.i2b2.im + + + + edu.harvard.i2b2 + edu.harvard.i2b2.pm + + + + edu.harvard.i2b2 + edu.harvard.i2b2.fr + + + + + + + \ No newline at end of file diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/conf/axis2.xml b/i2b2/src/main/webapp/WEB-INF/conf/axis2.xml similarity index 100% rename from edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/conf/axis2.xml rename to i2b2/src/main/webapp/WEB-INF/conf/axis2.xml diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/include/LeftFrame.jsp b/i2b2/src/main/webapp/WEB-INF/include/LeftFrame.jsp similarity index 96% rename from edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/include/LeftFrame.jsp rename to i2b2/src/main/webapp/WEB-INF/include/LeftFrame.jsp index 35b1b749..1b521793 100644 --- a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/include/LeftFrame.jsp +++ b/i2b2/src/main/webapp/WEB-INF/include/LeftFrame.jsp @@ -1,205 +1,205 @@ -<%-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --%> - -<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> -<%@ page import="org.apache.axis2.Constants" %> -<%@ page import="org.apache.axis2.context.ConfigurationContext" %> -<%@ page import="org.apache.axis2.context.ServiceContext" %> -<%@ page import="org.apache.axis2.context.ServiceGroupContext" %> -<%@ page import="org.apache.axis2.deployment.util.PhasesInfo" %> -<%@ page import="org.apache.axis2.description.AxisModule" %> -<%@ page import="org.apache.axis2.description.AxisOperation" %> -<%@ page import="org.apache.axis2.description.AxisService" %> -<%@ page import="org.apache.axis2.description.AxisServiceGroup" %> -<%@ page import="org.apache.axis2.description.Parameter" %> -<%@ page import="org.apache.axis2.engine.AxisConfiguration" %> -<%@ page import="org.apache.axis2.engine.Handler" %> -<%@ page import="org.apache.axis2.engine.Phase" %> -<%@ page import="org.apache.axis2.util.JavaUtils" %> -<%@ page import="java.util.ArrayList" %> -<%@ page import="java.util.Collection" %> -<%@ page import="java.util.Enumeration" %> -<%@ page import="java.util.HashMap" %> -<%@ page import="java.util.Hashtable" %> -<%@ page import="java.util.Iterator" %> -<%@ page contentType="text/html;charset=UTF-8" language="java" %> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - Tools -
    -      - - ">Upload Service -
    - System Components         -
    -      - - ">Available Services -
    -      - - ">Available Service Groups -
    -      - - ">Available Modules -
    -      - - ">Globally Engaged Modules -
    -      - - ">Available Phases -
    - Execution Chains -
    -      - - ">Global Chains -
    -      - - ">Operation Specific Chains -
    - Engage Module -
    -      - - ">For all Services -
    -      - - ">For a Service Group -
    -      - - ">For a Service -
    -      - - ">For an Operation -
    - Services -
    -      - - ">Deactivate Service -
    -      - - ">Activate Service -
    -      - - ">Edit Parameters -
    - Contexts -
    -      - - ">View Hierarchy -
    +<%-- + ~ Licensed to the Apache Software Foundation (ASF) under one + ~ or more contributor license agreements. See the NOTICE file + ~ distributed with this work for additional information + ~ regarding copyright ownership. The ASF licenses this file + ~ to you under the Apache License, Version 2.0 (the + ~ "License"); you may not use this file except in compliance + ~ with the License. You may obtain a copy of the License at + ~ + ~ http://www.apache.org/licenses/LICENSE-2.0 + ~ + ~ Unless required by applicable law or agreed to in writing, + ~ software distributed under the License is distributed on an + ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + ~ KIND, either express or implied. See the License for the + ~ specific language governing permissions and limitations + ~ under the License. + --%> + +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> +<%@ page import="org.apache.axis2.Constants" %> +<%@ page import="org.apache.axis2.context.ConfigurationContext" %> +<%@ page import="org.apache.axis2.context.ServiceContext" %> +<%@ page import="org.apache.axis2.context.ServiceGroupContext" %> +<%@ page import="org.apache.axis2.deployment.util.PhasesInfo" %> +<%@ page import="org.apache.axis2.description.AxisModule" %> +<%@ page import="org.apache.axis2.description.AxisOperation" %> +<%@ page import="org.apache.axis2.description.AxisService" %> +<%@ page import="org.apache.axis2.description.AxisServiceGroup" %> +<%@ page import="org.apache.axis2.description.Parameter" %> +<%@ page import="org.apache.axis2.engine.AxisConfiguration" %> +<%@ page import="org.apache.axis2.engine.Handler" %> +<%@ page import="org.apache.axis2.engine.Phase" %> +<%@ page import="org.apache.axis2.util.JavaUtils" %> +<%@ page import="java.util.ArrayList" %> +<%@ page import="java.util.Collection" %> +<%@ page import="java.util.Enumeration" %> +<%@ page import="java.util.HashMap" %> +<%@ page import="java.util.Hashtable" %> +<%@ page import="java.util.Iterator" %> +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + Tools +
    +      + + ">Upload Service +
    + System Components         +
    +      + + ">Available Services +
    +      + + ">Available Service Groups +
    +      + + ">Available Modules +
    +      + + ">Globally Engaged Modules +
    +      + + ">Available Phases +
    + Execution Chains +
    +      + + ">Global Chains +
    +      + + ">Operation Specific Chains +
    + Engage Module +
    +      + + ">For all Services +
    +      + + ">For a Service Group +
    +      + + ">For a Service +
    +      + + ">For an Operation +
    + Services +
    +      + + ">Deactivate Service +
    +      + + ">Activate Service +
    +      + + ">Edit Parameters +
    + Contexts +
    +      + + ">View Hierarchy +
    diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/include/adminfooter.inc b/i2b2/src/main/webapp/WEB-INF/include/adminfooter.inc similarity index 100% rename from edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/include/adminfooter.inc rename to i2b2/src/main/webapp/WEB-INF/include/adminfooter.inc diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/include/adminfooter.jsp b/i2b2/src/main/webapp/WEB-INF/include/adminfooter.jsp similarity index 100% rename from edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/include/adminfooter.jsp rename to i2b2/src/main/webapp/WEB-INF/include/adminfooter.jsp diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/include/adminheader.jsp b/i2b2/src/main/webapp/WEB-INF/include/adminheader.jsp similarity index 97% rename from edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/include/adminheader.jsp rename to i2b2/src/main/webapp/WEB-INF/include/adminheader.jsp index c6c4373a..ba2224ed 100644 --- a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/include/adminheader.jsp +++ b/i2b2/src/main/webapp/WEB-INF/include/adminheader.jsp @@ -1,82 +1,82 @@ -<%-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --%> - -<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> -<%@ page import="org.apache.axis2.Constants" %> -<%@ page import="org.apache.axis2.context.ConfigurationContext" %> -<%@ page import="org.apache.axis2.context.ServiceContext" %> -<%@ page import="org.apache.axis2.context.ServiceGroupContext" %> -<%@ page import="org.apache.axis2.deployment.util.PhasesInfo" %> -<%@ page import="org.apache.axis2.description.AxisModule" %> -<%@ page import="org.apache.axis2.description.AxisOperation" %> -<%@ page import="org.apache.axis2.description.AxisService" %> -<%@ page import="org.apache.axis2.description.AxisServiceGroup" %> -<%@ page import="org.apache.axis2.description.Parameter" %> -<%@ page import="org.apache.axis2.engine.AxisConfiguration" %> -<%@ page import="org.apache.axis2.engine.Handler" %> -<%@ page import="org.apache.axis2.engine.Phase" %> -<%@ page import="org.apache.axis2.util.JavaUtils" %> -<%@ page import="java.util.ArrayList" %> -<%@ page import="java.util.Collection" %> -<%@ page import="java.util.Enumeration" %> -<%@ page import="java.util.HashMap" %> -<%@ page import="java.util.Hashtable" %> -<%@ page import="java.util.Iterator" %> -<%-- -~ Licensed to the Apache Software Foundation (ASF) under one -~ or more contributor license agreements. See the NOTICE file -~ distributed with this work for additional information -~ regarding copyright ownership. The ASF licenses this file -~ to you under the Apache License, Version 2.0 (the -~ "License"); you may not use this file except in compliance -~ with the License. You may obtain a copy of the License at -~ -~ http://www.apache.org/licenses/LICENSE-2.0 -~ -~ Unless required by applicable law or agreed to in writing, -~ software distributed under the License is distributed on an -~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -~ KIND, either express or implied. See the License for the -~ specific language governing permissions and limitations -~ under the License. ---%> -<%@ page contentType="text/html;charset=iso-8859-1" language="java" %> - - - - - Axis2 :: Administration Page - - - - - - - - - -
    - - - - - - -
    Back  |  ">Log out
    +<%-- + ~ Licensed to the Apache Software Foundation (ASF) under one + ~ or more contributor license agreements. See the NOTICE file + ~ distributed with this work for additional information + ~ regarding copyright ownership. The ASF licenses this file + ~ to you under the Apache License, Version 2.0 (the + ~ "License"); you may not use this file except in compliance + ~ with the License. You may obtain a copy of the License at + ~ + ~ http://www.apache.org/licenses/LICENSE-2.0 + ~ + ~ Unless required by applicable law or agreed to in writing, + ~ software distributed under the License is distributed on an + ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + ~ KIND, either express or implied. See the License for the + ~ specific language governing permissions and limitations + ~ under the License. + --%> + +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> +<%@ page import="org.apache.axis2.Constants" %> +<%@ page import="org.apache.axis2.context.ConfigurationContext" %> +<%@ page import="org.apache.axis2.context.ServiceContext" %> +<%@ page import="org.apache.axis2.context.ServiceGroupContext" %> +<%@ page import="org.apache.axis2.deployment.util.PhasesInfo" %> +<%@ page import="org.apache.axis2.description.AxisModule" %> +<%@ page import="org.apache.axis2.description.AxisOperation" %> +<%@ page import="org.apache.axis2.description.AxisService" %> +<%@ page import="org.apache.axis2.description.AxisServiceGroup" %> +<%@ page import="org.apache.axis2.description.Parameter" %> +<%@ page import="org.apache.axis2.engine.AxisConfiguration" %> +<%@ page import="org.apache.axis2.engine.Handler" %> +<%@ page import="org.apache.axis2.engine.Phase" %> +<%@ page import="org.apache.axis2.util.JavaUtils" %> +<%@ page import="java.util.ArrayList" %> +<%@ page import="java.util.Collection" %> +<%@ page import="java.util.Enumeration" %> +<%@ page import="java.util.HashMap" %> +<%@ page import="java.util.Hashtable" %> +<%@ page import="java.util.Iterator" %> +<%-- +~ Licensed to the Apache Software Foundation (ASF) under one +~ or more contributor license agreements. See the NOTICE file +~ distributed with this work for additional information +~ regarding copyright ownership. The ASF licenses this file +~ to you under the Apache License, Version 2.0 (the +~ "License"); you may not use this file except in compliance +~ with the License. You may obtain a copy of the License at +~ +~ http://www.apache.org/licenses/LICENSE-2.0 +~ +~ Unless required by applicable law or agreed to in writing, +~ software distributed under the License is distributed on an +~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +~ KIND, either express or implied. See the License for the +~ specific language governing permissions and limitations +~ under the License. +--%> +<%@ page contentType="text/html;charset=iso-8859-1" language="java" %> + + + + + Axis2 :: Administration Page + + + + + + + + + +
    + + + + + + +
    Back  |  ">Log out
    diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/include/footer.inc b/i2b2/src/main/webapp/WEB-INF/include/footer.inc similarity index 100% rename from edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/include/footer.inc rename to i2b2/src/main/webapp/WEB-INF/include/footer.inc diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/include/header.inc b/i2b2/src/main/webapp/WEB-INF/include/header.inc similarity index 100% rename from edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/include/header.inc rename to i2b2/src/main/webapp/WEB-INF/include/header.inc diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/include/httpbase.jsp b/i2b2/src/main/webapp/WEB-INF/include/httpbase.jsp similarity index 100% rename from edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/include/httpbase.jsp rename to i2b2/src/main/webapp/WEB-INF/include/httpbase.jsp diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/include/link-footer.inc b/i2b2/src/main/webapp/WEB-INF/include/link-footer.inc similarity index 100% rename from edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/include/link-footer.inc rename to i2b2/src/main/webapp/WEB-INF/include/link-footer.inc diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/include/link-footer.jsp b/i2b2/src/main/webapp/WEB-INF/include/link-footer.jsp similarity index 97% rename from edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/include/link-footer.jsp rename to i2b2/src/main/webapp/WEB-INF/include/link-footer.jsp index c1b94fbc..da069c35 100644 --- a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/include/link-footer.jsp +++ b/i2b2/src/main/webapp/WEB-INF/include/link-footer.jsp @@ -1,70 +1,70 @@ -<%-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --%> - -<%@ page import="org.apache.axis2.AxisFault" %> -<%@ page import="org.apache.axis2.Constants" %> -<%@ page import="org.apache.axis2.addressing.EndpointReference" %> -<%@ page import="org.apache.axis2.client.Options" %> -<%@ page import="org.apache.axis2.client.ServiceClient" %> -<%@ page import="org.apache.axis2.context.ConfigurationContext" %> -<%@ page import="org.apache.axis2.context.ConfigurationContextFactory" %> -<%@ page import="org.apache.axis2.description.AxisOperation" %> -<%@ page import="org.apache.axis2.description.AxisService" %> -<%@ page import="org.apache.axis2.description.Parameter" %> -<%@ page import="org.apache.axis2.engine.AxisConfiguration" %> -<%@ page import="org.apache.axis2.util.JavaUtils" %> -<%@ page import="javax.xml.parsers.SAXParser" %> -<%@ page import="javax.xml.parsers.SAXParserFactory" %> -<%@ page import="java.io.IOException" %> -<%@ page import="java.io.InputStream" %> -<%@ page import="java.io.StringWriter" %> -<%@ page import="java.util.Collection" %> -<%@ page import="java.util.Enumeration" %> -<%@ page import="java.util.HashMap" %> -<%@ page import="java.util.Hashtable" %> -<%@ page import="java.util.Iterator" %> -<%-- -~ Licensed to the Apache Software Foundation (ASF) under one -~ or more contributor license agreements. See the NOTICE file -~ distributed with this work for additional information -~ regarding copyright ownership. The ASF licenses this file -~ to you under the Apache License, Version 2.0 (the -~ "License"); you may not use this file except in compliance -~ with the License. You may obtain a copy of the License at -~ -~ http://www.apache.org/licenses/LICENSE-2.0 -~ -~ Unless required by applicable law or agreed to in writing, -~ software distributed under the License is distributed on an -~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -~ KIND, either express or implied. See the License for the -~ specific language governing permissions and limitations -~ under the License. ---%> -<%@ page session="false" %> - - - -
    - - - - -
    Back Home  |   Refresh
    -
     
    +<%-- + ~ Licensed to the Apache Software Foundation (ASF) under one + ~ or more contributor license agreements. See the NOTICE file + ~ distributed with this work for additional information + ~ regarding copyright ownership. The ASF licenses this file + ~ to you under the Apache License, Version 2.0 (the + ~ "License"); you may not use this file except in compliance + ~ with the License. You may obtain a copy of the License at + ~ + ~ http://www.apache.org/licenses/LICENSE-2.0 + ~ + ~ Unless required by applicable law or agreed to in writing, + ~ software distributed under the License is distributed on an + ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + ~ KIND, either express or implied. See the License for the + ~ specific language governing permissions and limitations + ~ under the License. + --%> + +<%@ page import="org.apache.axis2.AxisFault" %> +<%@ page import="org.apache.axis2.Constants" %> +<%@ page import="org.apache.axis2.addressing.EndpointReference" %> +<%@ page import="org.apache.axis2.client.Options" %> +<%@ page import="org.apache.axis2.client.ServiceClient" %> +<%@ page import="org.apache.axis2.context.ConfigurationContext" %> +<%@ page import="org.apache.axis2.context.ConfigurationContextFactory" %> +<%@ page import="org.apache.axis2.description.AxisOperation" %> +<%@ page import="org.apache.axis2.description.AxisService" %> +<%@ page import="org.apache.axis2.description.Parameter" %> +<%@ page import="org.apache.axis2.engine.AxisConfiguration" %> +<%@ page import="org.apache.axis2.util.JavaUtils" %> +<%@ page import="javax.xml.parsers.SAXParser" %> +<%@ page import="javax.xml.parsers.SAXParserFactory" %> +<%@ page import="java.io.IOException" %> +<%@ page import="java.io.InputStream" %> +<%@ page import="java.io.StringWriter" %> +<%@ page import="java.util.Collection" %> +<%@ page import="java.util.Enumeration" %> +<%@ page import="java.util.HashMap" %> +<%@ page import="java.util.Hashtable" %> +<%@ page import="java.util.Iterator" %> +<%-- +~ Licensed to the Apache Software Foundation (ASF) under one +~ or more contributor license agreements. See the NOTICE file +~ distributed with this work for additional information +~ regarding copyright ownership. The ASF licenses this file +~ to you under the Apache License, Version 2.0 (the +~ "License"); you may not use this file except in compliance +~ with the License. You may obtain a copy of the License at +~ +~ http://www.apache.org/licenses/LICENSE-2.0 +~ +~ Unless required by applicable law or agreed to in writing, +~ software distributed under the License is distributed on an +~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +~ KIND, either express or implied. See the License for the +~ specific language governing permissions and limitations +~ under the License. +--%> +<%@ page session="false" %> + + + +
    + + + + +
    Back Home  |   Refresh
    +
     
    diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/modules/addressing-2.0.0-SNAPSHOT.mar b/i2b2/src/main/webapp/WEB-INF/modules/addressing-2.0.0-SNAPSHOT.mar similarity index 100% rename from edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/modules/addressing-2.0.0-SNAPSHOT.mar rename to i2b2/src/main/webapp/WEB-INF/modules/addressing-2.0.0-SNAPSHOT.mar diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/modules/axis2-jaxws-mar-2.0.0-SNAPSHOT.mar b/i2b2/src/main/webapp/WEB-INF/modules/axis2-jaxws-mar-2.0.0-SNAPSHOT.mar similarity index 100% rename from edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/modules/axis2-jaxws-mar-2.0.0-SNAPSHOT.mar rename to i2b2/src/main/webapp/WEB-INF/modules/axis2-jaxws-mar-2.0.0-SNAPSHOT.mar diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/modules/mex-2.0.0-SNAPSHOT.mar b/i2b2/src/main/webapp/WEB-INF/modules/mex-2.0.0-SNAPSHOT.mar similarity index 100% rename from edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/modules/mex-2.0.0-SNAPSHOT.mar rename to i2b2/src/main/webapp/WEB-INF/modules/mex-2.0.0-SNAPSHOT.mar diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/modules/modules.list b/i2b2/src/main/webapp/WEB-INF/modules/modules.list similarity index 100% rename from edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/modules/modules.list rename to i2b2/src/main/webapp/WEB-INF/modules/modules.list diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/modules/mtompolicy-2.0.0-SNAPSHOT.mar b/i2b2/src/main/webapp/WEB-INF/modules/mtompolicy-2.0.0-SNAPSHOT.mar similarity index 100% rename from edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/modules/mtompolicy-2.0.0-SNAPSHOT.mar rename to i2b2/src/main/webapp/WEB-INF/modules/mtompolicy-2.0.0-SNAPSHOT.mar diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/modules/ping-2.0.0-SNAPSHOT.mar b/i2b2/src/main/webapp/WEB-INF/modules/ping-2.0.0-SNAPSHOT.mar similarity index 100% rename from edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/modules/ping-2.0.0-SNAPSHOT.mar rename to i2b2/src/main/webapp/WEB-INF/modules/ping-2.0.0-SNAPSHOT.mar diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/modules/scripting-2.0.0-SNAPSHOT.mar b/i2b2/src/main/webapp/WEB-INF/modules/scripting-2.0.0-SNAPSHOT.mar similarity index 100% rename from edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/modules/scripting-2.0.0-SNAPSHOT.mar rename to i2b2/src/main/webapp/WEB-INF/modules/scripting-2.0.0-SNAPSHOT.mar diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/modules/soapmonitor-2.0.0-SNAPSHOT.mar b/i2b2/src/main/webapp/WEB-INF/modules/soapmonitor-2.0.0-SNAPSHOT.mar similarity index 100% rename from edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/modules/soapmonitor-2.0.0-SNAPSHOT.mar rename to i2b2/src/main/webapp/WEB-INF/modules/soapmonitor-2.0.0-SNAPSHOT.mar diff --git a/i2b2/src/main/webapp/WEB-INF/services/CRC.aar b/i2b2/src/main/webapp/WEB-INF/services/CRC.aar new file mode 100644 index 00000000..683cc8ef Binary files /dev/null and b/i2b2/src/main/webapp/WEB-INF/services/CRC.aar differ diff --git a/i2b2/src/main/webapp/WEB-INF/services/IM.aar b/i2b2/src/main/webapp/WEB-INF/services/IM.aar new file mode 100644 index 00000000..4f4b4841 Binary files /dev/null and b/i2b2/src/main/webapp/WEB-INF/services/IM.aar differ diff --git a/i2b2/src/main/webapp/WEB-INF/services/Ontology.aar b/i2b2/src/main/webapp/WEB-INF/services/Ontology.aar new file mode 100644 index 00000000..e11da1ce Binary files /dev/null and b/i2b2/src/main/webapp/WEB-INF/services/Ontology.aar differ diff --git a/i2b2/src/main/webapp/WEB-INF/services/PM.aar b/i2b2/src/main/webapp/WEB-INF/services/PM.aar new file mode 100644 index 00000000..a221370f Binary files /dev/null and b/i2b2/src/main/webapp/WEB-INF/services/PM.aar differ diff --git a/i2b2/src/main/webapp/WEB-INF/services/Workplace.aar b/i2b2/src/main/webapp/WEB-INF/services/Workplace.aar new file mode 100644 index 00000000..6d6efc9d Binary files /dev/null and b/i2b2/src/main/webapp/WEB-INF/services/Workplace.aar differ diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/services/services.list b/i2b2/src/main/webapp/WEB-INF/services/services.list similarity index 100% rename from edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/services/services.list rename to i2b2/src/main/webapp/WEB-INF/services/services.list diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/services/version-2.0.0-SNAPSHOT.aar b/i2b2/src/main/webapp/WEB-INF/services/version-2.0.0-SNAPSHOT.aar similarity index 100% rename from edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/services/version-2.0.0-SNAPSHOT.aar rename to i2b2/src/main/webapp/WEB-INF/services/version-2.0.0-SNAPSHOT.aar diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/tags/status.tag b/i2b2/src/main/webapp/WEB-INF/tags/status.tag similarity index 100% rename from edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/tags/status.tag rename to i2b2/src/main/webapp/WEB-INF/tags/status.tag diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/Login.jsp b/i2b2/src/main/webapp/WEB-INF/views/admin/Login.jsp similarity index 100% rename from edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/Login.jsp rename to i2b2/src/main/webapp/WEB-INF/views/admin/Login.jsp diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/SelectService.jsp b/i2b2/src/main/webapp/WEB-INF/views/admin/SelectService.jsp similarity index 97% rename from edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/SelectService.jsp rename to i2b2/src/main/webapp/WEB-INF/views/admin/SelectService.jsp index 16c1f6a0..bde3473c 100644 --- a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/SelectService.jsp +++ b/i2b2/src/main/webapp/WEB-INF/views/admin/SelectService.jsp @@ -1,69 +1,69 @@ -<%-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --%> - -<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> -<%@ page import="org.apache.axis2.Constants, - org.apache.axis2.description.AxisService, - java.util.Collection, - java.util.HashMap, - java.util.Iterator"%> -<%@ page contentType="text/html;charset=UTF-8" language="java" %> - - - <% - String buttonName="" ; - String status = (String)request.getSession().getAttribute(Constants.SELECT_SERVICE_TYPE); - String heading = ""; - String disc = ""; - if(status != null && status.equals("MODULE")) { - buttonName = " View Operations"; - heading = "Select a service to view operation specific chains"; - disc = "Select an Axis service from the combo and click on the 'View Operations' button to view operation specific Chains."; - } else if(status != null && status.equals("VIEW")){ - buttonName = " View "; - heading = "Select a service to view service handlers"; - disc = "Select an Axis service from the combo and click on the 'View' button to view service handlers."; - } else if (status != null && status.equals("SERVICE_PARAMETER")){ - buttonName = " Edit Parameters "; - heading = "Select a Service to Edit Parameters"; - disc = "Select an Axis service from the combo and click on the 'Edit Parameters' button to edit parameters."; - } - %> -

    <%=heading%>

    -

    <%=disc%>

    -
    "> - - - - - - - - -
    Select a Service : - -
     
      - -
    -
    - +<%-- + ~ Licensed to the Apache Software Foundation (ASF) under one + ~ or more contributor license agreements. See the NOTICE file + ~ distributed with this work for additional information + ~ regarding copyright ownership. The ASF licenses this file + ~ to you under the Apache License, Version 2.0 (the + ~ "License"); you may not use this file except in compliance + ~ with the License. You may obtain a copy of the License at + ~ + ~ http://www.apache.org/licenses/LICENSE-2.0 + ~ + ~ Unless required by applicable law or agreed to in writing, + ~ software distributed under the License is distributed on an + ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + ~ KIND, either express or implied. See the License for the + ~ specific language governing permissions and limitations + ~ under the License. + --%> + +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> +<%@ page import="org.apache.axis2.Constants, + org.apache.axis2.description.AxisService, + java.util.Collection, + java.util.HashMap, + java.util.Iterator"%> +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + + + <% + String buttonName="" ; + String status = (String)request.getSession().getAttribute(Constants.SELECT_SERVICE_TYPE); + String heading = ""; + String disc = ""; + if(status != null && status.equals("MODULE")) { + buttonName = " View Operations"; + heading = "Select a service to view operation specific chains"; + disc = "Select an Axis service from the combo and click on the 'View Operations' button to view operation specific Chains."; + } else if(status != null && status.equals("VIEW")){ + buttonName = " View "; + heading = "Select a service to view service handlers"; + disc = "Select an Axis service from the combo and click on the 'View' button to view service handlers."; + } else if (status != null && status.equals("SERVICE_PARAMETER")){ + buttonName = " Edit Parameters "; + heading = "Select a Service to Edit Parameters"; + disc = "Select an Axis service from the combo and click on the 'Edit Parameters' button to edit parameters."; + } + %> +

    <%=heading%>

    +

    <%=disc%>

    +
    "> + + + + + + + + +
    Select a Service : + +
     
      + +
    +
    + diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/activateService.jsp b/i2b2/src/main/webapp/WEB-INF/views/admin/activateService.jsp similarity index 96% rename from edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/activateService.jsp rename to i2b2/src/main/webapp/WEB-INF/views/admin/activateService.jsp index 41ecd18a..03ef529d 100644 --- a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/activateService.jsp +++ b/i2b2/src/main/webapp/WEB-INF/views/admin/activateService.jsp @@ -1,83 +1,83 @@ -<%-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --%> - -<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> -<%@ page import="org.apache.axis2.Constants, - org.apache.axis2.description.AxisService, - java.util.Collection, - java.util.HashMap, - java.util.Iterator"%> -<%@ page contentType="text/html;charset=UTF-8" language="java" %> - -

    Turn On Service

    -
    "> - - - - - - <% -String html = ""; -int count = 0; -%> - -<% - AxisService axisServices = (AxisService) pageContext.getAttribute("service"); - if(!axisServices.isActive()){ - count++; - html += ""; - } -%> - -<% -if (count > 0) { -%> - - - - - - - - - - -<% -} else { - %> - - <% -} -%> - - -
    -

    The services that are inactive are listed below. Although you can activate the services from this page, once system is restarted the services will be inactive again

    -
    Select Service : - -
    Activate Service -
      - - - No inactive services present.
    -
    - +<%-- + ~ Licensed to the Apache Software Foundation (ASF) under one + ~ or more contributor license agreements. See the NOTICE file + ~ distributed with this work for additional information + ~ regarding copyright ownership. The ASF licenses this file + ~ to you under the Apache License, Version 2.0 (the + ~ "License"); you may not use this file except in compliance + ~ with the License. You may obtain a copy of the License at + ~ + ~ http://www.apache.org/licenses/LICENSE-2.0 + ~ + ~ Unless required by applicable law or agreed to in writing, + ~ software distributed under the License is distributed on an + ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + ~ KIND, either express or implied. See the License for the + ~ specific language governing permissions and limitations + ~ under the License. + --%> + +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> +<%@ page import="org.apache.axis2.Constants, + org.apache.axis2.description.AxisService, + java.util.Collection, + java.util.HashMap, + java.util.Iterator"%> +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + +

    Turn On Service

    +
    "> + + + + + + <% +String html = ""; +int count = 0; +%> + +<% + AxisService axisServices = (AxisService) pageContext.getAttribute("service"); + if(!axisServices.isActive()){ + count++; + html += ""; + } +%> + +<% +if (count > 0) { +%> + + + + + + + + + + +<% +} else { + %> + + <% +} +%> + + +
    +

    The services that are inactive are listed below. Although you can activate the services from this page, once system is restarted the services will be inactive again

    +
    Select Service : + +
    Activate Service +
      + + + No inactive services present.
    +
    + diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/admin.jsp b/i2b2/src/main/webapp/WEB-INF/views/admin/admin.jsp similarity index 97% rename from edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/admin.jsp rename to i2b2/src/main/webapp/WEB-INF/views/admin/admin.jsp index 95837bee..061e587d 100644 --- a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/admin.jsp +++ b/i2b2/src/main/webapp/WEB-INF/views/admin/admin.jsp @@ -1,31 +1,31 @@ -<%-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --%> - -<%@ page contentType="text/html;charset=UTF-8" language="java" %> - -

    Welcome to Axis2 Web Admin Module !!

    -

    You are now logged into the Axis2 administration console from inside -the console you will be able to

    -
      -
    • to check on the health of your Axis2 deployment.
    • -
    • to change any parameters at run time.
    • -
    • to upload new services into Axis2 [Service hot-deployment].
    • -
    - - +<%-- + ~ Licensed to the Apache Software Foundation (ASF) under one + ~ or more contributor license agreements. See the NOTICE file + ~ distributed with this work for additional information + ~ regarding copyright ownership. The ASF licenses this file + ~ to you under the Apache License, Version 2.0 (the + ~ "License"); you may not use this file except in compliance + ~ with the License. You may obtain a copy of the License at + ~ + ~ http://www.apache.org/licenses/LICENSE-2.0 + ~ + ~ Unless required by applicable law or agreed to in writing, + ~ software distributed under the License is distributed on an + ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + ~ KIND, either express or implied. See the License for the + ~ specific language governing permissions and limitations + ~ under the License. + --%> + +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + +

    Welcome to Axis2 Web Admin Module !!

    +

    You are now logged into the Axis2 administration console from inside +the console you will be able to

    +
      +
    • to check on the health of your Axis2 deployment.
    • +
    • to change any parameters at run time.
    • +
    • to upload new services into Axis2 [Service hot-deployment].
    • +
    + + diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/deactivateService.jsp b/i2b2/src/main/webapp/WEB-INF/views/admin/deactivateService.jsp similarity index 96% rename from edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/deactivateService.jsp rename to i2b2/src/main/webapp/WEB-INF/views/admin/deactivateService.jsp index 31272e05..4d7c9df8 100644 --- a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/deactivateService.jsp +++ b/i2b2/src/main/webapp/WEB-INF/views/admin/deactivateService.jsp @@ -1,84 +1,84 @@ -<%-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --%> - -<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> -<%@ page import="org.apache.axis2.Constants, - org.apache.axis2.description.AxisService, - java.util.Collection, - java.util.HashMap, - java.util.Iterator"%> -<%@ page contentType="text/html;charset=UTF-8" language="java" %> - -

    Deactivate Service

    -
    "> - - - - - -<% -String html = ""; -int count = 0; -%> - -<% - AxisService axisServices = (AxisService) pageContext.getAttribute("service"); - if(axisServices.isActive()){ - count++; - html += ""; - } -%> - -<% -if (count > 0) { -%> - - - - - - - - - - - -<% -} else { - %> - - <% -} -%> - - -
    -

    Only the services that are active are listed below. Note that although you can activate a service from this page, once system is restarted the service will be active again

    -
    Select Service : - -
    Deactivate Service -
      - - - No active services present.
    -
    - +<%-- + ~ Licensed to the Apache Software Foundation (ASF) under one + ~ or more contributor license agreements. See the NOTICE file + ~ distributed with this work for additional information + ~ regarding copyright ownership. The ASF licenses this file + ~ to you under the Apache License, Version 2.0 (the + ~ "License"); you may not use this file except in compliance + ~ with the License. You may obtain a copy of the License at + ~ + ~ http://www.apache.org/licenses/LICENSE-2.0 + ~ + ~ Unless required by applicable law or agreed to in writing, + ~ software distributed under the License is distributed on an + ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + ~ KIND, either express or implied. See the License for the + ~ specific language governing permissions and limitations + ~ under the License. + --%> + +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> +<%@ page import="org.apache.axis2.Constants, + org.apache.axis2.description.AxisService, + java.util.Collection, + java.util.HashMap, + java.util.Iterator"%> +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + +

    Deactivate Service

    +
    "> + + + + + +<% +String html = ""; +int count = 0; +%> + +<% + AxisService axisServices = (AxisService) pageContext.getAttribute("service"); + if(axisServices.isActive()){ + count++; + html += ""; + } +%> + +<% +if (count > 0) { +%> + + + + + + + + + + + +<% +} else { + %> + + <% +} +%> + + +
    +

    Only the services that are active are listed below. Note that although you can activate a service from this page, once system is restarted the service will be active again

    +
    Select Service : + +
    Deactivate Service +
      + + + No active services present.
    +
    + diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/editServiceParameters.jsp b/i2b2/src/main/webapp/WEB-INF/views/admin/editServiceParameters.jsp similarity index 100% rename from edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/editServiceParameters.jsp rename to i2b2/src/main/webapp/WEB-INF/views/admin/editServiceParameters.jsp diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/engageGlobally.jsp b/i2b2/src/main/webapp/WEB-INF/views/admin/engageGlobally.jsp similarity index 97% rename from edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/engageGlobally.jsp rename to i2b2/src/main/webapp/WEB-INF/views/admin/engageGlobally.jsp index 47421cca..dbf73896 100644 --- a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/engageGlobally.jsp +++ b/i2b2/src/main/webapp/WEB-INF/views/admin/engageGlobally.jsp @@ -1,65 +1,65 @@ -<%-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --%> - -<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> -<%@ taglib prefix="t" tagdir="/WEB-INF/tags" %> -<%@ page import="org.apache.axis2.Constants, - org.apache.axis2.description.AxisModule, - java.util.Collection, - java.util.HashMap, - java.util.Iterator" %> -<%@ page import="org.apache.axis2.util.Utils" %> - -

    Engage Module Globally

    - -

    To engage a module on all services across the system, select a module from the combo box below - and click on the "Engage" button. Any module that needs to place handlers into the pre-dispatch - phase needs to be engaged globally.

    - -
    "> - - - - - - - - -
    Select a Module : - -
      - -
    -
    - - +<%-- + ~ Licensed to the Apache Software Foundation (ASF) under one + ~ or more contributor license agreements. See the NOTICE file + ~ distributed with this work for additional information + ~ regarding copyright ownership. The ASF licenses this file + ~ to you under the Apache License, Version 2.0 (the + ~ "License"); you may not use this file except in compliance + ~ with the License. You may obtain a copy of the License at + ~ + ~ http://www.apache.org/licenses/LICENSE-2.0 + ~ + ~ Unless required by applicable law or agreed to in writing, + ~ software distributed under the License is distributed on an + ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + ~ KIND, either express or implied. See the License for the + ~ specific language governing permissions and limitations + ~ under the License. + --%> + +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> +<%@ taglib prefix="t" tagdir="/WEB-INF/tags" %> +<%@ page import="org.apache.axis2.Constants, + org.apache.axis2.description.AxisModule, + java.util.Collection, + java.util.HashMap, + java.util.Iterator" %> +<%@ page import="org.apache.axis2.util.Utils" %> + +

    Engage Module Globally

    + +

    To engage a module on all services across the system, select a module from the combo box below + and click on the "Engage" button. Any module that needs to place handlers into the pre-dispatch + phase needs to be engaged globally.

    + +
    "> + + + + + + + + +
    Select a Module : + +
      + +
    +
    + + diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/engageToOperation.jsp b/i2b2/src/main/webapp/WEB-INF/views/admin/engageToOperation.jsp similarity index 97% rename from edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/engageToOperation.jsp rename to i2b2/src/main/webapp/WEB-INF/views/admin/engageToOperation.jsp index bb45a645..f7dc49c2 100644 --- a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/engageToOperation.jsp +++ b/i2b2/src/main/webapp/WEB-INF/views/admin/engageToOperation.jsp @@ -1,122 +1,122 @@ -<%-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --%> - -<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> -<%@ taglib prefix="t" tagdir="/WEB-INF/tags" %> -<%@ page contentType="text/html; charset=iso-8859-1" language="java" import="org.apache.axis2.Constants, - org.apache.axis2.description.AxisModule, - org.apache.axis2.description.AxisOperation, - org.apache.axis2.util.Utils, - java.util.Collection, - java.util.HashMap, - java.util.Iterator"%> - -

    Engage Module for an Operation

    -

    To engage a module for an axis operation,

    -
      -
    1. select the module you want to engage
    2. -
    3. select the axis operation you like the module to be engaged.
    4. -
    5. click "Engage".
    6. -
    - -
    "> -"> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    -   -   -
    Select a Module :
    - -
    -   -   -
    Select an Operation :
    - -
    -   -   -
    - -
    -   -   -
    -   -   -
    - -
    -
    - +<%-- + ~ Licensed to the Apache Software Foundation (ASF) under one + ~ or more contributor license agreements. See the NOTICE file + ~ distributed with this work for additional information + ~ regarding copyright ownership. The ASF licenses this file + ~ to you under the Apache License, Version 2.0 (the + ~ "License"); you may not use this file except in compliance + ~ with the License. You may obtain a copy of the License at + ~ + ~ http://www.apache.org/licenses/LICENSE-2.0 + ~ + ~ Unless required by applicable law or agreed to in writing, + ~ software distributed under the License is distributed on an + ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + ~ KIND, either express or implied. See the License for the + ~ specific language governing permissions and limitations + ~ under the License. + --%> + +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> +<%@ taglib prefix="t" tagdir="/WEB-INF/tags" %> +<%@ page contentType="text/html; charset=iso-8859-1" language="java" import="org.apache.axis2.Constants, + org.apache.axis2.description.AxisModule, + org.apache.axis2.description.AxisOperation, + org.apache.axis2.util.Utils, + java.util.Collection, + java.util.HashMap, + java.util.Iterator"%> + +

    Engage Module for an Operation

    +

    To engage a module for an axis operation,

    +
      +
    1. select the module you want to engage
    2. +
    3. select the axis operation you like the module to be engaged.
    4. +
    5. click "Engage".
    6. +
    + +
    "> +"> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +   +   +
    Select a Module :
    + +
    +   +   +
    Select an Operation :
    + +
    +   +   +
    + +
    +   +   +
    +   +   +
    + +
    +
    + diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/engageToService.jsp b/i2b2/src/main/webapp/WEB-INF/views/admin/engageToService.jsp similarity index 97% rename from edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/engageToService.jsp rename to i2b2/src/main/webapp/WEB-INF/views/admin/engageToService.jsp index 921be879..b32aec2d 100644 --- a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/engageToService.jsp +++ b/i2b2/src/main/webapp/WEB-INF/views/admin/engageToService.jsp @@ -1,123 +1,123 @@ -<%-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --%> - -<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> -<%@ taglib prefix="t" tagdir="/WEB-INF/tags" %> -<%@ page contentType="text/html; charset=iso-8859-1" language="java" import="org.apache.axis2.Constants, - org.apache.axis2.description.AxisModule, - org.apache.axis2.description.AxisService, - java.util.Collection, - java.util.HashMap, - java.util.Iterator" - %> -<%@ page import="org.apache.axis2.util.Utils" %> - -

    Engage Module for a Service

    - -

    To engage a module for a axis service,

    - -
      -
    1. select the module you want to engage
    2. -
    3. select the axis service you like the module to be engaged.
    4. -
    5. click "Engage".
    6. -
    - -
    "> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    -   -   -
    Select a Module :
    - -
    -   -   -
    Select a Service :
    - -
    -   -   -
    - -
    -   -   -
    -   -   -
    - -
    -
    - +<%-- + ~ Licensed to the Apache Software Foundation (ASF) under one + ~ or more contributor license agreements. See the NOTICE file + ~ distributed with this work for additional information + ~ regarding copyright ownership. The ASF licenses this file + ~ to you under the Apache License, Version 2.0 (the + ~ "License"); you may not use this file except in compliance + ~ with the License. You may obtain a copy of the License at + ~ + ~ http://www.apache.org/licenses/LICENSE-2.0 + ~ + ~ Unless required by applicable law or agreed to in writing, + ~ software distributed under the License is distributed on an + ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + ~ KIND, either express or implied. See the License for the + ~ specific language governing permissions and limitations + ~ under the License. + --%> + +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> +<%@ taglib prefix="t" tagdir="/WEB-INF/tags" %> +<%@ page contentType="text/html; charset=iso-8859-1" language="java" import="org.apache.axis2.Constants, + org.apache.axis2.description.AxisModule, + org.apache.axis2.description.AxisService, + java.util.Collection, + java.util.HashMap, + java.util.Iterator" + %> +<%@ page import="org.apache.axis2.util.Utils" %> + +

    Engage Module for a Service

    + +

    To engage a module for a axis service,

    + +
      +
    1. select the module you want to engage
    2. +
    3. select the axis service you like the module to be engaged.
    4. +
    5. click "Engage".
    6. +
    + +
    "> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +   +   +
    Select a Module :
    + +
    +   +   +
    Select a Service :
    + +
    +   +   +
    + +
    +   +   +
    +   +   +
    + +
    +
    + diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/engageToServiceGroup.jsp b/i2b2/src/main/webapp/WEB-INF/views/admin/engageToServiceGroup.jsp similarity index 100% rename from edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/engageToServiceGroup.jsp rename to i2b2/src/main/webapp/WEB-INF/views/admin/engageToServiceGroup.jsp diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/errorModule.jsp b/i2b2/src/main/webapp/WEB-INF/views/admin/errorModule.jsp similarity index 100% rename from edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/errorModule.jsp rename to i2b2/src/main/webapp/WEB-INF/views/admin/errorModule.jsp diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/globalModules.jsp b/i2b2/src/main/webapp/WEB-INF/views/admin/globalModules.jsp similarity index 97% rename from edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/globalModules.jsp rename to i2b2/src/main/webapp/WEB-INF/views/admin/globalModules.jsp index 3f2bb60d..3880f4b0 100644 --- a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/globalModules.jsp +++ b/i2b2/src/main/webapp/WEB-INF/views/admin/globalModules.jsp @@ -1,55 +1,55 @@ - <%-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --%> <%@ page import="org.apache.axis2.Constants, - org.apache.axis2.description.AxisModule, - java.util.Collection, - java.util.Iterator"%> - <%@ page contentType="text/html;charset=UTF-8" language="java" %> - -

    Globally Engaged Modules

    - <% - boolean foundModules = false; - boolean wroteUL = false; - String modulename = ""; - Collection moduleCol = (Collection) request.getSession().getAttribute(Constants.MODULE_MAP); - request.getSession().setAttribute(Constants.MODULE_MAP, null); - if (moduleCol != null && moduleCol.size() > 0) { - for (Iterator iterator = moduleCol.iterator(); iterator.hasNext();) { - AxisModule axisOperation = (AxisModule) iterator.next(); - modulename = axisOperation.getName(); - if (!wroteUL) { - wroteUL = true; - %> -
      -<% - } - %>
    • <%=modulename%>
    • -
      <% - } - if (wroteUL){ -%> -
    -<% - } - } else{ - %> -

    There are no modules engaged globally

    - <% - } - %> - + <%-- + ~ Licensed to the Apache Software Foundation (ASF) under one + ~ or more contributor license agreements. See the NOTICE file + ~ distributed with this work for additional information + ~ regarding copyright ownership. The ASF licenses this file + ~ to you under the Apache License, Version 2.0 (the + ~ "License"); you may not use this file except in compliance + ~ with the License. You may obtain a copy of the License at + ~ + ~ http://www.apache.org/licenses/LICENSE-2.0 + ~ + ~ Unless required by applicable law or agreed to in writing, + ~ software distributed under the License is distributed on an + ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + ~ KIND, either express or implied. See the License for the + ~ specific language governing permissions and limitations + ~ under the License. + --%> <%@ page import="org.apache.axis2.Constants, + org.apache.axis2.description.AxisModule, + java.util.Collection, + java.util.Iterator"%> + <%@ page contentType="text/html;charset=UTF-8" language="java" %> + +

    Globally Engaged Modules

    + <% + boolean foundModules = false; + boolean wroteUL = false; + String modulename = ""; + Collection moduleCol = (Collection) request.getSession().getAttribute(Constants.MODULE_MAP); + request.getSession().setAttribute(Constants.MODULE_MAP, null); + if (moduleCol != null && moduleCol.size() > 0) { + for (Iterator iterator = moduleCol.iterator(); iterator.hasNext();) { + AxisModule axisOperation = (AxisModule) iterator.next(); + modulename = axisOperation.getName(); + if (!wroteUL) { + wroteUL = true; + %> +
      +<% + } + %>
    • <%=modulename%>
    • +
      <% + } + if (wroteUL){ +%> +
    +<% + } + } else{ + %> +

    There are no modules engaged globally

    + <% + } + %> + diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/listModules.jsp b/i2b2/src/main/webapp/WEB-INF/views/admin/listModules.jsp similarity index 97% rename from edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/listModules.jsp rename to i2b2/src/main/webapp/WEB-INF/views/admin/listModules.jsp index 0cabfb5d..79f35216 100644 --- a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/listModules.jsp +++ b/i2b2/src/main/webapp/WEB-INF/views/admin/listModules.jsp @@ -1,81 +1,81 @@ - <%-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --%> <%@ page import="org.apache.axis2.Constants, - org.apache.axis2.description.AxisModule, - java.util.Collection"%> - <%@ page import="java.util.Enumeration"%> - <%@ page import="java.util.HashMap"%> - <%@ page import="java.util.Hashtable"%> - <%@ page import="java.util.Iterator"%> - <%@ page contentType="text/html;charset=UTF-8" language="java" %> - -

    Available Modules

    - <% - boolean foundModules = false; - boolean wroteUL = false; - HashMap moduleMap = (HashMap)request.getSession().getAttribute(Constants.MODULE_MAP); - request.getSession().setAttribute(Constants.MODULE_MAP,null); - Hashtable errornesModules =(Hashtable)request.getSession().getAttribute(Constants.ERROR_MODULE_MAP); - if (moduleMap!=null && !moduleMap.isEmpty()){ - String modulename ; - String moduleDescription ; - Collection moduleNames = moduleMap.values(); - for (Iterator iterator = moduleNames.iterator(); iterator.hasNext();) { - foundModules = true; - AxisModule moduleQName = (AxisModule) iterator.next(); - modulename = moduleQName.getName(); - moduleDescription = moduleQName.getModuleDescription(); - if(moduleDescription==null){ - moduleDescription = "[ -- No module description found --]"; - } - if (!wroteUL){ - wroteUL = true; -%> -
      -<% - } - %>
    • <%=modulename%> : <%=moduleDescription%>
    • - <% - } - if (wroteUL){ -%> -
    -<% - } - } - %> - <%if(errornesModules.size()>0){ - %> -

    Faulty Modules

    - <% - Enumeration faultyModules = errornesModules.keys(); - while (faultyModules.hasMoreElements()) { - foundModules = true; - String faultyModuleName = (String) faultyModules.nextElement(); - %> - <%=faultyModuleName%> - <% - } - } - if(! foundModules) { - %> -

    There are no modules deployed in the system.

    - <% - } - %> + <%-- + ~ Licensed to the Apache Software Foundation (ASF) under one + ~ or more contributor license agreements. See the NOTICE file + ~ distributed with this work for additional information + ~ regarding copyright ownership. The ASF licenses this file + ~ to you under the Apache License, Version 2.0 (the + ~ "License"); you may not use this file except in compliance + ~ with the License. You may obtain a copy of the License at + ~ + ~ http://www.apache.org/licenses/LICENSE-2.0 + ~ + ~ Unless required by applicable law or agreed to in writing, + ~ software distributed under the License is distributed on an + ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + ~ KIND, either express or implied. See the License for the + ~ specific language governing permissions and limitations + ~ under the License. + --%> <%@ page import="org.apache.axis2.Constants, + org.apache.axis2.description.AxisModule, + java.util.Collection"%> + <%@ page import="java.util.Enumeration"%> + <%@ page import="java.util.HashMap"%> + <%@ page import="java.util.Hashtable"%> + <%@ page import="java.util.Iterator"%> + <%@ page contentType="text/html;charset=UTF-8" language="java" %> + +

    Available Modules

    + <% + boolean foundModules = false; + boolean wroteUL = false; + HashMap moduleMap = (HashMap)request.getSession().getAttribute(Constants.MODULE_MAP); + request.getSession().setAttribute(Constants.MODULE_MAP,null); + Hashtable errornesModules =(Hashtable)request.getSession().getAttribute(Constants.ERROR_MODULE_MAP); + if (moduleMap!=null && !moduleMap.isEmpty()){ + String modulename ; + String moduleDescription ; + Collection moduleNames = moduleMap.values(); + for (Iterator iterator = moduleNames.iterator(); iterator.hasNext();) { + foundModules = true; + AxisModule moduleQName = (AxisModule) iterator.next(); + modulename = moduleQName.getName(); + moduleDescription = moduleQName.getModuleDescription(); + if(moduleDescription==null){ + moduleDescription = "[ -- No module description found --]"; + } + if (!wroteUL){ + wroteUL = true; +%> +
      +<% + } + %>
    • <%=modulename%> : <%=moduleDescription%>
    • + <% + } + if (wroteUL){ +%> +
    +<% + } + } + %> + <%if(errornesModules.size()>0){ + %> +

    Faulty Modules

    + <% + Enumeration faultyModules = errornesModules.keys(); + while (faultyModules.hasMoreElements()) { + foundModules = true; + String faultyModuleName = (String) faultyModules.nextElement(); + %> + <%=faultyModuleName%> + <% + } + } + if(! foundModules) { + %> +

    There are no modules deployed in the system.

    + <% + } + %> diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/listServiceGroups.jsp b/i2b2/src/main/webapp/WEB-INF/views/admin/listServiceGroups.jsp similarity index 100% rename from edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/listServiceGroups.jsp rename to i2b2/src/main/webapp/WEB-INF/views/admin/listServiceGroups.jsp diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/listServices.jsp b/i2b2/src/main/webapp/WEB-INF/views/admin/listServices.jsp similarity index 97% rename from edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/listServices.jsp rename to i2b2/src/main/webapp/WEB-INF/views/admin/listServices.jsp index 3f3d3dbc..d182e521 100644 --- a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/listServices.jsp +++ b/i2b2/src/main/webapp/WEB-INF/views/admin/listServices.jsp @@ -1,149 +1,149 @@ -<%-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --%> - -<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> -<%@ taglib prefix="t" tagdir="/WEB-INF/tags" %> -<%@ page import="org.apache.axis2.Constants, - org.apache.axis2.description.AxisModule" %> -<%@ page import="org.apache.axis2.description.AxisOperation" %> -<%@ page import="org.apache.axis2.description.AxisService" %> -<%@ page import="java.util.Collection" %> -<%@ page import="java.util.Enumeration" %> -<%@ page import="java.util.HashMap" %> -<%@ page import="java.util.Hashtable" %> -<%@ page import="java.util.Iterator" %> -<%@ page contentType="text/html;charset=UTF-8" language="java" %> - - -

    Available Services

    - -<% String prefix = request.getAttribute("frontendHostUrl") + (String)request.getAttribute(Constants.SERVICE_PATH) + "/"; -%> -<% - Hashtable errornessservice = (Hashtable) request.getSession().getAttribute(Constants.ERROR_SERVICE_MAP); - boolean status = false; -%> - -<% - AxisService axisService = (AxisService) pageContext.getAttribute("service"); - Iterator operations = axisService.getOperations(); - String serviceName = axisService.getName(); -%>

    <%=serviceName%>

    -<% - String serviceDescription = axisService.getDocumentation(); - if (serviceDescription == null || "".equals(serviceDescription)) { - serviceDescription = "No description available for this service"; - } -%> -

    Service Description : <%=serviceDescription%>
    -Service EPR : <%=prefix + axisService.getName()%>
    -Service Status : <%=axisService.isActive() ? "Active" : "InActive"%> -

    ">

    -<% - Collection engagedModules = axisService.getEngagedModules(); - String moduleName; - boolean modules_present = false; - if (engagedModules.size() > 0) { -%> -Engaged modules for the service -<% - for (Iterator iteratorm = engagedModules.iterator(); iteratorm.hasNext();) { - AxisModule axisOperation = (AxisModule) iteratorm.next(); - moduleName = axisOperation.getName(); - if (!modules_present) { - modules_present = true; -%> -
      - <% } - %>
    • "><%=moduleName%> ::
    • - - <% - } - if (modules_present) {%> -
    -<% - } - } - if (operations.hasNext()) { -%> -
    -Available operations -<% -} else { -%> There are no Operations specified -<% - } -%> -
      <% - operations = axisService.getOperations(); - while (operations.hasNext()) { - AxisOperation axisOperation = (AxisOperation) operations.next(); -%>
    • <%=axisOperation.getName().getLocalPart()%>
    • - <%--
      Operation EPR : <%=prifix + axisService.getName().getLocalPart() + "/"+ axisOperation.getName().getLocalPart()%>--%> - <% - engagedModules = axisOperation.getEngagedModules(); - if (engagedModules.size() > 0) { - %> -
    • - - Engaged Modules for the Operation -
        - <% - for (Iterator iterator2 = engagedModules.iterator(); iterator2.hasNext();) { - AxisModule moduleDecription = (AxisModule) iterator2.next(); - moduleName = moduleDecription.getName(); - %> -
      • -
        "><%=moduleName%> ::
        -
      • - <% - } - %> -
    • <% - } - - } -%> -
    -<% - status = true; -%> -
    -<% - if (errornessservice != null) { - if (errornessservice.size() > 0) { - request.getSession().setAttribute(Constants.IS_FAULTY, Constants.IS_FAULTY); -%> -

    Faulty Services

    -<% - Enumeration faultyservices = errornessservice.keys(); - while (faultyservices.hasMoreElements()) { - String faultyserviceName = (String) faultyservices.nextElement(); -%>

    - <%=faultyserviceName%>

    -<% - } - } - status = true; - } - if (!status) { -%> No services listed! Try hitting refresh. <% - } -%> - +<%-- + ~ Licensed to the Apache Software Foundation (ASF) under one + ~ or more contributor license agreements. See the NOTICE file + ~ distributed with this work for additional information + ~ regarding copyright ownership. The ASF licenses this file + ~ to you under the Apache License, Version 2.0 (the + ~ "License"); you may not use this file except in compliance + ~ with the License. You may obtain a copy of the License at + ~ + ~ http://www.apache.org/licenses/LICENSE-2.0 + ~ + ~ Unless required by applicable law or agreed to in writing, + ~ software distributed under the License is distributed on an + ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + ~ KIND, either express or implied. See the License for the + ~ specific language governing permissions and limitations + ~ under the License. + --%> + +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> +<%@ taglib prefix="t" tagdir="/WEB-INF/tags" %> +<%@ page import="org.apache.axis2.Constants, + org.apache.axis2.description.AxisModule" %> +<%@ page import="org.apache.axis2.description.AxisOperation" %> +<%@ page import="org.apache.axis2.description.AxisService" %> +<%@ page import="java.util.Collection" %> +<%@ page import="java.util.Enumeration" %> +<%@ page import="java.util.HashMap" %> +<%@ page import="java.util.Hashtable" %> +<%@ page import="java.util.Iterator" %> +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + + +

    Available Services

    + +<% String prefix = request.getAttribute("frontendHostUrl") + (String)request.getAttribute(Constants.SERVICE_PATH) + "/"; +%> +<% + Hashtable errornessservice = (Hashtable) request.getSession().getAttribute(Constants.ERROR_SERVICE_MAP); + boolean status = false; +%> + +<% + AxisService axisService = (AxisService) pageContext.getAttribute("service"); + Iterator operations = axisService.getOperations(); + String serviceName = axisService.getName(); +%>

    <%=serviceName%>

    +<% + String serviceDescription = axisService.getDocumentation(); + if (serviceDescription == null || "".equals(serviceDescription)) { + serviceDescription = "No description available for this service"; + } +%> +

    Service Description : <%=serviceDescription%>
    +Service EPR : <%=prefix + axisService.getName()%>
    +Service Status : <%=axisService.isActive() ? "Active" : "InActive"%> +

    ">

    +<% + Collection engagedModules = axisService.getEngagedModules(); + String moduleName; + boolean modules_present = false; + if (engagedModules.size() > 0) { +%> +Engaged modules for the service +<% + for (Iterator iteratorm = engagedModules.iterator(); iteratorm.hasNext();) { + AxisModule axisOperation = (AxisModule) iteratorm.next(); + moduleName = axisOperation.getName(); + if (!modules_present) { + modules_present = true; +%> +
      + <% } + %>
    • "><%=moduleName%> ::
    • + + <% + } + if (modules_present) {%> +
    +<% + } + } + if (operations.hasNext()) { +%> +
    +Available operations +<% +} else { +%> There are no Operations specified +<% + } +%> +
      <% + operations = axisService.getOperations(); + while (operations.hasNext()) { + AxisOperation axisOperation = (AxisOperation) operations.next(); +%>
    • <%=axisOperation.getName().getLocalPart()%>
    • + <%--
      Operation EPR : <%=prifix + axisService.getName().getLocalPart() + "/"+ axisOperation.getName().getLocalPart()%>--%> + <% + engagedModules = axisOperation.getEngagedModules(); + if (engagedModules.size() > 0) { + %> +
    • + + Engaged Modules for the Operation +
        + <% + for (Iterator iterator2 = engagedModules.iterator(); iterator2.hasNext();) { + AxisModule moduleDecription = (AxisModule) iterator2.next(); + moduleName = moduleDecription.getName(); + %> +
      • +
        "><%=moduleName%> ::
        +
      • + <% + } + %> +
    • <% + } + + } +%> +
    +<% + status = true; +%> +
    +<% + if (errornessservice != null) { + if (errornessservice.size() > 0) { + request.getSession().setAttribute(Constants.IS_FAULTY, Constants.IS_FAULTY); +%> +

    Faulty Services

    +<% + Enumeration faultyservices = errornessservice.keys(); + while (faultyservices.hasMoreElements()) { + String faultyserviceName = (String) faultyservices.nextElement(); +%>

    + <%=faultyserviceName%>

    +<% + } + } + status = true; + } + if (!status) { +%> No services listed! Try hitting refresh. <% + } +%> + diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/listSingleService.jsp b/i2b2/src/main/webapp/WEB-INF/views/admin/listSingleService.jsp similarity index 97% rename from edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/listSingleService.jsp rename to i2b2/src/main/webapp/WEB-INF/views/admin/listSingleService.jsp index d3b7351a..734897b9 100644 --- a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/listSingleService.jsp +++ b/i2b2/src/main/webapp/WEB-INF/views/admin/listSingleService.jsp @@ -1,89 +1,89 @@ -<%-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --%> - -<%@ page import="org.apache.axis2.Constants, - org.apache.axis2.description.AxisOperation" %> -<%@ page import="org.apache.axis2.description.AxisService" %> -<%@ page import="java.util.Hashtable" %> -<%@ page import="java.util.Iterator" %> -<%@ page contentType="text/html;charset=UTF-8" language="java" %> - -

    List Single Service

    -<% - String prefix = request.getAttribute("frontendHostUrl") + (String)request.getAttribute(Constants.SERVICE_PATH) + "/"; -%> -<% - String isFault = (String) request.getSession().getAttribute(Constants.IS_FAULTY); - String servicName = request.getParameter("serviceName"); - if (Constants.IS_FAULTY.equals(isFault)) { - Hashtable errornessservices = (Hashtable) request.getSession().getAttribute(Constants.ERROR_SERVICE_MAP); -%> -

    This Axis service has deployment faults.

    -

    <%=(String) errornessservices.get(servicName) %>

    -<% - -} else { - - AxisService axisService = - (AxisService) request.getSession().getAttribute(Constants.SINGLE_SERVICE); - if (axisService != null) { - Iterator opItr = axisService.getOperations(); - //operationsList = operations.values(); - String serviceName = axisService.getName(); -%> -

    <%=serviceName%>

    -

    -Service EPR : -<%=prefix + axisService.getName()%> -

    -<% - String serviceDescription = axisService.getDocumentation(); - if (serviceDescription == null || "".equals(serviceDescription)) { - serviceDescription = "No description available for this service"; - } -%> -

    Service Description : <%=serviceDescription%>

    -

    -Service Status : <%=axisService.isActive() ? "Active" : "InActive"%> -

    -<% - if (opItr.hasNext()) { -%>Available operations<% -} else { -%> There are no Operations specified<% - } - opItr = axisService.getOperations(); -%>
      <% - while (opItr.hasNext()) { - AxisOperation axisOperation = (AxisOperation) opItr.next(); -%>
    • <%=axisOperation.getName().getLocalPart()%>
    • - <%--
      Operation EPR : <%=prifix + axisService.getName().getLocalPart() + "/"+ axisOperation.getName().getLocalPart()%>--%> - <% - } - %>
    -<% -} else { -%> -

    No services found in this location

    -<% - } - - } -%> - +<%-- + ~ Licensed to the Apache Software Foundation (ASF) under one + ~ or more contributor license agreements. See the NOTICE file + ~ distributed with this work for additional information + ~ regarding copyright ownership. The ASF licenses this file + ~ to you under the Apache License, Version 2.0 (the + ~ "License"); you may not use this file except in compliance + ~ with the License. You may obtain a copy of the License at + ~ + ~ http://www.apache.org/licenses/LICENSE-2.0 + ~ + ~ Unless required by applicable law or agreed to in writing, + ~ software distributed under the License is distributed on an + ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + ~ KIND, either express or implied. See the License for the + ~ specific language governing permissions and limitations + ~ under the License. + --%> + +<%@ page import="org.apache.axis2.Constants, + org.apache.axis2.description.AxisOperation" %> +<%@ page import="org.apache.axis2.description.AxisService" %> +<%@ page import="java.util.Hashtable" %> +<%@ page import="java.util.Iterator" %> +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + +

    List Single Service

    +<% + String prefix = request.getAttribute("frontendHostUrl") + (String)request.getAttribute(Constants.SERVICE_PATH) + "/"; +%> +<% + String isFault = (String) request.getSession().getAttribute(Constants.IS_FAULTY); + String servicName = request.getParameter("serviceName"); + if (Constants.IS_FAULTY.equals(isFault)) { + Hashtable errornessservices = (Hashtable) request.getSession().getAttribute(Constants.ERROR_SERVICE_MAP); +%> +

    This Axis service has deployment faults.

    +

    <%=(String) errornessservices.get(servicName) %>

    +<% + +} else { + + AxisService axisService = + (AxisService) request.getSession().getAttribute(Constants.SINGLE_SERVICE); + if (axisService != null) { + Iterator opItr = axisService.getOperations(); + //operationsList = operations.values(); + String serviceName = axisService.getName(); +%> +

    <%=serviceName%>

    +

    +Service EPR : +<%=prefix + axisService.getName()%> +

    +<% + String serviceDescription = axisService.getDocumentation(); + if (serviceDescription == null || "".equals(serviceDescription)) { + serviceDescription = "No description available for this service"; + } +%> +

    Service Description : <%=serviceDescription%>

    +

    +Service Status : <%=axisService.isActive() ? "Active" : "InActive"%> +

    +<% + if (opItr.hasNext()) { +%>Available operations<% +} else { +%> There are no Operations specified<% + } + opItr = axisService.getOperations(); +%>
      <% + while (opItr.hasNext()) { + AxisOperation axisOperation = (AxisOperation) opItr.next(); +%>
    • <%=axisOperation.getName().getLocalPart()%>
    • + <%--
      Operation EPR : <%=prifix + axisService.getName().getLocalPart() + "/"+ axisOperation.getName().getLocalPart()%>--%> + <% + } + %>
    +<% +} else { +%> +

    No services found in this location

    +<% + } + + } +%> + diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/upload.jsp b/i2b2/src/main/webapp/WEB-INF/views/admin/upload.jsp similarity index 97% rename from edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/upload.jsp rename to i2b2/src/main/webapp/WEB-INF/views/admin/upload.jsp index 69d40548..611f7e75 100644 --- a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/upload.jsp +++ b/i2b2/src/main/webapp/WEB-INF/views/admin/upload.jsp @@ -1,64 +1,64 @@ -<%-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --%> - -<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> -<%@ taglib prefix="t" tagdir="/WEB-INF/tags" %> -<%@ page contentType="text/html;charset=UTF-8" language="java" %> - - -

    Upload an Axis Service Archive File

    - -

    You can upload a packaged Axis2 service from this page in two small steps.

    -
      -
    • Browse to the location and select the axis service archive file you wish to upload
    • -
    • Click "Upload" button
    • -
    -

    Simple as that!

    - - - -
    " - enctype="multipart/form-data"> - - - - - - - - - -
    Service archive :
     
    -
    -
    -

    Hot deployment of new service archives is <%=request.getAttribute("hotDeployment") %>

    -

    Hot update of existing service archives is <%=request.getAttribute("hotUpdate") %>

    -
    - +<%-- + ~ Licensed to the Apache Software Foundation (ASF) under one + ~ or more contributor license agreements. See the NOTICE file + ~ distributed with this work for additional information + ~ regarding copyright ownership. The ASF licenses this file + ~ to you under the Apache License, Version 2.0 (the + ~ "License"); you may not use this file except in compliance + ~ with the License. You may obtain a copy of the License at + ~ + ~ http://www.apache.org/licenses/LICENSE-2.0 + ~ + ~ Unless required by applicable law or agreed to in writing, + ~ software distributed under the License is distributed on an + ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + ~ KIND, either express or implied. See the License for the + ~ specific language governing permissions and limitations + ~ under the License. + --%> + +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> +<%@ taglib prefix="t" tagdir="/WEB-INF/tags" %> +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + + +

    Upload an Axis Service Archive File

    + +

    You can upload a packaged Axis2 service from this page in two small steps.

    +
      +
    • Browse to the location and select the axis service archive file you wish to upload
    • +
    • Click "Upload" button
    • +
    +

    Simple as that!

    + + + +
    " + enctype="multipart/form-data"> + + + + + + + + + +
    Service archive :
     
    +
    +
    +

    Hot deployment of new service archives is <%=request.getAttribute("hotDeployment") %>

    +

    Hot update of existing service archives is <%=request.getAttribute("hotUpdate") %>

    +
    + diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/viewContexts.jsp b/i2b2/src/main/webapp/WEB-INF/views/admin/viewContexts.jsp similarity index 97% rename from edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/viewContexts.jsp rename to i2b2/src/main/webapp/WEB-INF/views/admin/viewContexts.jsp index 2d12be0b..4c746daf 100644 --- a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/viewContexts.jsp +++ b/i2b2/src/main/webapp/WEB-INF/views/admin/viewContexts.jsp @@ -1,68 +1,68 @@ -<%-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --%> - -<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> -<%@ page import="org.apache.axis2.Constants"%> -<%@ page import="org.apache.axis2.context.ConfigurationContext"%> -<%@ page import="org.apache.axis2.context.ServiceContext"%> -<%@ page import="org.apache.axis2.context.ServiceGroupContext"%> -<%@ page import="java.util.Iterator"%> -<%@ page contentType="text/html;charset=UTF-8" language="java" %> - -

    Running Context Hierarchy

    -<% - ConfigurationContext configContext = (ConfigurationContext) request.getSession().getAttribute( - Constants.CONFIG_CONTEXT); - - String[] serviceGroupIds = configContext.getServiceGroupContextIDs(); - if (serviceGroupIds.length > 0) { -%> -
      - <% - - for (int i = 0; i < serviceGroupIds.length; i++) { - String groupContextID = serviceGroupIds[i]; - ServiceGroupContext groupContext = configContext.getServiceGroupContext(groupContextID); - %> -
    • <%=groupContextID%>"> - View "> - Remove
    • - -
    • - <% - Iterator serviceContextItr = groupContext.getServiceContexts(); - %>
        <% - while (serviceContextItr.hasNext()) { - ServiceContext serviceContext = (ServiceContext)serviceContextItr.next(); - String serviceConID = serviceContext.getAxisService().getName(); - %> -
      • <%=serviceConID%>"> - View
      • - <% - } - %>

      -
    • <% - } - %>
    - <% - } else {%> -

    No running contexts were found on the system.

    - <%} -%> - +<%-- + ~ Licensed to the Apache Software Foundation (ASF) under one + ~ or more contributor license agreements. See the NOTICE file + ~ distributed with this work for additional information + ~ regarding copyright ownership. The ASF licenses this file + ~ to you under the Apache License, Version 2.0 (the + ~ "License"); you may not use this file except in compliance + ~ with the License. You may obtain a copy of the License at + ~ + ~ http://www.apache.org/licenses/LICENSE-2.0 + ~ + ~ Unless required by applicable law or agreed to in writing, + ~ software distributed under the License is distributed on an + ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + ~ KIND, either express or implied. See the License for the + ~ specific language governing permissions and limitations + ~ under the License. + --%> + +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> +<%@ page import="org.apache.axis2.Constants"%> +<%@ page import="org.apache.axis2.context.ConfigurationContext"%> +<%@ page import="org.apache.axis2.context.ServiceContext"%> +<%@ page import="org.apache.axis2.context.ServiceGroupContext"%> +<%@ page import="java.util.Iterator"%> +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + +

    Running Context Hierarchy

    +<% + ConfigurationContext configContext = (ConfigurationContext) request.getSession().getAttribute( + Constants.CONFIG_CONTEXT); + + String[] serviceGroupIds = configContext.getServiceGroupContextIDs(); + if (serviceGroupIds.length > 0) { +%> +
      + <% + + for (int i = 0; i < serviceGroupIds.length; i++) { + String groupContextID = serviceGroupIds[i]; + ServiceGroupContext groupContext = configContext.getServiceGroupContext(groupContextID); + %> +
    • <%=groupContextID%>"> + View "> + Remove
    • + +
    • + <% + Iterator serviceContextItr = groupContext.getServiceContexts(); + %>
        <% + while (serviceContextItr.hasNext()) { + ServiceContext serviceContext = (ServiceContext)serviceContextItr.next(); + String serviceConID = serviceContext.getAxisService().getName(); + %> +
      • <%=serviceConID%>"> + View
      • + <% + } + %>

      +
    • <% + } + %>
    + <% + } else {%> +

    No running contexts were found on the system.

    + <%} +%> + diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/viewGlobalChains.jsp b/i2b2/src/main/webapp/WEB-INF/views/admin/viewGlobalChains.jsp similarity index 97% rename from edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/viewGlobalChains.jsp rename to i2b2/src/main/webapp/WEB-INF/views/admin/viewGlobalChains.jsp index 97766f07..dd47a18c 100644 --- a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/viewGlobalChains.jsp +++ b/i2b2/src/main/webapp/WEB-INF/views/admin/viewGlobalChains.jsp @@ -1,137 +1,137 @@ -<%-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --%> - -<%@ page import="org.apache.axis2.Constants, - org.apache.axis2.engine.AxisConfiguration, - org.apache.axis2.engine.Handler, - org.apache.axis2.engine.Phase, - java.util.List"%> -<%@ page contentType="text/html;charset=UTF-8" language="java" %> - -

    View Global Execution Chains

    - <% - AxisConfiguration axisConfig = (AxisConfiguration)request.getSession(). - getAttribute(Constants.GLOBAL_HANDLERS); - if(axisConfig != null ){ - List handlers ; - List phases = axisConfig.getInFlowPhases(); - %> -

    In Flow Up To and Including Dispatcher

    -
      - <% - for (int i = 0; i < phases.size(); i++) { - Phase phase = (Phase) phases.get(i); - %> -
    • Phase Name : <%=phase.getPhaseName()%>
    • -
        - <% - handlers = phase.getHandlers(); - for (int j = 0; j < handlers.size(); j++) { - Handler handler = (Handler) handlers.get(j); - %> -
      • Handler Name : <%=handler.getHandlerDesc().getName()%>
      • - <% - } - %> -
      - <% - } - %> -
    - <% - phases = axisConfig.getInFaultFlowPhases(); - %> -

    In Fault Flow

    -
      - <% - for (int i = 0; i < phases.size(); i++) { - Phase phase = (Phase) phases.get(i); - %> -
    • Phase Name : <%=phase.getPhaseName()%>
    • -
        - <% - handlers = phase.getHandlers(); - for (int j = 0; j < handlers.size(); j++) { - Handler handler = (Handler) handlers.get(j); - %> -
      • Handler Name : <%=handler.getHandlerDesc().getName()%>
      • - <% - } - %> -
      - <% - } - %> -
    - <% - - phases = axisConfig.getOutFlowPhases(); - %> -

    Out Flow

    -
      - <% - for (int i = 0; i < phases.size(); i++) { - Phase phase = (Phase) phases.get(i); - %> -
    • Phase Name : <%=phase.getPhaseName()%>
    • -
        - <% - handlers = phase.getHandlers(); - for (int j = 0; j < handlers.size(); j++) { - Handler handler = (Handler) handlers.get(j); - %> -
      • Handler Name : <%=handler.getHandlerDesc().getName()%>
      • - <% - } - %> -
      - <% - } - %> -
    - <% - phases = axisConfig.getOutFaultFlowPhases(); - %> -

    Out Fault Flow

    -
      - <% - for (int i = 0; i < phases.size(); i++) { - Phase phase = (Phase) phases.get(i); - %> -
    • Phase Name : <%=phase.getPhaseName()%>
    • -
        - <% - handlers = phase.getHandlers(); - for (int j = 0; j < handlers.size(); j++) { - Handler handler = (Handler) handlers.get(j); - %> -
      • Handler Name : <%=handler.getHandlerDesc().getName()%>
      • - <% - } - %> -
      - <% - } - %> -
    - <% - - } - %> - +<%-- + ~ Licensed to the Apache Software Foundation (ASF) under one + ~ or more contributor license agreements. See the NOTICE file + ~ distributed with this work for additional information + ~ regarding copyright ownership. The ASF licenses this file + ~ to you under the Apache License, Version 2.0 (the + ~ "License"); you may not use this file except in compliance + ~ with the License. You may obtain a copy of the License at + ~ + ~ http://www.apache.org/licenses/LICENSE-2.0 + ~ + ~ Unless required by applicable law or agreed to in writing, + ~ software distributed under the License is distributed on an + ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + ~ KIND, either express or implied. See the License for the + ~ specific language governing permissions and limitations + ~ under the License. + --%> + +<%@ page import="org.apache.axis2.Constants, + org.apache.axis2.engine.AxisConfiguration, + org.apache.axis2.engine.Handler, + org.apache.axis2.engine.Phase, + java.util.List"%> +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + +

    View Global Execution Chains

    + <% + AxisConfiguration axisConfig = (AxisConfiguration)request.getSession(). + getAttribute(Constants.GLOBAL_HANDLERS); + if(axisConfig != null ){ + List handlers ; + List phases = axisConfig.getInFlowPhases(); + %> +

    In Flow Up To and Including Dispatcher

    +
      + <% + for (int i = 0; i < phases.size(); i++) { + Phase phase = (Phase) phases.get(i); + %> +
    • Phase Name : <%=phase.getPhaseName()%>
    • +
        + <% + handlers = phase.getHandlers(); + for (int j = 0; j < handlers.size(); j++) { + Handler handler = (Handler) handlers.get(j); + %> +
      • Handler Name : <%=handler.getHandlerDesc().getName()%>
      • + <% + } + %> +
      + <% + } + %> +
    + <% + phases = axisConfig.getInFaultFlowPhases(); + %> +

    In Fault Flow

    +
      + <% + for (int i = 0; i < phases.size(); i++) { + Phase phase = (Phase) phases.get(i); + %> +
    • Phase Name : <%=phase.getPhaseName()%>
    • +
        + <% + handlers = phase.getHandlers(); + for (int j = 0; j < handlers.size(); j++) { + Handler handler = (Handler) handlers.get(j); + %> +
      • Handler Name : <%=handler.getHandlerDesc().getName()%>
      • + <% + } + %> +
      + <% + } + %> +
    + <% + + phases = axisConfig.getOutFlowPhases(); + %> +

    Out Flow

    +
      + <% + for (int i = 0; i < phases.size(); i++) { + Phase phase = (Phase) phases.get(i); + %> +
    • Phase Name : <%=phase.getPhaseName()%>
    • +
        + <% + handlers = phase.getHandlers(); + for (int j = 0; j < handlers.size(); j++) { + Handler handler = (Handler) handlers.get(j); + %> +
      • Handler Name : <%=handler.getHandlerDesc().getName()%>
      • + <% + } + %> +
      + <% + } + %> +
    + <% + phases = axisConfig.getOutFaultFlowPhases(); + %> +

    Out Fault Flow

    +
      + <% + for (int i = 0; i < phases.size(); i++) { + Phase phase = (Phase) phases.get(i); + %> +
    • Phase Name : <%=phase.getPhaseName()%>
    • +
        + <% + handlers = phase.getHandlers(); + for (int j = 0; j < handlers.size(); j++) { + Handler handler = (Handler) handlers.get(j); + %> +
      • Handler Name : <%=handler.getHandlerDesc().getName()%>
      • + <% + } + %> +
      + <% + } + %> +
    + <% + + } + %> + diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/viewOperationSpecificChains.jsp b/i2b2/src/main/webapp/WEB-INF/views/admin/viewOperationSpecificChains.jsp similarity index 97% rename from edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/viewOperationSpecificChains.jsp rename to i2b2/src/main/webapp/WEB-INF/views/admin/viewOperationSpecificChains.jsp index 37dde6d0..a89be842 100644 --- a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/viewOperationSpecificChains.jsp +++ b/i2b2/src/main/webapp/WEB-INF/views/admin/viewOperationSpecificChains.jsp @@ -1,147 +1,147 @@ -<%-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --%> - -<%@ page import="org.apache.axis2.Constants, - org.apache.axis2.description.AxisOperation, - org.apache.axis2.description.AxisService, - org.apache.axis2.engine.Handler, - org.apache.axis2.engine.Phase, - java.util.ArrayList, - java.util.List, - java.util.Iterator"%> -<%@ page contentType="text/html;charset=UTF-8" language="java" %> - - -

    View Operation Specific Chains

    - <% - AxisService axisService = (AxisService)request.getSession(). - getAttribute(Constants.SERVICE_HANDLERS); - if(axisService != null ){ - List handlers ; - Iterator operations = axisService.getOperations(); - while (operations.hasNext()) { - AxisOperation axisOperationon = (AxisOperation) operations.next(); - %>

    Operation Name : <%=axisOperationon.getName().getLocalPart()%>

    <% - ArrayList phases = axisOperationon.getRemainingPhasesInFlow(); - %> -

    In Flow

    -
      - <% - for (int i = 0; i < phases.size(); i++) { - Phase phase = (Phase) phases.get(i); - %> -
    • Phase Name : <%=phase.getPhaseName()%>
    • -
        - <% - handlers = phase.getHandlers(); - for (int j = 0; j < handlers.size(); j++) { - Handler handler = (Handler) handlers.get(j); - %> -
      • Handler Name : <%=handler.getHandlerDesc().getName()%>
      • - <% - } - %> -
      - <% - } - %> -
    - <% - phases = axisOperationon.getPhasesInFaultFlow(); - %> -

    In Fault Flow

    -
      - <% - for (int i = 0; i < phases.size(); i++) { - Phase phase = (Phase) phases.get(i); - %> -
    • Phase Name : <%=phase.getPhaseName()%>
    • -
        - <% - handlers = phase.getHandlers(); - for (int j = 0; j < handlers.size(); j++) { - Handler handler = (Handler) handlers.get(j); - %> -
      • Handler Name : <%=handler.getHandlerDesc().getName()%>
      • - <% - } - %> -
      - <% - } - %> -
    - <% - - phases = axisOperationon.getPhasesOutFlow(); - %> -

    Out Flow

    -
      - <% - for (int i = 0; i < phases.size(); i++) { - Phase phase = (Phase) phases.get(i); - %> -
    • Phase Name : <%=phase.getPhaseName()%>
    • -
        - <% - handlers = phase.getHandlers(); - for (int j = 0; j < handlers.size(); j++) { - Handler handler = (Handler) handlers.get(j); - %> -
      • Handler Name : <%=handler.getHandlerDesc().getName()%>
      • - <% - } - %> -
      - <% - } - %> -
    - <% - phases = axisOperationon.getPhasesOutFaultFlow(); - %> -

    Out Fault Flow

    -
      - <% - for (int i = 0; i < phases.size(); i++) { - Phase phase = (Phase) phases.get(i); - %> -
    • Phase Name : <%=phase.getPhaseName()%>
    • -
        - <% - handlers = phase.getHandlers(); - for (int j = 0; j < handlers.size(); j++) { - Handler handler = (Handler) handlers.get(j); - %> -
      • Handler Name : <%=handler.getHandlerDesc().getName()%>
      • - <% - } - %> -
      - <% - } - %> -
    - <% - - } - } - - %> +<%-- + ~ Licensed to the Apache Software Foundation (ASF) under one + ~ or more contributor license agreements. See the NOTICE file + ~ distributed with this work for additional information + ~ regarding copyright ownership. The ASF licenses this file + ~ to you under the Apache License, Version 2.0 (the + ~ "License"); you may not use this file except in compliance + ~ with the License. You may obtain a copy of the License at + ~ + ~ http://www.apache.org/licenses/LICENSE-2.0 + ~ + ~ Unless required by applicable law or agreed to in writing, + ~ software distributed under the License is distributed on an + ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + ~ KIND, either express or implied. See the License for the + ~ specific language governing permissions and limitations + ~ under the License. + --%> + +<%@ page import="org.apache.axis2.Constants, + org.apache.axis2.description.AxisOperation, + org.apache.axis2.description.AxisService, + org.apache.axis2.engine.Handler, + org.apache.axis2.engine.Phase, + java.util.ArrayList, + java.util.List, + java.util.Iterator"%> +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + + +

    View Operation Specific Chains

    + <% + AxisService axisService = (AxisService)request.getSession(). + getAttribute(Constants.SERVICE_HANDLERS); + if(axisService != null ){ + List handlers ; + Iterator operations = axisService.getOperations(); + while (operations.hasNext()) { + AxisOperation axisOperationon = (AxisOperation) operations.next(); + %>

    Operation Name : <%=axisOperationon.getName().getLocalPart()%>

    <% + ArrayList phases = axisOperationon.getRemainingPhasesInFlow(); + %> +

    In Flow

    +
      + <% + for (int i = 0; i < phases.size(); i++) { + Phase phase = (Phase) phases.get(i); + %> +
    • Phase Name : <%=phase.getPhaseName()%>
    • +
        + <% + handlers = phase.getHandlers(); + for (int j = 0; j < handlers.size(); j++) { + Handler handler = (Handler) handlers.get(j); + %> +
      • Handler Name : <%=handler.getHandlerDesc().getName()%>
      • + <% + } + %> +
      + <% + } + %> +
    + <% + phases = axisOperationon.getPhasesInFaultFlow(); + %> +

    In Fault Flow

    +
      + <% + for (int i = 0; i < phases.size(); i++) { + Phase phase = (Phase) phases.get(i); + %> +
    • Phase Name : <%=phase.getPhaseName()%>
    • +
        + <% + handlers = phase.getHandlers(); + for (int j = 0; j < handlers.size(); j++) { + Handler handler = (Handler) handlers.get(j); + %> +
      • Handler Name : <%=handler.getHandlerDesc().getName()%>
      • + <% + } + %> +
      + <% + } + %> +
    + <% + + phases = axisOperationon.getPhasesOutFlow(); + %> +

    Out Flow

    +
      + <% + for (int i = 0; i < phases.size(); i++) { + Phase phase = (Phase) phases.get(i); + %> +
    • Phase Name : <%=phase.getPhaseName()%>
    • +
        + <% + handlers = phase.getHandlers(); + for (int j = 0; j < handlers.size(); j++) { + Handler handler = (Handler) handlers.get(j); + %> +
      • Handler Name : <%=handler.getHandlerDesc().getName()%>
      • + <% + } + %> +
      + <% + } + %> +
    + <% + phases = axisOperationon.getPhasesOutFaultFlow(); + %> +

    Out Fault Flow

    +
      + <% + for (int i = 0; i < phases.size(); i++) { + Phase phase = (Phase) phases.get(i); + %> +
    • Phase Name : <%=phase.getPhaseName()%>
    • +
        + <% + handlers = phase.getHandlers(); + for (int j = 0; j < handlers.size(); j++) { + Handler handler = (Handler) handlers.get(j); + %> +
      • Handler Name : <%=handler.getHandlerDesc().getName()%>
      • + <% + } + %> +
      + <% + } + %> +
    + <% + + } + } + + %> diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/viewServiceContext.jsp b/i2b2/src/main/webapp/WEB-INF/views/admin/viewServiceContext.jsp similarity index 100% rename from edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/viewServiceContext.jsp rename to i2b2/src/main/webapp/WEB-INF/views/admin/viewServiceContext.jsp diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/viewServiceGroupContext.jsp b/i2b2/src/main/webapp/WEB-INF/views/admin/viewServiceGroupContext.jsp similarity index 100% rename from edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/viewServiceGroupContext.jsp rename to i2b2/src/main/webapp/WEB-INF/views/admin/viewServiceGroupContext.jsp diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/viewphases.jsp b/i2b2/src/main/webapp/WEB-INF/views/admin/viewphases.jsp similarity index 97% rename from edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/viewphases.jsp rename to i2b2/src/main/webapp/WEB-INF/views/admin/viewphases.jsp index 1f54e602..3b485ea4 100644 --- a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/admin/viewphases.jsp +++ b/i2b2/src/main/webapp/WEB-INF/views/admin/viewphases.jsp @@ -1,111 +1,111 @@ - <%-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --%> <%@ page import="org.apache.axis2.Constants, - org.apache.axis2.deployment.util.PhasesInfo, - org.apache.axis2.engine.Phase"%> - <%@ page import="java.util.List"%> -<%@ page contentType="text/html;charset=UTF-8" language="java" %> - -

    Available Phases

    - <% - PhasesInfo phases = (PhasesInfo)request.getSession().getAttribute(Constants.PHASE_LIST); - request.getSession().setAttribute(Constants.PHASE_LIST,null); - List tempList = phases.getGlobalInflow(); - %>

    System Pre-defined Phases

    - InFlow Up to Dispatcher -
    - <% - for (int i = 0; i < tempList.size(); i++) { - Phase phase = (Phase) tempList.get(i); - %><%=phase.getPhaseName()%>
    <% - } - %> -
    - InFaultFlow -
    - <% - tempList = phases.getGlobalInFaultPhases(); - for (int i = 0; i < tempList.size(); i++) { - Phase phase = (Phase) tempList.get(i); - %><%=phase.getPhaseName()%>
    <% - } - %> -
    - OutFlow -
    - <% - tempList = phases.getGlobalOutPhaseList(); - for (int i = 0; i < tempList.size(); i++) { - Phase phase = (Phase) tempList.get(i); - %><%=phase.getPhaseName()%>
    <% - } - %> -
    - OutFaultFlow -
    - <% - tempList = phases.getOUT_FaultPhases(); - for (int i = 0; i < tempList.size(); i++) { - Phase phase = (Phase) tempList.get(i); - %><%=phase.getPhaseName()%>
    <% - } - %> -
    -
    -

    User Defined Phases

    - Inflow after Dispatcher -
    - <% - tempList = phases.getOperationInPhases(); - for (int i = 0; i < tempList.size(); i++) { - Phase phase = (Phase) tempList.get(i); - %><%=phase.getPhaseName()%>
    <% - } - %> -
    - InFaultFlow after Dispatcher -
    - <% - tempList = phases.getOperationInFaultPhases(); - for (int i = 0; i < tempList.size(); i++) { - Phase phase = (Phase) tempList.get(i); - %><%=phase.getPhaseName()%>
    <% - } - %> -
    - OutFlow -
    - <% - tempList = phases.getOperationOutPhases(); - for (int i = 0; i < tempList.size(); i++) { - Phase phase = (Phase) tempList.get(i); - %><%=phase.getPhaseName()%>
    <% - } - %> -
    - OutFaultFlow -
    - <% - tempList = phases.getOperationOutFaultPhases(); - for (int i = 0; i < tempList.size(); i++) { - Phase phase = (Phase) tempList.get(i); - %><%=phase.getPhaseName()%>
    <% - } - %> -
    - + <%-- + ~ Licensed to the Apache Software Foundation (ASF) under one + ~ or more contributor license agreements. See the NOTICE file + ~ distributed with this work for additional information + ~ regarding copyright ownership. The ASF licenses this file + ~ to you under the Apache License, Version 2.0 (the + ~ "License"); you may not use this file except in compliance + ~ with the License. You may obtain a copy of the License at + ~ + ~ http://www.apache.org/licenses/LICENSE-2.0 + ~ + ~ Unless required by applicable law or agreed to in writing, + ~ software distributed under the License is distributed on an + ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + ~ KIND, either express or implied. See the License for the + ~ specific language governing permissions and limitations + ~ under the License. + --%> <%@ page import="org.apache.axis2.Constants, + org.apache.axis2.deployment.util.PhasesInfo, + org.apache.axis2.engine.Phase"%> + <%@ page import="java.util.List"%> +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + +

    Available Phases

    + <% + PhasesInfo phases = (PhasesInfo)request.getSession().getAttribute(Constants.PHASE_LIST); + request.getSession().setAttribute(Constants.PHASE_LIST,null); + List tempList = phases.getGlobalInflow(); + %>

    System Pre-defined Phases

    + InFlow Up to Dispatcher +
    + <% + for (int i = 0; i < tempList.size(); i++) { + Phase phase = (Phase) tempList.get(i); + %><%=phase.getPhaseName()%>
    <% + } + %> +
    + InFaultFlow +
    + <% + tempList = phases.getGlobalInFaultPhases(); + for (int i = 0; i < tempList.size(); i++) { + Phase phase = (Phase) tempList.get(i); + %><%=phase.getPhaseName()%>
    <% + } + %> +
    + OutFlow +
    + <% + tempList = phases.getGlobalOutPhaseList(); + for (int i = 0; i < tempList.size(); i++) { + Phase phase = (Phase) tempList.get(i); + %><%=phase.getPhaseName()%>
    <% + } + %> +
    + OutFaultFlow +
    + <% + tempList = phases.getOUT_FaultPhases(); + for (int i = 0; i < tempList.size(); i++) { + Phase phase = (Phase) tempList.get(i); + %><%=phase.getPhaseName()%>
    <% + } + %> +
    +
    +

    User Defined Phases

    + Inflow after Dispatcher +
    + <% + tempList = phases.getOperationInPhases(); + for (int i = 0; i < tempList.size(); i++) { + Phase phase = (Phase) tempList.get(i); + %><%=phase.getPhaseName()%>
    <% + } + %> +
    + InFaultFlow after Dispatcher +
    + <% + tempList = phases.getOperationInFaultPhases(); + for (int i = 0; i < tempList.size(); i++) { + Phase phase = (Phase) tempList.get(i); + %><%=phase.getPhaseName()%>
    <% + } + %> +
    + OutFlow +
    + <% + tempList = phases.getOperationOutPhases(); + for (int i = 0; i < tempList.size(); i++) { + Phase phase = (Phase) tempList.get(i); + %><%=phase.getPhaseName()%>
    <% + } + %> +
    + OutFaultFlow +
    + <% + tempList = phases.getOperationOutFaultPhases(); + for (int i = 0; i < tempList.size(); i++) { + Phase phase = (Phase) tempList.get(i); + %><%=phase.getPhaseName()%>
    <% + } + %> +
    + diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/listFaultyService.jsp b/i2b2/src/main/webapp/WEB-INF/views/listFaultyService.jsp similarity index 100% rename from edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/listFaultyService.jsp rename to i2b2/src/main/webapp/WEB-INF/views/listFaultyService.jsp diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/listServices.jsp b/i2b2/src/main/webapp/WEB-INF/views/listServices.jsp similarity index 97% rename from edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/listServices.jsp rename to i2b2/src/main/webapp/WEB-INF/views/listServices.jsp index fb8664a3..7bf5a0ab 100644 --- a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/views/listServices.jsp +++ b/i2b2/src/main/webapp/WEB-INF/views/listServices.jsp @@ -1,112 +1,112 @@ -<%-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --%> - -<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> -<%@ page session="false" %> -<%@ page import="org.apache.axis2.Constants, - org.apache.axis2.description.AxisOperation" %> -<%@ page import="org.apache.axis2.description.AxisService" %> -<%@ page import="org.apache.axis2.util.Utils" %> -<%@ page import="java.util.Collection" %> -<%@ page import="java.util.Enumeration" %> -<%@ page import="java.util.HashMap" %> -<%@ page import="java.util.Hashtable" %> -<%@ page import="java.util.Iterator" %> -<%@ page contentType="text/html;charset=UTF-8" language="java" %> - - - - -List Services - - - - - - -

    Available services

    -<% String prefix = request.getAttribute("frontendHostUrl") + (String)request.getAttribute(Constants.SERVICE_PATH) + "/"; -%> -<% - Hashtable errornessservice = (Hashtable) request.getAttribute(Constants.ERROR_SERVICE_MAP); - boolean status = false; -%> - -<% - AxisService axisService = (AxisService) pageContext.getAttribute("service"); - if (!Utils.isHiddenService(axisService)) { - Iterator opItr = axisService.getOperations(); - String serviceName = axisService.getName(); -%>

    <%=serviceName%>

    -<% - String serviceDescription = axisService.getDocumentation(); - if (serviceDescription == null || "".equals(serviceDescription)) { - serviceDescription = "No description available for this service"; - } -%> -
    Service Description : <%=serviceDescription%>
    -
    Service EPR : <%=prefix + axisService.getName()%>
    -
    Service Status : <%=axisService.isActive() ? "Active" : "InActive"%>

    -<% - if (opItr.hasNext()) { -%>Available Operations<% -} else { -%> There are no Operations specified<% - } - opItr = axisService.getOperations(); -%>
      <% - while (opItr.hasNext()) { - AxisOperation axisOperation = (AxisOperation) opItr.next(); -%>
    • <%=axisOperation.getName().getLocalPart()%>
    • - <%--
      Operation EPR : <%=prifix + axisService.getName().getLocalPart() + "/"+ axisOperation.getName().getLocalPart()%>--%> - <% - } - %>
    -<% - status = true; - } -%> -
    -<% - if (errornessservice != null) { - if (errornessservice.size() > 0) { - request.setAttribute(Constants.IS_FAULTY, Constants.IS_FAULTY); -%> -
    - -

    Faulty Services

    -<% - Enumeration faultyservices = errornessservice.keys(); - while (faultyservices.hasMoreElements()) { - String faultyserviceName = (String) faultyservices.nextElement(); -%> -

    - <%=faultyserviceName%>

    -<% - } - } - status = true; - } - if (!status) { -%> No services listed! Try hitting refresh. <% - } -%> - - - +<%-- + ~ Licensed to the Apache Software Foundation (ASF) under one + ~ or more contributor license agreements. See the NOTICE file + ~ distributed with this work for additional information + ~ regarding copyright ownership. The ASF licenses this file + ~ to you under the Apache License, Version 2.0 (the + ~ "License"); you may not use this file except in compliance + ~ with the License. You may obtain a copy of the License at + ~ + ~ http://www.apache.org/licenses/LICENSE-2.0 + ~ + ~ Unless required by applicable law or agreed to in writing, + ~ software distributed under the License is distributed on an + ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + ~ KIND, either express or implied. See the License for the + ~ specific language governing permissions and limitations + ~ under the License. + --%> + +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> +<%@ page session="false" %> +<%@ page import="org.apache.axis2.Constants, + org.apache.axis2.description.AxisOperation" %> +<%@ page import="org.apache.axis2.description.AxisService" %> +<%@ page import="org.apache.axis2.util.Utils" %> +<%@ page import="java.util.Collection" %> +<%@ page import="java.util.Enumeration" %> +<%@ page import="java.util.HashMap" %> +<%@ page import="java.util.Hashtable" %> +<%@ page import="java.util.Iterator" %> +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + + + + +List Services + + + + + + +

    Available services

    +<% String prefix = request.getAttribute("frontendHostUrl") + (String)request.getAttribute(Constants.SERVICE_PATH) + "/"; +%> +<% + Hashtable errornessservice = (Hashtable) request.getAttribute(Constants.ERROR_SERVICE_MAP); + boolean status = false; +%> + +<% + AxisService axisService = (AxisService) pageContext.getAttribute("service"); + if (!Utils.isHiddenService(axisService)) { + Iterator opItr = axisService.getOperations(); + String serviceName = axisService.getName(); +%>

    <%=serviceName%>

    +<% + String serviceDescription = axisService.getDocumentation(); + if (serviceDescription == null || "".equals(serviceDescription)) { + serviceDescription = "No description available for this service"; + } +%> +
    Service Description : <%=serviceDescription%>
    +
    Service EPR : <%=prefix + axisService.getName()%>
    +
    Service Status : <%=axisService.isActive() ? "Active" : "InActive"%>

    +<% + if (opItr.hasNext()) { +%>Available Operations<% +} else { +%> There are no Operations specified<% + } + opItr = axisService.getOperations(); +%>
      <% + while (opItr.hasNext()) { + AxisOperation axisOperation = (AxisOperation) opItr.next(); +%>
    • <%=axisOperation.getName().getLocalPart()%>
    • + <%--
      Operation EPR : <%=prifix + axisService.getName().getLocalPart() + "/"+ axisOperation.getName().getLocalPart()%>--%> + <% + } + %>
    +<% + status = true; + } +%> +
    +<% + if (errornessservice != null) { + if (errornessservice.size() > 0) { + request.setAttribute(Constants.IS_FAULTY, Constants.IS_FAULTY); +%> +
    + +

    Faulty Services

    +<% + Enumeration faultyservices = errornessservice.keys(); + while (faultyservices.hasMoreElements()) { + String faultyserviceName = (String) faultyservices.nextElement(); +%> +

    + <%=faultyserviceName%>

    +<% + } + } + status = true; + } + if (!status) { +%> No services listed! Try hitting refresh. <% + } +%> + + + diff --git a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/web.xml b/i2b2/src/main/webapp/WEB-INF/web.xml similarity index 97% rename from edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/web.xml rename to i2b2/src/main/webapp/WEB-INF/web.xml index 20619f36..310c1e18 100644 --- a/edu.harvard.i2b2.server-common/lib/axis2.war/WEB-INF/web.xml +++ b/i2b2/src/main/webapp/WEB-INF/web.xml @@ -42,11 +42,11 @@ 1 - + + + + org.apache.commons + commons-lang3 + ${commons.lang.version} + + + + org.apache.logging.log4j + log4j-core + ${log4j.version} + + + commons-logging + commons-logging + ${commons-logging.version} + + + + junit + junit + ${junit.version} + test + + + + + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.14.0 + + ${java.version} + ${java.version} + + + + org.apache.maven.plugins + maven-war-plugin + 3.4.0 + + false + + + + org.codehaus.mojo + exec-maven-plugin + 3.5.1 + + + + com.diffplug.spotless + spotless-maven-plugin + ${spotless_version} + + + + apply + check + + compile + + + + + + ${spotless.exclude.pattern} + + + + + + + + + true + 4 + + + + + + true + ,java|javax,\# + + + + + + + + *.md + .gitignore + *.java + + + + + + + + + + + + + \ No newline at end of file